Skip to content

Add CPU optimizer-state offload and atomic state movement for Gefen - #77

Open
thad0ctor wants to merge 4 commits into
mainfrom
feat/cpu-offload-tier3
Open

thad0ctor wants to merge 4 commits into
mainfrom
feat/cpu-offload-tier3

Conversation

@thad0ctor

@thad0ctor thad0ctor commented Jul 16, 2026

Copy link
Copy Markdown
Owner

Summary

Adds a modular optimizer-state movement engine (src/gefen/offload.py, StateOffloadMixin) and wires it into Gefen/GefenMuon with a minimal, fully flag-gated core integration:

  • move_state_(device=None) — fail-atomic movement of authoritative optimizer state (momentum codebook indices, magnitudes, second moments, counters) to the live parameter devices, or to an explicit co-located device. Available on both Gefen and GefenMuon.
  • offload_state_() / restore_state_() — synchronous CPU-authoritative optimizer state for plain replicated-CUDA Gefen: persistent per-parameter state lives on CPU between steps; each step stages it to the parameter device, runs the ordinary (non-fused, non-batched) update, and copies it back to CPU. The shared codebook stays CUDA-resident.

Everything is opt-in and gated on state_offload_active (default off), so existing single-GPU and distributed (FSDP2 / ZeRO / DDP) training paths are behaviorally unchanged — the core gefen.py diff is 32 lines.

Scope and safety

Native CPU offload supports plain Gefen with ordinary replicated CUDA parameters (single-GPU and DDP-style data parallelism). It fails closed (raises before mutating anything) under:

  • DTensor / FSDP2 sharded parameters,
  • Gefen's rank-local sharded-state mode,
  • capturable / CUDA-graph execution, torch.compile, and custom tensor-valued state extensions.

Sharded offload requires a separate paging policy and is left as future work.

Robustness

  • Atomic activation / restore / move: state is staged and validated (device, dtype, shape, tight contiguous storage, no aliasing) before the live mapping is swapped; a copy failure is a true no-op.
  • Copyback poisoning: if the post-update CPU copyback fails, the optimizer is marked poisoned and refuses to step or export state until a known-good checkpoint is loaded.
  • Recovery via load (fix): a committed load_state_dict() clears the copyback-poison flag unconditionally — recovery no longer depends on offload still being active at load time (previously, restore_state_() before loading left the optimizer permanently bricked).
  • CPU-mapped codebook (fix): loading a checkpoint with map_location='cpu' while offload is active now co-locates the shared codebook back onto the parameter device, so the next step keeps the codebook CUDA-resident (previously it raised "codebook must remain CUDA-resident").

Testing

tests/test_state_offload.py — 17 tests (bit-exact offloaded stepping across factored + block second-moment paths, activate-before-first-step, periodic codebook refresh, activation/restore/move failure atomicity, cross-device movement for Gefen/GefenMuon, active-offload checkpoint load, copyback poison stickiness + recovery, CPU-mapped codebook co-location, persistent-storage alias rejection).

Validated on an RTX 3090 (CUDA 12.x):

  • Full test_state_offload.py: 17 passed.
  • Load/checkpoint/distributed suites (test_native_load_atomicity, test_hybrid_load_atomicity, test_cpu_step_checkpoint, test_gefen_fsdp2_checkpoint, test_muon_distributed_checkpoint_safety, test_state_offload): 107 passed, 3 skipped.
  • Distributed fail-closed behavior confirmed on a single-rank NCCL harness: DTensor and rank-local sharded state reject; DDP-replicated offload is bit-exact vs. the non-offload path.

Summary by CodeRabbit

  • New Features
    • Added fail-atomic optimizer-state movement for Gefen and GefenMuon via move_state_().
    • Added synchronous CPU optimizer-state offload for standard replicated-CUDA Gefen using offload_state_() / restore_state_(), with per-step readiness/validation.
    • Preserves active offload across checkpoint loads and fails closed on unsuccessful CPU copyback; recovery supported after a subsequent known-good load.
    • Improved map_location='cpu' checkpoint behavior to restore CUDA codebook placement when offload is enabled later.
  • Documentation
    • Expanded the roadmap with setup, usage flow, and compatibility limitations.
  • Tests
    • Added end-to-end and multi-GPU DDP coverage to confirm bit-exact updates and CPU authority.

Introduce src/gefen/offload.py (StateOffloadMixin) and wire it into Gefen
and GefenMuon with a minimal, fully flag-gated core integration:

- move_state_(device=None): fail-atomic movement of authoritative optimizer
  state to the live parameter devices or an explicit co-located device.
- offload_state_() / restore_state_(): synchronous CPU-authoritative
  optimizer state for plain replicated-CUDA Gefen; each step stages state to
  the parameter device, runs the ordinary (non-fused, non-batched) update,
  and copies it back to CPU while the shared codebook stays CUDA-resident.

All new behavior is gated on state_offload_active (default off), so existing
single-GPU and distributed (FSDP2/ZeRO/DDP) paths are behaviorally unchanged.
Native offload supports plain Gefen with ordinary replicated CUDA parameters
and fails closed under DTensor/FSDP sharding, rank-local sharded state,
capturable/CUDA-graph execution, custom tensor-valued state, and torch.compile.

Activation, restore, move, and checkpoint load are staged and validated
(device, dtype, shape, tight contiguous storage, no aliasing) before the live
mapping is swapped, so a copy failure is a true no-op. A failed post-update
CPU copyback marks the optimizer poisoned and refuses further step/export;
loading a known-good checkpoint clears the poison unconditionally (regardless
of whether offload is still active) and co-locates a map_location='cpu'
codebook back onto the parameter device.

tests/test_state_offload.py adds 17 tests; full suite green on RTX 3090.
@coderabbitai

coderabbitai Bot commented Jul 16, 2026

Copy link
Copy Markdown

Review Change Stack

Warning

Review limit reached

You’ve reached a temporary PR review limit under our Fair Usage Limits Policy.

Your recent review volume is higher than typical usage, so adaptive limits are currently applied.

Next review available in: 2 minutes

Enable usage-based reviews in Billing to review now. Otherwise, wait until the next included review is available.
You're only billed for reviews past your plan's rate limits ($0.25/file).

How can I continue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

To avoid repeated limits, reduce automatic review volume by pausing incremental auto-reviews earlier, using label-based review opt-in, excluding WIP or generated PR titles, or requesting reviews manually when the PR is ready. If your team needs uninterrupted high-volume reviews, an organization admin can enable usage-based reviews.

How do review limits work?

CodeRabbit enforces per-developer PR review limits for each organization. Most developers receive the normal plan review availability.

For paid Pro and Pro+ PR reviews, CodeRabbit uses adaptive limits for sustained high-volume activity. When a developer's recent PR review activity reaches the 95th percentile or higher among CodeRabbit users, additional reviews become available more gradually as earlier reviews age out of the rolling window.

Please refer docs for additional details.

Review details
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 225cf8c7-b249-4efd-96f0-94cb60fc7afc

📥 Commits

Reviewing files that changed from the base of the PR and between 9c3ac4c and d39070a.

📒 Files selected for processing (1)
  • tests/test_state_offload_distributed.py
📝 Walkthrough

Walkthrough

Gefen adds atomic optimizer-state movement and synchronous CPU offload for replicated CUDA parameters. Offload-aware stepping, checkpoint reconciliation, poison recovery, codebook placement, documentation, and CUDA/DDP validation are included.

Changes

Optimizer state movement

Layer / File(s) Summary
Atomic state movement contracts
src/gefen/offload.py, src/gefen/gefen.py, tests/test_state_offload.py
Adds validated, atomic state movement with codebook relocation, offload status fields, and failure-preservation tests.

CPU-authoritative stepping

Layer / File(s) Summary
CPU-authoritative stepping
src/gefen/offload.py, src/gefen/gefen.py, tests/test_state_offload.py, tests/test_state_offload_distributed.py
Stages per-parameter state to CUDA for updates, copies it back to CPU, rejects unsupported configurations, poisons after copyback failure, and routes factored and standard steps through offload handling with CUDA/DDP coverage.

Checkpoint and offload lifecycle

Layer / File(s) Summary
Checkpoint and offload lifecycle
src/gefen/gefen.py, src/gefen/offload.py, tests/test_state_offload.py, README.md, CHANGELOG.md
Adds checkpoint safety and load reconciliation, preserves active offload, clears poison after committed loads, restores codebook placement, and documents the API and constraints.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant GefenStep
  participant StateOffloadMixin
  participant CUDAParameter
  participant CPUOptimizerState
  GefenStep->>StateOffloadMixin: validate offload readiness
  StateOffloadMixin->>CPUOptimizerState: stage state for update
  CPUOptimizerState->>CUDAParameter: copy state to parameter device
  GefenStep->>CUDAParameter: perform optimizer update
  CUDAParameter->>CPUOptimizerState: copy updated state back
Loading

Possibly related PRs

  • thad0ctor/Gefen-X#1: Related Gefen codebook placement and optimizer-state checkpoint restoration.
  • thad0ctor/Gefen-X#64: Related Gefen checkpointing and optimizer-state serialization/load behavior.
