Repository navigation
refactor(definitions): read raw example inputs from the base capture source, not per-model run_input_capture stashes - #6495
Merged
Conversation
…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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
StageInputsCapture.cache_inputshands the same moved example tobegin_input_capture_exampleandrun_input_capture(gptqmodel/looper/stage_inputs_capture.py:589-615).BaseQModel.begin_input_capture_examplekeeps that example asself._layer_type_replay_sourceuntilend_input_capture_exampleclears 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:
run_input_captureonly to set and restore a_<model>_capture_*_maskattribute aroundsuper(). These overrides are deleted._layer_type_replay_source["attention_mask"].begin/end_input_capture_examplepair copiedinput_ids. The pair is deleted. The capture hook reads and validates the sourceinput_ids.create_causal_mask/create_recurrent_attention_maskreplay code are deleted. Both configs declarelayer_typeswith distinct types, and ZDTaichu5'stext_configproperty already returnsllm_config. So onorigin/mainthe basecapture_layer_type_replay_kwargsalready cached one mask per type for both models. Theirprepare_layer_replay_kwargsoverrides calledsuper(), 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.
layer.forwardand every layer output. All are bit-identical toorigin/main, including left- and right-padded batches.git diff --shortstat origin/main:11 files changed, 138 insertions(+), 250 deletions(-)(net −112)gptqmodel/:4 files changed, 7 insertions(+), 223 deletions(-)(net −216).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;awq_get_modules_for_scalingis 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_inputsis unchanged.gptqmodel/models/definitions/mimo_v2.py: removed_CAPTURE_ATTENTION_MASK_ATTRand therun_input_captureoverride.capture_first_layer_input_kwargsreads(self.__dict__.get("_layer_type_replay_source") or {}).get("attention_mask"), the same object the stash held.gptqmodel/models/definitions/glm5_next.py: removed thebegin_input_capture_example/end_input_capture_exampleoverrides.capture_first_layer_input_kwargsreads 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
ValueErroris now raised from the layer-0 hook during the capture forward, not before it. In both cases it propagates out ofcache_inputsbefore 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_capturecalls 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). Itsbegin_input_capture_examplevalidateslabelsand derives the MTP decode mask. #6435 kept it on purpose. Note for a follow-up: since #6435 the threeMTP_CAPTURE_*keys appear to have no consumer except theprepare_layer_replay_kwargsthat 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, becauseZDTaichu5_0_Config.text_configis a property returningllm_config(gptqmodel/models/ports/zdtaichu5/configuration.py:79-81). The recorder shows the base layer-type kwargs are already cached for zdtaichu5 onorigin/main.Tests
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).begin_input_capture_example→run_input_capture→ layer-0 hook →end_input_capture_example.prepare_layer_replay_kwargsand asserts:torch.equalto what the removed solar code built (create_causal_mask/create_recurrent_attention_maskfrom the raw 2-D mask);torch.equalto the native forward.origin/main'ssolar_open2.pytoo, so it pins the transition._declared_layer_typespatched toNone), 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_masksnow captures throughbegin_input_capture_example+capture_layer_type_replay_kwargs. The mask assertions are unchanged.tests/test_zdtaichu5_support.py:_TinyZDTaichuWrapperexposesconfig.text_configlike the real config;test_zdtaichu5_hybrid_replay_masks_match_dense_layerscaptures through begin/end andcapture_layer_type_replay_kwargs;test_zdtaichu5_capture_preserves_raw_padding_maskbecametest_zdtaichu5_capture_rebuilds_masks_from_raw_padding_mask. It asserts that the DeltaNet entry is the raw padding mask (Nonewhen unpadded).tests/test_mimo_layer_replay.py,tests/test_mimo_v2_local_port.py:run_input_captureis bracketed by begin/end, as the capture stage does.tests/test_glm5_next_support.py::test_capture_preserves_original_token_ids_for_mtp_replayasserts 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":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:tests/test_mimo_v2_local_port.py::test_media_count_and_processor_failure_repair_retry:UnsafeModelArtifactError: ... preprocessor_config.json: invalid JSON, the Reject suspicious GGUF payloads, chat templates, and unsafe checkpoint shards #6475 artifact gate.tests/test_solar_open2_local_port.py::test_package_selection_ignores_checkpoint_python[False-None|True-1]andtests/models/test_solar_open2.py::test_solar_open2_lazy_turtle_materializes_released_expert_weights:TypeError: SolarOpen2ForCausalLM.__init__() got an unexpected keyword argument 'device_map'. These are new onmainsince Remove accelerate: explicit WeightLoader for weight loading, placement and offload (#6471) #6473:build_shell_modelforwards the tests'device_mapto the local model class. They pass on 580b1a1. The quantize path throughGPTQModel.loadis unaffected (see the GPU A/B).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.StageInputsCapture.cache_inputs:pre_quantize_generate_hook_start;move_input_capture_example,begin_input_capture_example,run_input_capturestopped by a layer-0 pre-hook that mirrors_capture_layer_inputs(includingcapture_layer_type_replay_kwargs),end_input_capture_example;ForwardExecutor's replay over every layer: thesupport_batch_quantizemask rule,prepare_layer_replay_kwargs, the layer forward andupdate_layer_replay_kwargs_from_output.layer.forward;attention_mask;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/main186737f vs branch; the 580b1a1 run printed the same lines):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 vsorigin/main186737f. 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):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_MAPentry, 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) andawq_module_replay_inputs(zdtaichu5) are untouched. AWQ consumes the per-type masks from the base capture cache, whichorigin/mainalready produced for both models. The AWQ GPU A/B for both is bit-identical.Logic Flow Documentation
file:lineevidence.docs/repeats the diagrams, titled for the mechanism, and is linked fromREADME.md. The section lives indocs/calibration-replay.md, which is already linked fromREADME.mdanddocs/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:#cf1322origin/main186737f)run_input_capturestashsolar_open2.py:147; padding key at capture:162; per-layer mask rebuild:183capture_layer_type_replay_kwargs(base.py:5750) +_apply_layer_type_replay_kwargs(base.py:6005)zdtaichu5.py:122; padding key:137; mask builders:166,:172; per-layer rebuild:177text_config→llm_config)mimo_v2.py:178capture_first_layer_input_kwargs(mimo_v2.py:177) reads the sourcebegin/end_input_capture_exampleglm5_next.py:444,:457capture_first_layer_input_kwargs(glm5_next.py:444) reads and validates the sourcetry/finallyrestore aroundrun_input_capturebase.py:5534set /:5551cleared, around the samerun_input_capturecall (stage_inputs_capture.py:600-615)Review Requirements
Kernel Accuracy Requirements
Notes
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.attention_mask, unpadded batches where the masks are causal-skipNone, and both layer orders (full-first / linear-first). These cover the base-type rule that keeps the incoming mask when the rebuilt one isNone. The removed code overwrote withNonein that case; withuse_cache=Falsethe incoming mask is the same native mask, so the result is the same.normalize_seq_maskof 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