Skip to content

refactor(definitions): read raw example inputs from the base capture source, not per-model run_input_capture stashes - #6495

Merged
Qubitium merged 1 commit into
mainfrom
refactor/defs-capture-source-stashes
Nov 30, 2026
Merged

Qubitium merged 1 commit into
mainfrom
refactor/defs-capture-source-stashes

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

StageInputsCapture.cache_inputs hands the same moved example to begin_input_capture_example and run_input_capture (gptqmodel/looper/stage_inputs_capture.py:589-615). BaseQModel.begin_input_capture_example keeps that example as self._layer_type_replay_source until end_input_capture_example clears it (gptqmodel/models/base.py:5534-5555). bailing_moe and ricursive already read it.

Four definitions kept their own copy of that example anyway, and two of them also rebuilt replay masks that the base per-layer-type replay already builds. This PR deletes those copies and the duplicated mask code:

  • solar_open2, zdtaichu5, mimo_v2: each overrode run_input_capture only to set and restore a _<model>_capture_*_mask attribute around super(). These overrides are deleted.
    • mimo_v2's capture hook now reads _layer_type_replay_source["attention_mask"].
  • glm5_next: its begin/end_input_capture_example pair copied input_ids. The pair is deleted. The capture hook reads and validates the source input_ids.
  • solar_open2, zdtaichu5: their capture-time padding-mask key and per-layer create_causal_mask/create_recurrent_attention_mask replay code are deleted. Both configs declare layer_types with distinct types, and ZDTaichu5's text_config property already returns llm_config. So on origin/main the base capture_layer_type_replay_kwargs already cached one mask per type for both models. Their prepare_layer_replay_kwargs overrides called super(), which applied those masks, and then overwrote them with equal tensors.

This is a behavior-preserving refactor: no change to numerics, checkpoint format or public API.

  • Recorder A/B on 9 tiny-model configurations, run before and after the rebase, covers every kwarg handed to every replayed layer.forward and every layer output. All are bit-identical to origin/main, including left- and right-padded batches.
  • GPU quantize A/B gives bit-identical checkpoints for the Qwen2.5-0.5B control and for seeded tiny Solar-Open2 and ZDTaichu5 checkpoints, under GPTQ, AWQ, GPTAQ and FOEM.

git diff --shortstat origin/main: 11 files changed, 138 insertions(+), 250 deletions(-) (net −112)

  • Under gptqmodel/: 4 files changed, 7 insertions(+), 223 deletions(-) (net −216).
  • The rest is test updates, one new parametrized test and a short docs section.

What Changed

  • gptqmodel/models/definitions/solar_open2.py: removed

    • _PADDING_MASK_KEY, _CAPTURE_PADDING_MASK_ATTR;
    • run_input_capture, capture_first_layer_input_kwargs, prepare_layer_replay_kwargs;
    • three now-unused imports.

    awq_get_modules_for_scaling is untouched.

  • gptqmodel/models/definitions/zdtaichu5.py: removed

    • _PADDING_MASK_KEY, _CAPTURE_PADDING_MASK_ATTR;
    • run_input_capture, capture_first_layer_input_kwargs, _recurrent_attention_mask, _causal_attention_mask, prepare_layer_replay_kwargs.

    awq_module_replay_inputs is unchanged.

  • gptqmodel/models/definitions/mimo_v2.py: removed _CAPTURE_ATTENTION_MASK_ATTR and the run_input_capture override. capture_first_layer_input_kwargs reads (self.__dict__.get("_layer_type_replay_source") or {}).get("attention_mask"), the same object the stash held.

  • gptqmodel/models/definitions/glm5_next.py: removed the begin_input_capture_example/end_input_capture_example overrides. capture_first_layer_input_kwargs reads the source and raises the same errors:

    • RuntimeError("GLM-5.3 calibration token capture is unavailable") when no example is open;
    • ValueError("GLM-5.3 calibration requires rank-2 input_ids") for missing or non-rank-2 ids.

    The only difference: that ValueError is now raised from the layer-0 hook during the capture forward, not before it. In both cases it propagates out of cache_inputs before anything is cached.

  • docs/calibration-replay.md: a short "Raw example inputs in definitions" section with a flow diagram and a before/after table.

