Repository navigation
Description
Problem
The fixes merged during 2026-11-15 02:28 UTC–2026-11-17 02:28 UTC show a structural component to recurring regressions: the same invariant is reconstructed by several consumers, or ownership changes without an explicit handoff. More targeted tests are necessary, but testing each helper separately cannot make these contracts compositional.
This is a design proposal, not a report that the fixed bugs still reproduce. The observations below come from merged diffs and source inspection; no new hardware reproduction is claimed. Current-code links are pinned to e4c558c402a8ac164f8421afc2718f136d38bbe1.
Evidence and proposed contracts
| Area | Evidence of a cross-cutting contract problem | Better contract |
|---|---|---|
| Checkpoint representation and ownership | #4334 fixed packed/scale dtype loss; #4417 covered other buffers; #4507 covered dense Parameters. #4330, #4414, and #4425 repaired different qzero transfer paths; #4608 repaired MoE export-shell ownership. | One module-owned persistence contract and one checkpoint-to-runtime binding path, reused by load, state-dict transfer, offload, and export. Storage representation is not inferred from model compute dtype or a constructor placeholder. |
| Quantization attempts and offload lifecycle | #4442 added a CPU block retry; #4492 corrected reuse of partially mutated weights. Cleanup in #4409 broke live offload consumers, requiring #4416 and later normal-model restoration in #4498. | A stage attempt owns its mutations and resources until commit. Failure discards attempt-local state; retry starts from an immutable source or reproducible preparation recipe. Resources end at last-consumer release, not an incidental save() return. |
| Asynchronous workspace ownership | #4436 reduced QQQ scratch memory with per-device sharing; #4524 had to make writable scratch stream-exclusive. #4527 repaired a future published before pruning could fail. | Writable workspace is owned through completion of the consuming work; allocation locking is not ownership. Every published future has exactly one terminal success/error/cancellation outcome. |
| Requested versus resolved policy | #4497 separated derived kernel policy from caller settings; #4553 fixed stale typed-leaf cache results; #4585 fixed forward-time global policy reads; #4606 fixed enum load-policy inheritance. | Mutable user configuration is input to resolution, never the execution state. Resolve a deep immutable, value-keyed snapshot at the API boundary and pass that same snapshot to all consumers. |
The first row is a repeated family, not proof each PR caused the next. The offload and scratch sequences contain explicit regressions introduced by earlier fixes. The OOM sequence also exposed a fixture gap: a diagonal Hessian and failure at the first allocation hid partial mutation.
Related open symptom reports are #4595 (finalizers outliving a failed run) and #4604 (fallback parity in GPTAQ/FOEM). Those reports were not independently reproduced in this audit; this proposal complements rather than replaces their targeted fixes.
1. Unify persistence without inventing another model tree
Current code already has useful pieces: qzero layout hooks in GPTQQuantLinear, storage-dtype restoration in load_checkpoint_in_model_then_tie_weights, and the export-shell missing-slot guard. The latter currently identifies quantized payloads with a central suffix list. The proposal is to consolidate these mechanisms, not add another parallel registry.
- Extend the existing kernel-owned persistence declarations to describe each owned payload's role, storage dtype/layout, allowed runtime conversion, and canonical export conversion. Keep compute/activation dtype separate. Handle unknown/uninitialized layout explicitly rather than assigning a valid-looking default.
- Build bindings using checkpoint keys, existing ModulePlan ownership, and declared conversion mappings. Before publication, account for every source payload as bound, explicitly transformed/aliased, or intentionally excluded with a reason; reject unexplained omissions. Include dense fallback tensors and non-quantized weights, not only known suffixes.
- Reuse that binding/codec path for initial load,
assigntransfers, offload/restore, and export. Export must not mutate live runtime layout. Preserve legacy-read compatibility and existing safetensors formats; no format migration is needed just to consolidate internal contracts.
Acceptance: one registry-driven conformance suite runs pack/load/forward/save/reload/re-save, fresh and initialized state transfers, both assign modes, and offload/restore for each applicable backend. Assert complete key accounting, packed contents, stored dtype, layout idempotence, and forward parity. Tiny real MoE shells and mixed dense/quantized checkpoints are mandatory cases. Unknown ownership fails before publishing a valid-looking artifact.
2. Give each mutating stage a commit/abort boundary
The current GPTQ block retry now correctly reconstructs pre-pass weights and resets coupled state. Preserve that memory-efficient behavior, but make it the shared attempt contract rather than a recipe each fallback must independently remember.
- Start with the existing GPTQ block pass: factor its source/preparation recipe and mutable attempt state into one owner. A retry invokes the same preparation on a new device; weights, permutations, static groups, scales, and quantizer progress cannot be moved/reset independently.
- Commit the completed payload once. Abort first cancels/joins the run's outstanding producers, then releases attempt hooks, captures, temporary tensors, and unpublished files; it cannot expose partial quantization as a completed result. Cleanup is idempotent, preserves the originating error, and applies to cancellation as well as ordinary errors. Stage atomicity is not whole-model rollback: explicitly record any already-committed prefix and which operations/retries remain valid after failure.
- Explicitly distinguish run scratch from storage still backing a live model. Save borrows the latter. Release it only after successful materialization/ownership transfer or final consumer teardown. A failed save must retain enough state for retry.
- Do not implement this by cloning the whole dense model or retaining dense inference weights. Use immutable checkpoint/module sources, bounded stage snapshots only where unavoidable, and the existing reconstruction path. Prototype one stage before generalizing to other quantizers.
Acceptance: inject failure before mutation, after multiple nonzero error-feedback updates, and during publication; compare retries with a fresh reference run. Exercise cancellation followed by normal forward/retry, save followed by forward and another save, and eventual resource release. Assert bounded retries and unchanged non-OOM exception behavior.
3. Make asynchronous ownership an API property
QQQ's current scratch helper already keys by device/stream. Keep this fix; do not claim it is currently broken. Generalize the ownership rule only where other scratch users need it:
- Scratch acquisition returns stream-owned storage or an explicit lease with a completion dependency. Cross-stream reuse, growth, clearing, or release must respect in-flight consumers, not merely the Python call's return. Same-stream reuse remains cheap; immutable weights are not copied per stream.
- Install future finalization immediately when ownership is published, before pruning/build/validation callbacks. All exits notify waiters and permit a same-key retry; preserve the originating error.
- Reuse existing locks, stream/event utilities, and cache owners. Avoid a new global scheduler or device-wide synchronization on every forward.
Acceptance: cold concurrent use builds once; owner failure wakes every waiter; warm same-stream reuse works; overlapping streams do not alias writable scratch; clear/growth respects in-flight use. Native numerical overlap tests and free-threaded qualification complement CPU ownership tests, with timeouts for hangs.
4. Finish the requested/resolved policy separation
resolve_quantize_backend already separates requested kernel/runtime from _resolved_kernel. Build on it rather than introducing a second config hierarchy:
- Resolve enum/typed/inherited/explicit requests once with provenance and conflict checks. Return a deep immutable execution snapshot; pass it to module construction and every dispatch helper. Process defaults apply only when creating a new snapshot, never as a hidden forward-time fallback for an already bound module.
- Key resolution caches by normalized values/version, including nested typed leaves. A changed user config creates a new snapshot; an existing module's snapshot remains unchanged. Keep explicit caller mutation semantics and serialize requested configuration separately from derived runtime state.
Acceptance: reuse one config across operations; mutate a warmed typed leaf; serialize/reload non-default requests; construct A under P1 and B under P2 and forward A again. Each consumer must use the expected snapshot, and unknown/conflicting options fail before mutation.
Scope and next step
Prioritize persistence and retry boundaries because failures can silently alter or omit weights. Land one conformance suite and one migrated path per change, retaining existing fast paths and recording memory/latency costs. These are proposed internal contracts, not a request for an immediate broad rewrite.
Localized defects such as a missing stride normalization or isolated tail mask still primarily need focused unit tests. Escalate to a design change when fixes repeatedly transfer responsibility between owners, duplicate normalization/conversion, or rely on undocumented state ordering. Tests verify the new contract; they do not substitute for specifying it.
Maintainer decision requested: agree on these invariants and start with the checkpoint binding/persistence contract, or identify an existing owner that should absorb it.
Activity
test(policy): compose the requested-vs-resolved snapshot contract (#4615