Skip to content

Refactor: Consolidate duplicated RolloutBuffer implementations - #83

Merged
chrisjz merged 1 commit into
mainfrom
refactor/consolidate-rollout-buffer
Mar 21, 2026
Merged

Refactor: Consolidate duplicated RolloutBuffer implementations#83
chrisjz merged 1 commit into
mainfrom
refactor/consolidate-rollout-buffer

Conversation

@chrisjz

@chrisjz chrisjz commented Mar 21, 2026

Copy link
Copy Markdown
Member

Summary

  • Extracts duplicated PPO RolloutBuffer into a shared module at brain/arch/_ppo_buffer.py
  • Replaces 3 near-identical inline copies (~350 lines removed) in _reservoir_hybrid_base.py, mlpppo.py, and _hybrid_common.py
  • Fixes mlpppo's bare .squeeze() which could collapse the batch dimension for single-step buffers (now uses .reshape(-1))
  • Adds len(advantages) > 1 guard to prevent degenerate single-step advantage normalization
  • QLIFLSTMRolloutBuffer and QSNNRolloutBuffer left as-is (different interfaces with extra per-step data)

Closes #77

Test plan

  • All 1791 unit/integration tests pass
  • Pre-commit (ruff, pyright) passes
  • Smoke tests on PR CI

🤖 Generated with Claude Code

Summary by CodeRabbit

  • Refactor
    • Consolidated the PPO rollout buffer into a single shared implementation to reduce duplication, simplify maintenance, and centralize minibatch/advantage computation logic while preserving existing training behavior and interfaces.

@coderabbitai

coderabbitai Bot commented Mar 21, 2026

Copy link
Copy Markdown

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: 3046bfad-146b-4fc0-8df6-37fa7a2c0adf

📥 Commits

Reviewing files that changed from the base of the PR and between 23c84a3 and b369f05.

📒 Files selected for processing (4)
  • packages/quantum-nematode/quantumnematode/brain/arch/_hybrid_common.py
  • packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py
  • packages/quantum-nematode/quantumnematode/brain/arch/_reservoir_hybrid_base.py
  • packages/quantum-nematode/quantumnematode/brain/arch/mlpppo.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/quantum-nematode/quantumnematode/brain/arch/mlpppo.py

📝 Walkthrough

Walkthrough

Extracted duplicated PPO rollout logic into a new shared RolloutBuffer implementation and replaced per-module local buffer classes by importing and re-exporting that shared buffer across affected brain architecture modules. Typing cleanup accompanied the replacements.

Changes

Cohort / File(s) Summary
New shared buffer
packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py
Added centralized RolloutBuffer class: storage, add/reset, is_full/__len__, compute_returns_and_advantages (GAE), and get_minibatches (tensor conversion, advantage normalization, RNG-permuted minibatches).
Hybrid common
packages/quantum-nematode/quantumnematode/brain/arch/_hybrid_common.py
Removed local _CortexRolloutBuffer implementation; now imports and re-exports RolloutBuffer from _ppo_buffer under alias _CortexRolloutBuffer. Eliminated local typing conditional for Iterator/TYPE_CHECKING.
Reservoir hybrid base
packages/quantum-nematode/quantumnematode/brain/arch/_reservoir_hybrid_base.py
Replaced file-local _RolloutBuffer with imported RolloutBuffer as _RolloutBuffer. Removed conditional typing imports; construction and usages unchanged.
MLP PPO brain
packages/quantum-nematode/quantumnematode/brain/arch/mlpppo.py
Deleted inline RolloutBuffer class and now imports shared RolloutBuffer. Removed unused Iterator import. Internal training code continues to call compute_returns_and_advantages / get_minibatches via the shared buffer API.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Poem

🐇 I hopped through loops of code and found,

