Skip to content

[BUG] Follow-up on #4111/#4102: concurrent module-tree branches calibrated on the text decoder's output (vision tower silently mis-quantized / crash), CPU BF16x3 matmul guard still un-refcounted #4116

Closed

Description

@Qubitium

Audit of main @ ffa0502, RTX 4090. This is a follow-up on #4111 (for #1998) and #4102 (for #4094).

1. #4111 incomplete: concurrent module-tree branches are calibrated from another branch's hidden states (high, silent)

#4111 has module_tree="auto" (or an explicit multi-variant tree) return one variant per concurrent stack, e.g. model.layers and vision_tower.layers. docs/parallel-module-trees.md says they "are all quantizable in the same run". The per-branch leaf, subset and hook resolution in #4111 is correct, but the looper still treats all variants as one sequential stack:

  • get_layers_with_prefixes (utils/model.py:494, called from looper/module_looper.py:1872) concatenates the variants.
  • stage_inputs_capture.py:155 (first_layer = layers[0]) captures inputs only for the first text layer.
  • Each layer is then replayed on the previous layer's output.

So vision_tower.layers.0 is calibrated on the output of the text decoder's last layer, with the text attention kwargs. The vision inputs that a real forward pass produces are never captured.

Repro: a remote-code Qwen2-style model with 2 text layers plus a sibling vision_tower.layers (2 ViT blocks with self_attn.{q,k,v,o}_proj and mlp.fc1/fc2), loaded with GPTQModel.load(..., GPTQConfig(4, 128), module_tree="auto", trust_remote_code=True) and quantized on 8 C4 texts. Hooks record each branch's first-layer inputs.

vision width == text width (896):
  layers node: ['model.layers', 'vision_tower.layers']
  vision_tower.layers.0 calibration inputs that are text-decoder (model.layers[-1]) outputs: 24/24
  quantized vision modules: 12        <- GPTQ Hessians built from text hidden states, no warning
vision width 512:
  RuntimeError: Given normalized_shape=[512], expected input with shape [*, 512], but got input of size[1, 250, 896]   (base.py:2159 quantize)

Save and reload with the explicit tree works; the defect is in calibration only. Image calibration data would not help, because only the first text layer's input is captured. The registered multi-variant trees (mllama, qwen2.5/3-omni) are layout alternatives where only one stack exists, so they are unaffected.

Fix:

  • Capture inputs per branch: hook each variant's first layer in cache_inputs, and restart the replay chain at each branch boundary.
  • If a branch's first layer is never reached by the calibration forward, skip it with a warning or fail closed.
  • Until then, reject multi-variant trees whose stacks are not sequential.

tests/module_tree/test_auto_detect.py only checks tree, prefix and leaf resolution. It needs an end-to-end quantize of a two-branch model.

2. Sibling of #4094 missed by #4102: the CPU BF16x3 matmul guards save/restore the process-global torch.backends.mkldnn.matmul.fp32_precision without a refcount (low-medium)

Both guards use the per-entry save/restore pattern that #4102 removed from the TF32 and BLAS guards:

  • utils/cpu_features.py:88 cpu_bf16x3_matmul, used by GGUF CPU (qlinear/gguf.py:1860) and bitsandbytes CPU (qlinear/bitsandbytes.py:730);
  • the duplicate nn_modules/exllamav3_torch.py:74 _cpu_bf16x3_matmul, used by the EXL3 CPU forward (:555).

With A entering, then B entering, then A exiting, A restores none while B is still inside, so B's remaining matmuls run IEEE fp32 instead of BF16x3. A thread outside the guard also picks up BF16x3 while another thread is inside. docs/concurrency.md lists only three global resources and omits this one.

A in, B in, A out -> B sees:
  cpu_features.cpu_bf16x3_matmul     {'b_entry': 'bf16', 'b_after_A_exit': 'none'}
  exllamav3_torch._cpu_bf16x3_matmul {'b_entry': 'bf16', 'b_after_A_exit': 'none'}
bf16x3 vs ieee, 4096-wide fp32 matmul (avx512_bf16 host): max abs diff 2.9e-4
2048-wide ExllamaV3TorchLinear CPU forward while a 2nd thread runs short EXL3 forwards:
  PYTHON_GIL=0: output differs from serial in 5/30 calls;  GIL on: 1/30

