Skip to content

fix(cpu): stop host-memory duplication in GGUF CPU, offload, and pinned staging (#4395) - #4439

Merged
Qubitium merged 2 commits into
mainfrom
fix/host-mem-4395
Nov 16, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/host-mem-4395

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Four host-memory findings from #4395:

  1. GGUF_CPP_CPU allocated a ggml buffer and copied the whole packed weight on every forward (522 MiB/token on Llama-3.2-1B).
  2. Pinned host memory from quantize and reload stayed in PyTorch's pinned-memory cache for the life of the process; nothing ever called torch._C._host_emptyCache().
  3. Quantize wrote a byte-identical copy of the dense embed_tokens (and final norm) into the offload dir, then read it back — 55% of a 1B run's offload dir, ~1.05 GB at 8B.
  4. LazyTurtle's "re-read once per layer" warning overstated the I/O.

Addresses items 2-5 of #4395. Item 1 (CPU int4 checkpoint-layout qweight snapshot) is intentionally not addressed: a real fix needs an exact inverse of ATen's CPU int4pack layout, which Torch does not expose, and the AVX512 path cannot be executed on this host — implementing it here would be unverified and risks checkpoint corruption.

What Changed

  • gguf_cpp.py: wrap caller-owned packed-weight storage with ggml_backend_cpu_buffer_from_ptr + ggml_backend_tensor_alloc when it is 32-byte aligned (ggml's TENSOR_ALIGNMENT), and free the wrapper buffer in the existing finally; unaligned/older-ABI builds keep the copy path. post_init aligns real safetensors mmap views.
  • utils/torch.py, utils/model.py, models/base.py: release the pinned host cache (torch._C._host_emptyCache()) at the end of quantize() and after the loader's checkpoint load.
  • utils/offload.py, looper/module_looper.py, looper/weight_only_looper.py: write a safetensors reference for base modules whose tensors are untouched source tensors instead of re-serializing them; a missing or content-mismatched source falls back to the old bundle.
  • utils/structure.py: warning now says the shard is re-opened and its header re-parsed per layer while the data is read once.
  • Docs: docs/gguf-kernel-selection.md, docs/safetensors-reference-offload.md (+ README links). New regressions: tests/kernels/test_gguf_cpp_zero_copy_4395.py, tests/test_pinned_host_cache_4395.py, tests/test_offload_reference_4395.py.

Tests

PYTHONPATH=/root/work-4395 /root/venv/bin/python -m pytest \
  tests/kernels/test_gguf_cpp_zero_copy_4395.py tests/test_pinned_host_cache_4395.py \
  tests/test_offload_reference_4395.py tests/test_lazy_turtle_shard_layout_warning.py -q
20 passed

PYTHONPATH=/root/work-4395 /root/venv/bin/python -m pytest \
  tests/test_offload_files.py tests/test_offload_base_modules_restored.py \
  tests/test_offload_run_cleanup_4368.py tests/test_offload_run_namespace.py \
  tests/test_offload_autograd.py tests/test_qzeros_disk_offload_4380.py \
  tests/test_loader_offload_staging_4385.py tests/test_quantize_config_offload_tempdir.py \
  tests/test_quantize_run_summary.py -q
143 passed, 2 skipped

PYTHONPATH=/root/work-4395 /root/venv/bin/python -m pytest \
  tests/kernels/test_gguf_cpp.py tests/kernels/test_gguf_cpp_path_selection.py \
  tests/kernels/test_gguf_cpp_bias_epilogue.py tests/kernels/test_gguf_cpp_activation_quantization.py -q
71 passed, 37 skipped
/root/venv/bin/python -m ruff check <changed files>
All checks passed!

Measured: GGUF CPU 2048x8192 Q4_K_S layer M=1 copy 1.07-1.56 ms -> zero-copy 0.35-0.76 ms (~2.5-3.2x) with bitwise-equal output; pinned host bytes after quantize() 115.70 MiB -> 0.00 MiB (1B GPTQ), 554.87 -> ~0.00 MiB after a CUDA reload; embed_tokens offload dir 525,336,576 B -> 367 B with a bitwise-identical restore and byte-identical saved tensor.

Pre-existing failures left untouched (proven identical on pristine main): test_gguf_cpp_matmul_accuracy_4316.py::test_default_path_is_unchanged (stale env-var test), 9 Q8_K/Q8_1 cases in test_gguf_all_formats.py, 14 AVX512 cases in test_kernel_audit_regressions.py (aarch64 host).

Not executed: full GGUF model benchmark (no GGUF checkpoint cached), Marlin load (CUDA_HOME unset; used GPTQ_TORCH, same accelerate pinned staging), 8B models.

Logic Flow Documentation

New docs/gguf-kernel-selection.md and docs/safetensors-reference-offload.md document the zero-copy selection/fallback and the reference-offload lifecycle (with the missing/mismatched-source fallback path) using real symbol names.

Review Requirements

  • Reviewed; no env-var behavior switches.
  • Reference offload requires the source checkpoint to stay available until save; a missing/changed source falls back to the old bundle (covered by tests).

…ed staging (#4395)

- GGUF_CPP_CPU: bind the packed qweight in place with
  ggml_backend_cpu_buffer_from_ptr/ggml_backend_tensor_alloc instead of
  allocating and copying the whole weight on every forward. post_init()
  32-byte aligns mmap-loaded qweight; unaligned or rejected layouts fall
  back to the copy path. M=1 synthetic Q4_K layer 1.60 -> 0.64 ms (2.49x),
  bitwise-equal output.
- Release PyTorch's pinned host cache at the end of quantize() and after the
  loader's checkpoint load. Llama-3.2-1B GPTQ pinned bytes 115.70 -> 0.00 MiB
  after quantize; GPTQ checkpoint load 554.87 -> ~0.00 MiB.
- Quantize base-module offload: publish an Accelerate index that references
  byte-identical source safetensors tensors instead of re-serializing them;
  fall back to the bundle when any tensor differs. Llama-3.2-1B embed_tokens
  offload dir 525,336,576 B -> 367 B, bitwise restore.
- Reword the LazyTurtle non-layer-wise warning: the header is re-parsed per
  layer while the data is read once.
- Add targeted regressions for each fixed item and document the flows.

Item 1 (CPU int4 checkpoint-layout snapshot) is not included: borrowing the
snapshot storage is memory-neutral, and Torch exposes no inverse for the ATen
int4pack layout, so an on-demand rebuild would be unverified on this host.
Comment thread gptqmodel/utils/offload.py Fixed
@Qubitium
Qubitium merged commit 978c7c1 into main Nov 16, 2026
9 checks passed
@Qubitium
Qubitium deleted the fix/host-mem-4395 branch November 16, 2026 15:38
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