Skip to content

perf(calibration): strip pre-padded rows before sorting and batching (#4889) - #4946

Merged
Qubitium merged 1 commit into
mainfrom
root/calib-strip-pad-4889
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/calib-strip-pad-4889

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Fixes #4889. prepare_calibration_dataset stripped pad positions only when a row
was over the model's position budget (#4238) or when concat_size was set
(#4311). A row that was merely pre-padded — what
tokenizer(texts, padding=True) and padding="max_length" produce, and what
#4193/#4652 route into this path — kept its padding all the way into the forward
passes. Three consequences:

  • every capture and per-layer replay forward ran at the padded width (the mask
    keeps the pads out of the Hessian, so the checkpoint was fine — pure waste);
  • sort="desc" (the default) keyed on len(item["input_ids"][0]), the padded
    width, so on pre-padded input it was a no-op and batch_size > 1 batches were
    no longer length-grouped;
  • collate_data padded each batch to the widest row of the whole dataset.

+24/−0 in gptqmodel/utils/calibration.py (one else branch in the per-row
loop), one new test module, one docs section.

What Changed

  • gptqmodel/utils/calibration.py: in the per-row loop, a row that is not
    over the position budget now has its contiguous edge pad positions stripped
    before the all-pad/min-length filters, the sort, and collate_data.
    rows_changed is set only when something was actually removed, so the
    unpadded path is bit-identical.
  • Rows whose truthy mask positions are not one contiguous run (interior mask
    zeros, i.e. a caller-built mask rather than tokenizer padding) are left
    untouched, as the issue suggested. Documented in the new docs section.
  • concat_size behaviour is untouched: the concat packer already stripped pads,
    and it now receives already-stripped rows, producing the same windows.
  • Three existing tests asserted the old padded output as a side effect of their
    real subject (ids precedence, rank-4 mask collapse); they now assert the
    stripped rows. No API change.

Tests

Red, origin/main @ c2a76ce1c, library unchanged, new test module only:

$ /root/venv-kernels/bin/python /tmp/root-rt.py tests/test_calibration_strip_padding_4889.py -q
FAILED test_padded_rows_are_stripped_before_sorting_and_batching
FAILED test_padding_max_length_is_stripped_too
FAILED test_batches_are_padded_to_their_own_widest_row
3 failed, 2 passed

Green, with the fix:

$ /root/venv-kernels/bin/python /tmp/root-rt.py tests/test_calibration_strip_padding_4889.py -q
5 passed

Delta on the requested suites (same host, CPU-only, CUDA_VISIBLE_DEVICES=""):

$ python /tmp/root-rt.py tests/test_calibration_padding_mask.py tests/test_prepare_dataset.py \
    tests/test_calibration*.py tests/test_generator_calibration_4307.py -q
base  (origin/main @ c2a76ce1c)     2 failed, 248 passed, 5 skipped  in 507 s
head  (root/calib-strip-pad-4889)   2 failed, 253 passed, 5 skipped  in 509 s

The two failures are identical on both sides and are the known pre-existing
test_calibration_data_device.py nodes
(test_stage_capture_balanced_mode_empty_filter_fallback,
test_balanced_mode_fallback_when_input_device_not_in_forward_devices). The
only delta is the 5 new tests.

ruff check passes on gptqmodel/utils/calibration.py and every changed test
file.

What the new module pins:

Test Invariant
test_padded_rows_are_stripped_before_sorting_and_batching padding=True and unpadded input give the same total batch width, and sort="desc" orders by real length
test_padding_max_length_is_stripped_too padding="max_length" rows are stripped below the requested width
test_padded_and_unpadded_keep_the_same_real_tokens_and_nsamples identical per-row real-token content, identical sample count, bitwise-equal mask-filtered Hessian
test_interior_mask_zeros_are_preserved a caller-built [1, 1, 0, 0, 1] mask is not rewritten
test_batches_are_padded_to_their_own_widest_row batch_size=2 collates to each batch's own widest row ([11, 7]), not the dataset width ([11, 11])

Measurements

Token count — 128 wikitext docs, SmolLM2-135M tokenizer, max_length=2048,
batch_size=1, sort="desc":

calibration input tokens forwarded real tokens sort order
base, padding=True 59,648 (2.86x) 20,882 padded width → no-op
head, padding=True 20,882 (1.00x) 20,882 real length
base/head, unpadded 20,882 20,882 real length (unchanged)

quantize() time — SmolLM2-135M fp16, GPTQ 4-bit g128, CPU, 8 docs,
max_length=128, batch_size=1. The shared host was at load average ~250
during the runs, so the wall-clock delta is smaller than the token delta and
noisy; the two runs per side were back-to-back:

forwarded tokens quantize()
base, padding=True 768 (708 real) 286.0 s / 290.0 s
head, padding=True 708 (708 real) 277.5 s / 282.5 s

Model Support / Module Plan

Not applicable: no MODEL_MAP entry, alias, or definition change.

AWQ onboarding safety

Not applicable: no model onboarding, grouping, replay, or fold change.

Logic Flow Documentation

The per-row flow gains one branch. Diagram (also added to
docs/calibration-row-trimming.md, linked from README.md line 153):

flowchart TD
    A["row_ids, row_mask"] --> B{"padded width > max_positions"}
    B -- "yes" --> C["strip truthy positions, then truncate by truncation_side"]
    B -- "no" --> D{"row_mask has exactly one<br/>contiguous run of truthy positions"}
    D -- "no, interior zeros" --> E["keep the row as given"]
    D -- "yes" --> F["row_ids[first_real : last_real + 1]<br/>row_mask[first_real : last_real + 1]"]
    C --> G["all-pad / min-length filters"]
    E --> G
    F --> G
    G --> H["sort by real length, then collate_data re-pads per batch"]
    style E fill:#e6f4ff,stroke:#0958d9
    style F fill:#e6f4ff,stroke:#0958d9
Loading
Situation Before After
Row padded below the budget (calibration.py:983, the new else) Pads kept Edge pads stripped
Row with interior mask zeros Kept Kept (unchanged)
Row with no padding at all Kept Kept, rows_changed not set (bit-identical)
Over-long row Strip + truncate (#4238) Unchanged
concat_size set Packer strips Packer strips; rows arrive stripped, same windows
support_batch_quantize=False, item left ragged by stripping n/a Re-padded to the item's widest real row, padding_side honoured

Review Requirements

  • Reviewed this PR.
  • Matches existing project structure and conventions (the strip lives beside the trim branch it mirrors).
  • No monkeypatching; no new extension point.
  • Minimal surface: one branch plus tests/docs.
  • Regression considered: the unpadded path is bit-identical, interior masks are preserved, concat_size output is unchanged.

Kernel Accuracy Requirements

Not applicable: no kernel change.

Notes

tests/test_docs_contract_refs.py is not green on this base (4 failures in
docs/awq-scale-folding.md, docs/calibration-replay.md x2,
docs/fp8-scale-semantics.md pointing at gptqmodel/models/base.py lines that
#4909 shifted). Same 4 failures on a clean origin/main worktree; this PR
touches neither base.py nor those pages.

Rebased onto current main, which now also carries #4916's concat_size packing
order (#4892), #4930's position_ids capture change and #4927's messages/tools
rendering. The strip sits in the else of #4916's
if not concat_mode and max_positions is not None and row_len > max_positions:,
so both changes compose: the concat path keeps its pack-then-filter order, and
its windows are unchanged because the packer already stripped pads.

…4889)

prepare_calibration_dataset strips pad positions only inside the over-long
branch (#4238) and in the concat packer (#4311). A row that was merely padded -
what tokenizer(texts, padding=True) and padding="max_length" produce - went
through unchanged, so:

* every capture and per-layer replay forward ran at the padded width, though the
  mask kept the pads out of the Hessian;
* sort="desc" (default) keyed on len(input_ids[0]), the padded width, so on
  pre-padded input it was a no-op and batch_size > 1 batches were no longer
  length-grouped;
* collate_data padded every batch to the widest row of the whole dataset.

Strip the edge pad positions of every row, not only the over-long ones, so the
sort and collate_data see real lengths and re-pad per batch. A row whose truthy
mask positions are not one contiguous run carries interior mask zeros (a
caller-built mask, not tokenizer padding) and is left untouched. The unpadded
path is bit-identical: nothing changes when the mask has no edge zeros.

128 wikitext docs, SmolLM2-135M tokenizer, max_length=2048, padding=True:

  forwarded tokens   base 59,648 for 20,882 real (2.86x)  ->  20,882 (1.00x)
  sort="desc"        sorted by padded width (no-op)       ->  sorted by real length

Quantize, SmolLM2-135M fp16, GPTQ 4-bit g128, CPU, 8 docs, max_length=128,
batch_size=1 (host load average ~250, so times are noisy):

  forwarded tokens   base 768 (708 real)  ->  708 (708 real)
  quantize()         base 286.0 s         ->  277.5 s
@Qubitium
Qubitium force-pushed the root/calib-strip-pad-4889 branch from 24c6967 to 68f7212 Compare November 17, 2026 19:42
@Qubitium
Qubitium merged commit f3433d1 into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the root/calib-strip-pad-4889 branch November 17, 2026 19:52
Qubitium added a commit that referenced this pull request Nov 29, 2026
A6/A13 were already realigned on main by #5535 (95c4ad9), which is why
the pretokenized VLM calibration nodes are green today. The realigned
tests cover the leading edge, an interior caller mask, and one qwen3.5
trailing case, but no test asserts the trailing edge or the all-padding
drop across every VLM `prepare_dataset` override.

Add `test_both_edge_pads_are_stripped_and_all_pad_rows_dropped` over the
same introspection-discovered definition set. It asserts that a trailing
tokenizer pad run is stripped, an interior mask zero survives verbatim,
and an all-padding row is dropped instead of reaching the looper. With
the strip disabled the new node fails 37/37, so it guards the #4946
contract rather than restating the shape oracle.
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