Skip to content

fix(awq): bound token-row activation capture to sampling budget (#5137) - #5175

Merged
Qubitium merged 3 commits into
ModelCloud:mainfrom
Prajwal7-2002:fix/awq-token-rows-streaming-reservoir-5137
Nov 18, 2026
Merged

Qubitium merged 3 commits into
ModelCloud:mainfrom
Prajwal7-2002:fix/awq-token-rows-streaming-reservoir-5137

Conversation

@Prajwal7-2002

Copy link
Copy Markdown
Contributor

Summary

Resolves #5137.

Under token_rows aggregation, AWQ previously copied every calibration token of every module to host memory in _record_input_feature, retaining all raw activations until _layer_input_features executed _pack_token_rows and discarded ~98-99% of rows after the layer forward finished. For large calibration datasets (512+ docs) or wide MoE architectures (e.g., OLMoE-2L with 64 experts $\times$ 3 linears = 192 modules, especially under ExpertsRoutingOverride), peak host RAM scaled linearly with calibration size (growing from 6.4 to 17.8 GiB for 128 $\to$ 512 docs, and spiking to 28 GiB/layer) even though retained rows remained capped at 906. ParoProcessor exhibited the same unbounded host accumulation pattern before post-forward downsampling.

Root Cause

  1. AWQ Capture Accumulation: _record_input_feature appended raw activation slices into entry["inputs"] across all batches without bounds.
  2. Provenance & Mask Rebuilding Invariant: _token_row_source_structure and _kept_row_grid_positions validate that row_count == flat_keep.sum().item() (the unpadded token count of that calibration batch). Naively downsampling at capture time without tracking original batch lengths broke block-diagonal attention mask and position ID reconstruction.
  3. Paro Accumulation: ParoProcessor._record_input_feature stored all raw tokens on host memory and concatenated them before optimize_paro_linear sampled train_rows + val_rows rows.

Fix

  1. Precomputed Quota & Sampling Plan:
    • In AWQProcessor, _token_row_plan_for_module computes a deterministic sampling plan from inputs_cache unpadded batch lengths when known up front (dense modules, MoE roots, and experts under ExpertsRoutingOverride).
    • _compute_token_row_quotas matches the deterministic quota allocation and exact local row selection of _pack_token_rows bit-for-bit.
    • Slices are downsampled to their batch quotas immediately in _record_input_feature, bounding host memory during capture.
  2. Streaming Reservoir for Dynamic MoE:
    • For dynamically routed MoE experts or cache-less setups where batch token counts vary dynamically, a deterministic streaming reservoir in _record_input_feature bounds accumulated rows to budget_cap across all batches.
  3. Provenance & Original Batch Length Tracking:
    • Recorded entry["batch_row_counts"] tracks original unpadded batch lengths, which are passed to _token_row_replay_kwargs and _pack_token_aligned_kwargs.
    • Block-diagonal causal attention masks and rotary position IDs are reconstructed with 100% fidelity.
  4. Sibling Sharing:
    • Sibling modules (q_proj, k_proj, v_proj and gate_proj, up_proj) share the same sampled host tensor objects via _capture_sampled_cache and cat_cache.
  5. ParoQuant Bounded Capture:
    • In ParoProcessor._record_input_feature, activations are bounded per-batch to per_batch_quota = max(1, 2 * (target_rows + batch_count - 1) // max(1, batch_count)) where target_rows = opt_train_samples + opt_validation_samples.
    • In _layer_input_features, concatenated activations are downsampled to target_rows using _sample_activation_rows.

Verification

  • Unit Tests:
    • tests/test_awq_token_rows_bounded_capture_5137.py (all 5 passed):
      • Peak host tokens in entry["inputs"] stay strictly bounded by the sampling budget (256 rows vs 16,384 raw tokens across 32 batches).
      • Sibling projection host tensor sharing (q is k is v).
      • Block-diagonal causal mask and position ID reconstruction fidelity.
      • Dynamic streaming reservoir bounds token accumulation for routed MoE experts ($\le 100$ rows across 2,500 tokens).
      • ParoQuant bounded capture and layer downsampling.
    • tests/test_awq_scale_search_memory.py and tests/test_awq_weight_mean.py (100 passed, 1 skipped).
    • tests/test_paro_capture_order.py and tests/test_paro_rotation_pairs.py (6 passed).
  • Linting:
    • ruff check passed with zero errors across all modified and new files.

…lCloud#5137)

AWQ feature capture copied every calibration token of every module to host RAM,
retaining every batch's full activation until _layer_input_features collapsed and
downsampled ~1% of rows after the layer forward completed. For large calibration
sets or wide MoE architectures (e.g. OLMoE-2L with 64 experts x 3 linears = 192
modules), host RAM scaled linearly with calibration corpus size, growing from 6.4
to 17.8 GiB for 128 -> 512 docs and reaching 28 GiB/layer under
ExpertsRoutingOverride while retained rows remained capped at 906. ParoQuant
similarly accumulated unbounded batch activations before post-forward downsampling.

Precompute a deterministic token-row quota and sampling plan from inputs_cache
lengths when batch sizes are known upfront (dense modules, MoE roots, and experts
under routing override), and bound captured activations immediately in
_record_input_feature. For dynamically routed MoE experts, maintain a streaming
reservoir bounded by the token budget. Original unpadded batch lengths are
recorded in batch_row_counts so _token_row_source_structure and
_kept_row_grid_positions reconstruct block-diagonal causal attention masks and
position IDs with 100% fidelity. Sibling module sharing (q/k/v and gate/up) is
preserved across host materialization. In ParoProcessor, bound per-batch capture
to per_batch_quota and layer features to target_rows.

Refs ModelCloud#5137

Signed-off-by: Prajwal7-2002 <[email protected]>
Capture hooks can complete in device/runtime order, but
`_layer_input_features` replays tensors in calibration-batch order.
Provenance recorded the calibration batch id as its source slot while the
tensors were reordered, so the rebuilt mask and position ids described a
different batch than the rows they accompanied. Record capture-slot indices
and permute `batch_row_counts` and `provenance` alongside the tensors.

Also:
- Guard the streaming reservoir against a one-row budget (`M == 1`), which
  divided by `M - 1`.
- Memoize the per-layer batch-length scan so token-row plan lookup stays
  linear instead of quadratic in the calibration batch count.

Adds regression tests for each case.
@Qubitium

Copy link
Copy Markdown
Collaborator

Maintainer review: the bounded-capture design and quota math look right, and I verified a real 16-doc AWQ run keeps the same state_dict/logits as the pre-fix head. I pushed 09fe390b with three fixes found during review:

  1. Out-of-order provenance was misaligned. Capture hooks can complete in device/runtime order while _layer_input_features replays tensors in calibration-batch order. Provenance recorded the calibration batch id as its source slot, and batch_row_counts/provenance were not permuted with the tensors, so the rebuilt mask and position ids described a different batch than the rows they accompanied. Now provenance records the capture slot and both metadata lists are permuted with the tensors.
  2. M == 1 reservoir division. A one-row budget divided by M - 1 and raised ZeroDivisionError.
  3. Quadratic plan lookup. _extract_cache_batch_lengths scanned every batch on every capture; it is now memoized per layer-input identity (4.9 ms -> 0.05 ms at 512 batches).

Added four regression tests covering out-of-order exact and sampled rows, the single-row reservoir, and memo invalidation. Full format/check.sh and 114 related AWQ/Paro tests pass.

@Prajwal7-2002

Copy link
Copy Markdown
Contributor Author

Thanks @Qubitium for the review and the polish on out-of-order provenance permutation and memoization! Glad the bounded-capture design and quota math verified cleanly.

`_pack_token_rows` filters zero-row captures before allocating quotas, but
`_compute_token_row_quotas` counted them in `batch_count`. That let an empty
batch consume budget (or be selected for a zero-row index), diverging from the
legacy selection and risking an out-of-range index. Allocate over non-empty
batches only, matching the base implementation for every input shape.

Verified against the base `_pack_token_rows` over 118 length/budget cases:
all non-empty cases are bit-identical, and empty-batch cases now match too.
@Qubitium
Qubitium merged commit 0b1aea0 into ModelCloud:main Nov 18, 2026
1 check passed
Qubitium added a commit that referenced this pull request Nov 18, 2026
) (#5212)

#5175 bounded routed-expert capture by resampling the kept buffer evenly
together with each new batch. That is not a reservoir: once the buffer is
full, the `budget_cap` kept rows -- which stand for every earlier batch --
weigh the same as the fresh batch, so each new batch replaces about
`L / (cap + L)` of the sample and the surviving share decays geometrically.

On a 128-document calibration set this put 70-87% of every routed expert's
rows in the last quarter of the batches and left the first quarter at 1-5%,
so AWQ picked each expert's scales and clip ranges on a sample dominated by
the tail of the corpus. Dense modules and MoE roots were unaffected because
they match the precomputed plan.

Keep the `budget_cap` rows with the lowest deterministic uniform priority
instead. That is the deterministic equivalent of Algorithm R: a uniform
sample of every row seen, so a batch keeps a share proportional to its
length wherever it falls in the stream. Memory stays O(cap) and the sample
is reproducible across processes. Survivors are re-sorted into capture
order so replayed rows and provenance stay grouped.

Adds a regression test asserting every quarter of the calibration stream
keeps 15-35% of the rows (raw share 25%). It fails on the pre-fix tree
(quarter 0 kept 1.3%).
Qubitium added a commit that referenced this pull request Nov 18, 2026
…lan (#5215) (#5220)

#5175 moved token-row sampling from replay (AWQProcessor._pack_token_rows)
to capture (_token_row_plan_for_module), so the #5085 regression test's spy
was never called and its two integration tests were red on main while the
cap itself had no working guard.

Spy on the plan that now decides the replay length and assert
plan.max_tokens and sum(plan.quotas) stay within max_position_embeddings;
the batch-of-two case also proves the cap fires (uncapped budget 80 > 64).
The batch-of-one control now uses a single document so it asserts that every
row is kept, and a direct unit test keeps the legacy packer's cap covered.
This was referenced Nov 18, 2026
Qubitium added a commit that referenced this pull request Nov 18, 2026
…#5279)

#5175 made every Paro module replay its full row budget, which restored the
accuracy the pre-#5175 first-batch fallback had lost but multiplied the step
count. The stage loop is launch-bound: each step issues ~40 host launches over
a weight-sized tensor, so wall time tracks the number of steps, and the number
of steps is ceil(train_rows / opt_batch_size) per epoch.

Raise the default opt_batch_size from 64 to 128, so the 2048-row budget is
replayed in 16 steps per epoch instead of 32. Every row is still visited
exactly once per epoch (_chunk_rows slices contiguously and its chunks
concatenate back to the sampled order), so this trades no calibration data for
the lower launch count.

Measured on Qwen2.5-0.5B-Instruct (128 C4 docs, 10+10 epochs, wikitext-2 PPL),
both runs back-to-back on one RTX 4090:
  bs=64  171.9 s  PPL 20.0788
  bs=128 108.2 s  PPL 19.9411   -> 1.59x faster, PPL not worse

Adds two coverage guards for the invariant the speedup relies on: the chunker
reproduces the row budget exactly, and a stage runs one step per chunk.
Qubitium added a commit that referenced this pull request Nov 19, 2026
…) (#5327)

#5295 memoized the capture policy and skipped merges that cannot enter, but
two costs remained on the routed-expert path:

* every routed expert kept the layer-wide plan budget (906 rows on OLMoE)
  instead of the pre-#5175 per-expert rule (max(largest capture, captures);
  mean 254, median 203), so the clip search and the replay forward ran on
  ~3.6x the rows. The reservoir still keeps the lowest priorities, so the
  kept set stays a uniform sample of the stream.
* a growing budget re-seeded from ``inputs``, which cannot work because
  provenance is materialized only at replay, so growth silently dropped every
  kept row. Carry the rows the buffer already holds.
* the merge concatenated the kept priorities with the capture and wrote every
  surviving captured row into a slot. Select the drop set from the
  ``overflow`` largest kept priorities plus the capture and write only the
  surviving captured rows.

Accuracy on full 16-layer OLMoE-1B-7B (128 C4 docs, batch_size=1, RTX 4090):
PPL 11.2870 with the layer-wide cap vs 11.2814 with the per-expert rule, i.e.
no measurable loss, and quantize 655-690 s -> 490 s (measured with the rule
monkeypatched on main). On a 7-layer truncation the whole change is
997 s -> 541 s.

Tests: tests/test_awq_moe_quant_speed_5284.py (6, CPU-only).
Qubitium added a commit that referenced this pull request Nov 19, 2026
…#5356)

#5279 raised ParoConfig.opt_batch_size from 64 to 128 for speed, which halved
the optimizer steps per epoch at a fixed LR. On Llama-3.2-1B-Instruct that
cost 2.2% wikitext-2 PPL on the benchmark harness, giving back most of the
accuracy #5175 had recovered.

Scale the three stage LRs from the 64-row reference, so an opt-in larger step
still moves proportionally further per epoch, and put the default back on the
accuracy-tuned 64 rows.

Measured on Llama-3.2-1B-Instruct (Paro 4-bit g128 fp16, 128 C4 docs,
quantize -> save -> reload -> wikitext-2, 80x512):

  bs=64, 1x LR       20.0401  (reference)
  bs=128, 1x LR      20.4726  (+2.16%)
  bs=128, 2x LR      20.1953  (+0.77%)
  bs=128, 3x LR      20.1274  (+0.44%)
  bs=128, 4x LR      20.3361  (+1.48%)

Linear LR scaling recovers most of the loss but not all of it: the remaining
gap is the coarser best-state selection at half the validation checkpoints,
which no LR can fix. The default therefore stays at 64, and the scaling keeps
opt-in larger batches close to it.

tests/test_paro.py: 249 passed. tests/test_paro_batch_lr_5306.py: 5 new tests.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants