Skip to content

[BUG] #5447 (fix of #5392) regression: concurrent eval-mode grad + no-grad forwards now crash the CPU int4pack kernels (layout flips every call outside _cpu_transform_lock); TorchAten(Awq)Linear left permanently broken #5509

Closed

Description

@Qubitium

Found on main @ c2e23c4, CPU (x86 AVX512, torch 2.15 + transformers 5.23; also seen on the free-threaded 3.14t build).

What is wrong

#5447 (fix of #5392) stopped eval-mode grad forwards from latching linear_mode="train". That fixes the slowdown, but the CPU int4pack kernels now flip their weight layout on every eval-mode grad / no-grad pair: a grad forward calls restore_fused_train_state(self) (checkpoint layout back, fused buffers dropped) and the next no-grad forward calls self.transform(...) again.

Only that decision is under _cpu_transform_lock (torch_aten_kernel.py:503-537, torch_fused.py:669-701, and the AWQ / AVX512 siblings). The matmul that follows (_fused_op_forward(x) or dequantize_weight()) runs outside the lock and reads qweight/qzeros/scales. While one thread computes, another thread's grad forward restores the layout, or its no-grad forward transforms it. Before #5447 this transition happened at most twice per module and then latched. Now it happens on every call, so concurrent eval-mode grad and no-grad forwards on the same model crash. On TorchAtenLinear and TorchAtenAwqLinear the module can also be left permanently broken.

Scenario: a model in eval() serving torch.no_grad() generation on one thread while another thread computes input gradients (saliency, attribution, adversarial probes) on the same model. _cpu_transform_lock and test_cpu_lazy_transform_concurrency_4565.py show that concurrent forwards are meant to be safe.

Repro (layer level, uses the fixtures from the existing #5314 test)

import threading, time, torch
from tests import test_cpu_trainable_kernels_grad_after_inference_5314 as T
for name, mk in T.BUILDERS:
    layer = mk(); layer.eval()
    xs = [torch.randn(4, T.IN_FEATURES, dtype=torch.bfloat16) for _ in range(8)]
    with torch.no_grad(): [layer(x) for x in xs]
    exc = []; stop = time.time() + 10
    def worker(grad):
        i = 0
        while time.time() < stop:
            x = xs[i % 8]; i += 1
            try:
                if grad:
                    xx = x.clone().requires_grad_(True); layer(xx).float().sum().backward()
                else:
                    with torch.no_grad(): layer(x)
            except Exception as e: exc.append(repr(e)[:100])
    ts = [threading.Thread(target=worker, args=(g,)) for g in (False, False, True, True)]
    [t.start() for t in ts]; [t.join() for t in ts]
    try:
        with torch.no_grad(): layer(xs[0]); post = "ok"
    except Exception as e: post = "BROKEN: " + repr(e)[:80]
    print(name, "exceptions", len(exc), sorted(set(exc))[:2], "| after:", post)

Output on main (GIL enabled, 10 s per layer):

gptq-fused  exceptions 10      ['size of tensor a (128) must match the size of tensor b (32)', "_weight_int4pack_mm_cpu : expect B to be uint8 tensor."]  | after: ok
gptq-aten   exceptions 253562  ["'NoneType' object has no attribute 'to'", '"rshift_cpu" not implemented for \'Float\''] | after: BROKEN: NotImplementedError('"rshift_cpu" not implemented for 'Float'')
gptq-avx512 exceptions 2822    ['size of tensor a (128) must match the size of tensor b (32)'] | after: ok
awq-fused   exceptions 0
awq-aten    exceptions 163016  ["'NoneType' object has no attribute 'to'", "expect B to be uint8 tensor."] | after: BROKEN: NotImplementedError('"rshift_cpu" not implemented for 'Float'')
awq-avx512  exceptions 0

The same script on 1405751 (before #5447) gives 0 exceptions for all six kernels (the module latches train and stops flipping).

At model level (Llama-3.2-1B-Instruct GPTQ 4-bit, CPU AUTO = TorchCpuAvx512Linear), one thread looping generate(max_new_tokens=8) under no_grad and one thread looping inputs_embeds.requires_grad_() forward+backward for 40 s raised RuntimeError: The size of tensor a (1024) must match the size of tensor b (512) in the generate thread. On the old tree the same run raised 0 errors. The error rate is lower than at layer level because there is more work between transitions.

Single-threaded alternation is fine (6 grad/no-grad pairs per kernel: identical outputs, 0.5-1.4 ms per pair).

Suggested fix

Make a forward's layout snapshot consistent with the matmul that uses it. Either:

  • take references to the tensors a call needs (fused op / qweight, qzeros, scales) while holding _cpu_transform_lock, and have restore_fused_train_state/transform publish new objects instead of mutating the module's tensors in place, so an in-flight call keeps valid operands; or
  • keep the checkpoint layout alive next to the fused layout after the first transform. An eval-mode grad forward can then dequantize from it without tearing down the fused buffers that a concurrent no-grad forward is using. This also removes the per-pair transform cost.

Test that should have caught it

tests/test_cpu_fused_eval_grad_latch_5392.py is single-threaded. Add a case like the repro to tests/test_cpu_lazy_transform_concurrency_4565.py: no-grad and eval-mode grad forwards on two threads each, assert no exception and a working module afterwards.

Severity: medium. This is a regression from #5447: a crash, and a CPU-served model permanently broken by concurrent inference plus gradient requests.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 19, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-5509-int4pack is working on this issue now.

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