Skip to content

fix(kernels): share QQQ reduce scratch and GGUF CUDA plan arena, cut QQQTorch temporaries (#4387) - #4436

Merged
Qubitium merged 2 commits into
mainfrom
fix/kernel-mem-4387
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/kernel-mem-4387

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Three of the four memory findings in #4387, all in the QQQ/GGUF kernel paths:

  1. Every QQQLinear registered its own (max_par*64, out_features) INT32 reduce scratch and passed it as the kernel's C argument. C is per-call global-reduce scratch, so a Llama-3-8B QQQ model retained ~5.25 GiB of zeroed buffers (more than its weights) and QQQTorchLinear inherited a buffer it never used.
  2. GGUF_CPP_CUDA allocated one ggml backend buffer per plan (per module and per row count, up to 8 each), holding that call's input/output/intermediates. Plans are pure scratch (inputs are copied in, outputs copied out) and forwards are serialized per device, so a 211 MiB model retained 6.4 GiB outside the torch allocator.
  3. QQQTorchLinear rebuilt its dense weight through INT64 floor_divide unpacking and FP32 gather temporaries on every forward (~108 MiB transient for one 896x4864 layer at M=1).

Item 3 (FP8 checkpoint-load peak) is intentionally not addressed here.

Addresses items 1, 2 and 4 of #4387.

What Changed

  • qqq.py: one lazily grown flat INT32 scratch per device (_shared_reduce_scratch), sliced into a contiguous (max_par*64, N) view; QQQTorchLinear has no reduce buffer. Inside torch.compile the module takes a per-call allocation instead of capturing the cache as a graph constant.
  • qqq.py: _unpack_uint4 uses INT32 shift/mask into a UINT8 plane; _int8_weight_for_forward() builds the transient INT8 plane directly (grouped codes use a broadcast scale multiply instead of an in_features x out_features gather). Nothing is cached — an INT4->INT8 expansion would violate the quantized-storage rule.
  • gguf_cpp.py: plans now own graph metadata only; tensors bind into one per-device _GGMLCudaScratch arena via ggml_backend_tensor_alloc. Growth frees the old buffer and bumps a generation counter; forward closes stale plans on generation mismatch and direct stale-plan use raises a hard error instead of silently reusing.
  • New docs/kernel-scratch-lifecycle.md (with Mermaid lifecycle diagrams) and README link; regressions in tests/test_qqq_kernel_memory_4387.py, tests/kernels/test_gguf_cuda_scratch_arena_4387.py; stale buffer assertions updated.

Tests

PYTHONPATH=/root/work-4387 /root/venv/bin/python -m pytest \
  tests/test_qqq_kernel_memory_4387.py tests/kernels/test_gguf_cuda_scratch_arena_4387.py \
  tests/kernels/test_gguf_cuda_plan_weights.py tests/test_qqq_cpu.py \
  tests/test_qqq_export_scale.py tests/test_gsq_method_adapters.py \
  tests/kernels/test_gguf_cpp.py tests/test_qqq_quantizer.py -q
195 passed, 63 skipped

/root/venv/bin/python -m ruff check <changed files>
All checks passed!

Measured: QQQ reduce scratch 5376 MiB -> ~56 MiB (96 modules, N=14336); GGUF plans 59.85 -> 11.25 MiB on a CPU ggml stand-in (20 plans); QQQTorch 896x4864 bf16 M=1 peak transient 108.06 -> 52.82 MiB. Bitwise equality asserted for the new unpacker, the INT8 weight plane and QQQTorch outputs.

Not executed here: the native qqq_gemm.cu extension (CUDA_HOME unset) and a GGML CUDA backend (llama-cpp-python is built CPU-only). Those paths are covered by mocked-kernel and ggml-CPU-stand-in tests; pre-existing CUDA_HOME failures reproduce identically on pristine main.

Logic Flow Documentation

New docs/kernel-scratch-lifecycle.md documents the QQQ per-device scratch and the GGUF plan-arena growth/invalidation flow with Mermaid diagrams and the stale-plan failure path.

Review Requirements

  • Reviewed; no env-var switches, config/API unchanged.
  • Quantized storage rule preserved (no dense/INT8 cache retained between forwards).

- QQQLinear: replace the per-module 1024xN int32 reduce buffer with one
  lazily grown flat buffer per device; QQQTorchLinear no longer inherits
  unused scratch.  A 96-module 8B model drops ~5.25 GiB to ~56 MiB.
- QQQTorchLinear: unpack INT4 codes with int32/uint8 bit ops and build the
  transient int8 weight directly.  Synthetic 896x4864 bf16 layer peak
  transient drops 108.06 -> 52.82 MiB; outputs stay bitwise identical.
- GGUFCudaKernel: bind plan input/output tensors into one per-device ggml
  scratch arena instead of a backend buffer per module and batch size.
  Arena growth invalidates cached plans via a generation counter.  CPU
  ggml stand-in: 20 plans 59.85 -> 11.25 MiB.
- Add targeted regressions, update stale buffer assertions, and document
  the scratch lifecycle in docs/kernel-scratch-lifecycle.md.

FP8 checkpoint-load peak (item 3) is not addressed.
@Qubitium
Qubitium merged commit 863549f into main Nov 16, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/kernel-mem-4387 branch November 16, 2026 15:14
Qubitium added a commit that referenced this pull request Nov 17, 2026
#4577)

GGUF_CPP_CUDA (#4387 item 2, left by #4436): the first forward uploaded
qweight into a ggml CUDA buffer but kept the Torch qweight allocated, so
every layer held its packed weight twice (211 + 211 MiB on Qwen2.5-0.5B
q4_k_m). ggml cannot read the Torch allocation (ggml-cuda reserves
zero-filled row padding past ggml_nbytes), so ownership is inverted: after
the upload, qweight becomes a zero-copy __cuda_array_interface__ view of the
ggml buffer. The buffer is reference counted (kernel, plans, any Torch view)
and freed by the last holder under the ggml-cuda lock. clear_weight_cache
keeps a weight that backs qweight; load_state_dict writes through; .cpu()
frees it; __getstate__ keeps raw ggml handles out of copies.

GGUF_CPP_CPU (#4439 trade-off): post_init copies an unaligned safetensors
mmap qweight into 32-byte aligned memory, but the mmap pages it read stayed
mapped next to the copy (+522 MiB RssFile on Llama-3.2-1B q4_k_m). The
whole pages inside the source tensor are now madvise(MADV_DONTNEED)-ed when
they are file backed and hold no private copy-on-write page; the zero-copy
forward is unchanged.

Measured (per-process counters): Qwen2.5-0.5B CUDA memory_allocated
471.2 -> 259.9 MiB, process VRAM 1328 -> 1104 MiB; Llama-3.2-1B CUDA
1023.1 -> 501.1 MiB, 2218 -> 1702 MiB; Llama-3.2-1B CPU VmRSS after load
2181 -> 1660 MiB (RssFile 943 -> 423, RssAnon unchanged), token time
unchanged. Logits bitwise equal to main for GGUF_CPP_CUDA, GGUF_CPP_CPU,
GGUF_TORCH and GGUF_TRITON; save() writes a byte-identical checkpoint.

Co-authored-by: Claude Opus 5.5 <[email protected]>
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