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.
QQQ per-device reduce-scratch sharing has no in-flight stream ownership
Severity: P2
Contract and impact
Distinct concurrent native QQQ calls must not share writable global-reduction storage unless their CUDA work is ordered through completion; an allocation lock is not a scratch-use lease.
Two distinct eager QQQ modules on one device can hand overlapping native kernels the identical C scratch range while retaining independent per-module lock arrays. One kernel can overwrite partial reductions before the other reads them. This is a source-proven ownership/data-race defect, not an observed CUDA output-error measurement.
To reproduce / evidence
Two distinct QQQLinear modules on the same NVIDIA SM80+ device, eager mode, concurrent non-default CUDA streams, supported split-K shapes such as M=16,K=4096,N=64, group_size=-1, with at least two participating CTAs. Warm up/synchronize allocation first, then overlap native calls so both use the current shared buffer. Same-width modules with identical max_par share the exact storage pointer. Serial single-stream inference and the per-call torch.compile allocation are excluded.
Independently executed command: python reproduce.py. Extracts exact shipped allocation/cache declarations with AST solely to prove CPU storage aliasing; native writable-C/current-stream/lock source supplies the asynchronous ownership proof. This is NOT a GPU arithmetic reproduction. Complete script (adapt ROOT/fixture paths to your checkout):
"""Storage-lifetime proof only; no CUDA execution or arithmetic claim."""
import ast
import pathlib
import threading
import torch
path = pathlib.Path('./gptqmodel/nn_modules/qlinear/qqq.py')
tree = ast.parse(path.read_text())
selected = []
for node in tree.body:
if isinstance(node, ast.Assign) and any(isinstance(t, ast.Name) and t.id == '_REDUCE_SCRATCH_LOCK' for t in node.targets):
selected.append(node)
if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name) and node.target.id == '_REDUCE_SCRATCH':
selected.append(node)
if isinstance(node, ast.FunctionDef) and node.name == '_shared_reduce_scratch':
selected.append(node)
env = {'torch':torch, 'threading':threading}
exec(compile(ast.Module(body=selected, type_ignores=[]), str(path), 'exec'), env)
shared = env['_shared_reduce_scratch']
first_live_call = shared(torch.device('cpu'), 64)
second_live_call = shared(torch.device('cpu'), 64)
first_live_call.fill_(1)
second_live_call.fill_(2)
print({'same_pointer':first_live_call.data_ptr()==second_live_call.data_ptr(),
'first_shape':tuple(first_live_call.shape), 'second_shape':tuple(second_live_call.shape),
'first_after_second_write':first_live_call[0,0].item()})
assert first_live_call.data_ptr() == second_live_call.data_ptr()
assert first_live_call[0,0].item() == 2
Observed and expected behavior
Observed {'same_pointer':True,'first_shape':(1024,64),'second_shape':(1024,64),'first_after_second_write':2}. Two simultaneously live call views are the same allocation. Expected exclusive live scratch per in-flight stream/call, or explicit completion ordering before reuse. A concrete bad GPU output was not observed on this CPU-only host.
Public source and history
GPTQModel/gptqmodel/nn_modules/qlinear/qqq.py
Lines 37 to 65 in 0b94d79
| # ``qqq_gemm`` uses its ``C`` argument only as the per-call INT32 global | |
| # reduce scratch. A buffer per module made a Llama-3-8B QQQ model retain | |
| # ~5.25 GiB of zeroed scratch (issue #4387), so all modules on a device share | |
| # one lazily grown flat buffer instead. The flat layout lets each caller take | |
| # a *contiguous* ``(max_par * 64, out_features)`` view even when the shared | |
| # allocation was grown for a wider layer; slicing columns of a 2-D buffer would | |
| # hand the kernel a stride it does not understand. | |
| _REDUCE_SCRATCH_LOCK = threading.Lock() | |
| _REDUCE_SCRATCH: dict[torch.device, torch.Tensor] = {} | |
| def _shared_reduce_scratch( | |
| device: torch.device, out_features: int, max_par: int = 16 | |
| ) -> torch.Tensor: | |
| """Return one per-device INT32 reduce scratch, grown to ``max_par * 64 x N``.""" | |
| device = torch.device(device) | |
| rows = max_par * 64 | |
| required = rows * out_features | |
| with _REDUCE_SCRATCH_LOCK: | |
| scratch = _REDUCE_SCRATCH.get(device) | |
| if scratch is None or scratch.numel() < required: | |
| # The kernel writes before it reads this scratch, but zeroing keeps | |
| # the shared buffer indistinguishable from the old per-module one. | |
| scratch = torch.zeros(required, dtype=torch.int32, device=device) | |
| _REDUCE_SCRATCH[device] = scratch | |
| return scratch[:required].view(rows, out_features) | |
GPTQModel/gptqmodel/nn_modules/qlinear/qqq.py
Lines 423 to 438 in 0b94d79
| The native kernel consumes ``C`` only for the duration of one call, so | |
| every ``QQQLinear`` on a device uses the same allocation. Inside | |
| ``torch.compile`` a process-wide mutable cache would be captured as a | |
| graph constant, so the compiled path gets a per-call allocation. | |
| """ | |
| if device is None: | |
| device = self.B.device if hasattr(self, "B") else torch.device("cpu") | |
| if torch.compiler.is_compiling(): | |
| return torch.zeros( | |
| (self.max_par * 64, self.out_features), | |
| dtype=torch.int32, | |
| device=device, | |
| ) | |
| return _shared_reduce_scratch(device, self.out_features, self.max_par) |
GPTQModel/gptqmodel/nn_modules/qlinear/qqq.py
Lines 619 to 630 in 0b94d79
| D = torch.empty(A.shape[0], self.out_features, dtype=A.dtype, device=A.device) | |
| mul( | |
| quant_A, # A | |
| self.B, # B | |
| self._reduce_scratch(A.device), # C | |
| D, # D | |
| s1, # s1 | |
| self.s_channel, # s2 | |
| self.s_group, # s3 | |
| self.workspace, | |
| max_par=self.max_par, | |
| ) |
GPTQModel/gptqmodel_ext/qqq/qqq_gemm.cu
Lines 620 to 687 in 0b94d79
| // This is why we need another INT32 maxtrix `C` to reduce instead of the | |
| // original half matrix `D`. | |
| auto global_reduce = [&] (bool first = false, bool last = false) { | |
| // We are very careful here to reduce directly in the output buffer to maximize L2 cache utilization in this step. | |
| // To do this, we write out results in FP16 (but still reduce with FP32 compute). | |
| constexpr int active_threads = 32 * thread_n_blocks / 4; | |
| if (threadIdx.x < active_threads) { | |
| int c_gl_stride = prob_n / 4; | |
| int c_gl_wr_delta_o = 8 * c_gl_stride; | |
| int c_gl_wr_delta_i = 8 * (active_threads / 32); | |
| int c_gl_wr = c_gl_stride * ((threadIdx.x % 32) / 4) + 8 * (threadIdx.x / 32) + (threadIdx.x % 4) * 2; | |
| c_gl_wr += (4 * thread_n_blocks) * slice_col; | |
| constexpr int c_sh_wr_delta = active_threads * 2; | |
| int c_sh_wr = 2 * threadIdx.x; | |
| int row = (threadIdx.x % 32) / 4; | |
| if (!first) { | |
| // Interestingly, doing direct global accesses here really seems to mess up the compiler and lead to slowdowns, | |
| // hence we also use async-copies even though these fetches are not actually asynchronous. | |
| #pragma unroll | |
| for (int i = 0; i < thread_m_blocks * 4; i++) { | |
| cp_async4_pred( | |
| &sh[c_sh_wr + c_sh_wr_delta * i], | |
| &C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2)], | |
| i < (thread_m_blocks - 1) * 4 || 8 * (i / 2) + row < prob_m | |
| ); | |
| cp_async4_pred( | |
| &sh[c_sh_wr + c_sh_wr_delta * i + 1], | |
| &C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2) + 1], | |
| i < (thread_m_blocks - 1) * 4 || 8 * (i / 2) + row < prob_m | |
| ); | |
| } | |
| cp_async_fence(); | |
| cp_async_wait<0>(); | |
| } | |
| #pragma unroll | |
| for (int i = 0; i < thread_m_blocks * 4; i++) { | |
| if (i < (thread_m_blocks - 1) * 4 || 8 * (i / 2) + row < prob_m) { | |
| if (!first) { | |
| int4 d_red1 = sh[c_sh_wr + i * c_sh_wr_delta]; | |
| int4 d_red2 = sh[c_sh_wr + i * c_sh_wr_delta + 1]; | |
| #pragma unroll | |
| for (int j = 0; j < 4; j++) { | |
| reinterpret_cast<int*>(&frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)] += | |
| reinterpret_cast<int*>(&d_red1)[j]; | |
| } | |
| #pragma unroll | |
| for (int j = 0; j < 4; j++) { | |
| reinterpret_cast<int*>(&frag_c)[4 * 2 * 4 * (i / 4) + 4 * (j + 4) + (i % 4)] += | |
| reinterpret_cast<int*>(&d_red2)[j]; | |
| } | |
| } | |
| if (!last) { | |
| int4 d1, d2; | |
| #pragma unroll | |
| for (int j = 0; j < 4; j++) { | |
| reinterpret_cast<int*>(&d1)[j] = | |
| reinterpret_cast<int*>(&frag_c)[4 * 2 * 4 * (i / 4) + 4 * j + (i % 4)]; | |
| } | |
| #pragma unroll | |
| for (int j = 0; j < 4; j++) { | |
| reinterpret_cast<int*>(&d2)[j] = | |
| reinterpret_cast<int*>(&frag_c)[4 * 2 * 4 * (i / 4) + 4 * (j + 4) + (i % 4)]; | |
| } | |
| C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2)] = d1; | |
| C[c_gl_wr + c_gl_wr_delta_o * (i / 2) + c_gl_wr_delta_i * (i % 2) + 1] = d2; |
GPTQModel/gptqmodel_ext/qqq/qqq_gemm.cu
Lines 809 to 812 in 0b94d79
| if (slice_count > 1) { // only globally reduce if there is more than one block in a slice | |
| barrier_acquire(&locks[slice_col], slice_idx); | |
| global_reduce(slice_idx == 0, last); | |
| barrier_release(&locks[slice_col], last); |
GPTQModel/gptqmodel_ext/qqq/qqq_gemm.cu
Lines 1100 to 1117 in 0b94d79
| A.data_ptr(), | |
| B.data_ptr(), | |
| C.data_ptr(), | |
| D.data_ptr(), | |
| s1.data_ptr(), | |
| s2.data_ptr(), | |
| s3.data_ptr(), | |
| prob_m, prob_n, prob_k, | |
| workspace.data_ptr(), | |
| groupsize, | |
| dev, | |
| at::cuda::getCurrentCUDAStream(dev), | |
| thread_k, | |
| thread_n, | |
| sms, | |
| max_par | |
| ); | |
863549f (PR #4436, 2026-11-16): replaces per-module reduce_buffer with _REDUCE_SCRATCH[device] and _shared_reduce_scratch, retaining per-module workspace. This is a new cross-module sharing gap, not a recurrence of the earlier lock-array capacity bug (#4215).
Existing reports
Related #4387 item1 motivates removing per-module scratch; #4436 implements the sharing. Its serial equality/memory evidence does not qualify simultaneous stream reuse. #4215 is the distinct lock-array capacity issue, repaired separately. Public open+closed QQQ-stream/QQQ-scratch-concurrent searches retrieved no exact new shared-C stream-ownership report.
Software / device info and validation limits
Static full caller-to-CUDA-launch ownership proof plus actual CPU storage alias probe. AST extraction is used ONLY for storage alias/lifetime control logic, never as a substitute for kernel arithmetic. NVIDIA execution, overlapping CUDA-stream numeric corruption, and an independent target-device Torch numerical oracle remain unexecuted. Do not present the probe as a CUDA numerical reproduction.
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(qqq): cover per-stream reduce scratch ownership (#4488)
fix(qqq): own reduce scratch per CUDA stream (#4488) (#4524)
fix(qqq): allocate the reduce scratch per call instead of caching it (#…