Repository navigation
fix(compile): scope the compiled forward to the model's device (#5101) - #5182
Merged
Merged
Conversation
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
marked this pull request as ready for review
November 18, 2026 08:45
This was referenced Nov 18, 2026
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.
This was referenced Nov 18, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
optimize()installs a compiled modelforwardthat 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 todevice = "cuda"— the current device. A model loaded and compiled oncuda:1therefore created a 388 MiB CUDA primary context oncuda:0when a latergenerate()recompiled for a new batch shape (GPTQ Marlin, AWQ Marlin), or on EXL3's firstgenerate()afteroptimize().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 (defaultcuda:0) leaked into inductor's compile of a recompiled frame.torch/_inductor/fx_passes/joint_graph.py:812—joint_graph_passescallslazy_init(input_device).torch/_inductor/fx_passes/fuse_attention.py:1514—_sfdp_init->_get_sfdp_patterns(input_device=None); with no device it usesdevice = "cuda", i.e. the current device.input_deviceisNone. Instrumentinglazy_initon the repro showsinput_device=Noneframes interleaved withcuda:1frames; theNoneones built their patterns oncuda:0.with torch.cuda.device(1):leftcuda:0untouched before the fix, identifying the current device as the input to the fallback.What changed
gptqmodel/utils/torch.py: newmodel_execution_device()andmodel_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 entertorch.cuda.device(device); other accelerator families use their owndevice()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 compileddequantize_weightproxy 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 oncuda:1,optimize()s, then generates batch 2 and batch 1, assertingtorch._C._cuda_hasPrimaryContext(0)staysFalse, 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;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;gptqmodel/models/base.py:461-470)joint_graph.py:812,fuse_attention.py:1514)"cuda"resolved to the currentcuda:0cuda:1dequantize_weightproxy (gptqmodel/nn_modules/qlinear/torch.py:87-95)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.devicechanges 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 oncuda:1,optimize(), then batch-2 and batch-1generate():04e745269)MarlinLinearctx0=Falseafter batch 2,ctx0=Trueafter batch 1ctx0=Falseafter both; 4 new tokens each; 244 dynamo frames tracedAwqMarlinLinearctx0=Falseafter batch 2,ctx0=Trueafter batch 1ctx0=Falseafter both; 4 new tokens eachExllamaV3Linear)optimize())exllamav3is not installed hereoptimize()(GPTQ Marlin)ctx0=Falsectx0=False; unchangedThe
with torch.cuda.device(1):control leftcuda:0untouched before the change.Tests
Results (rebased head
a60fede36onupstream/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).4863,excluded_device_warmup,optimize_generate_4669,optimize_no_reference_cycle_4937,generation_compile_policy_4669): 53 passed in 165.14s.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.LocalEntryNotFoundErrorforHuggingFaceTB/SmolLM2-135MwithHF_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_CHECKPOINTto point at one); it never downloads inside a device-context test.Unverified / out of scope
ExllamaV3Linear): no checkpoint cached andexllamav3is 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 EXL3generate()runs is covered by the shared scope.device()context and is a no-op when no accelerator tensor is present.torch.cuda.deviceis the HIP namespace, but no ROCm host was available.Review notes
model_execution_device_scopeintentionally follows the call's inputs so a device-mapped layer oncuda:2is scoped tocuda:2; the embedding is only a fallback.