Skip to content

fix(gguf): keep one resident copy of the packed weight on CUDA and CPU (#4387, #4395) - #4577

Merged
Qubitium merged 2 commits into
mainfrom
fix/gguf-weight-dup
Nov 17, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/gguf-weight-dup

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Removes the two remaining duplicate copies of GGUF packed weights left after #4436 (#4387 item 2) and #4439 (#4395). Output is bitwise identical, and save() is byte-identical to main.

1. GGUF_CPP_CUDA kept the packed weight twice (#4387 item 2)

On the first forward, GGUFCudaKernel._cuda_weight uploads qweight into a shared ggml CUDA buffer, but the Torch qweight stayed allocated next to it. ggml can't read Torch's memory in place: ggml-cuda pads rows that aren't a multiple of 512 past ggml_nbytes.

Change (gguf_cpp.py): the ggml buffer now owns the bytes, and qweight becomes a zero-copy torch.as_tensor view of it (via __cuda_array_interface__, created under inference_mode(False)). The Torch allocation is released.

  • Lifetime: the buffer is reference counted (the view, plans, state_dict() tensors) and freed under the ggml-cuda lock after a device sync.
  • Other paths:
    • load_state_dict writes straight into the buffer;
    • .cpu() frees it, and the next CUDA forward re-uploads;
    • clear_weight_cache keeps a buffer that backs qweight.
  • Copies: a new __getstate__ drops the raw ggml handles, so a deepcopy or pickle gets its own weight. Before, a deepcopy after a forward copied the handles, so the buffer could be freed twice.
  • Behaviour change: after the first forward, qweight lives outside the caching allocator, so it's invisible to torch.cuda.memory_allocated.
q4_k_m, RTX 4090 Torch qweight on CUDA memory_allocated process VRAM
Qwen2.5-0.5B 211.4 → 0 MiB 471.2 → 259.9 MiB 1328 → 1104 MiB
Llama-3.2-1B 522.0 → 0 MiB 1023.1 → 501.1 MiB 2218 → 1702 MiB

Decode time is unchanged within noise.

2. GGUF_CPP_CPU aligned copy left the checkpoint pages resident (#4439 trade-off)

post_init copies each unaligned mmap'd qweight into 32-byte-aligned memory for ggml zero-copy, but the file pages it read stayed mapped. Every Llama-3.2-1B qweight starts at 24 mod 32 (safetensors header), and remapping can't fix that.

Change: after the aligned copy, madvise(MADV_DONTNEED) drops the whole file-backed pages inside the source tensor. It runs only when /proc/self/maps says the range is file-backed and /proc/self/pagemap shows no copy-on-write or swapped page; otherwise it skips (heap, non-Linux, edge pages shared with other tensors). MADV_PAGEOUT was rejected because it keeps dirty pages of a freshly written file.

Llama-3.2-1B q4_k_m, CPU VmRSS RssFile checkpoint mmap Rss
after load 2181 → 1660 MiB 943 → 423 MiB 522 → 2 MiB
after forwards 2732 → 2212 MiB 1450 → 930 MiB 1023 → 503 MiB (the tied embedding read in place)

Peak VmHWM drops by ~520 MiB, and token time is unchanged within noise. RssAnon is unchanged: the single remaining copy is the aligned anonymous one. Binding ggml to the unaligned mmap pointer was rejected as undefined behaviour against ggml's 32-byte contract.

Verification

  • Equality: logits are bitwise equal to main on Qwen2.5-0.5B and Llama-3.2-1B, CUDA and CPU. state_dict() qweights equal the checkpoint; save() is byte-identical to main; reloading gives equal logits. GGUF_TORCH/TRITON are untouched and bitwise equal.
  • New tests:
    • tests/kernels/test_gguf_cuda_weight_storage_4387.py (7 tests; 6 fail on main): allocated memory drops by the qweight size, state-dict round trip and view lifetime, load_state_dict write-through, .cpu()/.cuda(), deepcopy isolation.
    • tests/kernels/test_gguf_cpp_cpu_mmap_residency.py (3 tests): source-page residency is 0 after post_init (main leaves all 143 pages resident), copy-on-write pages are kept with their data, heap is never advised.
    • The existing GGUF CUDA fakes are updated for the new backs/as_tensor/device contract.
  • GGUF suite (all *gguf* tests plus selection/registry/audit, 1583 collected): 1089 passed, 488 skipped, 6 failed. The same 6 test_gguf_all_formats q8_1/q8_k fallback cases fail on main.
  • Free-threaded: a torch.as_tensor-over-__cuda_array_interface__ probe is added to the free-threaded compat ledger; it passes under PYTHON_GIL=0.
  • Lint: ruff is clean.
  • Docs: docs/kernel-scratch-lifecycle.md and docs/gguf-kernel-selection.md have flow diagrams and before/after tables.

🤖 Generated with Claude Code

Qubitium and others added 2 commits November 17, 2026 01:50
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]>
@Qubitium
Qubitium merged commit 3cf609c into main Nov 17, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/gguf-weight-dup branch November 17, 2026 02:15
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