Fix: give it the same depth counter under an RLock as tf32_high_precision_guard, shared by both call sites (delete the EXL3 duplicate). Better, avoid global state by doing an explicit hi/lo bf16 split matmul. Add it to tests/test_concurrency_guards.py and docs/concurrency.md.

Plausible, not verified

  • After fix(concurrency): refcount global guards and serialize Triton JIT (#4094) #4102, a single transient dynamo guard race (another thread calling set_default_dtype) switches that compiled callable to eager for the rest of the process (state["fallback"]=True). A race that used to crash now costs performance permanently.
  • In Triton's AsyncCompileMode, _do_compile returns a future, so the real compile runs outside _TRITON_COMPILE_LOCK. gptqmodel does not enable this mode today.

Checked, clean

  • TF32 guard: nested, exception and A-in/B-in/A-out orders are correct, and depth returns to 0 after 8000 overlapping entries under GIL=0.
  • Concurrent quantize: two threads quantizing Qwen2.5-0.5B match the serial run in 795/795 tensors under GIL on and GIL=0, and the user's TF32 setting is restored.
  • JIT lock: it is taken only at warmup, launch throughput is unchanged, and lock order cannot invert. test_awq_triton_cold_jit.py passes.
  • Default end to end (offload_to_disk, DeviceThreadPool, disk writer, save/reload): GIL=0 and GIL on give the same checkpoint (0/794 tensors differ) and the same PPL.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 15, 2026

    @Qubitium
    CollaboratorAuthor

    Both items are now on main:

    Worth recording, because item 1's failure mode was silent rather than loud:

    The looper was treating all module-tree variants as one sequential stack — get_layers_with_prefixes concatenated them, stage_inputs_capture.py:155 captured inputs only for the first text layer, and each layer replayed on the previous layer's output. So the vision tower's Hessians were built from text activations. It now captures inputs per branch, restarts the replay chain at each branch boundary, and fails loudly with an actionable ValueError when a branch's first layer is never reached — the silent path is gone. Measured after the fix: 0/32 vision inputs are text-decoder outputs (was 24/24), and the mismatched-width case that used to die mid-quantize now completes. Registered multi-variant trees (mllama, qwen2.5/3-omni) still resolve identically, and Llama/Qwen2 single-branch resolution is byte-identical.

    For item 2, the two duplicate implementations were collapsed into one RLock + depth counter shared by GGUF CPU, bitsandbytes CPU and the EXL3 CPU forward. The A-in/B-in/A-out order now leaves B on bf16 instead of none (both former entry points), and the 30-trial race went from 11/30 and 2/30 differing calls to 0/30 under both GIL settings. A test now asserts the lock is an RLock, so a future downgrade to Lock fails immediately instead of deadlocking.

    One honest limitation carried from the fix: refcounting fixes the restore race, but a thread outside the scope still observes BF16x3 while another thread holds it. Eliminating that needs an explicit hi/lo bf16 split matmul, which changes arithmetic and cost — deliberately left out.

    Closing as resolved.

  2. Qubitium commented on Nov 15, 2026

    @Qubitium
    CollaboratorAuthor

    Item 2 also reproduces on ROCm (R9700, CPython 3.14t, PYTHON_GIL=0), and there is one more effect:

    • Leak into the user's TF32 setting. Inside tf32_high_precision_guard, the mkldnn.matmul child reads "ieee", inherited from the root. cpu_bf16x3_matmul then writes that value back explicitly. So after a GGUF/bnb CPU forward inside a quantize, mkldnn.matmul.fp32_precision is pinned to ieee, even though the user had set the root to tf32 (before: tf32 mkldnn.matmul tf32 -> after: tf32 mkldnn.matmul ieee). When the value read was inherited, restore "none" rather than the explicit value.
    • Unrelated threads are affected. 2 GGUF q4_k CPU threads plus 1 thread doing plain fp32 A@B: 613 GGUF calls differ from serial, and so do 2136 of the unrelated fp32 matmuls. With PYTHON_GIL=1, 5/603 GGUF calls differ.
    • Guard race test: 16 threads racing enter/exit with nesting and exceptions give 373-410 violations for bf16x3 and 0 for the BLAS and TF32 guards.

    🤖 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