One path change, with bit-identical output: solar_open2 now overrides none of _CAPTURE_REUSE_GUARDED_HOOKS. It therefore qualifies for the GPTAQ/FOEM first-capture reuse (#5831), and its GPTAQ/FOEM quantize runs one model-level capture pass instead of two (run_input_capture calls 8 → 4 on the tiny run). The saved checkpoints are bit-identical with and without the reuse (see the GPU A/B). zdtaichu5, mimo_v2 and glm5_next still override guarded hooks or declare side modules, so their eligibility is unchanged.

Out of scope: deepseek_v4 (deepseek_v4.py:500-548). Its begin_input_capture_example validates labels and derives the MTP decode mask. #6435 kept it on purpose. Note for a follow-up: since #6435 the three MTP_CAPTURE_* keys appear to have no consumer except the prepare_layer_replay_kwargs that pops them and the tests. That would be a separate dead-code PR.

Map premise corrected: the map proposed a layer_type_config_attr = "llm_config" data hook for zdtaichu5. It is not needed, because ZDTaichu5_0_Config.text_config is a property returning llm_config (gptqmodel/models/ports/zdtaichu5/configuration.py:79-81). The recorder shows the base layer-type kwargs are already cached for zdtaichu5 on origin/main.

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.

New test (CPU): tests/test_solar_open2_local_port.py::test_layer_replay_rebuilds_each_attention_mask_from_padded_capture[{eager,sdpa}-{full,linear}-first] (4 nodes).

  • It captures a left-padded batch through begin_input_capture_example → run_input_capture → layer-0 hook → end_input_capture_example.
  • It replays every layer through prepare_layer_replay_kwargs and asserts:
    • each layer's mask is torch.equal to what the removed solar code built (create_causal_mask / create_recurrent_attention_mask from the raw 2-D mask);
    • each replayed output is torch.equal to the native forward.
  • It passes with origin/main's solar_open2.py too, so it pins the transition.
  • Red check: with the base per-type replay disabled (_declared_layer_types patched to None), all 4 fail on the linear-attention mask.

Updated tests (they set or asserted the removed private attributes):

  • tests/models/test_solar_open2.py::test_solar_open2_replay_rebuilds_full_and_linear_attention_masks now captures through begin_input_capture_example + capture_layer_type_replay_kwargs. The mask assertions are unchanged.
  • tests/test_zdtaichu5_support.py:
    • _TinyZDTaichuWrapper exposes config.text_config like the real config;
    • test_zdtaichu5_hybrid_replay_masks_match_dense_layers captures through begin/end and capture_layer_type_replay_kwargs;
    • test_zdtaichu5_capture_preserves_raw_padding_mask became test_zdtaichu5_capture_rebuilds_masks_from_raw_padding_mask. It asserts that the DeltaNet entry is the raw padding mask (None when unpadded).
    • Red check: without the config the four nodes fail.
  • tests/test_mimo_layer_replay.py, tests/test_mimo_v2_local_port.py: run_input_capture is bracketed by begin/end, as the capture stage does.
  • tests/test_glm5_next_support.py::test_capture_preserves_original_token_ids_for_mtp_replay asserts that the source is released.

Affected test families: 42 files, selected by grep for every touched symbol and model type, plus the capture/replay suites (test_layer_type_replay, test_stage_modules, test_calibration_padding_mask, test_gptaq_foem_first_capture_5831, bailing). Both trees ran the same list with -n 16, CUDA_VISIBLE_DEVICES=2, -k "not TestSolarOpen2":

PYTHONPATH=<clone> python -P -m pytest -p no:cacheprovider -q -n 16 -rs -k "not TestSolarOpen2" $(cat test_files.txt)
# origin/main 186737ff5: 4 failed, 901 passed, 139 skipped
# branch (rebased):      4 failed, 905 passed, 139 skipped   (+4 new solar nodes; the 2 renamed zdtaichu5 nodes pass)
# (before the rebase, on 580b1a11f: main 1 failed / 904 passed, branch 1 failed / 908 passed, same node diff)
# after a final rebase onto 99fd14d56 (no affected file changed), the 11 directly touched test files: 4 failed (the same 4), 233 passed

The junit node sets differ only by the 4 new nodes and the 2 renamed zdtaichu5 nodes. No node changed status. All 4 failures are identical on both trees and pre-existing on main:

Skips and what they leave unverified:

  • 139, identical on both trees: tests/module_tree/test_moe_expert_coverage.py:330, opt-in -m meta_coverage. They leave the meta-device expert-coverage sweep unverified. That sweep checks module trees, which this PR does not touch.

  • Not run:

    • tests/models/test_solar_open2.py::TestSolarOpen2 (Solar-Open2-250B quality run);
    • tests/models/test_zdtaichu5.py, tests/models/test_glm5_next.py.

    These are full-checkpoint GPU quality runs. ZDTaichu5-9B is not on this host. The 250B/GLM-5.3 checkpoints do not fit the 32 GB test GPU. The seeded tiny-checkpoint GPU A/B below substitutes for them.

Structural A/B (recorder): capture_source_recorder.py + capture_source_compare.py.

  • Each case emulates StageInputsCapture.cache_inputs:
    • pre_quantize_generate_hook_start;
    • per example: move_input_capture_example, begin_input_capture_example, run_input_capture stopped by a layer-0 pre-hook that mirrors _capture_layer_inputs (including capture_layer_type_replay_kwargs), end_input_capture_example;
    • then ForwardExecutor's replay over every layer: the support_batch_quantize mask rule, prepare_layer_replay_kwargs, the layer forward and update_layer_replay_kwargs_from_output.
  • It records:
    • the exact kwargs dict passed to every layer.forward;
    • every layer output;
    • the cached first-layer kwargs;
    • leftover capture state;
    • per-layer native forward outputs.
  • Fixtures: tiny seeded vendored models built from the existing test helpers.
  • Examples:
    • all models: a left-padded batch (bs2), a right-padded batch (bs2), an unpadded batch (bs2) and bs1;
    • all except glm5_next: a batch with no attention_mask;
    • zdtaichu5 only: a left-padded image batch with mRoPE positions.
  • Tensors are compared with torch.equal. The only ignored keys are the two deleted private cache keys (_solar_open2_padding_mask, _zdtaichu5_padding_mask). No replay consumer sees them: the removed overrides popped them.

Output after the rebase (origin/main 186737f vs branch; the 580b1a1 run printed the same lines):

glm5_next: IDENTICAL  4 examples, 184 replayed layer calls (masks seen: 2D); replay-vs-native max abs old=0 new=0
mimo_v2_full_first: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 4D); replay-vs-native max abs old=0 new=0
mimo_v2_swa_first: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 4D); replay-vs-native max abs old=0 new=0
solar_open2_full_first_eager: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0
solar_open2_full_first_sdpa: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0
solar_open2_linear_first_eager: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0
solar_open2_linear_first_sdpa: IDENTICAL  5 examples, 20 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0
zdtaichu5_full_first_sdpa: IDENTICAL  6 examples, 24 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0
zdtaichu5_linear_first_eager: IDENTICAL  6 examples, 12 replayed layer calls (masks seen: 2D,4D,None); replay-vs-native max abs old=0 new=0

Fixture note: glm5_next's checkpoint-only MTP layer 45 is appended after post_init, so some of its tensors start as uninitialized memory. The recorder seeds them; without that, layer 45's output varies between processes regardless of tree.

GPU quantize A/B (gpu_ab.py, RTX 5090, CUDA_VISIBLE_DEVICES=2, fp16, seed 0, same calibration on both trees). The table is from the rebased branch vs origin/main 186737f. solar_foem was run before the rebase, against 580b1a1. Every other case was also bit-identical before the rebase, with the same tensor-set sha256. Every saved safetensors tensor is compared bytewise, and every other file byte-exact (quant_log ignoring time):

Case Model Method Result model-level captures (main → PR)
qwen2_5 Qwen/Qwen2.5-0.5B-Instruct, 32 wikitext rows, bs4 GPTQ g128 bit-identical (794 tensors)
solar_gptq seeded tiny Solar-Open2 (4 layers, full/linear), 16 rows of mixed length, bs4 (36 padded tokens) GPTQ g32 bit-identical (353 tensors)
solar_awq same AWQ g32 bit-identical (275 tensors)
solar_gptaq same GPTQ + GPTAQ bit-identical (353 tensors) 8 → 4
solar_foem same GPTQ + FOEM(0.25) bit-identical (353 tensors) 8 → 4
zdtaichu5_gptq seeded tiny ZDTaichu5 (4 layers, linear/full), 16 wikitext rows (bs forced to 1 by the definition) GPTQ g32 bit-identical (151 tensors)
zdtaichu5_awq same AWQ g32 bit-identical (125 tensors)

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

Measured Impact

Not applicable: no claimed issue. The only runtime difference is the GPTAQ/FOEM first-capture reuse for solar_open2 described above, which skips one model-level capture pass and leaves the output bit-identical.

Model Support / Module Plan

Not applicable: no MODEL_MAP entry, alias, module tree or fusion eligibility changes. Registry and module-plan tests for the four touched definitions are in the run above.

Model test node IDs and results (or "not applicable"): see Tests.

AWQ onboarding safety

Not applicable: no AWQ grouping, search, fold or replay code changes. awq_get_modules_for_scaling (solar_open2) and awq_module_replay_inputs (zdtaichu5) are untouched. AWQ consumes the per-type masks from the base capture cache, which origin/main already produced for both models. The AWQ GPU A/B for both is bit-identical.

Logic Flow Documentation

  • This change does not alter a major logic flow, or the required diagrams and docs page are included below.
  • New-flow Mermaid diagram(s) describe the shipped code using real symbol names.
  • The removed/replaced mechanism is shown or tabulated with file:line evidence.
  • Failure and ambiguity paths are marked and visually distinct from success.
  • A reference page under docs/ repeats the diagrams, titled for the mechanism, and is linked from README.md. The section lives in docs/calibration-replay.md, which is already linked from README.md and docs/README.md.
flowchart TD
    A["StageInputsCapture.cache_inputs<br/>move_input_capture_example"] --> B["begin_input_capture_example<br/>_layer_type_replay_source = example"]
    B --> C["run_input_capture(example)"]
    C --> D["decoder layer 0 pre-hook"]
    D --> E["capture_first_layer_input_kwargs<br/>mimo_v2: raw attention_mask<br/>glm5_next: input_ids for MTP layer 45"]
    D --> F["capture_layer_type_replay_kwargs<br/>solar_open2, zdtaichu5: one mask per layer type"]
    E --> G["end_input_capture_example<br/>_layer_type_replay_source = None"]
    F --> G
    E -. "glm5_next: no source or non rank-2 input_ids" .-> X["RuntimeError / ValueError"]
    style X fill:#ffccc7,stroke:#cf1322
Loading
Definition Removed (origin/main 186737f) Now
solar_open2 run_input_capture stash solar_open2.py:147; padding key at capture :162; per-layer mask rebuild :183 base capture_layer_type_replay_kwargs (base.py:5750) + _apply_layer_type_replay_kwargs (base.py:6005)
zdtaichu5 stash zdtaichu5.py:122; padding key :137; mask builders :166, :172; per-layer rebuild :177 same base path (its text_config → llm_config)
mimo_v2 stash mimo_v2.py:178 capture_first_layer_input_kwargs (mimo_v2.py:177) reads the source
glm5_next begin/end_input_capture_example glm5_next.py:444, :457 capture_first_layer_input_kwargs (glm5_next.py:444) reads and validates the source
source lifetime per-definition try/finally restore around run_input_capture base.py:5534 set / :5551 cleared, around the same run_input_capture call (stage_inputs_capture.py:600-615)

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, fusion or packing change.

Notes

  • Concurrent work: another refactor is deleting AWQ group overrides (awq_get_modules_for_scaling) in solar_open2.py and other files. This PR does not touch that method. The two removals sit in adjacent regions of solar_open2.py, so whichever lands second may need a trivial rebase.
  • Edge cases the recorder pins as identical: a batch without attention_mask, unpadded batches where the masks are causal-skip None, and both layer orders (full-first / linear-first). These cover the base-type rule that keeps the incoming mask when the rebuilt one is None. The removed code overwrote with None in that case; with use_cache=False the incoming mask is the same native mask, so the result is the same.
  • A non-2-D or width-mismatched source mask would make the base path skip the per-type rebuild, where the removed solar/zdtaichu code fell back to normalize_seq_mask of the captured mask. Calibration preparation always yields a 2-D mask whose width matches the decoder sequence for these two models, so I found no reachable input that takes that path.

🤖 Generated with Claude Code

…source, not per-model run_input_capture stashes

The capture stage passes the same moved example to begin_input_capture_example
and run_input_capture. BaseQModel already keeps it as
`_layer_type_replay_source` for exactly that span and clears it in
end_input_capture_example. Four definitions kept a private copy of that example
anyway:

- solar_open2, zdtaichu5 and mimo_v2 overrode run_input_capture only to set and
  restore a `_<model>_capture_*_mask` attribute around super(). Their capture
  hooks now read `_layer_type_replay_source` instead (with the same 2-D filter
  for solar_open2/zdtaichu5), and the overrides and `_CAPTURE_*_ATTR` constants
  are gone.
- glm5_next copied `input_ids` in its own begin/end pair. Its capture hook now
  reads and validates the source `input_ids`. The same RuntimeError/ValueError
  fire for a missing source or non-rank-2 ids; the ValueError is now raised in
  the layer-0 hook instead of before the forward.

solar_open2 and zdtaichu5 also rebuilt the full-attention and linear-attention
masks per layer in prepare_layer_replay_kwargs. Both configs declare
`layer_types` (ZDTaichu5's `text_config` property already resolves to
`llm_config`), so the base per-layer-type replay already built the same masks on
main and the definition overrides only overwrote them with equal tensors. Their
capture/replay mask code is deleted. Without a capture override, solar_open2 now
qualifies for the GPTAQ/FOEM first-capture reuse (#5831); its checkpoints are
bit-identical with and without the reuse.

deepseek_v4's begin/end pair is unchanged: it validates labels and derives the
MTP decode mask, which #6435 kept on purpose.

Tests that set the removed private attributes now go through
begin_input_capture_example, and a new solar_open2 test replays a left-padded
capture through every layer and checks each mask against the removed builders
and each output against the native forward.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@Qubitium
Qubitium marked this pull request as ready for review November 30, 2026 12:24
@Qubitium
Qubitium merged commit ad37dc2 into main Nov 30, 2026
6 checks passed
@Qubitium
Qubitium deleted the refactor/defs-capture-source-stashes branch November 30, 2026 12:24
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