🚥 Pre-merge checks | ✅ 5
✅ Passed checks (5 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly matches the main change: CPU optimizer-state offload and atomic state movement for Gefen.
Docstring Coverage ✅ Passed No functions found in the changed files to evaluate docstring coverage. Skipping docstring coverage check.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch feat/cpu-offload-tier3

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

@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

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@src/gefen/offload.py`:
- Around line 451-463: Update the offload activation method containing
_stage_all_parameter_state_to_cpu so the codebook is moved to CUDA within the
same atomic state update before marking offload active. Clear or refresh the
codebook’s device caches as part of that transaction, preserving rollback
behavior on failure, and add coverage for an inactive CPU-mapped load followed
by offload_state_() and a successful step().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: 43cc43ff-cd13-49d7-8269-84a29fd87b37

📥 Commits

Reviewing files that changed from the base of the PR and between e986963 and 5e4ef1c.

📒 Files selected for processing (5)
  • CHANGELOG.md
  • README.md
  • src/gefen/gefen.py
  • src/gefen/offload.py
  • tests/test_state_offload.py

Comment thread src/gefen/offload.py

@chatgpt-codex-connector chatgpt-codex-connector 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 5e4ef1c6af

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread src/gefen/offload.py
…pped load

offload_state_() validated with require_cpu_state=False, which permits a
CPU-resident codebook left behind by an inactive map_location='cpu' load, but
then marked offload active without relocating it. The next step() tripped the
"codebook must remain CUDA-resident" guard, bricking the common
resume-then-enable-offload flow.

Stage the codebook onto its parameter device inside offload_state_'s atomic
update (rollback-safe: staging precedes mutation) and clear the stale per-device
caches. Factor the staging into _stage_offload_codebook_on_parameter_device and
reuse it from the load-path co-location helper.

Adds test_offload_activation_colocates_cpu_mapped_codebook.
tests/test_state_offload_distributed.py: a two-rank NCCL DDP test asserting the
offloaded run is bit-identical to a non-offloaded run stepping the same
all-reduced gradients, with per-parameter state staying CPU-resident across
steps (block and factored second-moment paths). Gated on two CUDA GPUs + NCCL.

tests/test_state_offload.py: test_offload_end_to_end_training_loss_matches_baseline
drives a real forward/backward/step loop over a small MLP and asserts the
offloaded loss trajectory matches the non-offloaded baseline bit-for-bit.

README notes that offload is validated bit-identical under DistributedDataParallel.

@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.

🧹 Nitpick comments (1)
tests/test_state_offload_distributed.py (1)

44-108: 🩺 Stability & Availability | 🔵 Trivial | ⚡ Quick win

Setup/init failures bypass the error-reporting path.

torch.cuda.set_device(rank) and dist.init_process_group(...) (Lines 44-45) run before the try at Line 46, so a failure there is never written to result_queue and finally's dist.destroy_process_group() never executes for that rank. If one rank fails here while the other blocks inside the same collective init_process_group call, the parent's diagnostic ends up as a bare timeout ("DDP offload workers timed out") instead of the actual traceback, and the failure takes the full result_queue.get(timeout=180) + join(timeout=180) budget to surface instead of failing fast.

Widen the try/except/finally to cover setup, and guard the cleanup call:

♻️ Proposed fix
     os.environ["WORLD_SIZE"] = str(world)
-    torch.cuda.set_device(rank)
-    dist.init_process_group("nccl", rank=rank, world_size=world)
     try:
+        torch.cuda.set_device(rank)
+        dist.init_process_group("nccl", rank=rank, world_size=world)
         reference_model = _build_model()
@@
     finally:
-        dist.destroy_process_group()
+        if dist.is_initialized():
+            dist.destroy_process_group()
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/test_state_offload_distributed.py` around lines 44 - 108, Move the try
block in the distributed worker to encompass torch.cuda.set_device and
dist.init_process_group, so setup failures reach the existing BaseException
reporting path. Guard dist.destroy_process_group in the finally block with a
check that initialization succeeded before calling it, while preserving
traceback reporting through result_queue for rank 0.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Nitpick comments:
In `@tests/test_state_offload_distributed.py`:
- Around line 44-108: Move the try block in the distributed worker to encompass
torch.cuda.set_device and dist.init_process_group, so setup failures reach the
existing BaseException reporting path. Guard dist.destroy_process_group in the
finally block with a check that initialization succeeded before calling it,
while preserving traceback reporting through result_queue for rank 0.

ℹ️ Review info
⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: be011f8f-6d0d-4204-b56d-34461809ed3a

📥 Commits

Reviewing files that changed from the base of the PR and between cb5e48b and 9c3ac4c.

📒 Files selected for processing (3)
  • README.md
  • tests/test_state_offload.py
  • tests/test_state_offload_distributed.py
🚧 Files skipped from review as they are similar to previous changes (2)
  • README.md
  • tests/test_state_offload.py

Move torch.cuda.set_device and dist.init_process_group inside the worker's
try/except so a setup or process-group init failure reaches the result_queue
reporting path (surfacing the real traceback) rather than manifesting as a bare
parent-side timeout. Guard destroy_process_group with dist.is_initialized() so
cleanup does not itself raise when init never completed.
@thad0ctor

Copy link
Copy Markdown
Owner Author

Fixed in d39070a. Moved torch.cuda.set_device and dist.init_process_group inside the try so a setup/init failure reaches the result_queue reporting path (real traceback) instead of a bare parent-side timeout, and guarded destroy_process_group with dist.is_initialized(). DDP test still 2 passed on 2x3090.

@iwr-redmond

iwr-redmond commented Jul 16, 2026

Copy link
Copy Markdown

What is this PR intended to achieve? Offloading in inference terms usually means supplementing VRAM with ordinary RAM at the cost of speed to reduce or avoid OOM errors. Is that true for this PR too? If not, you may wish to reconsider the specific terminology to avoid confusion.

@thad0ctor

thad0ctor commented Jul 16, 2026

Copy link
Copy Markdown
Owner Author

What is this PR intended to achieve? Offloading in inference terms usually means supplementing VRAM with ordinary RAM at the cost of speed. Is that true for this PR too? If not, you may wish to reconsider the specific terminology to avoid confusion.

More or less, I was looking at ways to the implement optimizer-state offload similar to paged AdamW, it reduces persistent VRAM usage by keeping Gefen’s optimizer state in ordinary CPU RAM.

was going to make branches for a few different approaches to test if any are worth keeping for an even more aggressive VRAM savings.

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.

2 participants