Skip to content

fix(calibration): strip padding before the position budget - #4271

Merged
Qubitium merged 1 commit into
mainfrom
fix/issue-4238-calibration-padding-trim
Nov 16, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/issue-4238-calibration-padding-trim

Conversation

@ZX-ModelCloud

Copy link
Copy Markdown
Collaborator

TL;DR

prepare_calibration_dataset spent the model's position budget on padding
instead of on real tokens. Over-long rows are now measured on the tokens the
attention mask marks as real, truncated on truncation_side, and a row with no
real token left is dropped instead of being emitted as an all-pad row.

Net: 5 files changed, 264 insertions(+), 22 deletions(-); one function
(gptqmodel/utils/calibration.py) plus its tests and reference page.

Fixes #4238. Related: #4008 (introduced truncation_side), #4194.

1. The problem

The trimmed length was the padded width, so a left-padded row kept its
leading pads and lost real tokens from the end. When the padding alone filled
the budget, the row came out as pure padding with an all-zero attention mask and
still passed the calibration_data_min_length check, which also measures width.

flowchart TD
    A["row_ids, row_mask from _pack_ids"] --> B{"padded width > max_positions"}
    B -- "no" --> C["row kept unchanged"]
    B -- "yes" --> D{"truncation_side"}
    D -- "right (HF default)" --> E["row_ids[:max_positions]<br/>keeps leading pads"]
    D -- "left" --> F["row_ids[-max_positions:]<br/>drops BOS/sink"]
    E --> G["real tail tokens lost"]
    F --> G
    E --> H["padding at least budget-long:<br/>all-pad row, all-zero mask"]
    H --> I["passes min-length check<br/>Hessian receives zeros"]
    style G fill:#fff1f0,stroke:#d4380d
    style H fill:#ffccc7,stroke:#cf1322
    style I fill:#ffccc7,stroke:#cf1322
Loading

Observed on origin/main (7fa967742) and reproduced below: [[0,0,11,12]]
instead of [[11,12,13,14]], and [[0,0,0,0]] with an all-zero mask instead of
[[11,12]].

Mechanism being removed Where it lived Consequence
Budget applied to padded width utils/calibration.py:474-490 before this change Leading pads consume the budget; real tail tokens dropped
All-pad row accepted same block, then utils/calibration.py:498 All-zero mask row survives into the Hessian
Padding direction == truncation direction implied by width slicing padding_side="left" front-truncates every row

2. The new flow

flowchart TD
    A["row_ids, row_mask from _pack_ids"] --> B{"padded width > max_positions"}
    B -- "no" --> I
    B -- "yes" --> D["real_positions = positions where row_mask is truthy"]
    D --> E["real_ids = row_ids[real_positions]<br/>real_mask = row_mask[real_positions]"]
    E --> F{"truncation_side"}
    F -- "right (HF default)" --> G["real_ids[:max_positions]"]
    F -- "left" --> H["real_ids[-max_positions:]"]
    G --> I{"row has at least one real token"}
    H --> I
    I -- "no" --> J["dropped_padded_row_count += 1<br/>row not appended"]
    I -- "yes" --> K["append prepared row"]
    K --> L{"support_batch_quantize"}
    L -- "False and item is ragged" --> M["re-pad item to its widest row<br/>on padding_side"]
    L -- "True or uniform width" --> N["row list goes to collate_data / concat"]
    M --> N
    N --> O["batched tensors handed to the quantizer"]
    style J fill:#fff1f0,stroke:#d4380d
    style B fill:#e6f4ff,stroke:#0958d9
    style F fill:#e6f4ff,stroke:#0958d9
Loading

Decisions, and what each is made from:

3. Failure and ambiguity contract

stateDiagram-v2
    [*] --> Normalized
    Normalized --> Trimmed: padded width > max_positions
    Normalized --> Dropped: no truthy mask position
    Trimmed --> Dropped: no token left after truncation
    Trimmed --> Kept: at least one real token
    Dropped --> [*]: counted, WARN logged
    Kept --> [*]
Loading
Situation Before After
All-pad row, over the budget Emitted all-pad, all-zero mask Dropped; dropped_padded_row_count WARN
All-pad row, under the budget Emitted all-pad, all-zero mask Dropped by the same rule
Item where only some rows are all pad n/a Surviving rows kept in order; dropped row never reaches the Hessian
Every row of an item dropped n/a Item skipped and counted; an empty dataset returns an empty batch list, which the quantizer's existing zero-sample path handles
Item left ragged by stripping Not reachable (width slicing keeps width uniform) Non-batched path re-pads on padding_side with pad_token_id
Model declares no position limit No trimming Unchanged: no stripping
padding_side / truncation_side invalid ValueError Unchanged

