Skip to content

fix(capture): derive position_ids from the mask for a padded calibration batch (#4861) - #4930

Merged
Qubitium merged 1 commit into
mainfrom
fix/capture-position-ids
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/capture-position-ids

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Fixes #4861.

TL;DR

run_input_capture now derives position_ids from the attention mask when the
example 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_dataset honours tokenizer.padding_side == "left" when it
collates batch_size > 1 rows, and the capture forward then ran
self.model(**example, use_cache=False) with 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:

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:#0958d9
Loading

generate() already derives the same ids, so the calibration statistics were
taken 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.

padding before after
right 0.000e+00 0.000e+00
left 8.350e-02 0.000e+00

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
Loading

_with_capture_position_ids and _capture_accepts_position_ids are module-level
functions rather than methods: tests/test_calibration_data_device.py copies
BaseQModel.run_input_capture onto a stand-in class, and a self. helper would
have made that copy raise AttributeError.

The position_ids capability check is what keeps this from regressing other
backbones: a forward with no position_ids parameter and no **kwargs is left
alone instead of raising TypeError.

3. Before / after

Situation Before After
Left-padded batch, GPT-2/GPT-Neo Real tokens embedded at pad_len + i Embedded at i, matching batch_size=1 and generate()
Right-padded batch Exact Exact (derived ids equal arange on real tokens)
Unpadded batch arange Same values, derived explicitly
Explicit position_ids in the example Passed through Passed through
Model whose forward has no position_ids n/a Nothing derived, no TypeError
INPUT_EMBEDDING_EXTRA_ARGS (generate path) generate() derives Unchanged

4. Tests

tests/test_calibration_padding_mask.py:

Test Invariant
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_arange An unpadded batch derives arange, so nothing changes
test_capture_keeps_explicit_position_ids A caller-supplied tensor is not replaced
test_capture_skips_position_ids_when_the_model_does_not_accept_them No keyword, no TypeError

5. Validation

Red, origin/main @ cb99385, base.py unchanged:

$ python repro_4861.py
gpt2 pad=right max|diff| layer0 embedding vs single row = 0.000e+00
gpt2 pad=left  max|diff| layer0 embedding vs single row = 8.350e-02

$ pytest test_calibration_padding_mask.py -q
2 failed, 5 passed

Green, same host, with the fix:

$ python repro_4861.py
gpt2 pad=right max|diff| layer0 embedding vs single row = 0.000e+00
gpt2 pad=left  max|diff| layer0 embedding vs single row = 0.000e+00

$ pytest test_calibration_padding_mask.py -q
7 passed

$ pytest <15 calibration + VLM + multimodal modules> -q
306 passed, 1 deselected

The TestCalibrationDataDeviceIntegration cases load a real model on this host,
where flash_attn_2_cuda has an undefined symbol:

ImportError: .../flash_attn_2_cuda...so: undefined symbol: _ZN3c104cuda29c10_cuda_check_implementationEiPKcS2_jb

test_calibration_data_device_cpu_integration is deselected above and
test_calibration_data_device_balanced_integration fails with that
ImportError. Both fail identically on clean origin/main with base.py
stashed (verified), so they are pre-existing host issues, not this change.

ruff check passes on both changed files.

6. No new docs page

This is a localized fix inside run_input_capture; it adds no stage, selection
order or lifecycle. The dataset-side padding contract it depends on is already
documented in docs/calibration-row-trimming.md, and the diagram above is the
whole change.

Claim: agent-11788dff99fd, workload 886f38351024.

…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.
@Qubitium
Qubitium merged commit 5fb2529 into main Nov 17, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/capture-position-ids branch November 17, 2026 19:00
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>
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant