Skip to content

Harden convention codebook-scope preambles and contract validation - #76

Merged
thad0ctor merged 2 commits into
feat/platform-optimizer-contractsfrom
fix/convention-review-round
Jul 15, 2026
Merged

Harden convention codebook-scope preambles and contract validation#76
thad0ctor merged 2 commits into
feat/platform-optimizer-contractsfrom
fix/convention-review-round

Conversation

@thad0ctor

Copy link
Copy Markdown
Owner

Addresses a review round (Codex P1/P2 + CodeRabbit review 4707322434) on the slimmed optimizer convention. Base is feat/platform-optimizer-contracts — this PR stacks into #67, not main. Every finding is convention-specific (present only on #67).

Disposition

Finding Area Disposition
F1 — plain Gefen.step() preamble not synchronized before scoped header gefen.py Already addressed — the step preamble (capturable/capture-ready/closure) is already wrapped in try/except and synchronized via _synchronize_prevalidated_codebook_scope_failure("step preamble", scope_binding) before the header. Reconciled with F3 (below).
F2 — initialize_codebook() preamble not synchronized gefen.py Fixed — capture the failure-vote binding, wrap finalized-layout/runtime-binding/capture-readiness in try/except, and synchronize a one-sided failure before the scoped initialize header.
F3 — closure-time binding replacement before the step header gefen.py Fixed — the step preflight now rejects a runtime binding that no longer matches the captured scope_binding (swap to None or another binding) and routes it through the synchronized scope-failure path, so no rank skips/enters a different header collective. This is the F1/F3 reconciliation: F1 = preamble/closure failure sync (already present); F3 = closure replacing the group (added here).
F4 — _validate_collective_device rejects valid Gloo+CUDA checkpoint.py Fixed — keep NCCL→CUDA; drop the Gloo/MPI CPU-only restriction so a CUDA device reaches the availability check. Test updated to the CUDA-unavailable rejection case.
F5 — contract flags/schema_version accept non-exact types contracts.py Fixed — StateField.checkpointed, StateVariant.initialized/migration_only, CheckpointSupport.requires_collective/atomic_load require type(...) is bool; OptimizerContract.schema_version requires type(...) is int. (TrainingSupport and OptimizerCapabilities already enforced this.)
F6 — hybrid fast-path token blind to in-place owner replacement hybrid.py Fixed — the finalized-layout fast token folds in _state_param_owner keys and values (mirroring the base _param_names snapshot), so an in-place entry replacement preserving dict identity+length invalidates the cached verdict.
F7 — snapshot omits _gefen_codebook_by_device membership tests/_state_snapshot.py Fixed — snapshot records per-device cache dict identity + contents so a clear()/removal is detected even when retained tensors still match their clones.
F8 — Gloo-only tests spawn workers unconditionally tests/test_codebook_scope_distributed.py Fixed — added the repo's dist.is_available()/dist.is_gloo_available() skipif to the three unguarded Gloo tests.
F9 — _untouched never checks backup_parameter tests/test_hybrid_scoped_failure_protocol.py Fixed — _untouched takes backup_shard and asserts the backup parameter equals its _backup_initial() slice; all callers updated.
F10 — docs atomic_load=False contradicts portable guarantee docs/optimizer_contracts.md Fixed — clarified that only ordinary nested GefenMuonHybrid.load_state_dict() reports atomic_load=False; portable composite imports retain the fail-before-mutation guarantee.

Notes on collective symmetry

F2/F3 follow the existing convention: capture a validated failure-vote binding first, wrap rank-local checks (and user closure) in try/except, and vote through _synchronize_prevalidated_codebook_scope_failure on the captured binding before any scoped collective. No collective is entered/skipped on only some ranks; @torch._dynamo.disable and binding guards on the sibling primitives are untouched. F3 is scoped to plain Gefen per the finding; GefenMuon/Hybrid were left as-is.

Tests

New gloo regression tests (with bounded no-hang/liveness guards, mirroring _closure_preamble_worker):

  • test_initialize_codebook_preamble_failure_raises_symmetrically_across_the_scope (F2) — one-rank preamble failure makes both ranks raise fast.
  • test_plain_gefen_scoped_step_closure_group_swap_raises_symmetrically_across_the_scope (F3, new swap_group failure mode) — one-rank binding clear makes both ranks raise fast.

New/updated unit tests:

  • test_validate_collective_device_allows_gloo_cuda_but_requires_available_device + reworked distributed binding case (F4).
  • test_contract_flags_and_schema_version_reject_non_exact_types (F5).
  • test_composite_registry_in_place_entry_swap_is_detected_with_warm_verdict (F6).
  • test_deep_snapshot_detects_per_device_cache_membership_clear (F7).

