Skip to content

fix(compile): scope the compiled forward to the model's device (#5101) - #5182

Merged
Qubitium merged 1 commit into
mainfrom
fix/5101-compiled-forward-device
Nov 18, 2026
Merged

Qubitium merged 1 commit into
mainfrom
fix/5101-compiled-forward-device

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

optimize() installs a compiled model forward that ran with no device guard. Inductor initializes its lazy SDPA patterns from the traced frame's input device; a quantized-kernel graph break can leave that frame without a device-bearing input, so _get_sfdp_patterns(input_device=None) falls back to device = "cuda" — the current device. A model loaded and compiled on cuda:1 therefore created a 388 MiB CUDA primary context on cuda:0 when a later generate() recompiled for a new batch shape (GPTQ Marlin, AWQ Marlin), or on EXL3's first generate() after optimize().

This is the #4863 class on the compiled path. The fix adds model_execution_device_scope() and enters the model's execution device for the compiled call, restoring the caller's current device on success and on exception. Net diff: +383/-4 across 6 files.

Fixes #5101

Root cause

  • gptqmodel/models/base.py:461-476 — _CompiledModelForward.__call__ invoked the compiled forward directly, with no device guard, so the process current device (default cuda:0) leaked into inductor's compile of a recompiled frame.
  • torch/_inductor/fx_passes/joint_graph.py:812 — joint_graph_passes calls lazy_init(input_device).
  • torch/_inductor/fx_passes/fuse_attention.py:1514 — _sfdp_init -> _get_sfdp_patterns(input_device=None); with no device it uses device = "cuda", i.e. the current device.
  • Quantized kernels break the graph, so some frames carry no device-bearing input and input_device is None. Instrumenting lazy_init on the repro shows input_device=None frames interleaved with cuda:1 frames; the None ones built their patterns on cuda:0.
  • Control: wrapping the same GPTQ sequence in with torch.cuda.device(1): left cuda:0 untouched before the fix, identifying the current device as the input to the fallback.

What changed

  • gptqmodel/utils/torch.py: new model_execution_device() and model_execution_device_scope(). The device is the first accelerator input (nested tuples/lists/dicts inspected), else the input embedding, else the first accelerator parameter/buffer. CUDA/HIP enter torch.cuda.device(device); other accelerator families use their own device() context; CPU/no-accelerator is a no-op. Only the current device changes.
  • gptqmodel/models/base.py: the compiled-forward proxy runs inside the scope.
  • gptqmodel/nn_modules/qlinear/torch.py: the compiled dequantize_weight proxy runs inside the scope (it is reachable without the model-forward proxy).
  • tests/test_load_device_context_4863.py: subprocess regression that loads a real GPTQ Marlin checkpoint on cuda:1, optimize()s, then generates batch 2 and batch 1, asserting torch._C._cuda_hasPrimaryContext(0) stays False, tokens are produced, and dynamo traced frames > 0; plus unit cases for device restoration (including on exception) and input precedence.
  • docs/multi_gpu_quantization.md + README.md: mechanism page section with the diagrams below.

Flow: before

