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.

HIP JIT: key state and arch by the calling device (#187)

resynth1cb0b97b610e
diff --git a/exllamav3/modules/attention_fn/qsa_prefill_hip.py b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
index 08577fa..1443b86 100644
--- a/exllamav3/modules/attention_fn/qsa_prefill_hip.py
+++ b/exllamav3/modules/attention_fn/qsa_prefill_hip.py
@@ -2,6 +2,7 @@
import ctypes, hashlib, os, re, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "qsa_prefill.hip")
_state = {}
@@ -44,9 +45,11 @@ def hsaco_stats(path):
g = lambda k: (int(re.search(k + r":\s+(\d+)", t).group(1)) if re.search(k + r":\s+(\d+)", t) else -1)
return dict(vgpr = g(r"\.vgpr_count"), spill = g(r"\.vgpr_spill_count"), lds = g(r"\.group_segment_fixed_size"))
-def _load(defs = ""):
- if defs in _state: return _state[defs]
- cache = compile_hsaco(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(defs = "", device = None):
+ dev = select_device(device)
+ key = (dev, defs)
+ if key in _state: return _state[key]
+ cache = compile_hsaco(defs, device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -54,7 +57,7 @@ def _load(defs = ""):
fn = ctypes.c_void_p()
if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"qsa_pf") != 0: raise RuntimeError("qsa_prefill_hip: no function")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state["lib"] = lib; _state[defs] = fn; _state["mod", defs] = mod
+ _state["lib"] = lib; _state[key] = fn; _state["mod", key] = mod
return fn
def qsa_prefill_hip(q, k, v, indices, sm_scale, block_table, page_size, out = None, defs = ""):
@@ -71,7 +74,7 @@ def qsa_prefill_hip(q, k, v, indices, sm_scale, block_table, page_size, out = No
npages = block_table.shape[-1]
ntok = k.shape[0]
assert v.shape[0] == ntok
- fn = _load(defs)
+ fn = _load(defs, q.device)
cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, k, v, block_table, indices, out)] + \
[ctypes.c_int(x) for x in (q.stride(0), out.stride(0), bt_stride, k.stride(0), ntok, npages)] + [ctypes.c_float(sm_scale)]
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
diff --git a/exllamav3/modules/dsv41_fn/ds41_pf.py b/exllamav3/modules/dsv41_fn/ds41_pf.py
index 4633ec8..a1a7c94 100644
--- a/exllamav3/modules/dsv41_fn/ds41_pf.py
+++ b/exllamav3/modules/dsv41_fn/ds41_pf.py
@@ -2,6 +2,7 @@
import ctypes, hashlib, os, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ds41_pf.hip")
@@ -25,27 +26,33 @@ def compile_hsaco(arch="gfx1151"):
return cache
-def _fn(name):
- if name in _state:
- return _state[name]
- cache = compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _fn(name, device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key][name]
+ cache = compile_hsaco(device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0:
raise RuntimeError("ds41_pf: hipModuleLoad failed")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state.update(lib=lib, mod=mod)
+ fns = {}
for nm in _FUNCS:
fn = ctypes.c_void_p()
if lib.hipModuleGetFunction(ctypes.byref(fn), mod, nm.encode()) != 0:
raise RuntimeError("ds41_pf: no function " + nm)
- _state[nm] = fn
- return _state[name]
+ fns[nm] = fn
+ _state.update(lib=lib)
+ _state[key] = fns
+ _state["mod", key] = mod
+ return fns[name]
def _launch(name, grid, block, args):
- fn = _fn(name)
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ fn = _fn(name, device)
cargs = []
for a in args:
if isinstance(a, torch.Tensor):
@@ -95,7 +102,7 @@ def sparse_attention(q, kv, sink, idx, scale):
o = torch.empty_like(q)
if K == 0 or N == 0:
return o.zero_()
- fn = _fn("ds41_sparse_attn_pf")
+ fn = _fn("ds41_sparse_attn_pf", q.device)
cargs = [ctypes.c_void_p(a.data_ptr()) for a in (q, kv, idx, sink, o)] + [ctypes.c_int(K), ctypes.c_int(N), ctypes.c_float(scale)]
params = (ctypes.c_void_p * len(cargs))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in cargs])
r = _state["lib"].hipModuleLaunchKernel(fn, R, 1, 1, 512, 1, 1, 0, torch.cuda.current_stream().cuda_stream, params, None)
diff --git a/exllamav3/modules/dsv41_fn/dsv41_fuse.py b/exllamav3/modules/dsv41_fn/dsv41_fuse.py
index 0d39021..6ba7b2c 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_fuse.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_fuse.py
@@ -4,6 +4,7 @@ bit-identical to the torch chain it replaces (tools/ds41/fuse_check.py)."""
import ctypes, os
import torch
from . import dsv41_hip as H
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dsv41_fuse.hip")
@@ -18,10 +19,12 @@ def available(device) -> bool:
return torch.device(device).type == "cuda" and torch.cuda.is_available() and torch.version.hip is not None
-def _load():
- if "fns" in _state:
- return _state["fns"]
- cache = H.compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0], src_path=_SRC)
+def _load(device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ cache = H.compile_hsaco(device_arch(dev), src_path=_SRC)
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -34,12 +37,15 @@ def _load():
raise RuntimeError("dsv41_fuse: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state.update(lib=lib, fns=fns, mod=mod)
+ _state.update(lib=lib)
+ _state[key] = fns
+ _state["mod", key] = mod
return fns
def _launch(name, grid, block, args):
- fn = _load()[name]
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ fn = _load(device)[name]
cargs, params = H._pack(args)
r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], 1, 1, block, 1, 1, 0,
torch.cuda.current_stream().cuda_stream, params, None)
diff --git a/exllamav3/modules/dsv41_fn/dsv41_hip.py b/exllamav3/modules/dsv41_fn/dsv41_hip.py
index f4e57f8..7ddd685 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_hip.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_hip.py
@@ -4,6 +4,7 @@
import ctypes, hashlib, os, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -36,10 +37,12 @@ def compile_hsaco(arch="gfx1151", src_path=None):
return cache
-def _load():
- if "fns" in _state:
- return _state["fns"]
- cache = compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ cache = compile_hsaco(device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -52,7 +55,7 @@ def _load():
raise RuntimeError("dsv41_hip: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state["lib"], _state["fns"], _state["mod"] = lib, fns, mod
+ _state["lib"], _state[key], _state["mod", key] = lib, fns, mod
return fns
@@ -74,11 +77,11 @@ def _pack(args):
return cargs, params
-def _go(name, g, block, params):
+def _go(name, g, block, params, device=None):
emu = _state.get("emu") # tests only: CPU emulation of the kernel model (tests/dsv41/hipemu), CPU tensors
if emu:
return emu(name, g, block, params)
- fn = _load()[name]
+ fn = _load(device)[name]
r = _state["lib"].hipModuleLaunchKernel(fn, g[0], g[1], g[2], block, 1, 1, 0,
torch.cuda.current_stream().cuda_stream, params, None)
if r != 0:
@@ -87,7 +90,8 @@ def _go(name, g, block, params):
def _launch(name, grid, block, args):
cargs, params = _pack(args)
- _go(name, tuple(grid) + (1,) * (3 - len(grid)), block, params)
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ _go(name, tuple(grid) + (1,) * (3 - len(grid)), block, params, device)
class Launch:
@@ -97,6 +101,7 @@ class Launch:
def __init__(self, name, grid, block, args):
self.name, self.block = name, block
self.grid = tuple(grid) + (1,) * (3 - len(grid))
+ self.device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
self._keep = [a for a in args if isinstance(a, torch.Tensor)]
self.cargs, self.params = _pack(args)
@@ -104,7 +109,7 @@ class Launch:
self.cargs[i].value = v
def __call__(self):
- _go(self.name, self.grid, self.block, self.params)
+ _go(self.name, self.grid, self.block, self.params, self.device)
def prepare(name, grid, block, args):
diff --git a/exllamav3/modules/dsv41_fn/dsv41_idx.py b/exllamav3/modules/dsv41_fn/dsv41_idx.py
index dede4b3..501c02a 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_idx.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_idx.py
@@ -3,6 +3,7 @@ Same loader model as dsv41_hip.py (hipcc genco on first use, launched on torch's
import ctypes, os
import torch
from . import dsv41_hip as H
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "dsv41_idx.hip")
@@ -16,10 +17,12 @@ def available(device) -> bool:
return torch.device(device).type == "cuda" and torch.cuda.is_available() and torch.version.hip is not None
-def _load():
- if "fns" in _state:
- return _state["fns"]
- cache = H.compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0], src_path=_SRC)
+def _load(device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ cache = H.compile_hsaco(device_arch(dev), src_path=_SRC)
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -32,12 +35,15 @@ def _load():
raise RuntimeError("dsv41_idx: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state.update(lib=lib, fns=fns, mod=mod)
+ _state.update(lib=lib)
+ _state[key] = fns
+ _state["mod", key] = mod
return fns
def _launch(name, grid, block, args):
- fn = _load()[name]
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ fn = _load(device)[name]
cargs, params = H._pack(args)
r = _state["lib"].hipModuleLaunchKernel(fn, grid[0], grid[1], 1, block, 1, 1, 0,
torch.cuda.current_stream().cuda_stream, params, None)
diff --git a/exllamav3/modules/dsv41_fn/dsv41_moe.py b/exllamav3/modules/dsv41_fn/dsv41_moe.py
index d1f7f9c..eaaca3b 100644
--- a/exllamav3/modules/dsv41_fn/dsv41_moe.py
+++ b/exllamav3/modules/dsv41_fn/dsv41_moe.py
@@ -5,6 +5,7 @@ import ctypes, hashlib, os, subprocess
import torch
from . import dsv41_hip as H
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_DIR = os.path.dirname(os.path.abspath(__file__))
@@ -41,10 +42,12 @@ def _compile(arch):
return cache
-def _load():
- if "fns" in _state:
- return _state["fns"]
- cache = _compile(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ cache = _compile(device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -57,7 +60,9 @@ def _load():
raise RuntimeError("dsv41_moe: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state.update(lib=lib, fns=fns, mod=mod)
+ _state.update(lib=lib)
+ _state[key] = fns
+ _state["mod", key] = mod
return fns
@@ -69,7 +74,8 @@ class _L:
"""One launch with a prebuilt argument pack; `ptr(i, t)` re-points a tensor argument."""
def __init__(self, name, grid, block, args):
- self.fn = _load()[name]
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ self.fn = _load(device)[name]
self.grid, self.block = tuple(grid) + (1,) * (3 - len(grid)), block
self._keep = [a for a in args if isinstance(a, torch.Tensor)]
self.cargs, self.params = H._pack(args)
@@ -93,6 +99,7 @@ class UnifiedMoE:
def __init__(self, store, buffers, outs, H_, I_, limit, device):
dev = torch.device(device)
+ self.device = dev
self.store, self.outs, self.limit = store, outs, float(limit)
E = store.num_experts
self.G = store.num_groups
@@ -152,6 +159,7 @@ class UnifiedMoE:
self.l_down.ptr(1, sel)
self.l_final.ptr(1, sel).ptr(2, wh)
self.sig = sig
+ select_device(self.device)
s = torch.cuda.current_stream().cuda_stream
self.l_had(s); self.l_gu(s); self.l_mid(s); self.l_down(s); self.l_final(s)
return self.outs
diff --git a/exllamav3/modules/gr_fn/gr_mix_hip.py b/exllamav3/modules/gr_fn/gr_mix_hip.py
index 6be302f..658a515 100644
--- a/exllamav3/modules/gr_fn/gr_mix_hip.py
+++ b/exllamav3/modules/gr_fn/gr_mix_hip.py
@@ -3,6 +3,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gr_mix.hip")
@@ -27,9 +28,11 @@ def compile_hsaco(defs="", arch="gfx1151", src_path=None):
os.replace(tmp, cache)
return cache
-def _load(defs=""):
- if defs in _state: return _state[defs]
- cache = compile_hsaco(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(defs="", device=None):
+ dev = select_device(device)
+ key = (dev, defs)
+ if key in _state: return _state[key]
+ cache = compile_hsaco(defs, device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -40,7 +43,7 @@ def _load(defs=""):
if lib.hipModuleGetFunction(ctypes.byref(fn), mod, n.encode()) != 0: raise RuntimeError("gr_mix_hip: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state["lib"] = lib; _state[defs] = fns; _state["mod", defs] = mod
+ _state["lib"] = lib; _state[key] = fns; _state["mod", key] = mod
return fns
def _launch(fn, grid, block, args):
@@ -70,7 +73,7 @@ def gr_g1(normed, proj, t, post, defs=""):
# the best below that). EXL3_GR_G1_BM64=0 goes back; an explicit defs string always wins
if not defs and R >= 3072 and os.environ.get("EXL3_GR_G1_BM64", "1") != "0": defs = "BM1=64"
bn1, bm1 = _tile(defs, "BN1"), _tile(defs, "BM1")
- _launch(_load(defs)["gr_g1"], ((NTOT + bn1 - 1) // bn1, (R + bm1 - 1) // bm1), 256, [normed, proj, t, post, R, xp])
+ _launch(_load(defs, normed.device)["gr_g1"], ((NTOT + bn1 - 1) // bn1, (R + bm1 - 1) // bm1), 256, [normed, proj, t, post, R, xp])
def gr_g2(t, up, normed, mixed, defs=""):
"""t (R, 320) fp16, up (10240, 320) fp16 contiguous, normed (R*4, 2560) fp16; mixed (R, 2560) fp16 output."""
@@ -78,7 +81,7 @@ def gr_g2(t, up, normed, mixed, defs=""):
assert t.dtype == up.dtype == normed.dtype == mixed.dtype == torch.half and R >= 1
assert t.shape[1] == RANK and up.shape == (K1, RANK) and normed.shape == (R * H, DD) and mixed.shape == (R, DD)
for x in (t, up, normed, mixed): assert x.is_contiguous()
- _launch(_load(defs)["gr_g2"], (DD // 32, (R + 63) // 64), 256, [t, up, normed, mixed, R])
+ _launch(_load(defs, t.device)["gr_g2"], (DD // 32, (R + 63) // 64), 256, [t, up, normed, mixed, R])
def gr_g2s(t, up, normed, mixed, defs=""):
"""LDS-staged G2 (same contract as gr_g2; normed may also be the (R, K1) token-pitched view gr_g1 reads, stride(0) >= K1)."""
@@ -97,4 +100,4 @@ def gr_g2s(t, up, normed, mixed, defs=""):
pitch = mixed.stride(0) if R > 1 else DD
assert mixed.stride(1) == 1 and pitch >= DD and pitch % 8 == 0 and mixed.storage_offset() % 8 == 0, "gr_g2s: mixed layout"
assert mixed.storage_offset() + (R - 1) * pitch + DD <= mixed.untyped_storage().nbytes() // 2, "gr_g2s: mixed outside its storage"
- _launch(_load(defs)["gr_g2s"], (DD // 32, (R + 127) // 128), 256, [t, up, normed, mixed, R, pitch, ngp])
+ _launch(_load(defs, t.device)["gr_g2s"], (DD // 32, (R + 127) // 128), 256, [t, up, normed, mixed, R, pitch, ngp])
diff --git a/exllamav3/modules/ple_fn/ple_hip.py b/exllamav3/modules/ple_fn/ple_hip.py
index a1bc7ec..64b0e21 100644
--- a/exllamav3/modules/ple_fn/ple_hip.py
+++ b/exllamav3/modules/ple_fn/ple_hip.py
@@ -3,6 +3,7 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import device_arch, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "ple_hip.hip")
@@ -32,10 +33,12 @@ def compile_hsaco(arch="gfx1151", src_path=None):
return cache
-def _load():
- if "fns" in _state:
- return _state["fns"]
- cache = compile_hsaco(torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(device=None):
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ cache = compile_hsaco(device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod = ctypes.c_void_p()
@@ -48,12 +51,13 @@ def _load():
raise RuntimeError("ple_hip: no function " + n)
fns[n] = fn
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
- _state["lib"], _state["fns"], _state["mod"] = lib, fns, mod
+ _state["lib"], _state[key], _state["mod", key] = lib, fns, mod
return fns
def _launch(name, grid, block, args):
- fn = _load()[name]
+ device = next((a.device for a in args if isinstance(a, torch.Tensor)), None)
+ fn = _load(device)[name]
cargs = []
for a in args:
if isinstance(a, torch.Tensor):
diff --git a/exllamav3/util/arch_list.py b/exllamav3/util/arch_list.py
index a5c4064..704f597 100644
--- a/exllamav3/util/arch_list.py
+++ b/exllamav3/util/arch_list.py
@@ -31,6 +31,54 @@ def _rocm_device_arch(index: int) -> str:
)
+def device_index(device=None) -> int:
+ """CUDA index for a torch.device, an int, or None (the ambient device)."""
+ if device is None:
+ return torch.cuda.current_device()
+ if isinstance(device, torch.device):
+ if device.type != "cuda":
+ raise ValueError(f"not a CUDA device: {device}")
+ return device.index if device.index is not None else torch.cuda.current_device()
+ return int(device)
+
+
+def device_arch(device=None) -> str:
+ """ROCm arch of a device (index, torch.device, or None for the ambient device)."""
+ return _rocm_device_arch(device_index(device))
+
+
+def select_device(device=None) -> int:
+ """Select the ambient CUDA device when it differs from `device`; return its index.
+
+ The JIT loaders take the calling tensor's device explicitly, so their arch and cache
+ keys do not depend on a separate ambient-device hook having run first."""
+ index = device_index(device)
+ if torch.cuda.current_device() != index:
+ torch.cuda.set_device(index)
+ return index
+
+
+GFX115_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))
+_support_cache = {}
+
+
+def device_supported(device=None, archs=GFX115_ARCHS) -> bool:
+ """True when the device's ROCm arch is in `archs`; cached per (device, arch set)."""
+ try:
+ index = device_index(device)
+ key = (index, archs)
+ ok = _support_cache.get(key)
+ if ok is None:
+ ok = _support_cache[key] = device_arch(index) in archs
+ return ok
+ except Exception: # noqa: BLE001
+ return False
+
+
+def reset_support_cache():
+ _support_cache.clear()
+
+
def maybe_set_arch_list_env():
if os.environ.get('TORCH_CUDA_ARCH_LIST', None):
diff --git a/exllamav3/vendor/fla/__init__.py b/exllamav3/vendor/fla/__init__.py
index 69bd69d..1916125 100644
--- a/exllamav3/vendor/fla/__init__.py
+++ b/exllamav3/vendor/fla/__init__.py
@@ -32,6 +32,12 @@ _HIP_FAIL = [] # first failure disables the HIP path for the process
def _hip_ok(q, k, v, beta, Akk, Aqk, h0):
if _HIP_FAIL:
return False
+ try:
+ from .hip.kda_fused_h_hip import supported as _kda_fused_supported
+ if not _kda_fused_supported(q.device):
+ return False
+ except Exception: # noqa: BLE001
+ return False
bf = torch.bfloat16
ts = (q, k, v, beta, Akk, Aqk)
return (all(t.dtype == bf and t.is_contiguous() for t in ts)
diff --git a/exllamav3/vendor/fla/gdn_fused.py b/exllamav3/vendor/fla/gdn_fused.py
index 3b22b34..6abb833 100644
--- a/exllamav3/vendor/fla/gdn_fused.py
+++ b/exllamav3/vendor/fla/gdn_fused.py
@@ -13,6 +13,9 @@ _FAIL = []
def gdn_fuse_ok(q, k, v, g, beta, initial_state, chunk_size):
if _FAIL or chunk_size != 64:
return False
+ from .hip.gdn_fused_h_hip import supported
+ if not supported(q.device):
+ return False
bf = torch.bfloat16
B, T, H, K = k.shape
HV, V = v.shape[2], v.shape[-1]
diff --git a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
index f18b53f..4727959 100644
--- a/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_fused_h_hip.py
@@ -5,12 +5,20 @@
import ctypes, hashlib, os, shutil, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import GFX115_ARCHS, device_arch, device_supported, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gdn_fused_h.hip")
_state = {}
+def supported(device=None):
+ """gdn_fused_h.hip is a gfx11.5 WMMA kernel; refuse other archs before any hipcc attempt."""
+ if not torch.version.hip:
+ return False
+ return device_supported(device, GFX115_ARCHS)
+
+
def _hipcc():
return hip_compiler.hipcc()
@@ -30,11 +38,13 @@ def _compile(defs, arch):
return cache
-def _load(defs=""):
- # defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per defines string
- if defs in _state:
- return _state[defs]
- cache = _compile(defs, torch.cuda.get_device_properties(0).gcnArchName.split(":")[0])
+def _load(defs="", device=None):
+ # defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per (device, defines) string
+ dev = select_device(device)
+ key = (dev, defs)
+ if key in _state:
+ return _state[key]
+ cache = _compile(defs, device_arch(dev))
lib = load_hip_runtime()
torch.cuda.init()
mod, fn = ctypes.c_void_p(), ctypes.c_void_p()
@@ -44,8 +54,8 @@ def _load(defs=""):
raise RuntimeError("gdn_fused_h_hip: hipModuleGetFunction failed")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
_state["lib"] = lib
- _state[defs] = fn
- _state["mod", defs] = mod
+ _state[key] = fn
+ _state["mod", key] = mod
return fn
@@ -75,7 +85,7 @@ def chunk_gdn_fwd_fused_hip(q, k, v, g, beta, A, scale, initial_state=None, outp
assert c["s"].dtype == torch.float32 and c["s"].is_contiguous() and c["s"].shape == (B, HV, K, V)
if cks:
defs = (defs + " CKPT=1").strip()
- fn = _load(defs)
+ fn = _load(defs, v.device)
o = torch.empty(B, T, HV, V, device=v.device, dtype=v.dtype)
final_state = k.new_empty(B, HV, K, V, dtype=torch.float32) if output_final_state else None
h0 = initial_state
diff --git a/exllamav3/vendor/fla/hip/gdn_hf_hip.py b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
index eb55b39..12527d0 100644
--- a/exllamav3/vendor/fla/hip/gdn_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/gdn_hf_hip.py
@@ -9,44 +9,18 @@
import ctypes, hashlib, os, subprocess
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import GFX115_ARCHS, device_arch, device_supported, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "gdn_hf.hip")
_state = {}
-# gdn_hf.hip has only the RDNA3.5 (gfx11.5) WMMA path; gfx12 is refused before the
-# JIT so no compile is attempted (previously it tried the gfx11 builtin, failed, and
-# printed a warning before falling back to the Triton chain).
-_ARCHS = frozenset(("gfx1150", "gfx1151", "gfx1152"))
-_supported = {} # device index -> bool, once per process
-
-
-def _device_index(device=None):
- if device is None:
- return torch.cuda.current_device()
- if isinstance(device, torch.device):
- return device.index if device.index is not None else torch.cuda.current_device()
- return int(device)
-
-
-def _arch(device=None):
- return torch.cuda.get_device_properties(_device_index(device)).gcnArchName.split(":")[0]
-
def supported(device=None):
- """True when this device's arch has the gdn_hf.hip gfx11.5 fragment path. Cached per device:
- gdn_hf_ok runs once per GDN layer per prefill chunk, so re-probing get_device_properties there
- is pure overhead (the arch cannot change after init)."""
+ """True when this device's arch has the gdn_hf.hip gfx11.5 fragment path (shared gate)."""
if not torch.version.hip:
return False
- try:
- idx = _device_index(device)
- ok = _supported.get(idx)
- if ok is None:
- ok = _supported[idx] = _arch(idx) in _ARCHS
- return ok
- except Exception: # noqa: BLE001
- return False
+ return device_supported(device, GFX115_ARCHS)
def _gcc_flag():
@@ -72,9 +46,11 @@ def _compile_tail(lines, n=12):
def _load(device=None):
- arch = _arch(device)
- if ("fn", arch) in _state:
- return _state["fn", arch]
+ dev = select_device(device)
+ key = (dev, "")
+ if key in _state:
+ return _state[key]
+ arch = device_arch(dev)
src = open(_SRC, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-DKYO_RAW=1", *_gcc_flag()]
tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
@@ -100,8 +76,8 @@ def _load(device=None):
raise RuntimeError("gdn_hf_hip: hipModuleGetFunction failed")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
_state.update(lib=lib)
- _state["mod", arch] = mod
- _state["fn", arch] = fn
+ _state["mod", key] = mod
+ _state[key] = fn
return fn
diff --git a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
index 3049a18..6777930 100644
--- a/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_fused_h_hip.py
@@ -5,12 +5,20 @@
import ctypes, hashlib, os, shutil, subprocess, threading
import torch
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import GFX115_ARCHS, device_arch, device_index, device_supported, select_device
from exllamav3.util.hip_lib import load_hip_runtime
_SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kda_fused_h.hip")
_state = {}
+def supported(device=None):
+ """kda_fused_h.hip is a gfx11.5 WMMA kernel; refuse other archs before any hipcc attempt."""
+ if not torch.version.hip:
+ return False
+ return device_supported(device, GFX115_ARCHS)
+
+
def _hipcc():
return hip_compiler.hipcc()
@@ -52,11 +60,15 @@ def _precompile_siblings(defs, arch):
threading.Thread(target=run, name="kda-fused-h-precompile", daemon=True).start()
-def _load(defs=""):
- # defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per defines string
- if defs in _state:
- return _state[defs]
- arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
+def _load(defs="", device=None):
+ # defs: extra -D defines (timing experiments only, e.g. "ABL=4"); one module per (device, defines) string.
+ # The split runs this kernel on the front gfx1201 and the main gfx1151 in one process: each device needs
+ # its own arch build and function handle.
+ dev = select_device(device)
+ key = (dev, defs)
+ if key in _state:
+ return _state[key]
+ arch = device_arch(dev)
cache = _compile(defs, arch)
lib = load_hip_runtime()
torch.cuda.init()
@@ -67,11 +79,11 @@ def _load(defs=""):
raise RuntimeError("kda_fused_h_hip: hipModuleGetFunction failed")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
_state["lib"] = lib
- _state[defs] = fn
- _state["mod", defs] = mod
+ _state[key] = fn
+ _state["mod", key] = mod
base = " ".join(t for t in defs.split() if t not in _CK)
- if ("pre", base) not in _state:
- _state["pre", base] = True
+ if ("pre", dev, base) not in _state:
+ _state["pre", dev, base] = True
_precompile_siblings(defs, arch)
return fn
@@ -109,7 +121,7 @@ def chunk_kda_fwd_h_fused_hip(q, k, v, gk, beta, Akk, Aqk, scale, initial_state=
defs = (defs + " CK4=1").strip()
elif nslot == 8:
defs = (defs + " CK8=1").strip()
- fn = _load(defs)
+ fn = _load(defs, q.device)
if o is None:
o = torch.empty_like(v)
if output_final_state and final_state is None:
@@ -138,10 +150,11 @@ def chunk_kda_fwd_h_fused_hip(q, k, v, gk, beta, Akk, Aqk, scale, initial_state=
return None, None, o, (final_state if output_final_state else None)
-def read_prof(defs, n):
+def read_prof(defs, n, device=None):
# PROF=1 builds only: per-(WG, wave) phase cycle sums, uint32[n * 8 * 9]
import numpy as np
- lib, mod = _state["lib"], _state["mod", defs]
+ key = (device_index(device), defs)
+ lib, mod = _state["lib"], _state["mod", key]
ptr, size = ctypes.c_void_p(), ctypes.c_size_t()
if lib.hipModuleGetGlobal(ctypes.byref(ptr), ctypes.byref(size), mod, b"kda_prof") != 0:
raise RuntimeError("kda_prof missing")
diff --git a/exllamav3/vendor/fla/hip/kda_hf_hip.py b/exllamav3/vendor/fla/hip/kda_hf_hip.py
index e80c5f6..135c9df 100644
--- a/exllamav3/vendor/fla/hip/kda_hf_hip.py
+++ b/exllamav3/vendor/fla/hip/kda_hf_hip.py
@@ -6,6 +6,7 @@ import ctypes, hashlib, os, subprocess
import torch
import triton
from exllamav3.util import hip_compiler
+from exllamav3.util.arch_list import GFX115_ARCHS, device_arch, device_supported, select_device
from exllamav3.util.knobs import knob
from exllamav3.util.hip_lib import load_hip_runtime
@@ -13,11 +14,20 @@ _SRC = os.path.join(os.path.dirname(os.path.abspath(__file__)), "kda_hf.hip")
_state = {}
-def _load(defs=""):
- # defs: extra -D defines (experiments only, e.g. "KHF_TP=1"); one module per defines string
- if ("fn", defs) in _state:
- return _state["fn", defs]
- arch = torch.cuda.get_device_properties(0).gcnArchName.split(":")[0]
+def supported(device=None):
+ """kda_hf.hip is a gfx11.5 WMMA kernel; refuse other archs before any hipcc attempt."""
+ if not torch.version.hip:
+ return False
+ return device_supported(device, GFX115_ARCHS)
+
+
+def _load(defs="", device=None):
+ # defs: extra -D defines (experiments only, e.g. "KHF_TP=1"); one module per (device, defines) string
+ dev = select_device(device)
+ key = (dev, defs)
+ if key in _state:
+ return _state[key]
+ arch = device_arch(dev)
src = open(_SRC, "rb").read()
flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [f"-D{x}" for x in defs.split()]
flags += hip_compiler.gcc_flags()
@@ -37,15 +47,15 @@ def _load(defs=""):
raise RuntimeError("kda_hf_hip: hipModuleGetFunction failed")
lib.hipModuleLaunchKernel.argtypes = [ctypes.c_void_p] + [ctypes.c_uint] * 7 + [ctypes.c_void_p] * 3
_state["lib"] = lib
- _state["fn", defs] = fn
- _state["mod", defs] = mod
+ _state[key] = fn
+ _state["mod", key] = mod
return fn
def kda_hf_ok(q, k, v, g, beta, initial_state, chunk_size):
"""q, k [1, T, H, 128] bf16 (l2-normalized), v [1, T, HV, 128] bf16, g [1, T, HV, 128] fp32 = 64-row-local log2 cumsum,
beta [1, T, HV] bf16, all contiguous."""
- if knob("EXL3_KDA_HF", "0") != "1" or _state.get("fail"):
+ if knob("EXL3_KDA_HF", "0") != "1" or _state.get("fail") or not supported(q.device):
return False
B, T, H, K = q.shape
HV, V = v.shape[2], v.shape[3]
@@ -64,7 +74,7 @@ def chunk_kda_hf(q, k, v, g, beta, scale, initial_state, output_final_state, ckp
# per call) computes them in the kernel with bf16 WMMA (faster, but heavier per-token error tails on real GLM inputs)
defs = "" if knob("EXL3_KDA_HF_DIAG", "0") == "1" else "KHF_TP=1"
try:
- fn = _load(defs)
+ fn = _load(defs, q.device)
except Exception:
_state["fail"] = True # no hipcc / no module: the Triton/HIP chain for the rest of the process
raise
diff --git a/tests/test_gdn_hf_cpu.py b/tests/test_gdn_hf_cpu.py
index 863c59f..a6cc8a0 100644
--- a/tests/test_gdn_hf_cpu.py
+++ b/tests/test_gdn_hf_cpu.py
@@ -17,6 +17,7 @@ for _n in _PKGS:
sys.modules[_n] = _m; _added.append(_n)
try:
gdn_hf = importlib.import_module("exllamav3.vendor.fla.hip.gdn_hf_hip")
+ arch_list = importlib.import_module("exllamav3.util.arch_list")
finally:
for _n in _added:
sys.modules.pop(_n, None)
@@ -24,9 +25,9 @@ finally:
@pytest.fixture(autouse=True)
def _clean_state():
- gdn_hf._supported.clear()
+ arch_list.reset_support_cache()
yield
- gdn_hf._supported.clear()
+ arch_list.reset_support_cache()
def _dev(arch):
diff --git a/tests/test_multi_device_jit.py b/tests/test_multi_device_jit.py
new file mode 100644
index 0000000..11ead67
--- /dev/null
+++ b/tests/test_multi_device_jit.py
@@ -0,0 +1,244 @@
+"""JIT HIP loaders must key their module/function handles by the calling device.
+
+The engine can run the same kernel on two GPUs from one process. A loader that asks for
+device 0's arch or keeps one handle per defines string runs the wrong code object on the
+other card. The CDC tests below fake the compiler and the HIP runtime, so the state-key
+and arch-selection invariant is checked without a GPU; the hardware tests load every
+loader on both devices. gdn_hf, gdn_fused, kda_fused and kda_hf are gfx11.5-only: on
+gfx1201 their supported() gate must refuse before any hipcc attempt.
+"""
+import ctypes
+import importlib
+import os
+import subprocess
+import sys
+import types
+from pathlib import Path
+from types import SimpleNamespace
+
+import pytest
+import torch
+
+ROOT = Path(__file__).resolve().parent.parent
+_PKGS = ["exllamav3", "exllamav3.util", "exllamav3.vendor", "exllamav3.vendor.fla", "exllamav3.vendor.fla.hip",
+ "exllamav3.modules", "exllamav3.modules.ple_fn", "exllamav3.modules.gr_fn",
+ "exllamav3.modules.dsv41_fn", "exllamav3.modules.attention_fn"]
+_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:
+ hip_compiler = importlib.import_module("exllamav3.util.hip_compiler")
+ arch_list = importlib.import_module("exllamav3.util.arch_list")
+ gr_mix = importlib.import_module("exllamav3.modules.gr_fn.gr_mix_hip")
+ ple = importlib.import_module("exllamav3.modules.ple_fn.ple_hip")
+ qsa = importlib.import_module("exllamav3.modules.attention_fn.qsa_prefill_hip")
+ ds41_pf = importlib.import_module("exllamav3.modules.dsv41_fn.ds41_pf")
+ dsv41_hip = importlib.import_module("exllamav3.modules.dsv41_fn.dsv41_hip")
+ dsv41_idx = importlib.import_module("exllamav3.modules.dsv41_fn.dsv41_idx")
+ dsv41_fuse = importlib.import_module("exllamav3.modules.dsv41_fn.dsv41_fuse")
+ dsv41_moe = importlib.import_module("exllamav3.modules.dsv41_fn.dsv41_moe")
+ gdn_hf = importlib.import_module("exllamav3.vendor.fla.hip.gdn_hf_hip")
+ gdn_fused = importlib.import_module("exllamav3.vendor.fla.hip.gdn_fused_h_hip")
+ kda_fused = importlib.import_module("exllamav3.vendor.fla.hip.kda_fused_h_hip")
+ try:
+ kda_hf = importlib.import_module("exllamav3.vendor.fla.hip.kda_hf_hip")
+ except ImportError:
+ kda_hf = None
+finally:
+ for _n in _added:
+ sys.modules.pop(_n, None)
+
+GFX115 = arch_list.GFX115_ARCHS
+
+# name -> (module, load(device), arch gate)
+CASES = {
+ "gr_mix_hip": (gr_mix, lambda m, d: m._load("", d), GFX115),
+ "ple_hip": (ple, lambda m, d: m._load(d), None),
+ "qsa_prefill_hip": (qsa, lambda m, d: m._load("", d), GFX115),
+ "ds41_pf": (ds41_pf, lambda m, d: m._fn("ds41_gather_sum", d), GFX115),
+ "dsv41_hip": (dsv41_hip, lambda m, d: m._load(d), None),
+ "dsv41_idx": (dsv41_idx, lambda m, d: m._load(d), GFX115),
+ "dsv41_fuse": (dsv41_fuse, lambda m, d: m._load(d), None),
+ "dsv41_moe": (dsv41_moe, lambda m, d: m._load(d), None),
+ "gdn_hf": (gdn_hf, lambda m, d: m._load(d), GFX115),
+ "gdn_fused_h_hip": (gdn_fused, lambda m, d: m._load("", d), GFX115),
+ "kda_fused_h_hip": (kda_fused, lambda m, d: m._load("", d), GFX115),
+ "kda_hf_hip": (kda_hf, lambda m, d: m._load("", d), GFX115),
+}
+SUPPORTED = {"gdn_hf", "gdn_fused_h_hip", "kda_fused_h_hip", "kda_hf_hip"}
+
+
+class FakeCuda:
+ def __init__(self, archs):
+ self.archs = list(archs)
+ self.current = 0
+ self.set_calls = []
+
+ def current_device(self):
+ return self.current
+
+ def set_device(self, index):
+ self.set_calls.append(int(index))
+ self.current = int(index)
+
+ def get_device_properties(self, index):
+ return SimpleNamespace(gcnArchName = f"{self.archs[int(index)]}:sramecc+:xnack-")
+
+ def init(self):
+ pass
+
+ def synchronize(self, *_a, **_k):
+ pass
+
+
+class FakeLaunch:
+ argtypes = None
+
+ def __call__(self, *_a, **_k):
+ return 0
+
+
+class FakeLib:
+ def __init__(self):
+ self.hipModuleLaunchKernel = FakeLaunch()
+ self.loaded = []
+
+ def hipModuleLoad(self, ref, path):
+ self.loaded.append(path)
+ ctypes.cast(ref, ctypes.POINTER(ctypes.c_void_p))[0] = 0x1000 + len(self.loaded)
+ return 0
+
+ def hipModuleGetFunction(self, ref, _mod, name):
+ ctypes.cast(ref, ctypes.POINTER(ctypes.c_void_p))[0] = 0x2000 + sum(name) % 0x1000
+ return 0
+
+ def hipModuleGetGlobal(self, _ptr, _size, _mod, _name):
+ return 1
+
+
+def fake_jit(monkeypatch, tmp_path):
+ for k in ("EXL3_HIPCC", "EXL3_ROCM_SDK"):
+ monkeypatch.delenv(k, raising = False)
+ monkeypatch.setenv("HOME", str(tmp_path))
+ monkeypatch.setattr(torch.version, "hip", "7.2.0")
+ monkeypatch.setattr(hip_compiler, "_info",
+ {"path": "/bin/true", "version": "hipcc fake", "key": "deadbeef",
+ "sdk": None, "sdk_ok": True, "source": "test"})
+ monkeypatch.setattr(hip_compiler, "gcc_flags", list)
+ compiles = []
+
+ def fake_run(cmd, **_kwargs):
+ compiles.append(list(cmd))
+ if "-o" in cmd:
+ path = cmd[cmd.index("-o") + 1]
+ os.makedirs(os.path.dirname(path), exist_ok = True)
+ with open(path, "wb") as f:
+ f.write(b"built")
+ return SimpleNamespace(returncode = 0, stdout = "", stderr = "")
+
+ monkeypatch.setattr(subprocess, "run", fake_run)
+ monkeypatch.setattr(qsa, "require_proof", lambda *_a, **_k: None)
+ monkeypatch.setattr(kda_fused, "_precompile_siblings", lambda *_a, **_k: None)
+ cuda = FakeCuda(["gfx1151", "gfx1201"])
+ monkeypatch.setattr(torch.cuda, "current_device", cuda.current_device)
+ monkeypatch.setattr(torch.cuda, "set_device", cuda.set_device)
+ monkeypatch.setattr(torch.cuda, "get_device_properties", cuda.get_device_properties)
+ monkeypatch.setattr(torch.cuda, "init", cuda.init)
+ monkeypatch.setattr(torch.cuda, "synchronize", cuda.synchronize)
+ arch_list.reset_support_cache()
+ libs = {}
+ for module, _call, _gate in CASES.values():
+ if module is not None:
+ module._state.clear()
+ lib = FakeLib()
+ libs[module] = lib
+ monkeypatch.setattr(module, "load_hip_runtime", lambda lib = lib: lib)
+ yield compiles, cuda
+ for module in libs:
+ module._state.clear()
+ arch_list.reset_support_cache()
+
+
+def _call(case, module, device):
+ return case[1](module, device)
+
+
+def _handles(fn):
+ if isinstance(fn, dict):
+ return list(fn.values())
+ return [fn]
+
+
[email protected]("name", list(CASES))
+def test_state_keys_are_per_device(fake_jit, name):
+ module, _call_fn, _gate = CASES[name]
+ if module is None:
+ pytest.skip("module is not importable without Triton")
+ compiles, cuda = fake_jit
+ compiles.clear()
+
+ fn0 = _call(CASES[name], module, 0)
+ fn1 = _call(CASES[name], module, 1)
+
+ assert (0, "") in module._state, name
+ assert (1, "") in module._state, name
+ assert module._state[(0, "")] is not module._state[(1, "")], name
+ assert ("mod", (0, "")) in module._state and ("mod", (1, "")) in module._state, name
+ assert all(h.value for h in _handles(fn0)), name
+ assert all(h.value for h in _handles(fn1)), name
+ assert module._state["lib"] is not None, name
+
+ got = {x.split("=", 1)[1] for c in compiles for x in c if x.startswith("--offload-arch=")}
+ assert {"gfx1151", "gfx1201"} <= got, (name, got)
+ assert cuda.set_calls == [1], name
+
+
+def test_dsv41_emu_hook_survives_the_state_rewrite(fake_jit):
+ sentinel = object()
+ dsv41_hip._state["emu"] = sentinel
+ dsv41_hip._load(0)
+ assert dsv41_hip._state["emu"] is sentinel
+
+
[email protected]("name", sorted(SUPPORTED))
+def test_gfx12_gate_refuses_before_compiling(fake_jit, name):
+ module = CASES[name][0]
+ if module is None:
+ pytest.skip("module is not importable without Triton")
+ assert module.supported(1) is False
+ assert module.supported(0) is True
+ # No compile for the refused device: the state stays empty
+ assert not any(isinstance(k, tuple) and k[0] == 1 for k in module._state)
+
+
[email protected](not (torch.version.hip and torch.cuda.device_count() >= 2),
+ reason = "requires two ROCm GPUs")
+def test_each_loader_loads_on_both_devices():
+ prev = torch.cuda.current_device()
+ try:
+ archs = [arch_list.device_arch(i) for i in range(torch.cuda.device_count())]
+ for name, (module, call, gate) in CASES.items():
+ if module is None:
+ continue
+ module._state.clear()
+ arch_list.reset_support_cache()
+ for dev in range(2):
+ arch = archs[dev]
+ if gate is not None and arch not in gate:
+ if name in SUPPORTED:
+ assert module.supported(dev) is False
+ continue
+ torch.cuda.set_device(dev)
+ fn = call(module, dev)
+ assert all(h.value for h in _handles(fn)), (name, dev)
+ assert (dev, "") in module._state, (name, dev)
+ loaded = [d for d in range(2) if (d, "") in module._state]
+ if len(loaded) == 2:
+ assert module._state[(0, "")] is not module._state[(1, "")], name
+ finally:
+ torch.cuda.set_device(prev)