Skip to content

fix(cpu): refcount the BF16x3 matmul guard and drop the EXL3 duplicate (#4116) - #4127

Merged
Qubitium merged 2 commits into
mainfrom
fix/issue-4116-bf16x3-guard
Nov 15, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/issue-4116-bf16x3-guard

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 15, 2026 •

Copy link
Copy Markdown
Collaborator

Part of #4116 (item 2)

TL;DR

The CPU oneDNN BF16x3 matmul precision was guarded with the per-entry
save/restore pattern that #4102 removed from the TF32 and BLAS guards, in two
copies. It is now one reference-counted scope, cpu_bf16x3_scope, shared by
GGUF CPU, bitsandbytes CPU and the EXL3 torch kernel. The EXL3 duplicate is
deleted, so there is one implementation of the guard.

1. The problem

Call site Old mechanism file:line at fe302047d
GGUF CPU with cpu_bf16x3_matmul(): nn_modules/qlinear/gguf.py:1917
bitsandbytes CPU with cpu_bf16x3_matmul(): nn_modules/qlinear/bitsandbytes.py:730
EXL3 torch kernel with _cpu_bf16x3_matmul(): nn_modules/exllamav3_torch.py:555
Shared guard per-entry save/restore of torch.backends.mkldnn.matmul.fp32_precision utils/cpu_features.py:88-104
EXL3 duplicate the same per-entry save/restore nn_modules/exllamav3_torch.py:74-91

Both guards read the process-global precision, set bf16, and restore the
value they read on exit. Two overlapping callers therefore clobber each other:

flowchart TD
    A["caller A enters: reads none, sets bf16"] --> B["caller B enters: reads bf16, keeps it"]
    B --> C["A exits: restores none"]
    C --> D["B's remaining matmuls run IEEE fp32"]
    D --> E["B's output differs from an all-BF16x3 run"]
Loading

The issue measured the ordering directly: with A in, B in, then A out, B saw
none after A exited, from both former call sites.

2. The new flow

flowchart TD
    A["cpu_bf16x3_scope enter"] --> B{"_CPU_BF16X3_DEPTH == 0"}
    B -- yes --> C{"current precision is bf16"}
    C -- yes --> D["caller already asked for it: do not count"]
    C -- no --> E["set bf16, save _CPU_BF16X3_RESTORE"]
    E --> F["_CPU_BF16X3_DEPTH = 1"]
    B -- no --> G["_CPU_BF16X3_DEPTH += 1"]
    F --> H["caller's matmuls run"]
    G --> H
    D --> H
    H --> I["exit: _CPU_BF16X3_DEPTH -= 1"]
    I --> J{"depth == 0 and a snapshot exists"}
    J -- yes --> K["restore the saved precision"]
    J -- no --> L["another caller still inside"]
Loading

Three properties are deliberate:

  • RLock, not Lock. The scope is re-entrant (a nested entry, or an
    EXL3 forward inside a GGUF scope). The lock is only held for the counter and
    the setting write, never across yield, so it does not serialize matmuls.
  • entered flag. A caller that cannot apply the pin (the caller already
    selected BF16x3, or oneDNN refuses the write) yields without touching the
    counter. Otherwise it could raise the depth with no snapshot and stop the
    next eligible caller from applying the pin.
  • One implementation. cpu_bf16x3_matmul() is now a thin eligibility
    wrapper over cpu_bf16x3_scope(), and the EXL3 module imports the same
    scope. Its own gate (GPTQMODEL_EXL3_CPU_BF16X3, AVX512-BF16, the shape
    heuristic) is unchanged and still evaluated at the call site.

The capability probe is shared too: has_cpu_bf16x3_precision() in
utils/cpu_features.py holds the oneDNN probe, and each caller keeps its own
environment gate (has_cpu_bf16x3_matmul() for GGUF/bitsandbytes,
_cpu_bf16x3_support() for EXL3).

3. Failure and ambiguity contract

Situation Result
Caller already selected BF16x3 scope yields without counting; nothing to restore
oneDNN refuses the precision write scope yields without counting; forward runs in the caller's precision
Restore raises swallowed; the matmul result is already produced
Nested entry on one thread counted; one restore
Overlapping entry from another thread counted; the first exit does not restore

4. Change inventory

Area File +/- Purpose
Guard gptqmodel/utils/cpu_features.py +81/-33 shared RLock + depth + snapshot, shared capability probe
EXL3 gptqmodel/nn_modules/exllamav3_torch.py +12/-42 delete the duplicate guard, enter the shared scope
Docs docs/concurrency.md +40/-8 fourth global resource, diagram, contracts, measurements
Tests tests/test_concurrency_guards.py +108/-2 ordering, nesting, already-BF16x3, one-implementation, entry point
Tests tests/test_exllamav3_cpu.py +1/-1 the scope-restore test follows the shared symbol

5. Evidence

All measurements are CPU-only on a host with AVX512-BF16 (has_avx512_bf16()
true, has_cpu_bf16x3_matmul() true), torch 2.16.0.dev20261102+cu130,
Python 3.14.10. "Before" is a worktree of origin/main at fe302047d.

5.1 Guard order, both former call sites

A enters, B enters, A exits, B reads the precision:

PYTHONPATH=<tree> /opt/venvs/cu130t/bin/python /tmp/bf16x3_guard_order.py
Tree Call site Result
before cpu_features.cpu_bf16x3_matmul {"b_entry": "bf16", "b_after_A_exit": "none"}
before exllamav3_torch._cpu_bf16x3_matmul {"b_entry": "bf16", "b_after_A_exit": "none"}
after cpu_features.cpu_bf16x3_matmul {"b_entry": "bf16", "b_after_A_exit": "bf16"}
after exllamav3_torch.cpu_bf16x3_scope {"b_entry": "bf16", "b_after_A_exit": "bf16"}

After the fix the probe also reports {"duplicate_present": false, "same_object_as_cpu_features": true}: both call sites resolve to one function.

5.2 2048-wide ExllamaV3TorchLinear CPU forward, controlled interleaving

Real checkpoint Llama-3.2-1B-Instruct-EXL3-W4-ALL, q_proj (2048 -> 2048),
512-row activations. A GGUF/bitsandbytes scope exits after the forward's first
chunk; the precision is recorded at every chunk:

PYTHONPATH=<tree> /opt/venvs/cu130t/bin/python /tmp/bf16x3_forward_interleave.py
Tree Chunk precisions Forwards differing from the all-BF16x3 reference
before bf16, bf16, none, none 5/5
after bf16, bf16, bf16, bf16 0/5

5.3 Unconstrained race, 30 trials

A short EXL3 forward starts first; a 2048-wide EXL3 forward starts 25% of the
short forward's duration later and is compared against its all-BF16x3
reference:

PYTHONPATH=<tree> PYTHON_GIL=<0|1> /opt/venvs/cu130t/bin/python /tmp/bf16x3_forward_race.py
Tree PYTHON_GIL=0 PYTHON_GIL=1
before 11/30 differing 2/30 differing
after 0/30 differing 0/30 differing

The issue reported 5/30 and 1/30 on its own host; the hit rate depends on how
much of the guarded window is matmul rather than EXL3 weight decode, which is
why 5.2 (deterministic ordering) is the regression and this is the corroborating
sample.

6. Tests

PYTHONPATH=$PWD /opt/venvs/cu130t/bin/python -m pytest \
  tests/test_concurrency_guards.py tests/test_exllamav3_cpu.py -q
# 71 passed

PYTHONPATH=$PWD /opt/venvs/rocm101t/bin/python -m pytest \
  tests/test_concurrency_guards.py tests/test_exllamav3_cpu.py -q
# 67 passed, 4 skipped

ruff check gptqmodel docs/eora tests setup.py
# All checks passed!

New regressions in tests/test_concurrency_guards.py:

Test Invariant
test_cpu_bf16x3_matmul_entry_point_keeps_the_second_caller the GGUF/bitsandbytes entry point: A's exit does not restore while B is inside
test_cpu_bf16x3_scope_is_reference_counted first exit keeps BF16x3 for the second caller, last exit restores
test_cpu_bf16x3_scope_is_reentrant_and_restores_once nested entry works (asserts the lock is an RLock) and restores once
test_cpu_bf16x3_scope_keeps_a_caller_selected_precision a caller that already selected BF16x3 is not counted or restored
test_cpu_bf16x3_guard_has_one_implementation EXL3 and cpu_features share the scope; the duplicate is gone

Fail-before on fe302047d: this file reports 5 failed, 3 passed. The
entry-point test fails behaviourally with AssertionError: assert 'none' == 'bf16' at the "A exited, B still inside" line; the other four fail because the
shared scope does not exist there.

7. Reviewer notes

  • A thread that is not inside the scope still observes BF16x3 while another
    thread holds it. That is inherent to a process-global setting; removing it
    needs the issue's alternative (an explicit hi/lo bf16 split matmul), which
    changes arithmetic and cost and is not attempted here.
  • No new environment switches. GPTQMODEL_CPU_BF16X3 and
    GPTQMODEL_EXL3_CPU_BF16X3 keep their previous meanings; only the
    capability probe they share was factored out.
  • docs/concurrency.md now lists four global resources (it listed three) and
    the resource-map diagram includes cpu_bf16x3_scope.
  • No GPU was used; the RTX 5090 was not touched.

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.

1 participant