Skip to content

fix(loader): scope Defuser's cache flush to the converted model's devices (#5105) - #5158

Merged
Qubitium merged 2 commits into
mainfrom
fix/5105-moe-defuser-device-context
Nov 18, 2026
Merged

Qubitium merged 2 commits into
mainfrom
fix/5105-moe-defuser-device-context

Conversation

@Qubitium

Copy link
Copy Markdown
Collaborator

Summary

Fused-expert MoE loads no longer initialize a CUDA primary context on a GPU the caller excluded. The net change is +415 / −55 across 8 files (5 production files, 2 test files, README); the architectural effect is narrow: Defuser's cache flush now receives the device list of the model it is converting instead of synchronizing whatever device happens to be current.

Fixes #5105. Draft; not marking ready.

Root cause

ModelLoader.from_quantized converts fused experts before any weight reaches the target GPU (gptqmodel/models/loader.py:1094). The quantize load reaches the same helper from gptqmodel/models/loader.py:2390/2395/2440, and the Transformers bridge calls defuser.convert_model directly at gptqmodel/utils/hf_load.py:340.

defuser.modeling.moe_experts_interface.prepare_model_for_moe_quantization calls clear_memory() with no device list (defuser/modeling/moe_experts_interface.py:790). That helper runs torch.cuda.synchronize() with no device (defuser/utils/device.py:61), which targets the current device and therefore creates the primary context of cuda:0 — even when the model is still on CPU/meta and the caller asked for cuda:1 (or cpu).

The pinned Defuser API (>=0.0.31; the environment here has 0.0.28) has no device argument to convert_model, and 0.0.31 still contains the same clear_memory() call, so a dependency bump cannot fix this. The loader must supply the device list.

Old flow (before, e2f9676c6)

flowchart TD
    A["_convert_model_with_defuser<br/>loader.py:1094"] --> B["defuser.convert_model<br/>loader.py:1096"]
    B --> C["prepare_model_for_moe_quantization<br/>moe_experts_interface.py:790"]
    C --> D["clear_memory() with no device_list<br/>defuser/utils/device.py:61"]
    D --> E{"torch.cuda.is_available?"}
    E -- Yes --> F["torch.cuda.synchronize()<br/>current device is cuda:0"]
    F --> G["primary context created on cuda:0<br/>excluded GPU claimed"]
    E -- No --> H["no accelerator touched"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    class G failure;
Loading

New flow (after)

flowchart TD
    A["_convert_model_with_defuser<br/>loader.py:1101"] --> S["defuser_conversion_scope(model)<br/>utils/torch.py:679"]
    S --> D0["model_accelerator_devices(model)<br/>utils/torch.py:653"]
    D0 --> D1{"Accelerator tensors present?"}
    D1 -- Yes --> D2["device_list = exact ordinals"]
    D1 -- No --> D3["device_list = CPU-only"]
    D2 --> P["scope defuser<br/>moe_experts_interface.clear_memory"]
    D3 --> P
    P --> B["defuser.convert_model"]
    B --> C["prepare_model_for_moe_quantization<br/>moe_experts_interface.py:790"]
    C --> D["clear_memory(device_list=...)"]
    D --> E{"CUDA entries in device_list?"}
    E -- Yes --> F["torch.cuda.synchronize(ordinal)<br/>only devices holding tensors"]
    E -- No --> G["skip synchronize<br/>torch.cuda.empty_cache() only"]
    F --> R["restore original clear_memory"]
    G --> R
    R --> I["caller's device map still places every weight"]
    classDef failure fill:#ffe8e8,stroke:#b30000,color:#111;
    classDef ok fill:#e8f5e9,stroke:#1b5e20,color:#111;
    class I,R ok;
Loading

Failure contract

  • CPU/meta model → CPU-only device list. clear_memory skips synchronize(); torch.cuda.empty_cache() still runs and does not create a primary context (verified on torch 2.15.0+cu132).
  • Model already holding accelerator tensors → exactly those ordinals are synchronized, so a real barrier is never dropped.
  • Defuser layout without defuser.modeling.moe_experts_interface.clear_memory → the scope yields unchanged (fail-open to the old single-device synchronize) instead of failing the load.
  • Defuser's XPU flush synchronizes unconditionally and takes no device list; it stays outside this scope and remains unverified for exclusion.
  • Tensor placement and the caller's device map are untouched; only the set of devices the cache flush may synchronize changes.

Changes

File Purpose
gptqmodel/utils/torch.py (+81) model_accelerator_devices() reads the model's real ordinals; defuser_conversion_scope() scopes Defuser's clear_memory reference to that list and restores it.
gptqmodel/models/loader.py (±64) Wrap the native conversion (inference load and quantize load) in the scope.
gptqmodel/utils/hf_load.py (+9/−2) Wrap the Transformers bridge conversion, including the meta path.
gptqmodel/models/definitions/deepseek_v4.py (+7/−3) Wrap the DeepSeek V4 MTP conversion.
tests/test_load_device_context_4863.py (+84/−20) Adds a two-layer fused-expert OLMoE checkpoint to the cuda:1 load case; keeps the dense control.
tests/test_excluded_device_warmup.py (+132/−4) Adds the fused-expert OLMoE quantize load with device=("cuda:1",), records the context before/immediately after the load, and unit-tests the injected device list.
README.md, docs/multi_gpu_quantization.md Mechanism page and link.

Docs: Fused-expert conversion device scope.

Evidence

Hardware: RTX 5090 visible as cuda:1 (CUDA_VISIBLE_DEVICES=1,2), torch 2.15.0+cu132, transformers 5.22.1, Defuser 0.0.28.

Scenario Before (e2f9676c6) After
GPTQModel.load(OLMoE-q, device="cuda:1") + forward ctx0=True, ctx1=True, finite logits ctx0=False, ctx1=True, finite logits
GPTQModel.load(OLMoE-src, cfg, device=("cuda:1",)) + quantize before_load=False, after_load=True, claimed=True before_load=False, after_load=False, claimed=False, peak1>0, peak0=0
GPTQModel.load(OLMoE-q, device="cpu") ctx0=True ctx0=False, ctx1=False
Qwen1.5-MoE (Qwen2MoeForCausalLM) load on cuda:1 ctx0=False ctx0=False
Dense Qwen2 load on cuda:1 ctx0=False ctx0=False
AutoModelForCausalLM.from_pretrained(OLMoE-q, device_map={"": "cuda:1"}) not measured ctx0=False, ctx1=True, finite logits

Red evidence was produced in a detached worktree at e2f9676c6 (/tmp/pre5105) with only the two test files copied in:

  • test_load_device_context_4863.py::...[fused_expert_moe_checkpoint-cuda:1] fails at assert 'ctx0= False' in ... because the child printed ctx0= True.
  • test_excluded_device_warmup.py::test_quantize_fused_expert_moe_never_claims_the_excluded_device fails at after_load is False with {'before_load': False, 'after_load': True, 'before': True, 'claimed': True, 'peak0': 0, 'peak1': 403415552}.

Both pass on the fix.

Tests

CUDA_VISIBLE_DEVICES=1,2 PYTHONPATH=<worktree> HF_HUB_OFFLINE=1 \
  python -m pytest tests/test_load_device_context_4863.py -q -rs
# 4 passed (dense + fused-expert OLMoE × device / device_map)

CUDA_VISIBLE_DEVICES=1,2 PYTHONPATH=<worktree> HF_HUB_OFFLINE=1 \
  python -m pytest tests/test_excluded_device_warmup.py -q -rs
# 19 passed

CUDA_VISIBLE_DEVICES=1,2 PYTHONPATH=<worktree> HF_HUB_OFFLINE=1 \
  python -m pytest tests/test_load_device_context_4863.py tests/test_moe_reload_meta_4400.py \
  tests/test_docs_contract_refs.py -q -rs
# 30 passed

CUDA_VISIBLE_DEVICES=1,2 PYTHONPATH=<worktree> HF_HUB_OFFLINE=1 \
  python -m pytest tests/test_awq_moe_hf_load_4661.py -q -rs
# 3 passed

ruff check <changed files>
# All checks passed (ruff 0.17.4; pyproject pins 0.14.2, not available in this env)

Unverified / scope limits

  • Defuser 0.0.28 is installed while requirements.txt pins >=0.0.31; the loader logs its pre-existing version error. OLMoE still converts here. I checked the 0.0.31 sdist: it has the same clear_memory() call, so the guard is still required.
  • The XPU flush inside Defuser remains unconditional and is not covered.
  • No HIP run; the primary-context query is process-wide on HIP, so the CUDA-specific regression tests skip there (existing behavior).
  • I did not test a model that is already CUDA-resident at conversion time; the scope reads its ordinals and passes them through, but no regression exercises that branch.

…ices

Defuser's fused-expert conversion calls clear_memory() without a device
list, and that helper synchronizes the *current* CUDA device. Converting
a CPU/meta model therefore created a 386 MiB primary context on cuda:0
for every OLMoE-family load, including `device="cuda:1"` inference loads,
`device=("cuda:1",)` quantization loads, and CPU-only loads (#5105).

Defuser is pinned and exposes no device argument, so bound its
module-level clear_memory reference for the duration of the conversion:
`model_accelerator_devices()` reads the ordinals that actually hold
parameters or buffers. A model that already lives on an accelerator
synchronizes exactly those ordinals; a CPU/meta model passes a CPU-only
list, which skips the synchronize but keeps torch.cuda.empty_cache()
(that call does not create a context). Tensor placement is untouched.

Apply the scope at every Defuser entry point: the native loader (which
covers the inference and quantize loads), the Transformers bridge, and
the DeepSeek V4 MTP conversion.

Regression tests extend the existing device-context families with a
two-layer fused-expert OLMoE fixture for both load paths, plus a unit
test for the injected device list.

Fixes #5105
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