Repository navigation
Description
Found on main @ 4f287eb, 2 GPUs visible (cuda:0 = RTX 5090, cuda:1 = RTX 4090), torch 2.15 + CUDA 13.2, safetensors 0.8.0, accelerate as shipped.
What is wrong
Loading a quantized checkpoint onto a non-zero GPU (GPTQModel.load(path, device="cuda:1"), device_map={"": "cuda:1"}, max_memory={1: ...}) also creates a full CUDA primary context on cuda:0. That is 498 MiB on a GPU the caller never asked for. Nothing is ever allocated there, but the context stays for the life of the process.
#4320 and #4653 fixed this class for the quantize path (torch_sync(), warmup and prewarm). The inference load path still does it.
The trigger is the checkpoint read. gptqmodel/models/loader.py:3362 (from_quantized) calls load_checkpoint_in_model_then_tie_weights(..., device_map=device_map), which goes to utils/model.py:3600 -> accelerate.load_checkpoint_in_model -> accelerate.utils.modeling.load_state_dict -> safetensors.torch.load_file(file, device="cuda:1"). With a string device, safetensors' safe_open(..., device="cuda:1") initializes the primary context of the current device (cuda:0) as well as cuda:1. With an int device (device=1), or inside a torch.cuda.device(1) guard, it touches only cuda:1. GPTQModel normalizes every placement to the string form (Loader: device_map = {'': 'cuda:1'}), so every non-zero-ordinal load takes the bad path.
I installed a sys.setprofile hook that checks torch._C._cuda_hasPrimaryContext(0) after every call. The first frame that creates the cuda:0 context is:
gptqmodel/models/loader.py:3362 from_quantized -> load_checkpoint_in_model_then_tie_weights
gptqmodel/utils/model.py:3600 accelerate.load_checkpoint_in_model(model, ...)
accelerate/utils/modeling.py:1692 load_state_dict -> safe_load_file(checkpoint_file, device=target_device)
safetensors/torch.py:360 load_file -> f.get_tensors()
With only safe_open patched to receive the int ordinal, the same load, a forward and generate() leave cuda:0 with no context. Nothing else in the load/inference path touches it.
Repro
import os
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"; os.environ["CUDA_VISIBLE_DEVICES"] = "<gpuA>,<gpuB>"
import subprocess, torch
from gptqmodel import GPTQModel
def my_gpu_mem(): # this process's per-GPU usage as nvidia-smi sees it (no CUDA calls)
q = lambda a: subprocess.run(["nvidia-smi", a, "--format=csv,noheader,nounits"], capture_output=True, text=True).stdout.strip().splitlines()
idx = dict(l.split(", ") for l in q("--query-gpu=gpu_uuid,index"))
return {f"gpu{idx[u]}": int(m) for u, p, m in (map(str.strip, l.split(",")) for l in q("--query-compute-apps=gpu_uuid,pid,used_memory")) if int(p) == os.getpid()}
q = GPTQModel.load("Llama-3.2-1B-Instruct-GPTQ-4bits-gp128", device="cuda:1")
print(my_gpu_mem(), torch._C._cuda_hasPrimaryContext(0))Output (gpuA = physical 2 -> cuda:0, gpuB = physical 4 -> cuda:1):
{'gpu2': 498, 'gpu4': 1450} True
Measured for each placement form (same checkpoint; ctx_after_load is this process's MiB per physical GPU):
| load placement | cuda:0 (unrequested) | cuda:1 |
|---|---|---|
device="cuda:0" (reference) |
1642 | - |
device="cuda:1" |
498 | 1468 |
device_map={"": "cuda:1"} |
498 | 1468 |
max_memory={1: "20GiB"} |
498 | 1468 |
device_map={"": 1} (int) |
0 | 1468 |
The result is the same for every kernel I loaded on cuda:1: Marlin, TritonV2, ExllamaV2, Torch, W4AFP8, the AWQ GEMM / GEMM-Triton / Torch / ExllamaV2 / Marlin kernels, and ExllamaV3 (17-shard EXL3 checkpoint).
The root cause is reproducible with safetensors alone:
from safetensors import safe_open
with safe_open("model.safetensors", framework="pt", device="cuda:1") as f: f.get_tensor(next(iter(f.keys())))
# -> {'gpu2': 498, 'gpu4': 888} cuda:0 context created
with safe_open("model.safetensors", framework="pt", device=1) as f: f.get_tensor(next(iter(f.keys())))
# -> {'gpu4': 888} cuda:0 untouched
with torch.cuda.device(1), safe_open("model.safetensors", framework="pt", device="cuda:1") as f: ...
# -> {'gpu4': 888} cuda:0 untouchedImpact
- Every process that loads a model onto GPU N>0 without hiding GPU 0 claims about 0.5 GiB on GPU 0. With one model per GPU on an 8-GPU host, GPU 0 carries 7 stray contexts (about 3.5 GiB).
- If GPU 0 is full or in exclusive-process compute mode (another job owns it), creating the context fails. A load that never needed GPU 0 can then fail.
- This defeats the "excluded GPU is never touched" guarantee that [BUG] A GPU excluded via
device=still gets a CUDA context and linalg warmup allocations from the global DeviceThreadPool (follow-up to #4233) #4320 and [MEM] Excluded GPU still claimed during quantize (#4320/#4347 incomplete): torch_sync() synchronizes every visible device (498 MiB context), and QuantizeConfig.compute_device_filter gets full warmup/prewarm (1.48 GiB, 384 MiB peak alloc) #4653 established for quantize.
Suggested fix
Run the checkpoint read under a device guard for the target accelerator. For example, wrap the accelerate.load_checkpoint_in_model call in load_checkpoint_in_model_then_tie_weights with torch.cuda.device(first_accelerator_of(device_map)), or pass int ordinals for CUDA entries in the device_map handed to accelerate. A real safetensors read under the guard leaves cuda:0 clean, as shown above. The safetensors behavior is worth reporting upstream too, but GPTQModel can avoid it today with a one-line guard.
Test that should have caught it
tests/test_excluded_device_warmup.py covers only quantize. Add a 2-GPU test that loads a small checkpoint with device="cuda:1" and asserts not torch._C._cuda_hasPrimaryContext(0) after load + generate.
Severity
Medium: 0.5 GiB of memory wasted per process on an unrequested GPU, and a potential load failure when GPU 0 is full or exclusive.
🤖 Generated with Claude Code
Activity
Qubitium commentedon Nov 17, 2026
Agent claim:
agent-root-4863-cuda-ctxis working on this issue now.Started 2026-11-17T18:15:11Z. 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: stop the inference load path from creating a primary CUDA context on cuda:0 when the target is cuda:N (pass the int ordinal to safetensors)
fix(load): read the checkpoint with the int device ordinal so cuda:0 …
Qubitium commentedon Nov 17, 2026
Agent claim released — fixed and merged.
#4915 landed as
beb153af3onmain; the issue is closed.Merge origin/main into transformers5-local-models
fix(load): never test an int-ordinal device map for truthiness (Model…