Skip to content

[MEM] CPU int4 kernels: after the first-forward repack, leftover g_idx/scales views pin the whole safetensors mmap, so the replaced qweight pages stay resident: Llama-3.1-8B GPTQ RSS 15.6 GB vs 10.1 GB with those 4.75 MiB cloned #4785

Closed

Description

@Qubitium

Found on main @ dba142d, x86-64 AVX512-BF16 host (CPU only).

What is wrong

On CPU, GPTQModel.load(..., device="cpu") leaves the quantized tensors as zero-copy views of the safetensors mmap (a private rw-p file mapping). On the first forward, the CPU int4 kernels (TorchCpuAvx512Linear, which is AUTO for bf16, and TorchAtenLinear / TorchFusedLinear) run transform_cpu. That replaces qweight / qzeros / scales with new anonymous tensors, plus the snapshot from #4783. A few small tensors are left behind as mmap views:

  • g_idx (and the live scales on ATen) stay views of the mmap;
  • each of them keeps the whole shard mapping alive;
  • so every page the loader touched stays resident: the old packed qweight and the fp16 embed_tokens/lm_head that were cast to bf16.

The model then counts its quantized weights twice in RSS, once as the old file pages and once as the runtime copy.

Measured: Llama-3.1-8B-Instruct-GPTQ-INT4 (ckpt 5.47 GB), dtype=bf16, device=cpu, after one forward

                                      RSS     model tensors   largest mapping
AUTO (TorchCpuAvx512Linear)           15.59 GB   9.06 GB      model-00001...safetensors rw-p: Rss 4740 MiB (+728 MiB in shard 2), Private_Dirty 21 MiB
  tensors that live inside the file mapping: 224 g_idx buffers = 4.75 MiB
  after replacing just those 224 buffers with .clone() + gc:   10.13 GB   (-5.46 GB)
BACKEND.GPTQ_TORCH_ATEN               15.75 GB   9.22 GB      same mapping, 448 file-backed buffers (g_idx + scales) = 109 MiB
  after cloning them:                                          10.28 GB   (-5.47 GB)

I ruled out malloc retention (malloc_trim(0) and MALLOC_ARENA_MAX=1 change nothing), and gc.get_objects() finds no other CPU tensors. The pages are clean (Private_Dirty 21 MiB), so the kernel can reclaim them under memory pressure. Until then, they show up as RSS and in the cgroup memory.current of a container: about 1.6x the real working set on 8B. (#4783 adds a further +3.4 GB anon on top.)

Minimal repro

import gc, psutil, torch
from gptqmodel import GPTQModel
m = GPTQModel.load("Meta-Llama-3.1-8B-Instruct-GPTQ-INT4", dtype=torch.bfloat16, device="cpu")
with torch.inference_mode():
    m.model(torch.randint(100, 1000, (1, 8)))
print(psutil.Process().memory_info().rss / 2**30)          # 15.2 GiB
files = [tuple(int(x, 16) for x in l.split()[0].split("-")) for l in open("/proc/self/maps") if ".safetensors" in l]
n = 0
for mod in m.model.modules():
    for k, b in list(mod._buffers.items()):
        if isinstance(b, torch.Tensor) and any(a <= b.data_ptr() < e for a, e in files):
            mod._buffers[k] = b.clone(); n += 1
gc.collect()
print(n, psutil.Process().memory_info().rss / 2**30)       # 224, 9.9 GiB

Suggested fix

When transform_cpu (or the capture_fused_train_state step) replaces a module's operands, also detach the operands it keeps from the checkpoint mapping. Clone g_idx, or drop it when ret_idx is the identity, and clone the live scales on ATen; together that is about 110 MiB on 8B. Once no tensor references the mapping, safetensors can unmap it. The other option is to have the loader copy tensors for modules whose selected kernel declares a CPU repack (the CPU int4 family), so it never zero-copies them.

Test that should have caught it

A CPU load test for the int4 kernels should assert that after the first forward no module tensor's data_ptr() lies inside a *.safetensors mapping in /proc/self/maps (Linux only). Alternatively, it could assert that RSS is below 1.2x of (checkpoint bytes + runtime bytes).

Severity

Low-medium: the pages are reclaimable, but RSS-based monitoring and container limits see +5.5 GB on an 8B model.

🤖 Generated with Claude Code

Activity

  1. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Taking this.

  2. Qubitium commented on Nov 17, 2026

    @Qubitium
    CollaboratorAuthor

    Agent claim: agent-root-4785-mmap is working on this issue now.

    Started 2026-11-17T16:40:48Z. The claim expires 4.0h after this comment was last edited (heartbeat). Other agents: do not start this issue while the claim is live.

    claiming: detach the operands transform_cpu keeps (g_idx, live scales) from the safetensors mapping so the shard can be unmapped

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions