Skip to content

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

Closed

Description

@Qubitium

Impact

On 85caf6cc5 with the repository's pinned Tenstorrent torch==2.11.0+cpu, a warmed TorchLinear keeps its original packed weight alive after projection fusion creates a combined packed allocation. This is still observable after explicit gc.collect() and another fused forward. Installing the same fusion on TorchLinear(compile=False) releases both original weights. The extra live bytes are packed checkpoint weights, so both original and fused packed storage coexist.

TorchLinear.optimize() compiles the unbound method and passes the module to the callable. _FusionGroup._share_operands replaces its buffers with views of the fused allocation. The warmed compiled path still owns the original tensor through a reachable dict with key L__self___qweight. Resetting Dynamo in the test and collecting garbage releases it. #4969 described a similar failure that cleared with GC on Torch 2.15/2.16. This case persists through GC on Torch 2.11. On PyTorch 2.15.0+cpu, the standalone probe released both originals after collection, with compilation enabled or disabled. Accelerator memory remains unmeasured.

Reproduction

On CPU with Inductor available, the existing suite fails the original packed allocation check for gate/up, GQA QKV and MHA QKV across FP16 and BF16. The other 49 selected CPU fusion checks passed. The precise gate/up node is:

OMP_NUM_THREADS=1 OPENBLAS_NUM_THREADS=1 PYTHONPATH=. python -m pytest -q -rs \
  'tests/module_tree/test_fusion_kernel_backends.py::test_native_fusion_shapes_oracle_ownership_and_invalidation[gate_up-cpu-TorchLinear-torch.float16]'

Run in the configured Tenstorrent CPU profile. The smaller standalone probe uses two 128 × 128 4-bit projections. Both original 8192-byte allocations survive after fusion and fused-forward parity checks with compilation enabled. Both are released in the compile-disabled control.

import gc
import weakref

import torch
from transformers import LlamaConfig, LlamaForCausalLM

from gptqmodel.models.fusion import FusionDecision, _FusionGroup
from gptqmodel.nn_modules.qlinear.torch import TorchLinear
from gptqmodel.quantization import FORMAT


def survivors(refs):
    return [ref() is not None for ref in refs]


def report_owners(ref):
    if ref() is None:
        return
    for owner in gc.get_referrers(ref()):
        if isinstance(owner, dict):
            print('direct ref dict keys', [key for key, val in owner.items() if val is ref()])
            print('dict referrer types', [type(unit).__name__ for unit in gc.get_referrers(owner)])
        else:
            print('direct ref type', type(owner).__name__)


def exercise(compile_dequant):
    config = LlamaConfig(hidden_size=128, intermediate_size=128, num_hidden_layers=1,
                         num_attention_heads=4, num_key_value_heads=4, vocab_size=64)
    model = LlamaForCausalLM(config).half().eval()
    parent = model.model.layers[0].mlp
    projections = []
    for name in ('gate_proj', 'up_proj'):
        module = TorchLinear(bits=4, group_size=32, in_features=128, out_features=128,
                             sym=True, desc_act=False, bias=False, format=FORMAT.GPTQ_V2,
                             compile=compile_dequant)
        module.qweight.random_(-(2 ** 31), 2 ** 31)
        module.qzeros.fill_(-2004318072)
        module.scales.fill_(1 / 64)
        module.eval()
        module.post_init()
        setattr(parent, name, module)
        projections.append(module)
    x = torch.randn(1, 8, 128, dtype=torch.float16)
    with torch.inference_mode():
        expected = parent(x)
    refs = [weakref.ref(module.qweight) for module in projections]
    per_projection = projections[0].qweight.untyped_storage().nbytes()
    group = _FusionGroup(FusionDecision('gate_up', 'mlp', ('mlp.gate_proj', 'mlp.up_proj')),
                         parent, projections, activation_dtype=torch.float16)
    try:
        group.install()
        gc.collect()
        before = survivors(refs)
        print('compile', compile_dequant, 'after install + GC:', before,
              'packed bytes per original:', per_projection)
        report_owners(refs[0])
        with torch.inference_mode():
            torch.testing.assert_close(parent(x), expected, rtol=2e-3, atol=2e-3)
        gc.collect()
        print('after fused forward + GC:', survivors(refs))
        torch._dynamo.reset()
        gc.collect()
        print('after Dynamo reset + GC:', survivors(refs))
    finally:
        group.remove()


if __name__ == '__main__':
    torch.set_num_threads(1)
    torch.manual_seed(17)
    exercise(False)
    exercise(True)

Candidate fix

Make the compiled tensor decoder take packed operands as explicit tensor arguments and retain only immutable decode layout metadata. The wrapper would call it with the current qweight, qzeros, scales, and g_idx, so replacing a packed buffer can retire its original storage even if an older compilation entry remains cached. Add a post-warm-up fusion test covering both lifetime and numerical parity, then a mutation and unfuse test to exercise the new views.

Activity

  1. added
    scanned
    safe
    on Nov 20, 2026
  2. Qubitium commented on Nov 20, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-4e3a0639ecaf is working on this issue now.

    Started 2026-11-20T12:47:01Z. The claim expires 4.0h after this comment was last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    Stopping a fused compiled TorchLinear from retaining the original packed weight; validating on Ada

  3. Qubitium commented on Nov 20, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim released: agent-83ff5bec0c7b finished this issue.

    Pull request: #5955

    Compiling the packed 2/4/8-bit decode with explicit operands so a warmed fused TorchLinear releases the pre-fusion buffers; validating lifetime, parity and decode speed on the pinned TT torch 2.11 CPU profile

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

    performancesafescanned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions