Skip to content

[QUALITY] ParoQuant trains each module on its first calibration batch only whenever per-batch row counts differ: _layer_input_features torch.cat(dim=0) RuntimeError -> tensors[0] fallback (every routed MoE expert; dense layers with one short row, 133 of 2112 rows; #5175 hides it only for uniform dense batches) #5198

Closed

Description

@Qubitium

Found on main @ 396b5f0, RTX 4090 (CUDA 13.2, torch 2.15, transformers 5.22).

What is wrong

ParoProcessor._layer_input_features (gptqmodel/looper/paro_processor.py:423-427) joins the per-batch captures of a module like this:

try:
    features[name] = torch.cat(tensors, dim=0)
except RuntimeError:
    features[name] = tensors[0]

Each captured tensor is [1, rows_b, hidden] (or [bs, seq_b, hidden]). dim=0 is the batch axis, so the concat only succeeds when every batch has the same row count. When the counts differ, the RuntimeError is swallowed and the module is optimized on the first batch only. All other batches are discarded with no log message.

When does it happen:

  • Routed MoE experts: always. Each expert gets a different number of tokens in every batch. On OLMoE-2L, 384 of 392 modules fall back. An expert that captured 900-4211 rows across 32 batches is trained on 26-133 rows.
  • Dense models, after fix(awq): bound token-row activation capture to sampling budget (#5137) #5175: _record_input_feature (:362-384) now subsamples each batch to per_batch_quota = 2*ceil((train+val)/n_batches) rows (133 for 32 batches, 34 for 128). That makes the shapes equal, so dense layers concatenate correctly as long as every calibration row is longer than the quota. One row shorter than the quota (a short chat turn, a title, a code line) brings back the mixed shapes. Every module of every layer then trains on 133 rows instead of 2112.
  • Before fix(awq): bound token-row activation capture to sampling budget (#5137) #5175 (at 0b1aea0^): dense layers fell back too, because C4 rows have different token lengths. q_proj trained on 654 of 15646 rows. So the fallback is old (it dates from the initial ParoQuant import). fix(awq): bound token-row activation capture to sampling budget (#5137) #5175 hides it for dense layers with uniform long rows only. It does not fix it for experts or for short rows.

The ParoQuant optimizer then takes its opt_train_samples / opt_validation_samples split (default 2048 + 64) out of that one batch. The rotation and the fine-tune are therefore fit on, and validated against, a small and unrepresentative slice. Nothing errors or warns.

Repro

The snippet wraps _layer_input_features to log the captured rows against the rows the optimizer actually gets:

import torch
from gptqmodel import GPTQModel, CalibrationConfig
from gptqmodel.quantization.config import ParoConfig
from gptqmodel.looper import paro_processor as PP

orig = PP.ParoProcessor._layer_input_features
def patched(self, state):
    pre = {n: (self.tasks.get(n) or {}).get("inputs", []) for n in state.modules}
    out = orig(self, state)
    for n, f in out.items():
        t = pre[n]
        print(n, "batches", len(t), "captured_rows", sum(x.reshape(-1, x.shape[-1]).shape[0] for x in t),
              "distinct_shapes", len({tuple(x.shape) for x in t}), "-> used_rows", f.reshape(-1, f.shape[-1]).shape[0] if f.numel() else 0)
    return out
PP.ParoProcessor._layer_input_features = patched

texts = c4_rows[:32]                       # 32 C4 rows of >=1500 chars, cut to 2500 chars
# (b) only: texts[5] = "The quick brown fox jumps over the lazy dog. " * 2
m = GPTQModel.load(model_dir, ParoConfig(bits=4, group_size=128, opt_rotation_epochs=1, opt_finetune_epochs=1), dtype=torch.bfloat16)
m.quantize(CalibrationConfig(dataset=texts))

(a) OLMoE-1B-7B-0924 truncated to 2 layers, HEAD:

self_attn.q_proj          batches 32 captured_rows 4256 distinct_shapes 1  -> used_rows 2112
mlp.experts.0.gate_proj   batches 32 captured_rows 900  distinct_shapes 22 -> used_rows 26
mlp.experts.1.gate_proj   batches 32 captured_rows 1719 distinct_shapes 26 -> used_rows 47
mlp.experts.6.gate_proj   batches 32 captured_rows 4211 distinct_shapes 4  -> used_rows 133
...
384 of 392 modules have mixed shapes; median rows used 71, min 1

(b) Qwen2.5-0.5B-Instruct truncated to 2 layers, HEAD, with one short calibration row:

all-long rows : every module  batches 32 captured_rows 4256 distinct_shapes 1 -> used_rows 2112
one short row : every module  batches 32 captured_rows 4144 distinct_shapes 2 -> used_rows 133

(c) The same model as (a) at 0b1aea0^ (before #5175): all 392 modules fall back, including dense attention (q_proj captured_rows 15646 distinct_shapes 32 -> used_rows 654).

Suggested fix

Flatten before joining, so the batch structure cannot break the concat, and never swallow the error:

rows = [t.reshape(-1, t.shape[-1]) for t in tensors if t.numel()]
features[name] = torch.cat(rows, dim=0).unsqueeze(0) if rows else torch.empty(0)

With routed experts, the per-batch quota in _record_input_feature should also apply to expert modules by their own token count. A fixed 2*ceil(target/n_batches) per batch under-fills an expert that sees few tokens per batch. A per-module reservoir would bound memory without starving rare experts.

Test that should have caught it

tests/test_paro_capture_order.py and the #5175 tests feed equal-shape batches. A CPU unit test that records two batches of different lengths ([1, 5, H], [1, 7, H]) through _record_input_feature and asserts _layer_input_features returns 12 rows (or min(12, train+val)) would fail today.

Severity

High for ParoQuant on MoE models: every routed expert is optimized on one batch, silently. Medium for dense models: since #5175 it happens only when a calibration row is shorter than the per-batch quota, but then every module of every layer drops 94% of its data. Related, but a different root cause: the per-batch linspace in _record_input_feature always picks row 0 (the attention-sink token) of every batch.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-fb5145b84190 finished this issue.

    Pull request: #5234

    Flattening ParoQuant's per-batch captures before concat so mixed row counts stop silently training on the first batch only.

  2. Qubitium commented on Nov 18, 2026

    @Qubitium
    CollaboratorAuthor

    Additional data from a quality sweep on main @ 396b5f0 (RTX 4090 and R9700/ROCm). It measures how much full-model quality the first-batch fallback described here costs on dense models.

    Setup: ParoConfig(bits=4, group_size=128) defaults. 128 C4 rows (each >= 1500 chars, cut to 2500), fp16. Quantize, save, reload with AUTO, then wikitext-2 PPL over 80 x 512 windows.

    Before #5175 (e75181d), every row has a different token length. torch.cat(dim=0) raises and every module trains on batch 0 only. After #5175, each row is subsampled to the same per-batch quota, so the concat succeeds and all 128 batches are used. Bisecting the checkpoint hash gives exactly 0b1aea0: Qwen ROCm hash 4fba3649… at 307b688, 6c9a4f66… at 0b1aea0 and at HEAD.

    model platform PPL e75181d (batch 0 only) PPL 396b5f0 (all batches) change
    Qwen2.5-0.5B-Instruct RTX 4090 19.973 19.905 -0.34%
    Qwen2.5-0.5B-Instruct R9700 (ROCm) 19.943 19.647 -1.49%
    Llama-3.2-1B-Instruct RTX 4090 20.284 19.973 -1.53%
    Llama-3.2-1B-Instruct R9700 (ROCm) 20.253 19.862 -1.93%

    So on dense models the fallback cost 0.3-1.9% PPL, with no warning. The calibration in this sweep has only long rows, so HEAD avoids the fallback here. As this issue says, one calibration row shorter than the per-batch quota (34 rows for 128 batches at the default 2048 + 64 rows) brings back the mixed shapes. Every module then trains on one batch again, and this lost quality comes back. A regression test could assert that Paro PPL on a mixed-length calibration set matches a uniform-length one within noise. Flattening before the concat, as suggested above, removes the dependence on row lengths.

    🤖 Generated with Claude Code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions