Skip to content

Kyojin: open-source engine that runs 100 GB-class open models (GLM-5.3, Qwen3.8, DeepSeek V4.1) on one desktop machine. AMD Strix Halo, NVIDIA RTX and Apple Mac. OpenAI API, built on ExLlamaV3.

modules: select the module device at transitions (#186)

resynthb47b1e344d42
diff --git a/exllamav3/model/model_ls.py b/exllamav3/model/model_ls.py
index c166fda..b2c5f61 100644
--- a/exllamav3/model/model_ls.py
+++ b/exllamav3/model/model_ls.py
@@ -5,6 +5,7 @@ import time
import torch
from ..modules.attn import prepare_for_attn
+from ..modules.module import select_exec_device
from ..cache.recurrent_util import prepare_for_recurrence
from ..util.memory import (
set_memory_fraction_reserve,
@@ -197,6 +198,7 @@ class Model_LSMixin(ABC):
if measure:
torch.cuda.reset_peak_memory_stats(load_device)
alloc_before = torch.cuda.memory_allocated(load_device)
+ select_exec_device(module.device)
dummy_state = module.prepare_for_device(dummy_state, params)
dummy_state = module.forward(dummy_state, params)
for sm in module:
@@ -319,6 +321,7 @@ class Model_LSMixin(ABC):
params["layer_instance"] = instance
pf = (idx, instance) == self.last_kv_module_idx_instance
params["prefill"] = pf
+ select_exec_device(module.device)
x = module.prepare_for_device(x, params)
x = module.forward(x, params)
if x is None:
@@ -353,6 +356,7 @@ class Model_LSMixin(ABC):
if span:
x = _span_module(module, x, params)
continue
+ select_exec_device(module.device)
x = module.prepare_for_device(x, params)
x = module.forward(x, params)
return x
@@ -395,6 +399,7 @@ def _span_module(module, x, params):
torch.cuda.synchronize()
_span_state["name"] = f"{module.key}[{params.get('layer_instance')}]"
t0 = _span_state["t0"] = time.perf_counter()
+ select_exec_device(module.device)
x = module.prepare_for_device(x, params)
x = module.forward(x, params)
torch.cuda.synchronize()
diff --git a/exllamav3/modules/module.py b/exllamav3/modules/module.py
index ee520da..3cbcf2a 100644
--- a/exllamav3/modules/module.py
+++ b/exllamav3/modules/module.py
@@ -1,5 +1,6 @@
from __future__ import annotations
from abc import ABC, abstractmethod
+import threading
import torch
from ..util.device_copy import to_device
import os
@@ -11,6 +12,23 @@ from functools import cached_property
# Use host bounce when moving state from device to device in layer split
+# PyTorch guards restore the ambient device after a kernel, but Triton and unguarded extension
+# entry points read it directly. Select the module's device at each transition so those launches
+# stay on the device the tensors live on. Per-thread: CUDA's current device is thread-local too.
+_exec_device = threading.local()
+
+
+def select_exec_device(device) -> None:
+ if device is None:
+ return
+ device = torch.device(device)
+ if device.type != "cuda" or device.index is None:
+ return
+ if getattr(_exec_device, "index", None) != device.index or torch.cuda.current_device() != device.index:
+ torch.cuda.set_device(device.index)
+ _exec_device.index = device.index
+
+
class Module(ABC):
def __init__(
@@ -82,6 +100,7 @@ class Module(ABC):
module.unload()
def prepare_for_device(self, x: torch.Tensor, params: dict) -> torch.Tensor:
+ select_exec_device(self.device)
if x.device != self.device:
# Pinned CPU sources (e.g. the generator's staged input IDs) upload without
# blocking the host; the copy is stream-ordered ahead of the consuming kernels.
diff --git a/tests/test_select_exec_device.py b/tests/test_select_exec_device.py
new file mode 100644
index 0000000..ecacbe7
--- /dev/null
+++ b/tests/test_select_exec_device.py
@@ -0,0 +1,115 @@
+"""select_exec_device: select the module's device at a transition so Triton and unguarded
+extension launches see the device the tensors live on. The cache is thread-local and the
+helper compares against the real current device, so another library changing it is noticed."""
+import importlib
+import sys
+import threading
+import types
+from pathlib import Path
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+_PKGS = ["exllamav3", "exllamav3.modules", "exllamav3.util", "exllamav3.model"]
+_added = []
+for _n in _PKGS:
+ if _n not in sys.modules:
+ _m = types.ModuleType(_n)
+ _m.__path__ = [str(ROOT.joinpath(*_n.split(".")))]
+ sys.modules[_n] = _m
+ _added.append(_n)
+try:
+ module_mod = importlib.import_module("exllamav3.modules.module")
+finally:
+ for _n in _added:
+ sys.modules.pop(_n, None)
+
+
+class FakeCuda:
+ """Per-thread current device, like CUDA's, plus a log of set_device calls."""
+
+ def __init__(self):
+ self._current = threading.local()
+ self.set_calls = []
+ self._lock = threading.Lock()
+
+ def current_device(self):
+ return getattr(self._current, "index", 0)
+
+ def set_device(self, index):
+ with self._lock:
+ self.set_calls.append(int(index))
+ self._current.index = int(index)
+
+
+def fake_cuda(monkeypatch):
+ fake = FakeCuda()
+ monkeypatch.setattr(module_mod.torch.cuda, "current_device", fake.current_device)
+ monkeypatch.setattr(module_mod.torch.cuda, "set_device", fake.set_device)
+ module_mod._exec_device.index = None
+ yield fake
+
+
+def test_sets_the_current_device_and_the_cache(fake_cuda):
+ module_mod.select_exec_device(torch.device("cuda:1"))
+ assert fake_cuda.current_device() == 1
+ assert fake_cuda.set_calls == [1]
+ assert module_mod._exec_device.index == 1
+
+
+def test_accepts_a_device_string(fake_cuda):
+ module_mod.select_exec_device("cuda:1")
+ assert fake_cuda.current_device() == 1
+ assert module_mod._exec_device.index == 1
+
+
+def test_ignores_none_cpu_and_indexless_devices(fake_cuda):
+ for device in (None, "cpu", torch.device("cpu"), torch.device("cuda")):
+ module_mod.select_exec_device(device)
+ assert fake_cuda.set_calls == []
+ assert module_mod._exec_device.index is None
+
+
+def test_notices_an_external_change_behind_the_cache(fake_cuda):
+ module_mod._exec_device.index = 1
+ fake_cuda._current.index = 0
+ module_mod.select_exec_device(torch.device("cuda:1"))
+ assert fake_cuda.set_calls == [1]
+ assert fake_cuda.current_device() == 1
+
+
+def test_does_not_repeat_set_device_when_already_selected(fake_cuda):
+ module_mod.select_exec_device(torch.device("cuda:1"))
+ module_mod.select_exec_device(torch.device("cuda:1"))
+ assert fake_cuda.set_calls == [1]
+
+
+def test_another_thread_keeps_its_own_device(fake_cuda):
+ module_mod.select_exec_device(torch.device("cuda:1"))
+ seen = []
+
+ def worker():
+ seen.append(fake_cuda.current_device())
+ module_mod.select_exec_device(torch.device("cuda:0"))
+ seen.append(fake_cuda.current_device())
+
+ thread = threading.Thread(target = worker)
+ thread.start()
+ thread.join()
+
+ assert seen == [0, 0]
+ assert fake_cuda.current_device() == 1
+
+
[email protected](not torch.cuda.is_available(), reason = "requires a CUDA/ROCm device")
+def test_real_current_device_is_set():
+ prev = torch.cuda.current_device()
+ try:
+ target = 1 if torch.cuda.device_count() > 1 else 0
+ module_mod._exec_device.index = None
+ module_mod.select_exec_device(torch.device("cuda", target))
+ assert torch.cuda.current_device() == target
+ finally:
+ torch.cuda.set_device(prev)