flowchart TD
    A["generate() enters compiled forward<br/>base.py:461-470 proxy"] --> B["compiled forward<br/>no device guard"]
    B --> C["inductor joint_graph_passes<br/>joint_graph.py:812"]
    C --> D["lazy_init(input_device=None)<br/>graph-break frame has no device input"]
    D --> E["_sfdp_init -> _get_sfdp_patterns<br/>fuse_attention.py:1514"]
    E --> F["device = 'cuda'<br/>resolves to current device cuda:0"]
    F --> G["primary context on cuda:0<br/>excluded GPU claimed"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class G failure;
Loading

Flow: after

flowchart TD
    A["generate() enters compiled forward<br/>base.py:476"] --> S["model_execution_device_scope<br/>utils/torch.py:848"]
    S --> P0["model_execution_device<br/>utils/torch.py:816"]
    P0 --> P1{"first accelerator input?"}
    P1 -- Yes --> P2["use that input's device"]
    P1 -- No --> P3{"input embedding on an accelerator?"}
    P3 -- Yes --> P4["use the embedding's device"]
    P3 -- No --> P5["first accelerator parameter or buffer"]
    P2 --> E0{"accelerator device?"}
    P4 --> E0
    P5 --> E0
    E0 -- No --> C0["compiled forward unchanged<br/>CPU or no accelerator"]
    E0 -- Yes --> E1["enter torch.cuda.device(model device)"]
    E1 --> B["compiled forward"]
    B --> C["inductor joint_graph_passes<br/>joint_graph.py:812"]
    C --> D["lazy_init(input_device=None)"]
    D --> E["_sfdp_init -> _get_sfdp_patterns<br/>fuse_attention.py:1514"]
    E --> F["device = 'cuda'<br/>resolves to cuda:1"]
    F --> R["restore caller's current device<br/>on success and on exception"]
    classDef ok fill:#e8f5e9,stroke:#1b5e20,color:#111;
    class E1,F,R ok;
Loading
Mechanism Before After
Compiled forward proxy (gptqmodel/models/base.py:461-470) Ran with no device guard Enters the model's execution device and restores the caller's device
Inductor lazy SDPA init (joint_graph.py:812, fuse_attention.py:1514) Device-less fallback "cuda" resolved to the current cuda:0 Resolves inside the scope to the model's cuda:1
Compiled dequantize_weight proxy (gptqmodel/nn_modules/qlinear/torch.py:87-95) Direct compiled-kernel call had no device guard Scoped to the module's device
Multi-device map Not handled First accelerator input, then input embedding, then first parameter/buffer

Failure contract: the previous current device is restored on exception; CPU/no-accelerator calls are unchanged; tensor placement and the caller's device map are untouched; torch.cuda.device changes the current index without allocating.

Evidence

Two RTX 4090s visible as cuda:0/cuda:1; torch 2.15.0+cu132, transformers 5.22.1, triton 3.9. Load on cuda:1, optimize(), then batch-2 and batch-1 generate():

Checkpoint / kernel Before (04e745269) After
Llama-3.2-1B GPTQ-4bit-g128, MarlinLinear ctx0=False after batch 2, ctx0=True after batch 1 ctx0=False after both; 4 new tokens each; 244 dynamo frames traced
Qwen2.5-0.5B-Instruct-AWQ, AwqMarlinLinear ctx0=False after batch 2, ctx0=True after batch 1 ctx0=False after both; 4 new tokens each
EXL3 (ExllamaV3Linear) Reported in #5101 (first generate after optimize()) Unverified: no EXL3 checkpoint cached and exllamav3 is not installed here
No optimize() (GPTQ Marlin) ctx0=False ctx0=False; unchanged

The with torch.cuda.device(1): control left cuda:0 untouched before the change.

Tests

# red on upstream/main (fix reverted), green with the fix
CUDA_VISIBLE_DEVICES=0,1 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 \
TORCHINDUCTOR_CACHE_DIR=$PWD/.inductor-cache \
/root/venv/bin/python -m pytest tests/test_load_device_context_4863.py -q

# neighboring compile/device suites
CUDA_VISIBLE_DEVICES=0,1 PYTHONPATH=$PWD HF_HUB_OFFLINE=1 \
TORCHINDUCTOR_CACHE_DIR=$PWD/.inductor-cache \
/root/venv/bin/python -m pytest \
  tests/test_load_device_context_4863.py \
  tests/test_excluded_device_warmup.py \
  tests/test_optimize_generate_4669.py \
  tests/test_optimize_no_reference_cycle_4937.py \
  tests/test_generation_compile_policy_4669.py -q

uvx [email protected] check gptqmodel tests setup.py

Results (rebased head a60fede36 on upstream/main @ fba0d0eca):

  • tests/test_load_device_context_4863.py: 7 passed in 131.92s (includes the 4 load cases, the compiled Marlin regression, and the 2 scope unit cases).
  • Five required suites together (4863, excluded_device_warmup, optimize_generate_4669, optimize_no_reference_cycle_4937, generation_compile_policy_4669): 53 passed in 165.14s.
  • Red evidence on upstream/main (fba0d0eca, fix reverted, same test file): after_batch1_ctx0= True -> assert 'after_batch1_ctx0= False' fails; after_batch2_ctx0= False, compiled= True, traced_frames= 244. Same command passes on the fix.
  • uvx [email protected] check gptqmodel tests setup.py: All checks passed!
  • tests/test_optimize_dynamo_release_5020.py (not part of the required matrix) errors at fixture setup in this environment: huggingface_hub.errors.LocalEntryNotFoundError for HuggingFaceTB/SmolLM2-135M with HF_HUB_OFFLINE=1. Environmental, not caused by this change.

The compiled regression skips when no cached 4-bit GPTQ checkpoint is available (set GPTQMODEL_DEVICE_CONTEXT_GPTQ_CHECKPOINT to point at one); it never downloads inside a device-context test.

Unverified / out of scope

  • EXL3 (ExllamaV3Linear): no checkpoint cached and exllamav3 is not installed in this environment, so its first-generate() path was not executed. The mechanism is the same device-less inductor fallback, and the compiled-forward proxy that EXL3 generate() runs is covered by the shared scope.
  • Other accelerator families (XPU/NPU/MPS) were not exercised; the scope uses each family's own device() context and is a no-op when no accelerator tensor is present.
  • ROCm: torch.cuda.device is the HIP namespace, but no ROCm host was available.
  • Multi-device maps are covered by the unit case for input precedence, not by a real split model.

Review notes

  • model_execution_device_scope intentionally follows the call's inputs so a device-mapped layer on cuda:2 is scoped to cuda:2; the embedding is only a fallback.
  • No tensor placement, allocation or dtype change; the scope only sets the current device for the duration of the compiled call.

optimize() installs a compiled forward proxy that ran without a device
guard. Inductor initializes its lazy SDPA patterns from the traced
frame's input device; a quantized-kernel graph break can leave that
frame without a device-bearing input, so _get_sfdp_patterns falls back
to device="cuda" -- the current device. A model loaded and compiled on
cuda:1 therefore claimed cuda:0's 388 MiB primary context when a later
generate recompiled for a new batch shape (GPTQ Marlin, AWQ Marlin, and
EXL3's first generate).

Add model_execution_device_scope() in gptqmodel/utils/torch.py. It
enters the device of the first accelerator input, else the input
embedding, else the first accelerator parameter/buffer, and restores the
caller's previous current device on success and on exception. Tensor
placement is untouched. Wrap the compiled model-forward proxy and the
compiled dequantize_weight proxy in it.

Regression tests extend tests/test_load_device_context_4863.py with a
real GPTQ Marlin optimize()+batch-2+batch-1 generate in a subprocess,
asserting cuda:0 stays unclaimed, plus unit cases for device restoration
and input precedence. The compiled-call test fails on 04e7452 and
passes with the scope.

Fixes #5101
@Qubitium
Qubitium marked this pull request as ready for review November 18, 2026 08:45
@Qubitium
Qubitium merged commit a13fe7a into main Nov 18, 2026
6 checks passed
@Qubitium
Qubitium deleted the fix/5101-compiled-forward-device branch November 18, 2026 08:46
Qubitium added a commit that referenced this pull request Nov 18, 2026
…#5201) (#5217)

`docs/generate-cpu-offload-autograd.md` cited `gptqmodel/models/base.py:3939`
for `generate`. Three merges after #5165 repaired it, #5176 and #5182 moved
`def generate` to 3948, outside `LINE_WINDOW`, so
`test_docs_contract_refs.py::test_contract_reference_resolves` was red on
`main`.

Cite the symbol instead, as the test's own header already recommends for a
file that moves often. The registry keeps one `SYMBOL_CITATION` entry instead
of the line-anchored duplicate.

Also convert the remaining guarded `base.py:359` citation
(`_quantize_summary_counts`) and add
`test_models_base_citations_use_the_symbol_form`, which rejects any future
line-numbered citation into `models/base.py` in the registry. That file grows
with nearly every fix PR, so a line citation drifts within a couple of merges.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

1 participant