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.

9.3 KB
Raw Blame
# Loader for the hand-written HIP fused KDA state loop (kda_fused_h.hip). Compiles a gfx code object with the
# ROCm SDK hipcc on first use (cached by source hash) and launches it through torch's own libamdhip64 via
# hipModuleLaunchKernel on the current torch stream: no extension rebuild, no second HIP runtime.

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 = {}
# The kernel source has a gfx12 (RDNA4) fragment path. Its bf16 x bf16 products round to
# nearest even on gfx11.5 and gfx12 (f2bf_mul), which makes o and the final state bitwise equal
# to the Triton fused path on gfx1201 under Triton 3.9; both arches are enabled at the gate.
_ARCHS = GFX115_ARCHS | frozenset(("gfx1200", "gfx1201"))


def supported(device=None):
    """True for the gfx11.5 and gfx12 WMMA fragment paths of kda_fused_h.hip; refuse others before hipcc."""
    if not torch.version.hip:
        return False
    return device_supported(device, _ARCHS)


def _hipcc():
    return hip_compiler.hipcc()


def _compile(defs, arch):
    # hsaco path for these defines (compiled once, cached by source + flags hash); needs no GPU
    src = open(_SRC, "rb").read()
    flags = ["--genco", f"--offload-arch={arch}", "-O3", "-ffp-contract=off"] + [x if x.startswith("-") else f"-D{x}" for x in defs.split()]
    flags += hip_compiler.gcc_flags()
    tag = hashlib.sha1(src + " ".join(flags).encode() + b"\0" + hip_compiler.key().encode()).hexdigest()[:16]
    cache = os.path.join(os.path.expanduser("~/.cache/exllamav3"), f"kda_fused_h_{arch}_{tag}.hsaco")
    if not os.path.isfile(cache):
        os.makedirs(os.path.dirname(cache), exist_ok=True)
        tmp = cache + f".{os.getpid()}.{threading.get_ident()}.tmp"
        r = subprocess.run([_hipcc(), *flags, "-o", tmp, _SRC], capture_output=True)
        if r.returncode != 0:
            try:
                os.remove(tmp)
            except OSError:
                pass
            err = (r.stderr or r.stdout or b"").decode(errors="replace").strip().splitlines()
            raise RuntimeError(f"kda_fused_h_hip: hipcc failed for {arch}:\n" + "\n".join(hip_compiler.compile_tail(err)))
        os.replace(tmp, cache)
    return cache


_CK = ("CK4=1", "CK8=1")


def _siblings(defs):
    """The builds that differ from `defs` only in the checkpoint-slot count (2 slots: none, 4: CK4, 8: CK8)."""
    base = " ".join(t for t in defs.split() if t not in _CK)
    return [d for d in [base] + [f"{base} {t}".strip() for t in _CK] if d.split() != defs.split()]


def _precompile_siblings(defs, arch):
    # The number of checkpoint rows of a request picks the build. A prefill chunk and a short prompt tail use different
    # ones, so the first re-sent prompt would run hipcc (about 2.5 s) inside its own time to first token. Build the
    # others now, off the request path; a failure is not an error (the build then happens on first use as before).
    def run():
        for d in _siblings(defs):
            try:
                _compile(d, arch)
            except Exception:  # noqa: BLE001
                return
    threading.Thread(target=run, name="kda-fused-h-precompile", daemon=True).start()


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()
    mod, fn = ctypes.c_void_p(), ctypes.c_void_p()
    if lib.hipModuleLoad(ctypes.byref(mod), cache.encode()) != 0:
        raise RuntimeError("kda_fused_h_hip: hipModuleLoad failed")
    if lib.hipModuleGetFunction(ctypes.byref(fn), mod, b"kda_fused_h_o") != 0:
        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[key] = fn
    _state["mod", key] = mod
    base = " ".join(t for t in defs.split() if t not in _CK)
    if ("pre", dev, base) not in _state:
        _state["pre", dev, base] = True
        _precompile_siblings(defs, arch)
    return fn


