Skip to content

fix(torch): compile the packed decode with explicit operands (#5797) - #5955

Merged
Qubitium merged 1 commit into
mainfrom
fix/5797-fusion-compiled-decode
Nov 20, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5797-fusion-compiled-decode

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

TorchLinear.optimize() compiled type(self).dequantize_weight, so Dynamo
traced the module and lifted qweight/qzeros/scales/g_idx into the
compiled graph as L__self___* locals. _FusionGroup._share_operands then
replaced those buffers with views of the combined packed allocation, but the
cached graph still held the pre-fusion tensors. A warmed fused model therefore
kept a full second copy of every fused packed weight alive until a full
torch._dynamo.reset(), through gc.collect() and later fused forwards (#5797).

The fix compiles a new module-level _decode_248_weight(...) that takes every
packed operand and layout constant as an argument. TorchLinear._prepare_248_decode()
stages the eager-only work (cached zero-point/g_idx tables and the range-safe
decode dtype) outside the graph, and _CompiledDequantizeWeight calls the
compiled decoder with the current tensors. The compiled entry now guards on the
tensors it is handed, so replacing a packed buffer retires the original storage
even while an older compilation entry remains cached.

Fixes #5797

What Changed

No API or behavior change for callers. Decode results are bitwise identical to
the eager path, including num_itr > 1, an explicit dtype and training.
Out of scope: AwqTorchLinear and the other kernel classes do not use this
compiled decoder.

Tests

# Red: the new regression on clean origin/main (492641b15)
python -m pytest tests/module_tree/test_llama_fusion.py -k warm_compiled_decode -x -q
# 1 failed  (all 14 fused source qweights stayed alive)

# Green: with this PR (a1670fc65)
python -m pytest tests/module_tree/test_llama_fusion.py -k warm_compiled_decode -x -q
# 1 passed

python -m pytest tests/module_tree/test_llama_fusion.py -q
# 62 passed, 17 skipped

python -m pytest tests/test_torch_compile_fallback.py tests/test_gptq_torch_eval_decode_nan_5606.py \
  tests/test_torch_int8_tail_padding_4483.py tests/test_peft_adalora_training_4974.py \
  tests/test_dynamo_compiling_thread_5427.py tests/test_optimize_no_reference_cycle_4937.py \
  tests/test_quant_linear_release_4847.py -q
# 1 failed, 54 passed, 8 skipped
# test_foreign_compile_does_not_leak_into_eager_thread fails on clean origin/main too.

python -m pytest tests/test_compile_nested_suppression_5224.py tests/test_compile_load_scope_5304.py \
  tests/test_optimize_generate_4669.py tests/test_fp8_compile_scale_key_5687.py \
  tests/test_symmetric_range.py tests/test_forward_dtype_contract.py \
  tests/test_nf12_forward_no_inference_probe_5299.py -q
# 224 passed, 174 skipped

python -m pytest tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation -q
# 48 passed, 111 skipped

python -m pytest tests/module_tree tests/test_model_load_lock_4204.py -q
# 10 failed, 1786 passed, 821 skipped, 3 xfailed
# All 10 failures reproduce on clean origin/main (defuser 0.0.29 < 0.0.31: the
# granitemoe_swa/ernie 3-D expert defusion tests cannot split the fused tensors).

bash format/check.sh
# All checks passed!

Skips are the CUDA/Marlin, TTNN, MLX and Triton-only paths that this CPU host
cannot run; no skipped test covers the changed decode.

Decode parity probe (/tmp/probe_5797_parity.py): compiled vs eager decode is
bitwise equal, an independent reference gives max abs 0.0, and num_itr=2,
dtype=float32 and the training decode all match.

Measured Impact

Host: tt-quietbox, 4x Blackhole p300c, torch==2.11.0+cpu (pinned TT runtime),
CPU-only BACKEND.TORCH, ModelCloud/Opt-125-GPTQ-4bit-10-25-2024, BF16,
12-token batch-1 forward, median of 3 runs on each revision.

Metric (unit) Before (492641b15) After (a1670fc65) Change
Fused source projections still holding the pre-fusion qweight 36 of 36 0 of 36 −36
Retained pre-fusion qweight after fuse() + gc.collect() (MiB) 10.12 0.00 −10.12
12-token forward latency (ms) 31.0 24.3 −6.7 (−21.6%)
12-token forward throughput (tok/s) 387.2 493.7 +27.5%
Greedy token ids vs pre-fusion match match unchanged
Max abs logit delta vs pre-fusion (BF16) 0.125 0.125 unchanged

Commands:

python /tmp/model_5822.py torch     # 12-token forward, 3 runs per revision
python /tmp/measure_5797_bytes.py   # weakrefs captured before fuse()

VRAM itself is not measurable on this CPU host; the memory row is the retained
packed CPU storage, which is the same allocation that would stay resident on an
accelerator. The 0.125 logit delta is the existing fused-vs-unfused BF16
accumulation difference: it is identical before and after this PR, so this
change adds no accuracy drift.

Model Support / Module Plan

Not applicable: no model definitions, aliases, registry entries or fusion
eligibility change.

AWQ onboarding safety

Not applicable: no model, definition or AWQ changes.

Logic Flow Documentation

Not applicable: local fix. The decode entry points, dispatch order and fallbacks
are unchanged; only the compiled entry's operand passing and ownership changed,
inside _decode_248_weight and _CompiledDequantizeWeight.

Old: optimize() compiled the bound dequantize_weight(module, ...); Dynamo
lifted module.qweight/qzeros/scales into the graph
(torch.py:475-481 at 85caf6cc5).

New: optimize() compiles _decode_248_weight(operands...); the wrapper reads
the current tensors from the weak module reference and passes them explicitly.

Review Requirements

  • Reviewed this PR.
  • Checked that the code matches existing project structure, APIs, and conventions.
  • Avoided unnecessary monkeypatching and used the project's normal extension points where possible.
  • Minimized and compacted the impacted code surface.
  • Considered and eliminated potential regressions.

Kernel Accuracy Requirements

  • Accuracy drift measured against the eager decode (bitwise equal) and an independent Torch reference (max abs 0.0); model-level fused logits match the pre-fusion logits with identical greedy tokens and the same 0.125 BF16 delta before and after.
  • Fusion support changes preserve AUTO's native class — not applicable: no fusion kernel, planner or eligibility change.
  • Complete kernel inventory/device report — not applicable: no kernel inventory change; skips listed above.

Notes

  • #5797 is claimed by agent-83ff5bec0c7b; release follows this PR URL.
  • The fused packed allocation is still a persistent quantized representation;
    this PR only removes the duplicate pre-fusion packed storage.

`TorchLinear.optimize()` compiled `type(self).dequantize_weight`, so dynamo
traced the module and lifted `qweight`/`qzeros`/`scales` into the compiled
graph.  Fusion then replaced those buffers with views of the combined packed
allocation, but the cached graph still held the pre-fusion tensors, so a
warmed fused model kept a second copy of every packed weight alive until a
full `torch._dynamo.reset()`.

Compile a new `_decode_248_weight` that takes the packed operands and the
layout constants as arguments instead.  `_prepare_248_decode` stages the
eager-only work (zero-point/g_idx caches and the range-safe decode dtype) and
returns the operands, and the compiled wrapper routes training, non-2/4/8-bit
and Triton-eligible calls back to the eager class method.  The compiled entry
now guards on the tensors it is handed, so replacing a packed buffer retires
the original storage even while an older compilation entry remains cached.

Decode parity is unchanged (bitwise equal to the eager path, including
`num_itr > 1`, an explicit dtype and training), and the decode is faster
because the staged caches no longer run inside the graph.

Add a post-warm-up fusion regression test: a warm compiled decode, then
`fuse()`, then `gc.collect()`, must release every source `qweight` while the
fused logits stay within tolerance.
@Qubitium
Qubitium marked this pull request as ready for review November 20, 2026 18:59
@Qubitium
Qubitium merged commit 376f036 into main Nov 20, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5797-fusion-compiled-decode branch November 20, 2026 19:20
Qubitium added a commit that referenced this pull request Nov 29, 2026
…5325) (#6273)

A5 was a product defect, not a stale test: a meta move ran the int4pack
inverse (and its aten::equal identity check) against meta operands until
#5533 materialized the snapshot from its shape/dtype descriptor. A14 was
realigned by #5564, and the compiled entry now stages its operands outside
the traced graph (#5955), so the caches are published again. Both items are
green at main 2d3261d.

Extend the device-move test to assert every checkpoint operand's shape and
dtype is restored, not just qweight. Restore the cache expectations the A14
tests are named for: the compiled dequant publishes the g_idx cache on the
compute device, load_state_dict clears both metadata caches, and a full
forward still matches F.linear after the g_idx offload.

Co-authored-by: OpenAI Agent <[email protected]>
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.

[Audit][fusion] Compiled TorchLinear keeps original packed weights after fusion on the pinned TT Torch runtime

1 participant