Skip to content

refactor(looper): fold quantization_layer_boundary_checkpoint into LoopExtensions - #6477

Merged
Qubitium merged 1 commit into
mainfrom
refactor/looper-boundary-into-extensions
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/looper-boundary-into-extensions

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Looper R6, with the maintainer's decision to fold the protocol into LoopExtensions rather than delete it. The looper had two resume and commit mechanisms:

  • LoopExtensions (looper/extension.py). on_start returns a LoopPlan cursor and on_boundary commits a step after LoopBoundary.quiesce() has drained that step's finalizers. CheckpointConfig uses it.
  • A duck-typed model attribute, quantization_layer_boundary_checkpoint, with six methods: restore, commit_layer, is_catchup_layer, prepare_catchup_layer, finalize_catchup_layer and materialize_deferred_prefix. It came from feat(looper): carry causal replay and durable recovery callbacks #3600 (771b1e0) and was probed with getattr once in module_looper and six times in stage_layer. No class in gptqmodel/ implements it. Only test fakes in tests/test_stage_modules.py did.

This PR runs resume and commit through the extension calls that already exist and deletes the attribute protocol and its probes. Net −414 lines (5 files changed, 153 insertions(+), 567 deletions(-)). Production code is −335 lines: stage_layer.py +6/−295 and module_looper.py +8/−40.

No in-tree run sets the attribute, so in-tree behaviour does not change.

What Changed

Old attribute call (origin/main file:line) Now
restore(model, processors) returned a model-layer index (module_looper.py:2034-2055); run_layer_stage(start_layer_index=) skipped lower layers (stage_layer.py:670-682) LoopExtension.on_start(context) returns a LoopPlan cursor. This call already existed. The start_layer_index parameter is removed.
commit_layer(...) after a successful drain, gated on finalize_ok (stage_layer.py:1544,1695-1733) LoopExtension.on_boundary(boundary) through the existing extensions.publish(step, futures). boundary.quiesce() re-raises a failed finalizer, so a failed step is never committed. finalize_ok and the boolean return of _drain_finalize_futures are removed.
Setting the attribute forced synchronous finalizers (stage_layer.py:157-163) Removed. An extension quiesces at the boundary it commits.
Setting the attribute forced a layer-output replay for the last processor (stage_layer.py:1068-1073) Removed. Outputs replay only when a processor or quantization_layer_output_required needs them.
A TensorLifetimeDiagnostic per layer and processor, logged only at commit time (stage_layer.py:1046-1052) Removed, together with the import. The class itself stays in input_cache.py, where it has other users.
materialize_deferred_prefix(...) after the last layer (module_looper.py:1794-1806,2133) Removed. An extension installs restored state in on_start or in its last on_boundary.
Packed catch-up replay: is_catchup_layer, prepare_catchup_layer, finalize_catchup_layer (stage_layer.py:701-723,804-832,858-1001) Removed, with no new prepare_catchup hook (see "Why no catch-up hook" below).

Deprecation (approved). An external runtime that sets quantization_layer_boundary_checkpoint on its model stops working. It is not silently ignored: ModuleLooper.__init__ raises TypeError before any work starts:

`quantization_layer_boundary_checkpoint` was removed; pass a LoopExtension (`on_start` returns the resume cursor, `on_boundary` commits) through `ModuleLooper(extensions=...)`

This follows the fail-closed rule in AGENTS.md and the regression-test-design skill ("Do not silently accept an option the consumer ignores"). WeightOnlyLooper never read the attribute, so it gets no guard.

Why no catch-up hook. The catch-up replay re-forwarded a layer whose projections were already packed by a run that "predates activation boundaries". That is the ds4rt EXL3 projection checkpoint, which is being deprecated. Nothing in-tree produces such a layer: CheckpointExtension stores the complete InputCache with every committed step. ds4rt PR-G1 (subset-granular resume) also stores the current layer's InputCache, so it does not need catch-up either.

Shape left for G1. One publish site remains: extensions.publish(planned_step, boundary_futures) at the end of each plan step, followed by on_boundary → quiesce → commit. G1 adds LoopStep("subset", …) and a second publish after each subset's finalizers on this same path. It needs no model attribute and no other probe.

Out of scope. utils/exl3_projection_checkpoint.py::inspect_committed_manifests is documented as "the discovery half of layer-boundary catch-up". It is left to the EXL3 / ds4rt PRs.

Tests

  • Unit tests have been executed and passed, or the reason they are not applicable is documented.
  • I added a new simple/fast unit test for this change, or documented why that is not applicable.

Test migration in tests/test_stage_modules.py:

  • test_run_layer_stage_skips_boundary_commit_when_finalize_fails becomes test_run_layer_stage_commits_extension_boundaries_after_finalizers[3-1-False | 1-0-True], built on a LoopExtension fake. It asserts:
    • the resume cursor from on_start (1);
    • that steps before the cursor never run;
    • that on_boundary sees each later step once, in plan order, after that step's finalizers;
    • that a failed finalizer re-raises from quiesce() with no commit, and the loop stop was still requested.
  • This new test passes unchanged on origin/main too, so the extension path behaves the same on both trees.
  • New: test_module_looper_rejects_removed_layer_boundary_checkpoint. It fails on origin/main (DID NOT RAISE) and passes on this branch.
  • Removed with their mechanisms:
    • test_deferred_boundary_prefix_materializes_once_before_publication;
    • test_stage_layer_forces_sync_finalizers_for_durable_boundary;
    • test_run_layer_stage_catches_up_packed_layer_with_original_forward_topology, the catch-up test, which had no in-tree producer.
# both trees, CPU (CUDA_VISIBLE_DEVICES=), python -P, PYTHONPATH=<tree>
pytest tests/test_stage_modules.py tests/test_checkpoint_processor_adapter.py tests/test_dequant_resume_identity_5396.py \
       tests/test_loop_extensions.py tests/test_checkpoint_extension.py tests/test_weight_only_looper.py -rA
# origin/main: 112 passed, 2 skipped   branch: 111 passed, 2 skipped
# diff: the 4 removed tests and the 3 new ones above; no other outcome changed.
# The 2 skips are test_dense_scaling_state_and_aliases_roundtrip[cuda:0|cuda:1] ("requires cuda:N").
# Run on one GPU (CUDA_VISIBLE_DEVICES=2): cuda:0 passed on both trees; cuda:1 needs a second GPU and was not run.

pytest tests -k checkpoint -n 24 --continue-on-collection-errors -rA   # CPU
# origin/main: 1 failed, 1983 passed, 307 skipped, 1 error   branch: 1 failed, 1984 passed, 307 skipped, 1 error
# Per-test outcomes are identical; the only difference is the new test_module_looper_rejects_removed_layer_boundary_checkpoint.
# Pre-existing on both trees, environment-caused:
#   ERROR collecting tests/models/test_w4a_nvfp4_gptaq_experiment.py (module-level pytest.skip)
#   FAILED tests/test_checkpoint_tensor_headers.py::test_variable_shape_buffers_sit_on_exactly_the_old_quant_type_owners
#          (OSError: libnvrtc.so.12 missing on this host)
# Skips: 88 opt-in checkpoint_recovery (run separately below), plus GPU/Metal/MLX/TTNN/two-GPU gates (CUDA hidden).

pytest tests/test_checkpoint_method_compatibility.py -m checkpoint_recovery -n 4 -rA   # one GPU (CUDA_VISIBLE_DEVICES=2)
# origin/main: 6 failed, 67 passed, 15 skipped   branch: 8 failed, 65 passed, 15 skipped
# All failures on both trees are test_awq_checkpoint_recovery[*-qwen3_moe]. Every non-AWQ-MoE case passed on both trees.
# These failures are pre-existing GPU nondeterminism, not this change. Reruns of the 8 AWQ qwen3_moe cases:
#   origin/main failed 6, 2, 6; branch failed 8, 6, 7.
# Three uninterrupted AWQ qwen3_moe baseline runs per tree, with no checkpoint, already disagree with each other:
#   layer-1 experts.3.down_proj qweight/scales differ base-1 vs base-2, while base-3 == new-3.
# So "resumed == uninterrupted" cannot hold for this case on either tree.
# Skips (15): 14 "requires two CUDA devices" and 1 "requires the optional BitBLAS compiler/runtime"; not verified.

bash format/check.sh   # ruff 0.14.2: All checks passed!

Call-log A/B (tiny Llama, CPU, checkpoint save + resume)

The script is calllog_ab.py <repo> <workdir> <out.json>. It builds a 3-layer random Llama and runs GPTQ 4-bit g32 on CPU with CheckpointConfig, in four phases:

  1. uninterrupted run;
  2. SIGTERM at the layer-0 boundary, ending in CheckpointStopped;
  3. resume;
  4. rerun on the completed checkpoint.

It records LoopExtensions.start (plan steps and cursor), every publish (step and future count), CheckpointExtension.on_boundary, every CheckpointStore.commit (cursor and artifact names), every run_subset_stage (layer and subset), and a sha256 of every saved tensor.

origin/main vs branch: baseline, interrupted, resumed, completed, log -> all identical (42 call-log entries, 93 tensors)
plan = [model.layers.0, model.layers.1, model.layers.2]; interrupted: commit cursor 1 then stopped
resumed: start cursor=1, layers 1-2 only, commits 2 and 3; completed: start cursor=3
resumed and completed tensors == uninterrupted tensors on both trees

GPU A/B (GPTQ, Qwen2.5-0.5B-Instruct, checkpointing on, resume in a new process)

Setup: run_gpu_ab.sh / gpu_resume.py, one GPU, GPTQConfig(bits=4, group_size=128), fp16, seed 0, 32 fixed calibration texts. Each tree runs two processes:

  • process 1 quantizes with CheckpointConfig, sends SIGTERM at the model.layers.5 boundary and gets CheckpointStopped;
  • process 2 resumes, finishes and saves.
interrupt call log identical: True (19 entries: start cursor=0, publish/on_boundary/commit for layers 0-5)
resume    call log identical: True (55 entries: start cursor=6, publish/on_boundary/commit for layers 6-23)
saved checkpoint: 8 files, 794 safetensors tensors compared bit-for-bit, json configs equal -> BIT-IDENTICAL

Measured Impact

Not applicable: this is a refactor with no claimed issue. The GPU and CPU A/B runs above are bit-identical.

Model Support / Module Plan

Not applicable: no model, alias or definition changes.

AWQ onboarding safety

Not applicable: AWQ grouping, search, replay and folding are not touched.

Logic Flow Documentation

  • The required diagrams and docs page are included below.
  • The new-flow Mermaid diagram uses real symbol names.
  • The removed mechanism is tabulated with file:line evidence (What Changed).
  • Failure paths are marked.
  • A reference page under docs/ repeats the diagram: docs/looper-checkpoint-redesign.md § "Retired quantization_layer_boundary_checkpoint". That page is not linked from README.md today, and this PR does not add a link.
flowchart TD
    A["ModuleLooper.__init__"] -->|"model sets quantization_layer_boundary_checkpoint"| X["TypeError: pass a LoopExtension"]
    A --> B["_loop_impl builds LoopPlan"]
    B --> C["LoopExtensions.start: on_start returns cursor"]
    C --> D["run_layer_stage runs plan.steps from cursor"]
    D --> E["layer finalizers submitted"]
    E --> F["LoopExtensions.publish: on_boundary"]
    F --> G["boundary.quiesce"]
    G -->|"a finalizer failed"| Y["original error re-raised, step not committed"]
    G --> H["extension commits the step"]
    H --> D
    style X fill:#fee,stroke:#b22
    style Y fill:#fee,stroke:#b22
Loading
Situation Before After
No attribute (every in-tree run) Extensions only Same (call-log and GPU A/B identical)
Attribute set Duck-typed restore, commit and catch-up calls; TypeError only if a method was missing TypeError in ModuleLooper.__init__, before any work
Finalizer fails under a durable boundary Attribute: warning, commit skipped. Extension: quiesce re-raises. Extension: quiesce re-raises (unchanged)

docs/quantization-lifecycle-contracts.md no longer mentions "layer-boundary recovery".

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

Not applicable: no kernel, dispatch or fusion change.

Notes

  • Breaking for external code only: a runtime that set quantization_layer_boundary_checkpoint must pass a LoopExtension through ModuleLooper(extensions=...) instead. Its resume cursor is now a LoopPlan position, not a model-layer index.
  • No in-tree user has the semantics below, and the table in the docs page lists them for porting:
    • restore no longer skips input_embeddings while it skips layers;
    • setting the attribute no longer forces synchronous finalizers or the last-processor output replay;
    • there is no materialize_deferred_prefix call after the last layer.
  • Follow-up: ds4rt PR-G1 builds its per-subset publish on the remaining call site.

🤖 Generated with Claude Code

…opExtensions

The looper had two resume and commit mechanisms. LoopExtensions (on_start
returns a LoopPlan cursor, on_boundary commits a step after quiescing its
finalizers) drives CheckpointConfig. Next to it, a duck-typed model
attribute `quantization_layer_boundary_checkpoint` (restore,
commit_layer, is_catchup_layer, prepare_catchup_layer,
finalize_catchup_layer, materialize_deferred_prefix) was probed with
getattr in module_looper and five places in stage_layer. No class in
gptqmodel/ implements it; only test fakes did.

Drive resume and commit through the extension calls that already exist and
delete the attribute protocol:
- restore -> LoopExtension.on_start cursor (the start_layer_index
  parameter of run_layer_stage goes away).
- commit_layer -> LoopExtension.on_boundary. LoopBoundary.quiesce()
  re-raises a failed finalizer, which replaces the finalize_ok gate.
- The forced synchronous drain, the forced last-processor output replay
  and the per-layer TensorLifetimeDiagnostic existed only for the
  attribute and are removed.
- The packed catch-up replay and the deferred-prefix hook are removed
  without a replacement hook. Nothing in-tree produces a packed layer
  without its activation boundary: CheckpointExtension stores the
  InputCache with every committed step.

ModuleLooper raises TypeError when a model still sets the attribute, so
an external runtime fails before any work instead of quantizing without
its resume and commit callbacks.

In-tree runs never set the attribute, so their behaviour is unchanged.
The boundary test fakes in tests/test_stage_modules.py become a
LoopExtension fake that checks the resume cursor, the commit order after
finalizers, and that a failed finalizer is never committed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 03:54
@Qubitium
Qubitium merged commit dc6bca3 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/looper-boundary-into-extensions branch November 30, 2026 03:55
Qubitium added a commit that referenced this pull request Dec 1, 2026
…to disk for every processor (#6656)

ds4rt's disk-backed layer outputs (#3588) were reachable only through
per-model configure_*_store hooks that nothing in-tree calls. Make the same
DiskBackedLayerOutputWriter/Sequence available to every processor through
one typed field, CalibrationConfig.spill_path (map PR-G2):

- spill_writer() gives each pass a private, non-durable directory (no
  fsync, no resume journal) that weakref.finalize removes with its sequence,
  or with the writer when a failed pass never finalizes it.
- ForwardExecutor._output_collection spills every pass that produces all
  batches (replays, native capture) after the unchanged model hook; subset
  forwards that stop early keep their list. The first-layer capture moves
  each batch into a spill writer as soon as its forward returns.
- The writer records each batch's device and the sequence reads it back
  there, so consumers see the same tensors on the same device. Deep copies
  share the immutable files.
- ContinuationCodec stores a spilled cache as the list it replaces, so
  spill composes with CheckpointConfig (layer and subset steps).
- The lm_head stage copies a lazy cache into lists before the in-place
  norm hook.
- Delete TensorLifetimeDiagnostic, whose last consumer #6477 removed.

spill_path=None runs none of this: GPTQ and AWQ on Qwen2.5-0.5B-Instruct
are bit-identical to main. With spill on, GPTQ and AWQ on Qwen2.5-0.5B-Instruct
and GPTQ on OLMoE-1B-7B are bit-identical to spill off, and peak GPU memory
drops by the hidden-state sets the default path keeps resident.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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