Repository navigation
fix(capture): derive position_ids from the mask for a padded calibration batch (#4861) - #4930
Merged
Merged
Conversation
…ion batch (#4861) prepare_calibration_dataset honours tokenizer.padding_side == "left" when it collates batch_size > 1 rows, but the capture forward passed only input_ids and attention_mask. Models whose forward defaults position_ids to arange(seq_len) - GPT-2, GPT-Neo - therefore embedded every real token of a left-padded row at pad_len + i instead of i, so every calibration statistic came from hidden states the model never produces at inference. generate() already derives the ids from the mask; right padding and RoPE/ALiBi models were unaffected. run_input_capture now derives position_ids = mask.cumsum(-1) - 1 with pad slots set to 1 (exactly what generate() does) when the example has none, the mask is 2-D, and the model's forward accepts the parameter. The derivation is skipped for a model without position_ids so the keyword cannot raise TypeError, and an explicit position_ids is never replaced. The helpers are module-level functions, not methods: test_calibration_data_device copies BaseQModel.run_input_capture onto a stand-in class, and a self. helper would have made that copy raise AttributeError. Measured on a 1-layer GPT-2, layer-0 input of one row alone vs the same row in a padded batch: right 0.000e+00 -> 0.000e+00, left 8.350e-02 -> 0.000e+00.
This was referenced Nov 17, 2026
Qubitium
added a commit
that referenced
this pull request
Nov 17, 2026
…) (#4961) #4930 derived 2-D position_ids from the attention mask for every model whose forward accepts the parameter. Qwen3-VL/Qwen3.5/GLM-4V/Hunyuan-VL-class models compute their 3-D/4-D image-grid ids inside forward only when position_ids is None, so the derived ids replaced the mRoPE grid with sequential text positions and image calibration rows ran on hidden states up to 45% off. Derive only when the model does not own the computation. The predicate walks the module tree for compute_3d_position_ids / get_rope_index / compute_mrope_position_ids (the capability lives on the inner multimodal model, not the outer conditional-generation wrapper), and a new CAPTURE_DERIVE_POSITION_IDS definition attribute can force it either way. Models without the capability (GPT-2/GPT-Neo/OPT) keep the #4861 left-pad fix. Co-authored-by: Codex <codex@localhost>
This was referenced Nov 17, 2026
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…er-0 inputs (ModelCloud#4861) (ModelCloud#4944) The fix for ModelCloud#4861 landed in ModelCloud#4930 and its tests drive `run_input_capture` with a recording stand-in. They pin the derived `position_ids` but never check the symptom that motivated the issue: the layer-0 inputs a real absolute-position model produces for a left-padded row. Add that regression test on a tiny GPT-2 (2 layers, hidden 32, hand-built tokenizer, CPU/fp32): capture layer-0 inputs at batch_size=1 and at batch_size=2 with padding_side="left", drop the pad slots, and require max|diff| < 1e-5. It also covers the left-padded final window of `calibration_dataset_concat_size` packing, which the collation-level fix could not reach, and the negative controls the issue asked for: right padding still matches, and OPT (which derives positions from the mask itself) is unchanged. A model whose forward has no `position_ids` and no `**kwargs` is never given the keyword, and an unpadded single row stays bit-identical with and without the mask. Before the fix this file is red (4 failed, 5 passed); on current main it is green (9 passed).
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…elCloud#4967) (ModelCloud#4971) `tests/test_docs_contract_refs.py` was red on main again: four citations into `gptqmodel/models/base.py` were 114 lines out of the 8-line window, because base.py keeps growing under them (ModelCloud#4894, ModelCloud#4906, ModelCloud#4912, ModelCloud#4930): docs/awq-scale-folding.md _select_prev_op 5489 -> 5667 docs/calibration-replay.md capture_layer_type_replay_kwargs 4022 -> 4200 docs/calibration-replay.md _build_layer_type_position_embeddings 4005 -> 4183 docs/fp8-scale-semantics.md _decoder_fp8_scale_semantics 4752 -> 4930 Re-anchoring the numbers would rot again at the next base.py change, so the guard now accepts a symbol-anchored citation (`path.py::symbol`) and those four docs use it. The test still resolves the symbol in the source, so a renamed or removed symbol fails; only the line number stops being part of the contract. The line-number form stays for files that are not growing. Also re-anchored the stale `:5531` on the adjacent `:postnorm` row to `base.py::_select_prev_op` and `POST_NORM_FLAG` (base.py:560). And the test now runs pre-merge: it is the first file in the AWQ CPU `unit` suite, and `docs/**` plus the test itself are added to that workflow's path filter, so a base.py or docs change runs it. On unmodified main: 4 failed, 16 passed. With the fix: 20 passed. Copying only the new test onto main (docs still citing line numbers) also fails all four, which proves the new form is actually enforced. Closes ModelCloud#4967.
sLaffey
pushed a commit
to sLaffey/GPTQModel
that referenced
this pull request
Nov 18, 2026
…lCloud#4978) Seven tests went red because their doubles/oracles predate library changes that behave as intended. This is test-only; no product code changes. - test_fusion_kernel_backends: gc.collect() before the weakref check; ModelCloud#4871 leaves transient Dynamo trace garbage that keeps the pre-fusion weight alive. The refs are still asserted dead afterwards. - test_failed_run_fence_4595: del qmodel + gc.collect() so ModelCloud#4829's finalizer runs before the no-leak assertion; a late finalizer must not recreate the released run dir. - test_exl3_projection_resume: add _release_deferred_hessian_sources() to the _Capture double (ModelCloud#4837). - test_kernel_audit_regressions: stub _needs_torch_fallback=lambda: False on the SimpleNamespace self (ModelCloud#4835). - test_moe_resave_preserves_experts_4589: accept the earlier RuntimeError "does not provide tensors" refusal (ModelCloud#4810); still assert no safetensors. - test_positional_mask_capture_4660: build the native oracle with the same mask-derived position_ids the capture uses (ModelCloud#4930). - test_qqq_kernel_memory_4387: snapshot the oracle weight/s_channel before the first forward, which may drop the checkpoint layout (ModelCloud#4856).
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.
Fixes #4861.
TL;DR
run_input_capturenow derivesposition_idsfrom the attention mask when theexample has none, so a left-padded calibration batch stops shifting the
absolute position embeddings of every real token. +31/−1 in
gptqmodel/models/base.py, 4 new test cases.1. The problem
prepare_calibration_datasethonourstokenizer.padding_side == "left"when itcollates
batch_size > 1rows, and the capture forward then ranself.model(**example, use_cache=False)with onlyinput_idsandattention_mask. Models whose forward defaultsposition_idstoarange(seq_len)— GPT-2, GPT-Neo — therefore embedded every real token of aleft-padded row at
pad_len + iinstead ofi:flowchart TD A["left-padded row<br/>ids = 0 0 0 5 6 7<br/>mask = 0 0 0 1 1 1"] --> B{"position_ids passed?"} B -- "no (before)" --> C["model default<br/>arange = 0 1 2 3 4 5"] C --> D["real tokens embedded at 3, 4, 5<br/>NOT 0, 1, 2"] D --> E["captured hidden states the model<br/>never produces at inference"] B -- "yes (after)" --> F["cumsum(mask) - 1, pads set to 1<br/>= 1 1 1 0 1 2"] F --> G["real tokens embedded at 0, 1, 2"] G --> H["matches batch_size=1 and generate()"] style D fill:#fff1f0,stroke:#d4380d style E fill:#fff1f0,stroke:#d4380d style B fill:#e6f4ff,stroke:#0958d9generate()already derives the same ids, so the calibration statistics weretaken on inputs the model never sees at inference. RoPE/ALiBi models are
unaffected (relative positions), OPT derives its own positions from the mask,
and right padding was already exact.
Measured on a 1-layer GPT-2 (fp32, CPU): layer-0 input of one row run alone vs
the same row inside a padded batch.
2. The new flow
flowchart TD A["run_input_capture(example)"] --> B{"INPUT_EMBEDDING_EXTRA_ARGS"} B -- "yes" --> G["model.generate(**example)<br/>generate derives its own ids"] B -- "no" --> C{"example has position_ids"} C -- "yes" --> H["pass through unchanged"] C -- "no" --> D{"2-D attention_mask present"} D -- "no" --> H D -- "yes" --> E{"model.forward accepts position_ids"} E -- "no" --> H E -- "yes" --> F["position_ids = mask.cumsum(-1) - 1<br/>pads set to 1"] F --> I["model(**example, position_ids=..., use_cache=...)"] H --> I style E fill:#e6f4ff,stroke:#0958d9 style F fill:#e6f4ff,stroke:#0958d9_with_capture_position_idsand_capture_accepts_position_idsare module-levelfunctions rather than methods:
tests/test_calibration_data_device.pycopiesBaseQModel.run_input_captureonto a stand-in class, and aself.helper wouldhave made that copy raise
AttributeError.The
position_idscapability check is what keeps this from regressing otherbackbones: a forward with no
position_idsparameter and no**kwargsis leftalone instead of raising
TypeError.3. Before / after
pad_len + ii, matchingbatch_size=1andgenerate()arangeon real tokens)arangeposition_idsin the exampleposition_idsTypeErrorINPUT_EMBEDDING_EXTRA_ARGS(generate path)generate()derives4. Tests
tests/test_calibration_padding_mask.py:test_left_padded_capture_derives_position_ids_from_the_mask[0,0,1,1,1]→[1,1,0,1,2],[1,1,1,0,0]→[0,1,2,1,1]test_unpadded_capture_position_ids_are_arangearange, so nothing changestest_capture_keeps_explicit_position_idstest_capture_skips_position_ids_when_the_model_does_not_accept_themTypeError5. Validation
Red,
origin/main@cb99385,base.pyunchanged:Green, same host, with the fix:
The
TestCalibrationDataDeviceIntegrationcases load a real model on this host,where
flash_attn_2_cudahas an undefined symbol:test_calibration_data_device_cpu_integrationis deselected above andtest_calibration_data_device_balanced_integrationfails with thatImportError. Both fail identically on cleanorigin/mainwithbase.pystashed (verified), so they are pre-existing host issues, not this change.
ruff checkpasses on both changed files.6. No new docs page
This is a localized fix inside
run_input_capture; it adds no stage, selectionorder or lifecycle. The dataset-side padding contract it depends on is already
documented in
docs/calibration-row-trimming.md, and the diagram above is thewhole change.
Claim:
agent-11788dff99fd, workload886f38351024.