duplicates scattered on the ground.
One cozy buffer now holds the trail,
tidy footprints, no more flail.
Thump-thump—clean, shared, and sound 🎉

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 71.43% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately and concisely summarizes the main objective: consolidating duplicated RolloutBuffer implementations into a shared module.
Linked Issues check ✅ Passed The PR successfully implements all coding requirements from #77: extracts RolloutBuffer to _ppo_buffer.py, removes duplicates from three files, and unifies behavioral differences like .squeeze() normalization.
Out of Scope Changes check ✅ Passed All changes are directly aligned with #77 scope: the new buffer implementation, removals from specified files, and bug fixes for .squeeze() and advantage normalization fall within the consolidation objectives.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch refactor/consolidate-rollout-buffer

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@codecov

codecov Bot commented Mar 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🧹 Nitpick comments (1)
packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py (1)

21-22: Match the repo's docstring format for the shared buffer.

This class is now the shared PPO buffer API, so its docstring should follow the project's NumPy-style convention.

As per coding guidelines, "Use NumPy-style docstrings".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py` around
lines 21 - 22, The RolloutBuffer class docstring currently is a single-line
summary; replace it with a NumPy-style docstring for the shared PPO buffer API
(class RolloutBuffer) that includes a short summary, Parameters (e.g.,
buffer_size, observation_space, action_space, device), Attributes (e.g.,
observations, actions, rewards, dones, ptr, size), and a brief Notes or Methods
section listing key methods (add, sample, reset) so it matches the repo's
NumPy-style convention and documents the public API.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py`:
- Around line 103-119: The loop can produce minibatch_size==0 when batch_size <
num_minibatches (causing range() to error or produce wrong number of
minibatches); change the minibatch splitting to ensure a positive,
well-distributed size by computing minibatch_size = max(1, math.ceil(batch_size
/ num_minibatches)) (or equivalently compute start/end offsets using integer
division to produce exactly num_minibatches chunks) and then use that
minibatch_size for the for start in range(0, batch_size, minibatch_size) loop
while still indexing mb_indices = indices[start:end]; update imports if needed
and keep references to batch_size, num_minibatches, minibatch_size, indices and
the for loop so small buffers no longer yield zero-sized minibatches or extra
chunks.

---

Nitpick comments:
In `@packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py`:
- Around line 21-22: The RolloutBuffer class docstring currently is a
single-line summary; replace it with a NumPy-style docstring for the shared PPO
buffer API (class RolloutBuffer) that includes a short summary, Parameters
(e.g., buffer_size, observation_space, action_space, device), Attributes (e.g.,
observations, actions, rewards, dones, ptr, size), and a brief Notes or Methods
section listing key methods (add, sample, reset) so it matches the repo's
NumPy-style convention and documents the public API.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro

Run ID: e94998e6-ee03-4532-90a6-00e62d546cef

📥 Commits

Reviewing files that changed from the base of the PR and between 376e9af and 23c84a3.

📒 Files selected for processing (4)
  • packages/quantum-nematode/quantumnematode/brain/arch/_hybrid_common.py
  • packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py
  • packages/quantum-nematode/quantumnematode/brain/arch/_reservoir_hybrid_base.py
  • packages/quantum-nematode/quantumnematode/brain/arch/mlpppo.py

Comment thread packages/quantum-nematode/quantumnematode/brain/arch/_ppo_buffer.py
Extract the PPO RolloutBuffer (duplicated across 3 files) into a single
shared module at brain/arch/_ppo_buffer.py. The three near-identical
copies (_reservoir_hybrid_base, mlpppo, _hybrid_common) now import from
the shared module.

Key changes:
- Use reshape(-1) for value flattening (safe for single-step buffers)
- Add len(advantages) > 1 guard for advantage normalization
- Fix mlpppo's bare .squeeze() which could collapse batch dim

QLIFLSTMRolloutBuffer and QSNNRolloutBuffer are left as-is since they
store additional per-step data (LSTM states, spike caches) with
fundamentally different interfaces.

Closes #77

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
@chrisjz
chrisjz force-pushed the refactor/consolidate-rollout-buffer branch from 23c84a3 to b369f05 Compare March 21, 2026 05:17
@chrisjz
chrisjz merged commit 35560af into main Mar 21, 2026
3 checks passed
@chrisjz
chrisjz deleted the refactor/consolidate-rollout-buffer branch March 21, 2026 05:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Refactor: Consolidate duplicated RolloutBuffer implementations

1 participant