Skip to content

Harden distributed optimizer integration and release gates - #65

Merged
thad0ctor merged 14 commits into
mainfrom
agent/optimizer-production-hardening
Jul 12, 2026
Merged

Harden distributed optimizer integration and release gates#65
thad0ctor merged 14 commits into
mainfrom
agent/optimizer-production-hardening

Conversation

@thad0ctor

@thad0ctor thad0ctor commented Jul 12, 2026

Copy link
Copy Markdown
Owner

What this PR is

The 0.4.0 production-hardening release. Nothing here makes Gefen faster — it makes it dependable enough to bet a long training run on: checkpoints either resume correctly or refuse loudly, multi-GPU jobs fail fast instead of hanging or silently drifting, and a broken build can no longer reach PyPI. The guiding contract: it either works correctly or it stops with an error before touching state — nothing fails silently.

What changed

Determinism (deterministic=True) — opt-in bit-identical updates on matching GPUs for all three optimizers. This is how you prove a resumed run equals an uninterrupted one, and how you debug: if two runs differ, something real changed. Works everywhere the optimizer is constructed (PyTorch, HF Trainer, axolotl optim_args: { deterministic: true }).

Checkpoints can't lie

  • Parallel-Muon distributed checkpoints carry a versioned owner manifest, validate fully before any mutation, and resume across world sizes — including into a single-process optimizer (fixed during review; the initial format refused that load while v1 allowed it).
  • Plain Gefen and Muon approx optimizer state round-trips through PyTorch full-state DCP under FSDP2, same topology, all-ranks-collective. Out-of-scope loads (resharding, changed world size, stripped/corrupted payloads, quantized momentum that lost its codebook) are refused up front — the state is shard-relative, so any "successful" cross-topology load would be fabricating optimizer state.
  • CUDA-graph replays now advance device-side step counters, so stochastic-rounding checkpoints resume from the true step and correct seed.

Multi-GPU jobs fail fast instead of hanging — rank-divergent grad is None patterns are rejected before any Muon collective, order-insensitively (content-keyed meshes, sorted items — hardened during review after an adversarially-verified false-pass/deadlock scenario). AMP protocol selection is rank-synchronized; overflow steps mutate nothing, atomically across both hybrid children.

Releases are gated — publishing requires the actual built wheel to pass the CPU matrix (torch 2.5.0 floor + latest), a real Transformers Trainer save/resume gate, and the two-GPU CUDA/JIT/distributed gate with zero skipped tests. The GPU gate runs locally via scripts/release_gpu_gate.sh <tag> against the release run's artifact (no self-hosted runner exposure); approving the testpypi environment is the release manager's attestation it passed. Build tooling is pinned with byte-reproducible rebuild verification.

Review round

The branch went through a four-agent review (core optimizer, Muon/distributed, test quality, CI/release) plus an adversarial verification pass; every confirmed finding was fixed with a regression test that fails on the pre-fix code:

  • Consolidated v2 distributed checkpoints now load into a single-process optimizer (empty-process-group manifest rebind).
  • The grad-presence preflight is order-insensitive (reversed param-group order across ranks could previously false-pass and deadlock).
  • CPU-only mesh optimizers never touch CUDA capture queries; a deterministic: False-tagged checkpoint into a deterministic=True optimizer is refused (both now tested).
  • CHANGELOG discloses the behavior changes vs 0.3.x (fused=False CUDA period-search backend, eps > 0, quantized-momentum codebook refusal).
  • README distributed section rewritten as a plain compatibility table with details links.

Validation

  • ≈5,000 new test lines: AMP/GradScaler, capturable/CUDA-graph, deterministic mode, FSDP2 checkpoints, distributed checkpoint safety (real 2-rank gloo + NCCL spawns), grad presence, step-preflight atomicity, Trainer resume harness (benchmarks/trainer_resume/).
  • Full CPU suite, PyTorch 2.12: 432 passed. CPU floor, Python 3.10 + PyTorch 2.5.0: 427 passed.
  • Two-GPU installed-wheel CUDA/JIT/distributed gate on homogeneous RTX 3090s: 182 passed, zero skips, fresh kernel build root.
  • End-to-end release dry run (v0.4.0.dev1): tag push → build + all hosted gates green → local GPU gate against the downloaded run artifact passed → pipeline paused at the TestPyPI approval exactly as designed. The dry run itself caught and fixed two harness bugs (mp.Queue tensor transport flake, gh repo resolution).
  • Real Qwen3-0.6B fused-BF16 Trainer continuation passed for all three recipes; two-rank DDP continuation with exact model/optimizer/scheduler/loss/replica hashes.
  • Megatron factory + matrix harness: 108 passed against the 0.4.0 tree.
  • Reproducible builds: two pinned builds byte-identical; Twine + wheel-content checks passed.

Known scope

FSDP2 full-state optimizer checkpoints are same-topology by design, not caution: plain-Gefen/approx state is quantized against per-rank codebooks and per-shard block geometry, so no rearrangement of the saved bytes is valid on other shard boundaries (an approximate dequantize-and-rewarm migration tool is possible future work). Model-only DCP and Muon distributed checkpoints are unaffected. Megatron's Adam-specific distributed optimizer, FSDP, fp16, and CPU offload remain guarded rather than silently accepted.

Summary by CodeRabbit

  • New Features

    • Added deterministic optimization mode for Gefen, GefenMuon, and hybrid optimizers.
    • Improved AMP/GradScaler handling, including safe overflow detection and skipped-step behavior.
    • Expanded checkpoint and resume support for distributed, sharded, CUDA Graph, and Trainer workflows.
    • Added safeguards against invalid gradients and partial optimizer-state updates.
  • Bug Fixes

    • Improved distributed consistency checks and checkpoint validation to prevent unsafe or divergent restores.
    • Ensured non-fused CUDA operation does not trigger unnecessary extension builds.
  • Documentation

    • Updated compatibility, installation, distributed training, checkpointing, benchmarking, and release guidance.
  • Chores

    • Released version 0.4.0 with reproducible build and expanded release validation.

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
📝 Walkthrough

Walkthrough

This release adds deterministic and AMP-safe optimizer stepping, stricter distributed checkpoint validation, CUDA graph counter handling, a Trainer resume harness, reproducible packaging gates, expanded CI matrices, and extensive CPU/GPU regression coverage.

Changes

Optimizer correctness and validation

Layer / File(s) Summary
AMP, determinism, and capturable execution
src/gefen/gefen.py, src/gefen/hybrid.py, tests/test_amp_grad_scaler.py, tests/test_capturable.py
Adds AMP overflow handling, deterministic routing, per-device replay counters, capture-device validation, transactional codebook refresh, and corresponding CUDA/DTensor tests.
Distributed checkpoint safety
src/gefen/gefen.py, src/gefen/gefen_muon.py, tests/test_cpu_step_checkpoint.py, tests/test_gefen_fsdp2_checkpoint.py, tests/test_muon_distributed_checkpoint_safety.py
Adds versioned manifests, topology and state validation, hook-safe serialization, exact FSDP2/DCP restoration, and mutation-free rejection of invalid checkpoints.
Muon and hybrid configuration
src/gefen/gefen_muon.py, src/gefen/hybrid.py, tests/test_epsilon_muon_param_group_cpu.py, tests/test_muon_grad_presence.py
Adds deterministic propagation, stricter epsilon and parameter-group validation, collective-safe gradient-presence checks, and AMP-aware hybrid stepping.
Trainer resume benchmark
benchmarks/trainer_resume/*, tests/test_transformers_trainer_resume.py
Adds deterministic dataset generation, recipe-based optimizer construction, checkpoint lifecycle checks, state digests, and exact baseline-versus-resume comparisons.

Release and packaging

Layer / File(s) Summary
Reproducible release pipeline
.github/workflows/release.yml, scripts/release_gpu_gate.sh
Builds artifacts twice with normalized metadata, validates installed CPU/framework wheels, and adds mandatory GPU release testing before publishing.
Packaging and CI updates
pyproject.toml, MANIFEST.in, .github/workflows/ci.yml, .gitignore
Pins build tooling, updates dependencies and package version, prunes benchmark/test content from source distributions, expands CPU Torch testing, pins actions, and ignores generated benchmark output.
Release documentation
README.md, COMPATIBILITY.md, CONTRIBUTING.md, CHANGELOG.md, benchmarks/README.md
Documents deterministic behavior, checkpoint scope, Trainer resume validation, CUDA graph constraints, release gates, dependency changes, and the 0.4.0 release.

Estimated code review effort: 5 (Critical) | ~120 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Trainer
  participant Accelerate
  participant GefenOptimizer
  participant CheckpointStore
  Trainer->>Accelerate: construct and wrap optimizer
  Accelerate->>GefenOptimizer: execute staged training
  GefenOptimizer->>CheckpointStore: save optimizer and trainer state
  Trainer->>CheckpointStore: resume from staged checkpoint
  CheckpointStore->>GefenOptimizer: restore optimizer state
  GefenOptimizer-->>Trainer: continue training and report digests
Loading

Possibly related PRs

  • thad0ctor/Gefen-X#61: Both modify the GitHub Actions release pipeline and trusted publishing gates.
  • thad0ctor/Gefen-X#52: Both modify distributed Muon checkpoint consolidation, ownership manifests, and load validation.
  • thad0ctor/Gefen-X#33: Both modify capturable optimizer execution, CUDA graph counters, and related test coverage.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 11.86% 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
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.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main focus on distributed optimizer hardening and release gating changes.
✨ 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 agent/optimizer-production-hardening

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

@thad0ctor thad0ctor changed the title Harden optimizer state and runtime validation Harden optimizer state and add replica-exact fused mode Jul 12, 2026
@thad0ctor thad0ctor changed the title Harden optimizer state and add replica-exact fused mode Harden optimizer state, exact fused mode, and graph checkpoints Jul 12, 2026
@thad0ctor thad0ctor changed the title Harden optimizer state, exact fused mode, and graph checkpoints Harden distributed optimizer integration and release gates Jul 12, 2026
Consolidated version-2 Parallel-Muon checkpoints refused to load into an
optimizer with no eligible distributed process group (single-process
resume/eval), even though released-v1 and markerless loads of the same
state succeed; rebind the saved owner manifest to live parameters by
saved id and run the same per-parameter proof. Harden the Muon
grad-presence preflight the way the AMP DTensor preflight already is:
content-keyed meshes, sorted mesh and item order so rank-divergent
parameter-group order cannot falsely pass the positional activity vector
or interleave per-mesh collectives, and no CUDA query for CPU-only mesh
optimizers. Refresh the stale codebook-fallback comment and disclose the
fused=False CUDA backend change, the eps>0 constructor requirement, and
the quantized-momentum codebook refusal in the changelog. Both new gloo
regression tests fail on the previous code.
Tag pushes no longer require a registered self-hosted GPU runner: the
gpu_release_tests job is replaced by scripts/release_gpu_gate.sh, which
downloads the release run's dist artifact via gh, installs the wheel
into a cached --system-site-packages venv instead of mutating the host
Python, and runs the identical preflight, mandatory GPU test list, and
zero-skip enforcement. Approving the testpypi environment is the release
manager's attestation that the local gate passed; the hosted CPU and
Transformers Trainer wheel gates still block both publish jobs
mechanically. The workflow filename, tag trigger, both environment
gates, prerelease-skips-PyPI logic, and OIDC permission scoping are
unchanged.
@thad0ctor
thad0ctor marked this pull request as ready for review July 12, 2026 22:26
@thad0ctor

Copy link
Copy Markdown
Owner Author

@coderabbitai full review

@coderabbitai

coderabbitai Bot commented Jul 12, 2026

Copy link
Copy Markdown
✅ Action performed

Full review finished.


You're currently rate limited under our Fair Usage Limits Policy. Your recent PR review activity is in the 95th percentile or higher among CodeRabbit users, so adaptive limits apply. Your next review will be available in 59 minutes.

@thad0ctor

Copy link
Copy Markdown
Owner Author

@codex

@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)
tests/test_muon_grad_presence.py (1)

731-731: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

rank * 0 is dead arithmetic — make the intent explicit.

7300 + rank * 0 always evaluates to 7300, so every rank seeds identically. That is exactly what's required here (both ranks must build the same full tensor before distribute_tensor), but the rank * 0 reads like an incomplete edit and invites a "fix" to rank * N, which would silently break collective safety.

Suggested clarification
-        generator = torch.Generator(device="cpu").manual_seed(7300 + rank * 0)
+        # Identical seed on every rank: distribute_tensor needs the same full
+        # tensor across ranks to stay collective-safe.
+        generator = torch.Generator(device="cpu").manual_seed(7300)
🤖 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_muon_grad_presence.py` at line 731, Update the generator seed
expression in the relevant test to use the explicit constant seed 7300, removing
the dead rank arithmetic while preserving identical tensor construction across
all ranks before distribute_tensor.
🤖 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 `@tests/test_muon_distributed_checkpoint_safety.py`:
- Around line 587-588: Add a distributed/Gloo availability skipif guard to
test_mixed_parallel_fallback_and_rank_local_composition_cpu, matching the guard
pattern used by sibling distributed tests such as
test_consolidated_v2_checkpoint_loads_into_single_process_optimizer. Ensure the
test skips when torch.distributed or the Gloo backend is unavailable, while
preserving its existing behavior when supported.

---

Nitpick comments:
In `@tests/test_muon_grad_presence.py`:
- Line 731: Update the generator seed expression in the relevant test to use the
explicit constant seed 7300, removing the dead rank arithmetic while preserving
identical tensor construction across all ranks before distribute_tensor.
🪄 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: 7bc28d60-c710-4472-ba88-3eb19dbb7602

📥 Commits

Reviewing files that changed from the base of the PR and between 19bf3af and db1cb06.

📒 Files selected for processing (30)
  • .github/workflows/ci.yml
  • .github/workflows/release.yml
  • .gitignore
  • CHANGELOG.md
  • COMPATIBILITY.md
  • CONTRIBUTING.md
  • MANIFEST.in
  • README.md
  • benchmarks/README.md
  • benchmarks/trainer_resume/README.md
  • benchmarks/trainer_resume/__init__.py
  • benchmarks/trainer_resume/run.py
  • pyproject.toml
  • scripts/release_gpu_gate.sh
  • src/gefen/gefen.py
  • src/gefen/gefen_muon.py
  • src/gefen/hybrid.py
  • tests/test_amp_grad_scaler.py
  • tests/test_capturable.py
  • tests/test_cpu_step_checkpoint.py
  • tests/test_deterministic_mode.py
  • tests/test_dispatch_gating_cpu.py
  • tests/test_epsilon_muon_param_group_cpu.py
  • tests/test_gefen_fsdp2_checkpoint.py
  • tests/test_muon_distributed_checkpoint_safety.py
  • tests/test_muon_grad_presence.py
  • tests/test_step_preflight_atomicity.py
  • tests/test_training_matrix_harness.py
  • tests/test_transformers_trainer_resume.py
  • tests/test_validation_cpu.py

Comment thread tests/test_muon_distributed_checkpoint_safety.py
@thad0ctor
thad0ctor force-pushed the agent/optimizer-production-hardening branch from f82e2ad to 24ec6ec Compare July 12, 2026 22:42
@thad0ctor

Copy link
Copy Markdown
Owner Author

@codex

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep it up!

Reviewed commit: e8d86775a4

ℹ️ 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".

@thad0ctor
thad0ctor merged commit 7c37a01 into main Jul 12, 2026
15 checks passed
@thad0ctor
thad0ctor deleted the agent/optimizer-production-hardening branch July 12, 2026 23:29
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.

1 participant