Repository navigation
Description
Describe the bug
At 0b94d79c67, the cases below violate the stated supported contract. The validation scope for each case is explicit; source/dispatch proofs are not device numerical qualification.
BF16x3 capability probing bypasses the refcounted process-global precision owner
Severity: P2
Contract and impact
A library-owned CPU BF16x3 scope must retain bf16 precision until its last participant exits; capability detection must obey the same global-state owner.
Concurrent first-use capability probing silently restores IEEE precision while a BF16x3 forward scope is active. Actual setting changes are reproduced; no numerical drift or performance loss was measured.
To reproduce / evidence
On a BF16x3-eligible AVX512_BF16 CPU, with initial precision ieee and a cold lru_cache, A reads ieee in has_cpu_bf16x3_precision and pauses; B completes its own probe and enters cpu_bf16x3_scope; A resumes and restores its stale ieee snapshot. functools.lru_cache permits concurrent misses.
Independently executed command: python reproduce.py. Loads the shipped capability/scope module unchanged; wraps only the getter to select a deterministic schedule while performing actual Torch precision reads/writes. Complete script (adapt ROOT/fixture paths to your checkout):
import importlib.util
import pathlib
import sys
import threading
import types
import torch
ROOT = pathlib.Path('.')
for name, path in [('gptqmodel', ROOT/'gptqmodel'), ('gptqmodel.utils', ROOT/'gptqmodel/utils')]:
package = types.ModuleType(name)
package.__path__ = [str(path)]
sys.modules[name] = package
kernel = types.ModuleType('gptqmodel.utils.kernel')
kernel.get_kernel_config = lambda: types.SimpleNamespace(cpu_bf16x3_matmul=True)
sys.modules[kernel.__name__] = kernel
target = pathlib.Path(sys.argv[1]) if len(sys.argv) > 1 else ROOT/'gptqmodel/utils/cpu_features.py'
spec = importlib.util.spec_from_file_location('gptqmodel.utils.cpu_features', target)
mod = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = mod
spec.loader.exec_module(mod)
previous = torch.backends.mkldnn.matmul.fp32_precision
torch.backends.mkldnn.matmul.fp32_precision = 'ieee'
mod.has_cpu_bf16x3_precision.cache_clear()
read_done = threading.Event()
scope_entered = threading.Event()
probe_done = threading.Event()
real_getter = mod._cpu_bf16x3_precision
result = {}
def gated_getter():
value = real_getter()
if threading.current_thread().name == 'capability-probe':
read_done.set()
assert scope_entered.wait(5)
return value
mod._cpu_bf16x3_precision = gated_getter
def probe():
result['probe_supported'] = mod.has_cpu_bf16x3_precision()
probe_done.set()
def forward():
assert read_done.wait(5)
assert mod.has_cpu_bf16x3_precision()
with mod.cpu_bf16x3_scope():
result['scope_entry'] = real_getter()
scope_entered.set()
assert probe_done.wait(5)
result['scope_after_probe'] = real_getter()
result['active_depth'] = mod._CPU_BF16X3_DEPTH
try:
a = threading.Thread(target=probe, name='capability-probe')
b = threading.Thread(target=forward, name='forward')
a.start(); b.start(); a.join(10); b.join(10)
assert not a.is_alive() and not b.is_alive()
result['final'] = real_getter()
print('python', sys.version.split()[0], 'torch', torch.__version__, 'mkldnn', torch.backends.mkldnn.is_available())
print(result)
assert result['scope_entry'] == 'bf16'
assert result['scope_after_probe'] == 'ieee' and result['active_depth'] == 1
finally:
torch.backends.mkldnn.matmul.fp32_precision = previous
Historical breakpoint: git show 13ee428f2177eda9fc0255d7963af02bcdd3f0a1:gptqmodel/utils/cpu_features.py > reproduce.py; then python reproduce.py reproduce.py. Same failing precision-state interleaving independently observed.
Observed and expected behavior
Both current and #4127 source produced {'scope_entry': 'bf16', 'probe_supported': True, 'scope_after_probe': 'ieee', 'active_depth': 1, 'final': 'ieee'}. Expected scope_after_probe='bf16' at active_depth=1, final='ieee'.
Public source and history
GPTQModel/gptqmodel/utils/cpu_features.py
Lines 75 to 93 in 0b94d79
| @lru_cache(maxsize=1) | |
| def has_cpu_bf16x3_precision() -> bool: | |
| """Return whether oneDNN accepts the BF16x3 FP32 matmul precision. | |
| Capability only: the environment-variable gates stay in each caller's | |
| predicate (``has_cpu_bf16x3_matmul`` here and ``_cpu_bf16x3_support`` in the | |
| EXL3 torch kernel), so both entry points probe oneDNN the same way. | |
| """ | |
| if not torch.backends.mkldnn.is_available(): | |
| return False | |
| try: | |
| previous = _cpu_bf16x3_precision() | |
| _set_cpu_bf16x3_precision("bf16") | |
| _set_cpu_bf16x3_precision(previous) | |
| except (AttributeError, RuntimeError, ValueError): | |
| return False | |
| return True |
GPTQModel/gptqmodel/utils/cpu_features.py
Lines 112 to 176 in 0b94d79
| _CPU_BF16X3_LOCK = threading.RLock() | |
| _CPU_BF16X3_DEPTH = 0 | |
| _CPU_BF16X3_RESTORE = None | |
| @contextmanager | |
| def cpu_bf16x3_scope(): | |
| """Run FP32 matmuls as oneDNN BF16x3, reference-counted process-wide. | |
| ``torch.backends.mkldnn.matmul.fp32_precision`` is process-wide, so | |
| overlapping callers share one override. The first entry records the | |
| caller's precision and selects BF16x3; every later entry only increments | |
| ``_CPU_BF16X3_DEPTH``; the last exit restores the recorded precision. The | |
| old per-entry save/restore let the first caller to finish restore IEEE | |
| while another caller was still inside, so that caller's remaining matmuls | |
| ran in plain FP32 (issue #4116). | |
| The lock is an ``RLock`` on purpose: this scope is re-entrant, and a nested | |
| entry on the same thread would deadlock behind a plain ``Lock``. | |
| Callers decide whether BF16x3 is eligible for their input; this scope only | |
| owns the process-global setting. | |
| """ | |
| global _CPU_BF16X3_DEPTH, _CPU_BF16X3_RESTORE | |
| entered = False | |
| with _CPU_BF16X3_LOCK: | |
| if _CPU_BF16X3_DEPTH > 0: | |
| _CPU_BF16X3_DEPTH += 1 | |
| entered = True | |
| else: | |
| previous = _cpu_bf16x3_precision() | |
| if previous != "bf16": | |
| try: | |
| _set_cpu_bf16x3_precision("bf16") | |
| except (AttributeError, RuntimeError, ValueError): | |
| pass | |
| else: | |
| _CPU_BF16X3_RESTORE = previous | |
| _CPU_BF16X3_DEPTH = 1 | |
| entered = True | |
| if not entered: | |
| # Already BF16x3 (the caller's own setting) or the platform refused the | |
| # switch: nothing to restore, so leave the count alone. | |
| yield | |
| return | |
| try: | |
| yield | |
| finally: | |
| with _CPU_BF16X3_LOCK: | |
| _CPU_BF16X3_DEPTH -= 1 | |
| if _CPU_BF16X3_DEPTH == 0: | |
| previous = _CPU_BF16X3_RESTORE | |
| _CPU_BF16X3_RESTORE = None | |
| if previous is not None: | |
| try: | |
| _set_cpu_bf16x3_precision(previous) | |
| except (AttributeError, RuntimeError, ValueError): | |
| # Best effort: the matmul already produced its result, | |
| # and a platform that refuses the restore must not turn | |
| # a successful forward into a failure. | |
| pass |
GPTQModel/gptqmodel/nn_modules/exllamav3_torch.py
Lines 18 to 62 in 0b94d79
| from ..utils.cpu_features import cpu_bf16x3_scope, has_avx512_bf16, has_cpu_bf16x3_precision | |
| from ..utils.logger import setup_logger | |
| from ..utils.torch import TORCH_HAS_COMPILE, torch_compile | |
| from .compiled_state import compiled_module_getstate | |
| from .exllamav3 import _EXL3_BUFFER_NAMES, _torch_dtype | |
| log = setup_logger() | |
| _EXL3_3INST_MULT = 89226354 | |
| _EXL3_3INST_ADD = 64248484 | |
| _EXL3_MCG_MULT = 0xCBAC1FED | |
| _EXL3_MUL1_MULT = 0x83DCD12D | |
| _EXL3_MUL1_ACC = 0x6400 | |
| _EXL3_LOP3_MASK = 0x8FFF8FFF | |
| _EXL3_LOP3_BIAS = 0x3B603B60 | |
| _CPU_BF16X3_MIN_WEIGHT_ELEMENTS = 1 << 19 | |
| _CPU_BF16X3_MIN_MACS = 1 << 23 | |
| # Bound each transient decode to 512 output columns without serializing many small GEMMs. | |
| _EXL3_OUTPUT_TILES_PER_CHUNK = 32 | |
| @lru_cache(maxsize=1) | |
| def _cpu_bf16x3_capable() -> bool: | |
| """Return whether the host itself can run oneDNN BF16x3 FP32 matmul.""" | |
| return has_avx512_bf16() and has_cpu_bf16x3_precision() | |
| def _cpu_bf16x3_support() -> bool: | |
| """Return whether the active kernel policy enables BF16x3 on this host. | |
| The policy read stays outside the cache so toggling | |
| ``KernelConfig.cpu_bf16x3_matmul`` between runs is observed by the next | |
| forward. Only the hardware capability probe is cached. | |
| """ | |
| from ..utils.kernel import get_kernel_config | |
| if not get_kernel_config().cpu_bf16x3_matmul: | |
| return False | |
| return _cpu_bf16x3_capable() | |
| # Keep the documented re-arm knob on the capability probe. Callers (and tests) |
737d46a (PR #3430) first introduces the unguarded oneDNN capability mutation plus scope. 13ee428 (PR #4127) refcounts the forward scope but extracts the still-unguarded capability probe. Identical failure reproduced directly on #4127 source: incomplete fix, not reintroduction.
Existing reports
Related CLOSED #4116 item 2 and PR #4127 cover overlapping scope exits, not concurrent capability probing. CLOSED #4396 item 2 concerns cached mutable policy, a different invariant. Public state=all searches BF16x3, BF16x3 probe, and precision probe found no exact retrieved duplicate of the probe race.
Software / device info and validation limits
Actual oneDNN precision-state/control-flow reproduction on CPU Torch 2.15.0+cpu, no matmul accuracy claim. Getter instrumentation introduces the legal scheduling interval; scopes/setters and lru_cache are shipped. Hardware capability gate is bypassed by testing the public low-level scope/probe directly; both APIs work in this environment. No GPU involved.
Model / datasets
The evidence uses tiny synthetic tensors or local fixtures derived from the public tests; no private model or dataset is required. Device execution that remains untested is stated above.
Activity
Qubitium commentedon Nov 17, 2026
Claimed. This issue is now owned by a dedicated worker; a fix PR referencing it will follow. Please avoid duplicating work on it in the meantime.
test(concurrency): catch Exception in thread workers, not BaseExcepti…
fix(cpu): serialize BF16x3 capability probing with the precision owner (