Each new/changed test was verified to FAIL without its fix (F2/F3 hang → bounded liveness guard fails the run; F4–F7 assert) and PASS with it.

Validation (CPU gloo venv, CUDA_VISIBLE_DEVICES="")

test_codebook_scope_distributed.py, test_codebook_scope_cpu.py, test_hybrid_scoped_failure_protocol.py, test_optimizer_contracts.py, test_checkpoint_binding.py, test_native_load_atomicity.py, test_hybrid_load_atomicity.py, test_shard_identity_contracts.py, test_hybrid_layout_cache.py:

140 passed, 2 skipped (skips are NCCL/2-CUDA-device gated). 0 failures.

Address a round of Codex + CodeRabbit findings on the slimmed optimizer
convention (PR #67). All findings are convention-specific.

Codebook-scope collective symmetry:
- initialize_codebook() now captures the failure-vote binding and
  synchronizes a one-sided preamble failure (finalized layout / runtime
  binding / capture-readiness) through the scope before the scoped
  "initialize" operation header, so a member that fails its preamble no
  longer strands peers inside the header all_gather.
- plain Gefen.step() rejects a closure that replaces or clears the runtime
  codebook binding between capture and the header: the captured-binding
  recheck raises and is synchronized through the captured scope, so every
  rank follows the same header collective instead of one rank skipping it.

Checkpoint and contract validation:
- CheckpointProcessGroupBinding no longer rejects a CUDA collective device
  on Gloo/MPI (both support CUDA tensors); such a device now falls through
  to the existing device-availability check.
- Contract dataclasses enforce exact runtime types: StateField.checkpointed,
  StateVariant.initialized/migration_only, and
  CheckpointSupport.requires_collective/atomic_load must be real bools, and
  OptimizerContract.schema_version must be a real int, so truthy strings or
  bool/float look-alikes can no longer advertise false guarantees.
- The hybrid finalized-layout fast token folds in the _state_param_owner
  registry contents (keys and values), so an in-place owner replacement that
  preserves the dict identity and length invalidates the cached verdict.

Tests:
- Snapshot per-device cache membership so a cache clear/removal is detected.
- Verify the backup parameter is untouched in hybrid scoped-failure tests.
- Guard the remaining Gloo-only distributed tests with the dist/Gloo skipif.
- Documented that only ordinary nested GefenMuonHybrid.load_state_dict()
  reports atomic_load=False; portable composite imports keep the guarantee.
- New gloo regression tests for the initialize-preamble and step group-swap
  synchronization, plus unit tests for the checkpoint device, contract type,
  and hybrid owner-token fixes.
@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: defaults

Review profile: CHILL

Plan: Pro Plus

Run ID: f7474eeb-e406-4f09-b180-40d7dc392d8e

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/convention-review-round

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

@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: 57d72f58c4

ℹ️ 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/checkpoint.py Outdated
Comment on lines +125 to +128
# Gloo (and MPI) support CUDA tensors in addition to CPU, so no
# backend-level device restriction applies here; a CUDA collective
# device on those backends still falls through to the availability
# check below.

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Reject CUDA devices for non-CUDA-aware MPI

On CUDA hosts using the MPI backend without CUDA-aware MPI, this now lets validate_runtime() succeed for a CUDA checkpoint device just because the device index exists. The portable checkpoint path then moves its control/metadata tensors to binding.collective_device before dist.all_gather/broadcast (for example in src/gefen/portable_collective.py), so these bindings fail later with backend errors instead of being rejected during validation; keep MPI CPU-only unless CUDA-aware support can be detected explicitly.

Useful? React with 👍 / 👎.

@thad0ctor

Copy link
Copy Markdown
Owner Author

@coderabbitai review

@coderabbitai

coderabbitai Bot commented Jul 15, 2026

Copy link
Copy Markdown
✅ Action performed

Review finished.

Note: CodeRabbit is an incremental review system and does not re-review already reviewed commits. This command is applicable only when automatic reviews are paused.

Narrow the F4 relaxation: Gloo genuinely supports CUDA tensors, but MPI
moves GPU tensors only when built CUDA-aware, which PyTorch cannot reliably
detect. Reject a CUDA collective device on the MPI backend during
validate_runtime() instead of deferring a backend error to the portable
collective's all_gather/broadcast (Codex P2 on #76).
@thad0ctor
thad0ctor merged commit a1bd0d1 into feat/platform-optimizer-contracts Jul 15, 2026
15 checks passed
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