The all-pad drop fires even when max_positions is unresolved, so the "all-pad
row in the Hessian" hole is closed on both paths. That is the one behaviour
change beyond issue #4238's literal reproduction.

4. Change inventory

Area File ± Purpose
Trimming gptqmodel/utils/calibration.py +72 / -22 Strip padding, truncate real tokens, drop all-pad rows, re-pad ragged non-batched items
Tests tests/test_calibration_truncation.py +109 Issue repros plus the padding/budget contract
Docs docs/calibration-row-trimming.md +78 Reference page for the flow and its contracts
Docs index docs/README.md +1 Link the page
Docs entry point README.md +4 Link the page from the calibration guidance

5. Tests / guarantees

tests/test_calibration_truncation.py:

Test Invariant
test_left_padded_overlong_row_strips_padding_before_the_budget The issue's first case: [[0,0,11,12,13,14]] → [[11,12,13,14]]
test_padding_at_least_as_long_as_the_budget_keeps_real_tokens The issue's second case: 6 pads + 2 tokens with a budget of 4 → [[11,12]]
test_all_padding_row_below_the_budget_is_dropped_too "Never emit an all-pad row" is not conditional on trimming
test_all_padding_row_is_dropped_instead_of_kept_empty All-pad over-budget row is dropped, not emitted empty
test_padded_and_real_rows_in_one_item_keep_only_the_real_row Dropping one row does not drop its item
test_right_padding_is_stripped_too Right padding is stripped as well
test_truncation_side_left_keeps_the_real_tail truncation_side="left" selects the real tail
test_ragged_rows_after_stripping_are_re_padded_for_the_unbatched_path support_batch_quantize=False still stacks
Existing test_calibration_truncation.py cases Left/right padding trim identically; short rows untouched; invalid truncation_side rejected
tests/test_prepare_dataset.py::test_prepare_dataset_trims_left_padded_rows_from_the_left_edge The repo test that failed at HEAD now passes unchanged

6. Validation

pytest tests/test_calibration_truncation.py tests/test_prepare_dataset.py \
       tests/test_calibration_padding_mask.py tests/test_calibration_mapping_input.py \
       tests/test_conv_capture_padding.py tests/test_moe_padding_rows.py
# 69 passed, 2 warnings

pytest tests/test_calibration_data_device.py tests/test_calibration_windows.py \
       tests/test_multimodal_modality_calibration.py
# 45 passed, 1 warning

ruff check gptqmodel/utils/calibration.py tests/test_calibration_truncation.py
# All checks passed

The repo test that reproduces the issue failed before the change
(assert [[0, 0, 11, 12]] == [[11, 12, 13, 14]]).

End-to-end, on a real Llama-3.2-1B-Instruct tokenizer with a batch tokenized
padding="max_length", max_length=64 and the position budget lowered to 8
(2 rows, 11 real tokens each): the prepared batch is [2, 8], both rows keep 8
real tokens, and the retained ids equal the first 8 real tokens of each row.
The same data quantized end-to-end, saved, reloaded and generated. A second run
with a 180-wide padded batch, a 64-token budget and 4 documents included m.quantize,
m.save, reload and generation.

7. Model Support / Module Plan

N/A — no new model types, aliases, or registry changes. No checkpoint format or
kernel change.

8. Reviewer notes

`prepare_calibration_dataset` cut an over-long row purely by width:
`row_ids[:max_positions]` (or the tail when `truncation_side="left"`). A
left-padded row therefore spent its budget on leading pads and dropped real
tokens from the end, and a row whose padding alone filled the budget survived
as pure padding with an all-zero attention mask. That row still passed the
minimum-length check, which measures padded width, so the Hessian received
zeros for it.

Strip positions the attention mask marks as padding before applying the
position budget, then truncate the real tokens on `truncation_side`. A row with
no real token left is dropped whether or not it needed trimming, so no all-pad
row is ever emitted; the drop is counted and logged.

Stripping or dropping rows can leave a multi-row item ragged. The batched and
concatenation paths consume rows individually, so only the non-batched path,
which stacks an item into one tensor, re-pads the item to its widest row on
`padding_side`.

Fixes #4238.

Signed-off-by: ZX-ModelCloud <[email protected]>
@Qubitium
Qubitium merged commit 1104081 into main Nov 16, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/issue-4238-calibration-padding-trim branch November 16, 2026 06:39
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.

[BUG][calibration] Over-long left-padded rows keep their padding and drop real tokens; a heavily padded row becomes all padding (regression of #4008)

2 participants