Skip to content

fix(rotation): validate the calibration data before rotating the model (#4935) - #4977

Merged
Qubitium merged 1 commit into
mainfrom
root/rotation-validate-first-4935
Nov 17, 2026
Merged

Qubitium merged 1 commit into
mainfrom
root/rotation-validate-first-4935

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 17, 2026 •

Copy link
Copy Markdown
Collaborator

TL;DR

quantize() with rotation="hadamard" fused the layer norms and rotated the
weights before it validated the calibration data, so every calibration-data
error was raised on an already-mutated model and a retry rotated it a second
time (#4935). The calibration input is now prepared and validated before
fuse_layer_norms/rotate_model, and the exact batches are reused by the
processors. Net: +132/-24 in gptqmodel/models/base.py, one new 8-test
regression file, no API change, successful-run checkpoint bit-identical.

1. The problem

Old order on main (c9c2d7e / 1addb9c):

flowchart TD
    A["quantize(calibration)"] --> B["fuse_layer_norms (base.py:2533)"]
    B --> C["rotate_model (base.py:2546)"]
    C --> D["QuantizationRunPlan.build (base.py:2552)<br/>+ checkpoint gate"]
    D --> E{"calibration.dataset is None"}
    E -->|"yes"| X["ValueError (base.py:2604)<br/>model already fused and rotated"]
    E -->|"no"| F["LoopProcessor.__init__<br/>empty checks (loop_processor.py:562, :591)"]
    F -->|"empty / all rows dropped / bad row"| Y["ValueError<br/>model already fused and rotated"]
    F -->|"ok"| G["prepare_dataset per processor<br/>then quantize"]
    G --> H["_setup_rotation_online_had<br/>only on success"]
    style X fill:#fde2e1,stroke:#dc2626
    style Y fill:#fde2e1,stroke:#dc2626
Loading
Removed mechanism Where it lived on main
Rotation mutation before calibration validation base.py:2533 (fuse_layer_norms), base.py:2546 (rotate_model)
dataset is None check base.py:2604, after the mutation
Empty input / empty-after-min_length checks loop_processor.py:562, loop_processor.py:591, after the mutation
Run plan + checkpoint gate base.py:2552, after the mutation
Online Hadamard install _setup_rotation_online_had, success path only

Consequence (measured, see §8): after a failed call the embedding is rotated but
the down_proj online Hadamard is absent; a retry fuses/rotates again and
quantizes 16/40 state tensors differently from a first-time run, with
down_proj.qweight 100% different and embed_tokens.weight 98.4% different.

2. The new flow

flowchart TD
    A["quantize(calibration)"] --> B["validate_rotation_format /<br/>validate_rotation_model_support /<br/>validate_rotation_dimensions (base.py:2504)"]
    B --> R["QuantizationRunPlan.build (base.py:2579)<br/>+ checkpoint gate"]
    R -->|"unsupported chain"| E1["NotImplementedError<br/>no weights modified"]
    R --> P["_prepare_calibration_before_rotation (base.py:2603)"]
    P -->|"dataset is None"| E2["ValueError (base.py:2994)"]
    P -->|"empty input / bad row / all rows dropped"| E3["ValueError (base.py:3001, :3013)"]
    P -->|"prepared batches"| F["fuse_layer_norms (base.py:2627)"]
    F --> G["rotate_model (base.py:2640)"]
    G --> H["_quantize_with_calibration (base.py:3021)<br/>binds _already_prepared_calibration_dataset (base.py:863)"]
    H --> I["_setup_rotation_online_had"]
    style E1 fill:#fde2e1;stroke:#dc2626
    style E2 fill:#fde2e1;stroke:#dc2626
    style E3 fill:#fde2e1;stroke:#dc2626
Loading

_prepare_calibration_before_rotation applies exactly the checks
LoopProcessor.__init__ applies — dataset is None (only for a calibrated
run plan), an empty sized input, and an empty prepared dataset after the
min_length filter — plus the model's own prepare_dataset, so unsupported
rows also fail before the mutation. It returns the prepared batches;
_quantize_with_calibration passes them on and binds
_already_prepared_calibration_dataset so the processors reuse them instead of
tokenizing the corpus twice (same one-preparation precedent as #4307).
Non-rotation runs keep self.prepare_dataset and weight-only run plans
(run_plan.weight_only, e.g. RTN) prepare no calibration rows.

3. Change inventory

File +/- Purpose
gptqmodel/models/base.py +132 / -24 prepare+validate calibration before the mutation; run plan/checkpoint gate moved up; _already_prepared_calibration_dataset no-op preparer
tests/test_rotation_validate_first_4935.py +192 new regression: unchanged model after each failure, retry == first run
docs/rotation-model-support.md +47 / -1 flow diagram + "Calibration validation" section + failure-contract rows
.github/workflows/awq_cpu.yml +1 run the regression file in the AWQ CPU unit suite

4. Failure contract

Situation Before After
rotation + CalibrationConfig() (dataset=None) rotated, then ValueError ValueError before mutation
rotation + dataset=[] rotated, then ValueError ValueError before mutation
every row at/under min_length rotated, then ValueError ValueError before mutation
unsupported calibration row type rotated, then ValueError ValueError before mutation
unsupported checkpoint chain rotated, then NotImplementedError NotImplementedError before mutation
retry after any of the above fuses/rotates twice, silently identical to a first-time run
rotation=None / weight-only configs unchanged unchanged (no preparation)

Error messages are unchanged, so callers that match on them keep working.

5. Tests / guarantees

tests/test_rotation_validate_first_4935.py (8 tests, CPU, one-layer fp32
Llama, hidden_size=32, intermediate_size=64, GPTQConfig(bits=4, group_size=32, desc_act=False, rotation="hadamard")):

Test Invariant
test_failed_calibration_leaves_the_model_bitwise_unchanged[missing_dataset] embedding, layers[0].mlp.down_proj.weight, logits bitwise equal
...[empty_dataset] same
...[all_rows_too_short] same
...[unsupported_row_type] same
test_retry_after_a_failed_call_matches_a_first_time_run[...] (x4) failed call + valid retry state_dict bytes == first-time valid run

Red on unmodified origin/main (c9c2d7e), test file copied into
/root/worktrees/root-4935-base:

tests/test_rotation_validate_first_4935.py -> 8 failed, 2 warnings in 13.66s
  E AssertionError: the failed call rotated the input embedding
  E AssertionError: a failed call followed by a valid retry quantized a different
    (double-rotated) checkpoint than a first-time valid run

Green with the fix: 8 passed in 13.09s.

6. Measured before/after

Same model, dataset=None, fp32, CUDA_VISIBLE_DEVICES="":

Step main With this fix
Failed call changes the input embedding yes no
FP logits max abs diff after the failed call 0.0391 0.0000
Failed call + valid retry vs a first-time run 16/40 state tensors differ 0/40
model.layers.0.mlp.down_proj.qweight 100% of elements differ identical
model.embed_tokens.weight 98.4% of elements differ identical

Happy path is bit-identical: torch.save(state_dict()) of a successful
rotation="hadamard" run has sha256 88bedb0c…c5273 on both main and this
branch; rotation=None has sha256 3ed7af52…4838d on both.

7. Validation

# required selection, fixed worktree
tests/test_rotation_*.py tests/test_quantize*.py tests/test_calibration*.py \
  tests/test_rotation_validate_first_4935.py
-> 466 passed, 30 skipped, 2 failed in 539s
   both failures are tests/test_calibration_data_device.py
   (test_stage_capture_balanced_mode_empty_filter_fallback,
    test_balanced_mode_fallback_when_input_device_not_in_forward_devices)
   and fail identically on unmodified main on this CPU host
   (2 failed, 16 passed, 4 skipped) -> pre-existing, no delta.

tests/test_rotation_*.py tests/test_rotation_validate_first_4935.py \
  tests/test_prepare_dataset.py tests/test_calibration_config.py
-> 145 passed, 4 skipped

tests/test_docs_contract_refs.py -> same 4 pre-existing line-citation failures
  as unmodified main (no delta)

ruff check gptqmodel/models/base.py tests/test_rotation_validate_first_4935.py
-> All checks passed!

CI: AWQ CPU (unit/dense/moe), ruff-check and CodeQL all pass; the new file is
in the AWQ CPU unit list so the regression runs on every gptqmodel/models/**
change.

8. Model Support / Module Plan

Not applicable: no model definition, MODEL_MAP entry, module plan or fusion
config changed.

9. Logic Flow Documentation

docs/rotation-model-support.md (already linked from README.md) now carries
the new-flow Mermaid diagram, the calibration-validation section, the
before/after table above, and four new rows in its failure contract.

10. Reviewer notes

  • quantize() still tokenizes a rotation run's corpus exactly once; the
    prepared batches are shared with the native/EoRA processors.
  • The processor's "dataset size should be more than 256" warning now reports
    the prepared row count for rotation runs (raw count for every other path),
    because preparation happens first. Warning only.
  • Out of scope: calling quantize() again on an object that was already
    successfully quantized (a lifecycle question, not a refused-run one).

Closes #4935.

@Qubitium
Qubitium force-pushed the root/rotation-validate-first-4935 branch from 275e6a5 to d772c79 Compare November 17, 2026 20:41
#4935)

quantize() untied the embeddings, fused the layer norms and rotated the
weights before it validated the calibration input. Every calibration-data
error (dataset None, an empty dataset, every row at/under min_length, an
unsupported row type) was therefore raised on an already-rotated model, and
the online Hadamard a rotated down_proj needs is only installed at the end
of a successful run. A retry on the same object fused and rotated it a
second time and silently quantized from that state (#4935).

Prepare the calibration input once, before fuse_layer_norms/rotate_model,
with the same checks LoopProcessor.__init__ applies, and hand those batches
to the processors through _already_prepared_calibration_dataset so the
corpus is tokenized once instead of twice. QuantizationRunPlan.build and the
checkpoint gate move up with it, so an unsupported chain cannot leave a
rotated model either. Weight-only configs and rotation=None are untouched;
a successful run produces a bit-identical checkpoint.

tests/test_rotation_validate_first_4935.py pins the contract: after each
failure mode the embedding, a decoder weight and the logits are bitwise
unchanged, and a failed call followed by a valid retry matches a first-time
run byte for byte.
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