def chunk_kda_fwd_h_fused_hip(q, k, v, gk, beta, Akk, Aqk, scale, initial_state=None, output_final_state=False,
                              chunk_size=64, o=None, final_state=None, defs="", ckpt=None):
    """Same contract as chunk_kda_fwd_h_fused(fuse_o=True): returns (None, None, o, final_state).
    ckpt: optional dict {"s": fp32 [B, HV, K, V] contiguous, "chunk": n}; the kernel also writes the state after
    chunk n - 1 (row 64 n) to ckpt["s"] and sets ckpt["ok"] (EXL3_MIDCHUNK_CKPT=2)."""
    B, T, H, K = k.shape
    HV, V = v.shape[2], v.shape[-1]
    assert K == 128 and V == 128 and chunk_size == 64 and HV % H == 0
    assert q.dtype == k.dtype == v.dtype == beta.dtype == Akk.dtype == Aqk.dtype == torch.bfloat16 and gk.dtype == torch.float32
    for t in (q, k, v, gk, beta, Akk, Aqk):
        assert t.is_contiguous()
    # The EXL3_KDA_PF_SPLIT fast builds encode the gfx11 C row / o-store layout; gfx12 uses the
    # default defs="" build (bitwise equal, but the port does not carry those experiments).
    pf = os.environ.get("EXL3_KDA_PF_SPLIT", "0") if not defs and device_supported(q.device, GFX115_ARCHS) else ""
    if pf == "2":
        # spill-free build (0 VGPR spills vs 462): sched barriers (SB), opaque lane
        # indices (OPQ), pinned WMMA accumulators (OPV), uniform o-store base (ADR), no LSR,
        # plus PH1=4 PF=1 next-chunk register prefetch. Bitwise-identical to defs="".
        # Microbench T=4096 HV=64 (test box): 8.70 -> 5.40 ms (-38 %). Default off.
        defs = "BRL=1 UNI=1 OPQ=15 OPV=11 SB=15 ADR=1 PH1=4 PF=1 -mllvm -disable-lsr"
    elif pf == "1":
        # BRL (branchless f2bf, single basic block) + UNI (wave-uniform rows).
        # Bitwise-identical to defs="" (sweep T=4096: 10.979 -> 8.615 ms/layer, -21.5 %),
        # default off. Name kept per brief; the 2-WG split (lever a) was ruled NO-GO by
        # construction (w/tril/vn couple all halves).
        defs = "BRL=1 UNI=1"
    # ckpt: one dict or a list of up to 2 (EXL3_PF_NO_TAIL adds the prompt's last full page); up to 4 with the CK4 build, up to 8 with the CK8 build
    # (EXL3_NC2_CKPT4: an 8192-row chunk carries 3 interior checkpoints + the last full page)
    cks = [] if ckpt is None else (list(ckpt) if isinstance(ckpt, (list, tuple)) else [ckpt])
    nslot = 8 if len(cks) > 4 else 4 if len(cks) > 2 else 2
    assert len(cks) <= nslot
    if nslot == 4:
        defs = (defs + " CK4=1").strip()
    elif nslot == 8:
        defs = (defs + " CK8=1").strip()
    fn = _load(defs, q.device)
    if o is None:
        o = torch.empty_like(v)
    if output_final_state and final_state is None:
        final_state = k.new_empty(B, HV, K, V, dtype=torch.float32)
    h0 = initial_state
    if h0 is not None:
        assert h0.dtype == torch.float32 and h0.is_contiguous()
    P = ctypes.c_void_p
    args = [P(q.data_ptr()), P(k.data_ptr()), P(v.data_ptr()), P(gk.data_ptr()), P(beta.data_ptr()),
            P(Akk.data_ptr()), P(Aqk.data_ptr()), P(o.data_ptr()), P(0 if h0 is None else h0.data_ptr()),
            P(final_state.data_ptr() if output_final_state else 0), ctypes.c_float(scale), ctypes.c_int(T),
            ctypes.c_int(H), ctypes.c_int(HV)]
    cks = [c for c in cks if 0 < c["chunk"] <= (T + 63) // 64]
    for c in cks:
        assert c["s"].dtype == torch.float32 and c["s"].is_contiguous() and c["s"].shape == (B, HV, K, V)
    for i in range(nslot):
        c = cks[i] if i < len(cks) else None
        args += [P(0 if c is None else c["s"].data_ptr()), ctypes.c_int(-1 if c is None else c["chunk"])]
    params = (ctypes.c_void_p * len(args))(*[ctypes.cast(ctypes.byref(a), ctypes.c_void_p) for a in args])
    stream = torch.cuda.current_stream().cuda_stream
    r = _state["lib"].hipModuleLaunchKernel(fn, B * HV, 1, 1, 288 if "PFW=" in defs and "PFW=0" not in defs else 256, 1, 1, 0, stream, params, None)
    if r != 0:
        raise RuntimeError(f"kda_fused_h_hip: launch failed ({r})")
    for c in cks:
        c["ok"] = True
    return None, None, o, (final_state if output_final_state else None)


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
    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")
    torch.cuda.synchronize()
    out = np.zeros(n * 8 * 9, dtype=np.uint32)
    lib.hipMemcpyDtoH.argtypes = [ctypes.c_void_p, ctypes.c_void_p, ctypes.c_size_t]
    if lib.hipMemcpyDtoH(out.ctypes.data, ptr, out.nbytes) != 0:
        raise RuntimeError("hipMemcpyDtoH failed")
    return out.reshape(n, 8, 9)