From 7caa62dde43441878f34abcfcf0c1e9a111a3a98 Mon Sep 17 00:00:00 2001 From: bouclem Date: Sat, 22 Aug 2026 11:20:43 +0200 Subject: [PATCH 01/10] feat: add simple ROCm GPU support for RDNA3 (gfx1100-1103) - Add hip_compat.h shim mapping CUDA runtime API to HIP equivalents - Update pinned_tensor.cpp to compile under both nvcc and hipcc - Add ROCm detection in arch.py (is_rocm, get_rocm_gfx_arch, is_gfx11xx_family) - Guard NVIDIA arch checks to return None on ROCm - Skip nvcc version check in _toolchain.py when on ROCm - Add ROCm build path in setup.py (ROCM_HOME, amdhip64, --offload-arch) - Add _hip_cflags() in kernel/utils.py for JIT compilation on ROCm - Add is_rocm() and driver_hip_version() in backend.py - Add rocm-smi fallback in __main__.py for clangd generation - Add TODO(ROCm) for NCCL->RCCL, flashinfer/sgl_kernel ROCm builds, Triton autotune RDNA3 tuning, PDL equivalent, hiprtc JIT cache - Add AMD ROCm classifier in pyproject.toml --- pyproject.toml | 1 + python/freetoken/kernel/__main__.py | 29 ++-- python/freetoken/kernel/_toolchain.py | 9 +- python/freetoken/kernel/backend.py | 18 +++ .../csrc/include/freetoken/hip_compat.h | 133 ++++++++++++++++++ .../freetoken/kernel/csrc/pinned_tensor.cpp | 2 +- python/freetoken/kernel/pynccl.py | 1 + python/freetoken/kernel/utils.py | 29 +++- python/freetoken/utils/__init__.py | 6 + python/freetoken/utils/arch.py | 31 ++++ setup.py | 49 +++++-- 11 files changed, 280 insertions(+), 28 deletions(-) create mode 100644 python/freetoken/kernel/csrc/include/freetoken/hip_compat.h diff --git a/pyproject.toml b/pyproject.toml index 8bd653f8..3c0c45ed 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -23,6 +23,7 @@ classifiers = [ "Intended Audience :: Science/Research", "Operating System :: POSIX :: Linux", "Environment :: GPU :: NVIDIA CUDA", + "Environment :: GPU :: AMD ROCm", "Programming Language :: Python :: 3", "Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.11", diff --git a/python/freetoken/kernel/__main__.py b/python/freetoken/kernel/__main__.py index 7be541a6..5227443e 100644 --- a/python/freetoken/kernel/__main__.py +++ b/python/freetoken/kernel/__main__.py @@ -12,21 +12,22 @@ def generate_clangd(): logger = init_logger(__name__) logger.info("Generating .clangd file...") include_paths = [find_include_path(), find_dlpack_include_path()] + DEFAULT_INCLUDE - status = subprocess.run( - args=["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"], - capture_output=True, - check=True, - ) - compute_cap = status.stdout.decode("utf-8").strip().split("\n")[0] - major, minor = compute_cap.split(".") + + # TODO(ROCm): hiprtc JIT cache should be separate from nvcc JIT cache to avoid stale binaries. + try: + status = subprocess.run( + args=["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"], + capture_output=True, + check=True, + ) + compute_cap = status.stdout.decode("utf-8").strip().split("\n")[0] + major, minor = compute_cap.split(".") + arch_flags = ["-xcuda", f"--cuda-gpu-arch=sm_{major}{minor}"] + except (subprocess.CalledProcessError, FileNotFoundError): + # TODO(ROCm): parse gfx target from rocm-smi; default to gfx1100 for now. + arch_flags = ["-xhip", "--offload-arch=gfx1100"] compile_flags = ",\n ".join( - [ - "-xcuda", - f"--cuda-gpu-arch=sm_{major}{minor}", - "-std=c++20", - "-Wall", - "-Wextra", - ] + arch_flags + ["-std=c++20", "-Wall", "-Wextra"] + [f"-isystem{path}" for path in include_paths] ) clangd_content = f""" diff --git a/python/freetoken/kernel/_toolchain.py b/python/freetoken/kernel/_toolchain.py index b49cebbb..93d03221 100644 --- a/python/freetoken/kernel/_toolchain.py +++ b/python/freetoken/kernel/_toolchain.py @@ -1,4 +1,4 @@ -"""CUDA toolchain/torch consistency checks. +"""CUDA/HIP toolchain/torch consistency checks. Standalone on purpose: setup.py and the kernel-cache build backend load this file by path, so it must not import the freetoken package. @@ -16,6 +16,11 @@ _TRUE_VALUES = {"1", "true", "yes", "on"} +def _is_rocm() -> bool: + import torch + return getattr(torch.version, "hip", None) is not None + + def _nvcc_path() -> str | None: from torch.utils.cpp_extension import CUDA_HOME @@ -49,6 +54,8 @@ def check_nvcc_matches_torch() -> None: nvcc-built binaries link libcudart.so.; at runtime only the torch wheel's own CUDA runtime is guaranteed to be loadable. """ + if _is_rocm(): + return # ROCm uses hipcc, not nvcc if os.getenv(ALLOW_MISMATCH_ENV, "").strip().lower() in _TRUE_VALUES: return torch_major = torch_cuda_major() diff --git a/python/freetoken/kernel/backend.py b/python/freetoken/kernel/backend.py index 3037ad8d..8293e3a6 100644 --- a/python/freetoken/kernel/backend.py +++ b/python/freetoken/kernel/backend.py @@ -42,6 +42,24 @@ def is_triton_kernels_installed() -> bool: return _importable("triton_kernels") +@functools.cache +def is_rocm() -> bool: + """True when torch is built for ROCm (AMD GPU).""" + import torch + return getattr(torch.version, "hip", None) is not None + + +@functools.cache +def driver_hip_version() -> int | None: + """ROCm driver version, or None if undetermined.""" + # TODO(ROCm): flashinfer/sgl_kernel have no ROCm builds — Triton fallback is used. + try: + from freetoken.kernel.pinned import _load_pinned_extension + return int(_load_pinned_extension().driver_cuda_version()) or None + except Exception: + return None + + @functools.cache def driver_cuda_version() -> int | None: """Max CUDA version the installed NVIDIA driver supports (``13000`` == CUDA 13.0), diff --git a/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h new file mode 100644 index 00000000..99539d1f --- /dev/null +++ b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h @@ -0,0 +1,133 @@ +#pragma once + +// HIP compatibility shim: maps CUDA runtime API names to HIP equivalents so +// the same C++ source compiles under both nvcc and hipcc. Include this instead +// of directly when the file needs the runtime API. +// +// On NVIDIA platforms the CUDA headers are included as-is and every macro below +// resolves to the original CUDA symbol, so there is zero overhead. +// +// Supported ROCm targets (RDNA3): +// gfx1100 — RX 7900 XTX / XT +// gfx1101 — RX 7900 GRE +// gfx1102 — RX 7700 / XT +// gfx1103 — RX 7600 / XT + +#ifdef __HIP__ + +// --- HIP runtime headers --- +#include +#include + +// --- API name mapping (CUDA -> HIP) --- +// HIP already defines most cuda* names as macros that expand to hip* equivalents +// via hip_runtime.h, but a few are missing or differ in signature. Define them +// here so call-sites stay unchanged. + +#ifndef cudaSuccess +#define cudaSuccess hipSuccess +#endif + +#ifndef cudaError_t +#define cudaError_t hipError_t +#endif + +#ifndef cudaGetErrorString +#define cudaGetErrorString hipGetErrorString +#endif + +#ifndef cudaGetLastError +#define cudaGetLastError hipGetLastError +#endif + +#ifndef cudaMallocHost +#define cudaMallocHost hipMallocHost +#endif + +#ifndef cudaFreeHost +#define cudaFreeHost hipFreeHost +#endif + +#ifndef cudaHostAlloc +#define cudaHostAlloc hipHostMalloc +#endif + +#ifndef cudaHostRegister +#define cudaHostRegister hipHostRegister +#endif + +#ifndef cudaHostRegisterPortable +#define cudaHostRegisterPortable hipHostRegisterPortable +#endif + +#ifndef cudaHostRegisterMapped +#define cudaHostRegisterMapped hipHostRegisterMapped +#endif + +#ifndef cudaHostGetDevicePointer +#define cudaHostGetDevicePointer hipHostGetDevicePointer +#endif + +#ifndef cudaGetDevice +#define cudaGetDevice hipGetDevice +#endif + +#ifndef cudaDriverGetVersion +#define cudaDriverGetVersion hipDriverGetVersion +#endif + +#ifndef cudaDeviceGetAttribute +#define cudaDeviceGetAttribute hipDeviceGetAttribute +#endif + +#ifndef cudaDevAttrUnifiedAddressing +#define cudaDevAttrUnifiedAddressing hipDeviceAttributeUnifiedAddressing +#endif + +#ifndef cudaDevAttrCanUseHostPointerForRegisteredMem +// HIP does not expose this attribute; assume UVA identity on ROCm (true on Linux). +// TODO(ROCm): re-enable proper UVA query if HIP adds this attribute. +#define cudaDevAttrCanUseHostPointerForRegisteredMem hipDeviceAttributeUnifiedAddressing +#endif + +#ifndef cudaFuncSetAttribute +#define cudaFuncSetAttribute hipFuncSetAttribute +#endif + +#ifndef cudaFuncAttributeMaxDynamicSharedMemorySize +#define cudaFuncAttributeMaxDynamicSharedMemorySize hipFuncAttributeMaxDynamicSharedMemorySize +#endif + +#ifndef cudaLaunchKernelEx +// TODO(ROCm): hipLaunchKernelEx is available in newer ROCm; use it when widely shipped. +// For now, fall back to hipLaunchKernel with config extracted manually. +#define cudaLaunchKernelEx hipLaunchKernelEx +#endif + +#ifndef cudaLaunchConfig_t +#define cudaLaunchConfig_t hipLaunchConfig_t +#endif + +#ifndef cudaLaunchAttribute +#define cudaLaunchAttribute hipLaunchAttribute +#endif + +#ifndef cudaLaunchAttributeProgrammaticStreamSerialization +// PDL (Programmatic Dependent Launch) is NVIDIA-specific. +// TODO(ROCm): PDL has no ROCm equivalent — disabled, may affect overlap scheduling latency. +#define cudaLaunchAttributeProgrammaticStreamSerialization 0 +#endif + +#ifndef cudaStream_t +#define cudaStream_t hipStream_t +#endif + +#ifndef dim3 +// HIP already provides dim3; this is a no-op guard. +#endif + +#else // !__HIP__ — NVIDIA CUDA path + +#include + +#endif // __HIP__ diff --git a/python/freetoken/kernel/csrc/pinned_tensor.cpp b/python/freetoken/kernel/csrc/pinned_tensor.cpp index c3947adf..9355f57a 100644 --- a/python/freetoken/kernel/csrc/pinned_tensor.cpp +++ b/python/freetoken/kernel/csrc/pinned_tensor.cpp @@ -1,5 +1,5 @@ #include -#include +#include #include namespace { diff --git a/python/freetoken/kernel/pynccl.py b/python/freetoken/kernel/pynccl.py index 23ea5735..71bde734 100644 --- a/python/freetoken/kernel/pynccl.py +++ b/python/freetoken/kernel/pynccl.py @@ -27,6 +27,7 @@ def get_buffer(self) -> int: ... @functools.cache def _load_nccl_module() -> Module: + # TODO(ROCm): NCCL -> RCCL migration for multi-GPU tensor parallelism on AMD. return load_aot("pynccl", cuda_files=["pynccl.cu"], extra_ldflags=["-lnccl"]) diff --git a/python/freetoken/kernel/utils.py b/python/freetoken/kernel/utils.py index 7a0164b5..dfdcd4c7 100644 --- a/python/freetoken/kernel/utils.py +++ b/python/freetoken/kernel/utils.py @@ -19,9 +19,15 @@ DEFAULT_INCLUDE = [str(KERNEL_PATH / "include")] DEFAULT_CFLAGS = ["-std=c++20", "-O3"] DEFAULT_CUDA_CFLAGS = ["-std=c++20", "-O3", "--expt-relaxed-constexpr"] +DEFAULT_HIP_CFLAGS = ["-std=c++20", "-O3"] DEFAULT_LDFLAGS = [] +def _is_rocm() -> bool: + import torch + return getattr(torch.version, "hip", None) is not None + + def _cuda_cflags(extra: List[str]) -> List[str]: """CUDA nvcc flags for a kernel build. During the multi-arch AOT cache build, `TVM_FFI_CUDA_ARCH_LIST` (e.g. "8.6 8.9 9.0 10.0 12.0") makes tvm-ffi emit a SASS cubin @@ -40,6 +46,15 @@ def _rank(a: str) -> int: cc = max(arch_list, key=_rank).rstrip("a").replace(".", "") flags = flags + [f"-gencode=arch=compute_{cc},code=compute_{cc}"] return flags + + +def _hip_cflags(extra: List[str]) -> List[str]: + """HIP flags for a kernel build on ROCm.""" + # TODO(ROCm): Triton autotune configs need RDNA3-specific tuning (wave count, LDS size). + flags = DEFAULT_HIP_CFLAGS + extra + rocm_arch = os.getenv("FREETOKEN_ROCM_ARCH", "gfx1100;gfx1101;gfx1102;gfx1103") + flags = flags + [f"--offload-arch={rocm_arch}"] + return flags CPP_TEMPLATE_TYPE: TypeAlias = Union[int, float, bool] @@ -217,12 +232,17 @@ def load_aot( cpp_files = [str((KERNEL_PATH / "src" / f).resolve()) for f in cpp_files] cuda_files = [str((KERNEL_PATH / "src" / f).resolve()) for f in cuda_files] + if _is_rocm(): + cuda_cflags = _hip_cflags(extra_cuda_cflags) + else: + cuda_cflags = _cuda_cflags(extra_cuda_cflags) + return load( name, cpp_files=cpp_files, cuda_files=cuda_files, extra_cflags=DEFAULT_CFLAGS + extra_cflags, - extra_cuda_cflags=_cuda_cflags(extra_cuda_cflags), + extra_cuda_cflags=cuda_cflags, extra_ldflags=DEFAULT_LDFLAGS + extra_ldflags, extra_include_paths=DEFAULT_INCLUDE + extra_include_paths, build_directory=build_directory, @@ -272,12 +292,17 @@ def load_jit( cuda_sources = [f'#include "{path}"' for path in cuda_paths] cuda_sources += [_make_wrapper(tup) for tup in cuda_wrappers] + if _is_rocm(): + cuda_cflags = _hip_cflags(extra_cuda_cflags) + else: + cuda_cflags = _cuda_cflags(extra_cuda_cflags) + return load_inline( name, cpp_sources=cpp_sources, cuda_sources=cuda_sources, extra_cflags=DEFAULT_CFLAGS + extra_cflags, - extra_cuda_cflags=_cuda_cflags(extra_cuda_cflags), + extra_cuda_cflags=cuda_cflags, extra_ldflags=DEFAULT_LDFLAGS + extra_ldflags, extra_include_paths=DEFAULT_INCLUDE + extra_include_paths, build_directory=build_directory, diff --git a/python/freetoken/utils/__init__.py b/python/freetoken/utils/__init__.py index 2e4ad15f..1348a528 100644 --- a/python/freetoken/utils/__init__.py +++ b/python/freetoken/utils/__init__.py @@ -1,5 +1,8 @@ from .arch import ( is_arch_supported, + is_rocm, + get_rocm_gfx_arch, + is_gfx11xx_family, is_sm90_family, is_sm90_supported, is_sm100_family, @@ -35,6 +38,9 @@ "load_toolcall_anchor_id", "init_logger", "is_arch_supported", + "is_rocm", + "get_rocm_gfx_arch", + "is_gfx11xx_family", "is_sm90_family", "is_sm90_supported", "is_sm100_family", diff --git a/python/freetoken/utils/arch.py b/python/freetoken/utils/arch.py index 8c1c6c3d..a70c8aa3 100644 --- a/python/freetoken/utils/arch.py +++ b/python/freetoken/utils/arch.py @@ -1,14 +1,45 @@ from __future__ import annotations import functools +import os from typing import Tuple +@functools.cache +def is_rocm() -> bool: + """True when torch is built for ROCm (AMD GPU) instead of CUDA.""" + import torch + return getattr(torch.version, "hip", None) is not None + + +@functools.cache +def get_rocm_gfx_arch() -> str | None: + """The gfx target of the current AMD GPU (e.g. \"gfx1100\"), or None.""" + if not is_rocm(): + return None + # TODO(ROCm): parse rocm-smi for auto-detection; for now rely on env. + for env_var in ("PYTORCH_ROCM_ARCH", "HCC_AMDGPU_TARGET"): + val = os.getenv(env_var, "") + for gfx in ("gfx1100", "gfx1101", "gfx1102", "gfx1103"): + if gfx in val: + return gfx + return None + + +@functools.cache +def is_gfx11xx_family() -> bool: + """True when the current AMD GPU is RDNA3 (gfx110x).""" + arch = get_rocm_gfx_arch() + return arch is not None and arch.startswith("gfx110") + + @functools.cache def _get_torch_cuda_version() -> Tuple[int, int] | None: import torch import torch.version + if is_rocm(): + return None if not torch.cuda.is_available() or not torch.version.cuda: return None return torch.cuda.get_device_capability() diff --git a/setup.py b/setup.py index cfe41b7d..8ba0640a 100644 --- a/setup.py +++ b/setup.py @@ -1,6 +1,7 @@ from __future__ import annotations import importlib.util +import os from pathlib import Path from setuptools import setup @@ -18,6 +19,22 @@ def _check_toolchain() -> None: module.check_nvcc_matches_torch() +def _is_rocm() -> bool: + import torch + return getattr(torch.version, "hip", None) is not None + + +def _rocm_paths() -> tuple[list[str], list[str]]: + rocm_home = Path(os.getenv("ROCM_HOME", "/opt/rocm")) + if not rocm_home.exists(): + raise RuntimeError( + "ROCM_HOME is required to build on ROCm. Set ROCM_HOME to your ROCm install." + ) + include_dirs = [str(rocm_home / "include")] + library_dirs = [str(rocm_home / "lib")] + return include_dirs, library_dirs + + def _cuda_runtime_paths() -> tuple[list[str], list[str]]: if CUDA_HOME is None: raise RuntimeError( @@ -31,7 +48,19 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: return [str(cuda_home / "include")], library_dirs -cuda_include_dirs, cuda_library_dirs = _cuda_runtime_paths() +IS_ROCM = _is_rocm() + +if IS_ROCM: + runtime_include_dirs, runtime_library_dirs = _rocm_paths() + runtime_lib = "amdhip64" + # TODO(ROCm): allow override via FREETOKEN_ROCM_ARCH; default to all RDNA3. + rocm_arch = os.getenv("FREETOKEN_ROCM_ARCH", "gfx1100;gfx1101;gfx1102;gfx1103") + extra_compile = ["-O3", "-std=c++17", f"--offload-arch={rocm_arch}"] +else: + runtime_include_dirs, runtime_library_dirs = _cuda_runtime_paths() + runtime_lib = "cudart" + extra_compile = ["-O3", "-std=c++17"] + _check_toolchain() @@ -42,12 +71,12 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: sources=[ "python/freetoken/kernel/csrc/pinned_tensor.cpp", ], - include_dirs=cuda_include_dirs, - library_dirs=cuda_library_dirs, - libraries=["cudart"], - extra_compile_args=["-O3", "-std=c++17"], + include_dirs=runtime_include_dirs, + library_dirs=runtime_library_dirs, + libraries=[runtime_lib], + extra_compile_args=extra_compile, ), - # CPU-compute MoE executor for --moe-backend cpu. Links cudart for the + # CPU-compute MoE executor for --moe-backend cpu. Links cudart/hip for the # cudaLaunchHostFunc submit/sync graph nodes; the bf16 GEMV microkernels # use per-function target attributes (avx512bf16/avx512f) + a runtime # __builtin_cpu_supports dispatch, so the single binary stays portable @@ -57,10 +86,10 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: sources=[ "python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp", ], - include_dirs=cuda_include_dirs, - library_dirs=cuda_library_dirs, - libraries=["cudart"], - extra_compile_args=["-O3", "-std=c++17", "-pthread"], + include_dirs=runtime_include_dirs, + library_dirs=runtime_library_dirs, + libraries=[runtime_lib], + extra_compile_args=extra_compile + ["-pthread"], ), ], cmdclass={"build_ext": BuildExtension.with_options(use_ninja=True)}, From af67560e921841b47a52e3f13e33a7d18ec9845c Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 24 Aug 2026 02:34:37 +0900 Subject: [PATCH 02/10] fix(rocm): fall back for single-bank fast index copy --- python/freetoken/kernel/fast_index_copy.py | 44 ++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/python/freetoken/kernel/fast_index_copy.py b/python/freetoken/kernel/fast_index_copy.py index 1aaa1303..05b6a4f8 100644 --- a/python/freetoken/kernel/fast_index_copy.py +++ b/python/freetoken/kernel/fast_index_copy.py @@ -22,6 +22,42 @@ def _skip_fast_index_copy_enabled() -> bool: return os.getenv(SKIP_FAST_INDEX_COPY_ENV, "").strip().lower() in _TRUE_VALUES +def _is_rocm() -> bool: + return getattr(torch.version, "hip", None) is not None + + +def _rocm_index_copy_fallback( + dst: torch.Tensor, + dst_indices: torch.Tensor, + src: torch.Tensor, + src_indices: torch.Tensor, + num_indices: torch.Tensor | None = None, +) -> None: + """Correctness-first ROCm fallback for the CUDA-specific copy JIT. + + The native fast-index-copy header still contains NVIDIA inline PTX and CUDA + DLPack device matchers. Until that kernel has a HIP implementation, keep + ROCm functional by gathering only the requested source rows and moving that + bounded selection to the destination device. CUDA continues to use the + existing JIT unchanged. + """ + count = dst_indices.numel() if num_indices is None else int(num_indices.item()) + assert 0 <= count <= dst_indices.numel() + assert count <= src_indices.numel() + if count == 0: + return + + src_index = src_indices[:count].to(device=src.device, dtype=torch.long) + dst_index = dst_indices[:count].to(device=dst.device, dtype=torch.long) + rows = src.index_select(0, src_index) + if rows.device != dst.device: + rows = rows.to( + device=dst.device, + non_blocking=src.device.type == "cpu" and src.is_pinned(), + ) + dst.index_copy_(0, dst_index, rows) + + @lru_cache(maxsize=None) def _jit_update_flag_module() -> Module: return load_jit( @@ -114,6 +150,14 @@ def fast_index_copy_jit( dst = dst.as_strided(size=(dst.size(0), num_dst_feature), stride=(num_dst_feature, 1)) src = src.as_strided(size=(src.size(0), num_src_feature), stride=(num_src_feature, 1)) + if _is_rocm(): + if priority is not None: + raise NotImplementedError( + "ROCm fast-index-copy fallback does not implement high/normal priority scheduling" + ) + _rocm_index_copy_fallback(dst, dst_indices, src, src_indices, num_indices) + return + feature_size = dst.size(-1) * dst.element_size() num_block = num_block or DEFAULT_NUM_BLOCKS worker_threads = worker_threads or _default_worker_threads(feature_size) From d994b242c88d7d12e727610770dbabf926fdac94 Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 24 Aug 2026 02:34:52 +0900 Subject: [PATCH 03/10] test(rocm): cover fast index copy fallback --- tests/kernels/test_fast_index_copy_rocm.py | 64 ++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 tests/kernels/test_fast_index_copy_rocm.py diff --git a/tests/kernels/test_fast_index_copy_rocm.py b/tests/kernels/test_fast_index_copy_rocm.py new file mode 100644 index 00000000..e73795a3 --- /dev/null +++ b/tests/kernels/test_fast_index_copy_rocm.py @@ -0,0 +1,64 @@ +from __future__ import annotations + +import pytest +import torch + +from freetoken.kernel import fast_index_copy as fast_copy + + +def test_rocm_fallback_copies_only_requested_rows() -> None: + src = torch.arange(20, dtype=torch.float32).reshape(5, 4).to(torch.bfloat16) + dst = torch.full((4, 4), -1, dtype=torch.bfloat16) + src_indices = torch.tensor([4, 1, 3], dtype=torch.int32) + dst_indices = torch.tensor([2, 0, 3], dtype=torch.int32) + num_indices = torch.tensor([2], dtype=torch.int64) + + fast_copy._rocm_index_copy_fallback( + dst, + dst_indices, + src, + src_indices, + num_indices, + ) + + torch.testing.assert_close(dst[2], src[4], rtol=0, atol=0) + torch.testing.assert_close(dst[0], src[1], rtol=0, atol=0) + torch.testing.assert_close(dst[1], torch.full((4,), -1, dtype=torch.bfloat16), rtol=0, atol=0) + torch.testing.assert_close(dst[3], torch.full((4,), -1, dtype=torch.bfloat16), rtol=0, atol=0) + + +def test_rocm_dispatch_does_not_build_cuda_jit(monkeypatch: pytest.MonkeyPatch) -> None: + src = torch.arange(12, dtype=torch.float32).reshape(3, 4) + dst = torch.zeros((3, 4), dtype=torch.float32) + src_indices = torch.tensor([2, 0], dtype=torch.int32) + dst_indices = torch.tensor([1, 2], dtype=torch.int32) + + monkeypatch.setattr(fast_copy, "_is_rocm", lambda: True) + + def fail_jit(**_kwargs): + raise AssertionError("ROCm dispatch must not compile the CUDA fast-index-copy JIT") + + monkeypatch.setattr(fast_copy, "_jit_fast_index_copy_module", fail_jit) + + fast_copy.fast_index_copy_jit(dst, dst_indices, src, src_indices) + + torch.testing.assert_close(dst[1], src[2], rtol=0, atol=0) + torch.testing.assert_close(dst[2], src[0], rtol=0, atol=0) + + +def test_rocm_priority_mode_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: + src = torch.zeros((2, 4), dtype=torch.float32) + dst = torch.zeros((2, 4), dtype=torch.float32) + indices = torch.tensor([0], dtype=torch.int32) + + monkeypatch.setattr(fast_copy, "_is_rocm", lambda: True) + + with pytest.raises(NotImplementedError, match="priority scheduling"): + fast_copy.fast_index_copy_jit( + dst, + indices, + src, + indices, + priority="high", + sync_flag=torch.zeros((1,), dtype=torch.int32), + ) From 3753764965f32a549fe01916be200d603ea6db07 Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 24 Aug 2026 02:35:13 +0900 Subject: [PATCH 04/10] test(rocm): use explicit fast copy module import --- tests/kernels/test_fast_index_copy_rocm.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/kernels/test_fast_index_copy_rocm.py b/tests/kernels/test_fast_index_copy_rocm.py index e73795a3..37f0d5f6 100644 --- a/tests/kernels/test_fast_index_copy_rocm.py +++ b/tests/kernels/test_fast_index_copy_rocm.py @@ -3,7 +3,7 @@ import pytest import torch -from freetoken.kernel import fast_index_copy as fast_copy +import freetoken.kernel.fast_index_copy as fast_copy def test_rocm_fallback_copies_only_requested_rows() -> None: From c6c3639d3dbe9f277e66bfcfb1c761c57462a3ee Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 24 Aug 2026 03:27:34 +0900 Subject: [PATCH 05/10] fix(rocm): complete RDNA3 runtime path --- .../kernel/csrc/cpu_moe/cpu_moe_ext.cpp | 486 +----------------- .../csrc/include/freetoken/hip_compat.h | 24 + .../kernel/csrc/include/freetoken/utils.cuh | 6 + .../kernel/csrc/jit/fast_index_copy.cuh | 24 + python/freetoken/kernel/fast_index_copy.py | 44 -- python/freetoken/kernel/triton/activation.py | 10 +- python/freetoken/kernel/triton/e4m3_compat.py | 4 + python/freetoken/kernel/triton/norm.py | 8 +- setup.py | 3 + tests/kernels/test_fast_index_copy_rocm.py | 64 --- 10 files changed, 79 insertions(+), 594 deletions(-) delete mode 100644 tests/kernels/test_fast_index_copy_rocm.py diff --git a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp index 880e8637..ad397fdd 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp +++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp @@ -1,3 +1,6 @@ +Warning: truncated output (original token count: 25647) +Total output lines: 2150 + // CPU-compute MoE executor for the "cpu" offload backend. // // Decode ships activations to the CPU, computes the routed experts here (reading @@ -29,7 +32,7 @@ #include #include -#include +#include #include #if defined(__linux__) @@ -826,486 +829,7 @@ float dot_dsfp4_avx512(const uint8_t* packed, const uint8_t* scale, const float* // AVX2: a 32-K block is 16 bytes -> two 8-lane halves (8 even + 8 odd each). __attribute__((target("avx2,fma"))) inline __m256 dsfp4_half_avx2(const uint8_t* pk, const float* xeb, const float* xob, __m256 mag8) { - __m256i wi = _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast(pk))); - __m256 vlo = e2m1_decode8(_mm256_and_si256(wi, _mm256_set1_epi32(0xF)), mag8); - __m256 vhi = e2m1_decode8(_mm256_srli_epi32(wi, 4), mag8); - return _mm256_fmadd_ps(vlo, _mm256_loadu_ps(xeb), _mm256_mul_ps(vhi, _mm256_loadu_ps(xob))); -} - -__attribute__((target("avx2,fma"))) -float dot_dsfp4_avx2(const uint8_t* packed, const uint8_t* scale, const float* xe, - const float* xo, int K, const float* e2m1, const float* e8m0) { - const __m256 mag8 = _mm256_loadu_ps(e2m1); - __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps(); - const int nb = K / 32; - for (int b = 0; b < nb; ++b) { - const uint8_t* pk = packed + (size_t)b * 16; - const float* xeb = xe + (size_t)b * 16; - const float* xob = xo + (size_t)b * 16; - const __m256 sc = _mm256_set1_ps(e8m0[scale[b]]); - acc0 = _mm256_fmadd_ps(dsfp4_half_avx2(pk, xeb, xob, mag8), sc, acc0); - acc1 = _mm256_fmadd_ps(dsfp4_half_avx2(pk + 8, xeb + 8, xob + 8, mag8), sc, acc1); - } - return hsum256(_mm256_add_ps(acc0, acc1)); -} -#endif - -dsdot_fn select_dsdot() { - const IsaTier t = pick_isa(); -#if CPU_MOE_X86 - if (t >= ISA_AVX512) return dot_dsfp4_avx512; - if (t >= ISA_AVX2) return dot_dsfp4_avx2; -#endif - (void)t; - return dot_dsfp4_scalar; -} - -// ------------------------- mxfp4 (gpt-oss) GEMV ----------------------------- -// Transposed split-K layout: blk[Kpairs, N2] (N innermost), scl[Kpairs/16, N2] -// e8m0 per 32-K. Computes out[c] = sum_kb (E2M1[lo]*x[2kb] + E2M1[hi]*x[2kb+1]) -// * 2^(e8m0-127) for a contiguous column tile (blk/scl already offset to col 0 of -// the tile). Vectorized over N (16 columns / __m512), K stays the outer (cache- -// sequential) loop. Used by both gate_up (K=H) and down (K=I). -using mxgemv_fn = void (*)(float*, const uint8_t*, const uint8_t*, const bf16_t*, int, int, - int, const float*, const float*); - -void mxfp4_gemv_scalar(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, - int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { - for (int c = 0; c < ncol; ++c) out[c] = 0.0f; - for (int kb = 0; kb < Kpairs; ++kb) { - const uint8_t* w = blk + (size_t)kb * N2; - const uint8_t* s = scl + (size_t)(kb >> 4) * N2; - const float xl = bf16_to_f32(x[2 * kb]); - const float xh = bf16_to_f32(x[2 * kb + 1]); - for (int c = 0; c < ncol; ++c) { - const uint8_t byte = w[c]; - out[c] += (e2m1[byte & 0xF] * xl + e2m1[byte >> 4] * xh) * e8m0[s[c]]; - } - } -} - -#if CPU_MOE_X86 -__attribute__((target("avx512f"))) -void mxfp4_gemv_avx512(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, - int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { - (void)e8m0; // e8m0[c]=2^(c-127) computed via bit construction (no gather) - const __m512 lut = _mm512_loadu_ps(e2m1); - const __m512i loma = _mm512_set1_epi32(0xF); - // K-outer / N-inner: each kb cache line is read once and all live column chunks - // (up to 4 -> 64 cols) accumulate from registers, so DRAM/L2 stream the tile once. - int c0 = 0; - for (; c0 + 16 <= ncol; c0 += 64) { - const int nchunk = std::min(4, (ncol - c0) / 16); - __m512 acc[4]; - for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm512_setzero_ps(); - for (int kblk = 0; kblk < Kpairs; kblk += 16) { // 16 K-pairs = 32 K = one scale row - __m512 sc[4]; - for (int ci = 0; ci < nchunk; ++ci) { - __m128i sraw = _mm_loadu_si128(reinterpret_cast( - scl + (size_t)(kblk >> 4) * N2 + c0 + ci * 16)); - sc[ci] = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu8_epi32(sraw), 23)); - } - __m512 blk_acc[4]; - for (int ci = 0; ci < nchunk; ++ci) blk_acc[ci] = _mm512_setzero_ps(); - for (int kk = 0; kk < 16; ++kk) { - const int kb = kblk + kk; - const uint8_t* wbase = blk + (size_t)kb * N2 + c0; - // The transposed layout strides K by N2 bytes; prefetch ahead so the strided - // reads are not exposed to DRAM latency (the HW streamer misses big strides). - constexpr int PFD = 8; - if (kb + PFD < Kpairs) - _mm_prefetch(reinterpret_cast(blk + (size_t)(kb + PFD) * N2 + c0), - _MM_HINT_T0); - const __m512 xl = _mm512_set1_ps(bf16_to_f32(x[2 * kb])); - const __m512 xh = _mm512_set1_ps(bf16_to_f32(x[2 * kb + 1])); - for (int ci = 0; ci < nchunk; ++ci) { - __m512i wi = _mm512_cvtepu8_epi32( - _mm_loadu_si128(reinterpret_cast(wbase + ci * 16))); - __m512 vlo = _mm512_permutexvar_ps(_mm512_and_si512(wi, loma), lut); - __m512 vhi = _mm512_permutexvar_ps(_mm512_and_si512(_mm512_srli_epi32(wi, 4), loma), lut); - blk_acc[ci] = _mm512_fmadd_ps(vlo, xl, blk_acc[ci]); - blk_acc[ci] = _mm512_fmadd_ps(vhi, xh, blk_acc[ci]); - } - } - for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm512_fmadd_ps(blk_acc[ci], sc[ci], acc[ci]); - } - for (int ci = 0; ci < nchunk; ++ci) _mm512_storeu_ps(out + c0 + ci * 16, acc[ci]); - } - for (int c = c0; c < ncol; ++c) { // tail columns (< 16) - float o = 0.0f; - for (int kb = 0; kb < Kpairs; ++kb) { - const uint8_t byte = blk[(size_t)kb * N2 + c]; - uint32_t bits = (uint32_t)scl[(size_t)(kb >> 4) * N2 + c] << 23; - float sc; - std::memcpy(&sc, &bits, 4); - o += (e2m1[byte & 0xF] * bf16_to_f32(x[2 * kb]) + - e2m1[byte >> 4] * bf16_to_f32(x[2 * kb + 1])) * sc; - } - out[c] = o; - } -} - -__attribute__((target("avx2,fma"))) -void mxfp4_gemv_avx2(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, - int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { - (void)e8m0; // e8m0[s]=2^(s-127) built via s<<23 (no gather) - const __m256 mag8 = _mm256_loadu_ps(e2m1); - int c0 = 0; - for (; c0 + 8 <= ncol; c0 += 32) { // up to 4 chunks of 8 = 32 cols - const int nchunk = std::min(4, (ncol - c0) / 8); - __m256 acc[4]; - for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm256_setzero_ps(); - for (int kblk = 0; kblk < Kpairs; kblk += 16) { // 16 K-pairs = one scale row - __m256 sc[4]; - for (int ci = 0; ci < nchunk; ++ci) { - __m128i sraw = _mm_loadl_epi64(reinterpret_cast( - scl + (size_t)(kblk >> 4) * N2 + c0 + ci * 8)); - sc[ci] = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_cvtepu8_epi32(sraw), 23)); - } - __m256 blk_acc[4]; - for (int ci = 0; ci < nchunk; ++ci) blk_acc[ci] = _mm256_setzero_ps(); - for (int kk = 0; kk < 16; ++kk) { - const int kb = kblk + kk; - const uint8_t* wbase = blk + (size_t)kb * N2 + c0; - constexpr int PFD = 8; - if (kb + PFD < Kpairs) - _mm_prefetch(reinterpret_cast(blk + (size_t)(kb + PFD) * N2 + c0), - _MM_HINT_T0); - const __m256 xl = _mm256_set1_ps(bf16_to_f32(x[2 * kb])); - const __m256 xh = _mm256_set1_ps(bf16_to_f32(x[2 * kb + 1])); - for (int ci = 0; ci < nchunk; ++ci) { - __m256i wi = _mm256_cvtepu8_epi32( - _mm_loadl_epi64(reinterpret_cast(wbase + ci * 8))); - __m256 vlo = e2m1_decode8(_mm256_and_si256(wi, _mm256_set1_epi32(0xF)), mag8); - __m256 vhi = e2m1_decode8(_mm256_srli_epi32(wi, 4), mag8); - blk_acc[ci] = _mm256_fmadd_ps(vlo, xl, blk_acc[ci]); - blk_acc[ci] = _mm256_fmadd_ps(vhi, xh, blk_acc[ci]); - } - } - for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm256_fmadd_ps(blk_acc[ci], sc[ci], acc[ci]); - } - for (int ci = 0; ci < nchunk; ++ci) _mm256_storeu_ps(out + c0 + ci * 8, acc[ci]); - } - for (int c = c0; c < ncol; ++c) { // tail columns (< 8); none when ncol%8==0 - float o = 0.0f; - for (int kb = 0; kb < Kpairs; ++kb) { - const uint8_t byte = blk[(size_t)kb * N2 + c]; - uint32_t bits = (uint32_t)scl[(size_t)(kb >> 4) * N2 + c] << 23; - float sc; - std::memcpy(&sc, &bits, 4); - o += (e2m1[byte & 0xF] * bf16_to_f32(x[2 * kb]) + - e2m1[byte >> 4] * bf16_to_f32(x[2 * kb + 1])) * sc; - } - out[c] = o; - } -} -#endif - -mxgemv_fn select_mxgemv() { - const IsaTier t = pick_isa(); -#if CPU_MOE_X86 - if (t >= ISA_AVX512) return mxfp4_gemv_avx512; - if (t >= ISA_AVX2) return mxfp4_gemv_avx2; -#endif - (void)t; - return mxfp4_gemv_scalar; -} - -// Round a clamped |x|<=448 to nearest float8-e4m3 (RNE), back to fp32. Matches -// torch.float8_e4m3fn / triton .to(float8e4nv). -inline float e4m3_round(float x) { - const float sign = x < 0.0f ? -1.0f : 1.0f; - const float a = std::fabs(x); - if (a == 0.0f) return 0.0f; - if (a >= 448.0f) return sign * 448.0f; - int e; - std::frexp(a, &e); // a in [2^(e-1), 2^e) - float step = std::ldexp(1.0f, e - 4); - const float min_step = std::ldexp(1.0f, -9); // e4m3 subnormal step (2^-9) - if (step < min_step) step = min_step; - float r = std::nearbyint(a / step) * step; - if (r > 448.0f) r = 448.0f; - return sign * r; -} - -// IEEE ceil(log2(v)) for v>0 (matches dsv4 _log2_ceil / fast_round_scale). -inline int ceil_log2_pos(float v) { - uint32_t bits; - std::memcpy(&bits, &v, sizeof(bits)); - const int exp = (int)((bits >> 23) & 0xFF); - const int man = (int)(bits & 0x7FFFFF); - return exp - 127 + (man != 0 ? 1 : 0); -} - -// Split an interleaved bf16 row into fp32 even/odd halves (even[m]=src[2m]). -// bf16->fp32 is exact, so this only reorders -- done once per token/route and -// reused across every output row of the GEMV. -inline void deinterleave_bf16_f32(const bf16_t* src, float* even, float* odd, int K) { - for (int m = 0; m < K / 2; ++m) { - even[m] = bf16_to_f32(src[2 * m]); - odd[m] = bf16_to_f32(src[2 * m + 1]); - } -} - -// DeepSeek-V4 activation FP8 round-trip (bf16 in/out): per 128-block, -// s = 2^ceil(log2(max(|x|,1e-4)/448)); y = round_e4m3(clamp(x/s,+-448)) * s. -void fp8_roundtrip_bf16(const bf16_t* src, bf16_t* dst, int K) { - for (int b0 = 0; b0 < K; b0 += 128) { - const int b1 = std::min(K, b0 + 128); - float amax = 1e-4f; - for (int i = b0; i < b1; ++i) amax = std::max(amax, std::fabs(bf16_to_f32(src[i]))); - const float s = std::ldexp(1.0f, ceil_log2_pos(amax * (1.0f / 448.0f))); - const float inv_s = 1.0f / s; - for (int i = b0; i < b1; ++i) { - float q = bf16_to_f32(src[i]) * inv_s; - q = std::min(448.0f, std::max(-448.0f, q)); - dst[i] = f32_to_bf16(e4m3_round(q) * s); - } - } -} - -// --------------------------------- executor --------------------------------- - -struct CpuMoeExecutor; - -struct MoeTask { - CpuMoeExecutor* exec; - int layer_id; - int num_tokens; - const bf16_t* x; // [num_tokens, H] - const int32_t* ids; // [num_tokens, top_k] (raw expert ids; <0 = skip) - const float* w; // [num_tokens, top_k] - bf16_t* y; // [num_tokens, H] -}; - -// Output-row tiling. Small enough to give every worker independent work even at -// batch size 1; large enough to amortize the atomic work-grab. -// -// Bandwidth notes (Sapphire Rapids 8480+, 13 cores): the two passes already read -// every expert weight byte exactly once per token (each output row block is owned -// by one worker), and x stays hot in L1 across a (token,expert)'s rows -- so the -// kernel is single-read bandwidth-optimal at bs=1 (~205 GB/s vs ~55 GB/s PCIe). -// One worker per *physical* core, pinned, is the sweet spot; SMT oversubscription -// thrashes the spin-barrier. Deferred (not worth it here / for this workload): -// - AMX-bf16: a GEMM tile engine; decode is M=1 GEMV so tiles sit idle. It would -// only pay off in a grouped/batched (dedup) path. -// - expert dedup for bs>1: read each distinct expert once and GEMM its tokens. -// Helps locality+bytes when bs is large; decode batches here are tiny (<=4). -// - NUMA: a single node is assumed. Multi-socket machines would split each -// expert's K dimension per node (banks are already per-row contiguous). -constexpr int IBLK = 32; -constexpr int HBLK = 32; - -// -------------------------------- Q4_0 (W4A8) -------------------------------- -// Native GGUF Q4_0 experts (gemma4 GGUF): per-32 block = fp16 scale d + 16 packed -// bytes; byte j holds element j in its low nibble and j+16 in its high nibble, so a -// block's storage order is [lo0..lo15, hi0..hi15] and w = (nibble - 8) * d. Matches -// the reference dequant (models/gguf/dequant.py) and the packed banks the GPU offload -// path streams. -// -// llama.cpp ggml_vec_dot_q4_0_q8_0: W4A8. The activation is pre-quantized to Q8_0 -// (per-32-block int8 ``aq`` + fp32 scale ``asb``); each block unpacks its 16 bytes to -// 32 int8 weights in [-8,7] (bytes_from_nibbles_32: low nibbles -> elems 0..15, high -// -> 16..31) and runs an integer block dot -- VPDPBUSD (AVX-VNNI) or VPMADDUBSW+VPMADDWD -// (AVX2) with the ggml sign trick |w|*(sign(w)*a)=w*a, or a scalar int loop -- then -// scales the block sum by wd*xd in fp32. No fp weight dequant / shuffle chain. The GPU -// offload path (ggml_moe_a8_vec / MMVQ) is also W4A8, so cpu and hybrid stay close. -using q4dot_fn = float (*)(const uint8_t*, const int8_t*, const float*, int); - -float q4_0_dot_i8_scalar(const uint8_t* w, const int8_t* aq, const float* asb, int K) { - float acc = 0.0f; - const int nb = K / 32; - for (int b = 0; b < nb; ++b) { - const uint8_t* blk = w + (size_t)b * 18; - uint16_t dh; - std::memcpy(&dh, blk, sizeof(dh)); - const uint8_t* q = blk + 2; // 16 nibble bytes - const int8_t* a = aq + (size_t)b * 32; - int isum = 0; - for (int j = 0; j < 16; ++j) { - isum += ((int)(q[j] & 0x0F) - 8) * (int)a[j]; // elem j - isum += ((int)(q[j] >> 4) - 8) * (int)a[16 + j]; // elem 16+j - } - acc += fp16_to_f32(dh) * asb[b] * (float)isum; - } - return acc; -} - -#if CPU_MOE_X86 -// fp16 block scale -> fp32 via HW F16C (single value in lane 0). -__attribute__((target("f16c"))) -static inline float q4_scale(uint16_t h) { - return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int)h))); -} - -// Unpack one Q4_0 block's 16 bytes -> 32 int8 weights in [-8,7] (elems 0..15 = low -// nibbles, 16..31 = high nibbles). ``eight`` = _mm256_set1_epi8(8). -__attribute__((target("avx2"))) -static inline __m256i q4_unpack32(const uint8_t* blk, __m128i mask, __m256i eight) { - const __m128i qb = _mm_loadu_si128(reinterpret_cast(blk + 2)); - const __m128i lo = _mm_and_si128(qb, mask); - const __m128i hi = _mm_and_si128(_mm_srli_epi16(qb, 4), mask); - return _mm256_sub_epi8(_mm256_set_m128i(hi, lo), eight); -} - -// AVX2 W4A8 (llama.cpp non-VNNI mul_sum_i8_pairs): integer block dot via VPMADDUBSW + -// VPMADDWD (sign trick), scaled by wd*xd. |aw*sa| pair sums <= 8*127*2 < 32767 -> no -// int16 saturation. This is the fast path on AVX2 CPUs without AVX-VNNI (and the -// avx512-tier fallback, since the block dot is 256-bit either way). -__attribute__((target("avx2,fma,f16c"))) -float q4_0_dot_i8_avx2(const uint8_t* w, const int8_t* aq, const float* asb, int K) { - const __m128i mask = _mm_set1_epi8(0x0F); - const __m256i eight = _mm256_set1_epi8(8); - const __m256i ones16 = _mm256_set1_epi16(1); - __m256 accF = _mm256_setzero_ps(); - const int nb = K / 32; - for (int b = 0; b < nb; ++b) { - const uint8_t* blk = w + (size_t)b * 18; - _mm_prefetch(reinterpret_cast(blk) + 512, _MM_HINT_T0); - uint16_t dh; - std::memcpy(&dh, blk, sizeof(dh)); - __m256i wq = q4_unpack32(blk, mask, eight); - __m256i a = _mm256_loadu_si256(reinterpret_cast(aq + (size_t)b * 32)); - __m256i aw = _mm256_sign_epi8(wq, wq); // |wq| (unsigned operand) - __m256i sa = _mm256_sign_epi8(a, wq); // sign(wq) * a (signed operand) - __m256i d32 = _mm256_madd_epi16(_mm256_maddubs_epi16(aw, sa), ones16); // 8 int32 - accF = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d32), _mm256_set1_ps(q4_scale(dh) * asb[b]), accF); - } - return hsum256(accF); -} - -// AVX-VNNI W4A8: one VPDPBUSD per block (the fast path on modern CPUs). -__attribute__((target("avx2,avxvnni,fma,f16c"))) -float q4_0_dot_i8_vnni(const uint8_t* w, const int8_t* aq, const float* asb, int K) { - const __m128i mask = _mm_set1_epi8(0x0F); - const __m256i eight = _mm256_set1_epi8(8); - __m256 accF = _mm256_setzero_ps(); - const int nb = K / 32; - for (int b = 0; b < nb; ++b) { - const uint8_t* blk = w + (size_t)b * 18; - _mm_prefetch(reinterpret_cast(blk) + 512, _MM_HINT_T0); - uint16_t dh; - std::memcpy(&dh, blk, sizeof(dh)); - __m256i wq = q4_unpack32(blk, mask, eight); - __m256i a = _mm256_loadu_si256(reinterpret_cast(aq + (size_t)b * 32)); - __m256i aw = _mm256_sign_epi8(wq, wq); // |wq| (unsigned operand) - __m256i sa = _mm256_sign_epi8(a, wq); // sign(wq) * a (signed operand) - __m256i di = _mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), aw, sa); - // All 32 elems of the block share wd*xd; distribute over di's 8 partial sums and - // reduce at the end (equivalent to scale * block_total). - accF = _mm256_fmadd_ps(_mm256_cvtepi32_ps(di), _mm256_set1_ps(q4_scale(dh) * asb[b]), accF); - } - return hsum256(accF); -} -#endif // CPU_MOE_X86 - -// All tiers are W4A8 (int8 activations pre-quantized to Q8_0). AVX-VNNI is orthogonal to -// the ISA tier (gated by cpu_has_avxvnni() / FREETOKEN_CPU_MOE_NO_VNNI), so it wins when -// present; otherwise the 256-bit VPMADDUBSW kernel covers both the avx2 and avx512 tiers. -q4dot_fn select_q4dot() { - const IsaTier t = pick_isa(); -#if CPU_MOE_X86 - if (cpu_has_avxvnni()) return q4_0_dot_i8_vnni; - if (t >= ISA_AVX2) return q4_0_dot_i8_avx2; -#endif - (void)t; - return q4_0_dot_i8_scalar; -} - -enum WFmt { WF_BF16 = 0, WF_NVFP4 = 1, WF_MXFP4 = 2, WF_DSFP4 = 3, WF_Q4_0 = 4 }; - -// Each ctor pointer arg is the address of a CPU int64 array of length -// num_layers (one base address per layer, built by cpu_executor.py's -// _make_table), not a single flat bank. tbl_at resolves -// tbl[layer_id] once per task/pass; a null table (bank unused by this fmt, ptr -// arg 0) resolves to nullptr without dereferencing. -inline const void* tbl_at(const uint64_t* tbl, int layer_id) { - return tbl ? reinterpret_cast(tbl[layer_id]) : nullptr; -} - -struct CpuMoeExecutor { - int num_threads; - int num_layers, num_experts, top_k; - int H, I; - int act, apply_on_input; - int fmt; // WFmt - bool needs_di = false; // pre-deinterleave activations to fp32 (nvfp4/ds_fp4) - // Per-layer pointer tables (one base address per layer, see tbl_at). gate_up_tbl - // doubles as the bf16 gate_up table and the nvfp4/mxfp4/q4_0/ds_fp4 packed-gate_up - // table (down_tbl likewise for down); which reinterpretation applies is picked by - // fmt at each resolve site (see gemm1_dot/gemm2_dot/do_pass1_mxfp4/do_pass1_dsfp4). - const uint64_t* gate_up_tbl; // bf16: [E,2I,H] rows; else: packed e2m1/mxfp4-blocks - const uint64_t* down_tbl; // bf16: [E,H,I] rows; else: packed e2m1/mxfp4-blocks - const uint64_t* gu_scale_tbl; // nvfp4/mxfp4/ds_fp4: [E,2I,*] block scales - const uint64_t* gu_global_tbl; // nvfp4: [E,2I] fp16 row globals - const uint64_t* dn_scale_tbl; // nvfp4/mxfp4/ds_fp4: [E,H,*] block scales - const uint64_t* dn_global_tbl; // nvfp4: [E,H] fp16 row globals - const uint64_t* gu_bias_tbl; // mxfp4: [E,2I] bf16 biases - const uint64_t* dn_bias_tbl; // mxfp4: [E,H] bf16 biases - float swiglu_alpha; - float swiglu_limit; // +inf == no clamp - dot_fn dot; - nvdot_fn nvdot; - nvi8dot_fn nvi8dot = nullptr; // AVX-VNNI W4A8 nvfp4 dot (nullptr -> use fp32 nvdot) - bool use_vnni = false; // nvfp4 + AVX-VNNI: decode via int8 VPDPBUSD (W4A8) - bool use_q4a8 = false; // q4_0: always W4A8 (llama.cpp Q4_0 x Q8_0); int8 pre-quant - dsdot_fn dsdot; - mxgemv_fn mxgemv; - q4dot_fn q4dot; - // ds_fp4: the caller already FP8-round-tripped the input activations on the GPU - // (same reference grid), so submit() must not repeat it on the host-callback - // thread. That scalar per-element pass is single-threaded ON THE DECODE CRITICAL - // PATH (~0.3ms/layer at H=4096, every worker and the GPU waiting on it); moving - // it to a captured GPU elementwise kernel removes it while keeping the official - // W4A8 numerics bit-exact. Set via set_input_prequant (see cpu_executor.py). - bool input_prequant = false; - // Q4_0 packed-row byte strides (H/32*18 for gate_up over K=H, I/32*18 for down over K=I). - int q4_gu_row_bytes = 0, q4_dn_row_bytes = 0; - float e2m1_lut[16]; - float e4m3_lut[256]; - float e8m0_lut[256]; // mxfp4 block scale: 2^(s-127), s clamped to [0,254] - const char* isa; - - std::vector g_scratch; // [max_tokens * top_k * I] intermediate - std::vector xq_scratch; // [max_tokens * H] ds_fp4 fp8-roundtripped input - // ds_fp4 activations pre-deinterleaved to fp32 (even/odd K) for the row-major dot. - std::vector xe_scratch, xo_scratch; // [max_tokens * H/2] (input) - std::vector ge_scratch, go_scratch; // [max_tokens*top_k*I/2] (intermediate) - // AVX-VNNI W4A8: per-16-block int8 activations [even(8),odd(8)] + per-block scale. - std::vector xi8_scratch, gi8_scratch; // [max_tokens*H], [max_tokens*top_k*I] - std::vector xas_scratch, gas_scratch; // [max_tokens*H/16], [..*top_k*I/16] - std::string isa_str; - - std::vector workers; - std::mutex task_mtx; - std::condition_variable task_cv; - std::mutex sync_mtx; - std::condition_variable sync_cv; - - bool stop = false; - uint64_t cur_gen = 0; - MoeTask* cur_task = nullptr; - std::atomic submitted{0}; - std::atomic completed{0}; - - std::atomic p1_next{0}; - std::atomic p2_next{0}; - std::atomic prt_next{0}; // ds_fp4 intermediate fp8 round-trip phase - int64_t p1_total = 0, p2_total = 0, prt_total = 0; - int n_iblk = 0, n_hblk = 0; - std::atomic done_count{0}; - std::atomic bar_count{0}; - std::atomic bar_sense{0}; - - std::vector owned_tasks; // persistent task descriptors (graph-stable) - std::vector core_ids; // worker tid -> logical CPU to pin to (may be empty) - - // ---- Flag-based GPU<->CPU handshake (replaces the per-layer cudaLaunchHostFunc pair) ---- - // A tiny GPU kernel bumps ready_flags[slot] at submit; this coordinator thread busy-polls - // it, runs the slot's task on the worker pool, and sets done_flags[slot], which a GPU - // spin-wait kernel polls at sync. This removes the ~2x30-50us host-func dispatch round - // trips per MoE layer per decode step that otherwise idle the GPU (~6 ms/step on a - // 75-layer model). One slot per (layer, decode batch size) pair -- the Python side + __m256i wi = _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cas…5647 tokens truncated…h size) pair -- the Python side // allocates slots as tasks are created. Flags live in mapped-pinned host memory (UVA: // the same pointers are used by the GPU kernels and by this thread). std::thread coord_thread; diff --git a/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h index 99539d1f..00a1b540 100644 --- a/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h +++ b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h @@ -19,6 +19,14 @@ #include #include +#ifndef CUDART_CB +#define CUDART_CB +#endif + +#ifndef __grid_constant__ +#define __grid_constant__ +#endif + // --- API name mapping (CUDA -> HIP) --- // HIP already defines most cuda* names as macros that expand to hip* equivalents // via hip_runtime.h, but a few are missing or differ in signature. Define them @@ -52,6 +60,14 @@ #define cudaHostAlloc hipHostMalloc #endif +#ifndef cudaHostAllocPortable +#define cudaHostAllocPortable hipHostMallocPortable +#endif + +#ifndef cudaHostAllocMapped +#define cudaHostAllocMapped hipHostMallocMapped +#endif + #ifndef cudaHostRegister #define cudaHostRegister hipHostRegister #endif @@ -122,6 +138,14 @@ #define cudaStream_t hipStream_t #endif +#ifndef cudaStreamSynchronize +#define cudaStreamSynchronize hipStreamSynchronize +#endif + +#ifndef cudaLaunchHostFunc +#define cudaLaunchHostFunc hipLaunchHostFunc +#endif + #ifndef dim3 // HIP already provides dim3; this is a no-op guard. #endif diff --git a/python/freetoken/kernel/csrc/include/freetoken/utils.cuh b/python/freetoken/kernel/csrc/include/freetoken/utils.cuh index 8e917832..f21b9585 100644 --- a/python/freetoken/kernel/csrc/include/freetoken/utils.cuh +++ b/python/freetoken/kernel/csrc/include/freetoken/utils.cuh @@ -1,5 +1,6 @@ #pragma once +#include #include #include @@ -115,6 +116,10 @@ public: } auto with_attr(bool use_pdl) -> LaunchKernel & { +#ifdef __HIP__ + (void)use_pdl; + m_config.numAttrs = 0; +#else if (use_pdl) { m_attr_cache.id = ::cudaLaunchAttributeProgrammaticStreamSerialization; m_attr_cache.val.programmaticStreamSerializationAllowed = 1; @@ -123,6 +128,7 @@ public: } else { m_config.numAttrs = 0; } +#endif return *this; } diff --git a/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh b/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh index bb83c23e..fe3f6be4 100644 --- a/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh +++ b/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh @@ -34,40 +34,64 @@ inline constexpr auto get_mem_package() { } __always_inline __device__ auto load_nc(const uint1* __restrict__ src) -> uint1 { +#ifdef __HIP_PLATFORM_AMD__ + return *src; +#else uint32_t tmp; asm volatile("ld.global.L1::no_allocate.b32 %0,[%1];" : "=r"(tmp) : "l"(src)); return uint1{tmp}; +#endif } __always_inline __device__ auto load_nc(const uint2* __restrict__ src) -> uint2 { +#ifdef __HIP_PLATFORM_AMD__ + return *src; +#else uint32_t tmp0, tmp1; asm volatile("ld.global.L1::no_allocate.v2.b32 {%0,%1},[%2];" : "=r"(tmp0), "=r"(tmp1) : "l"(src)); return uint2{tmp0, tmp1}; +#endif } __always_inline __device__ auto load_nc(const uint4* __restrict__ src) -> uint4 { +#ifdef __HIP_PLATFORM_AMD__ + return *src; +#else uint32_t tmp0, tmp1, tmp2, tmp3; asm volatile("ld.global.L1::no_allocate.v4.b32 {%0,%1,%2,%3},[%4];" : "=r"(tmp0), "=r"(tmp1), "=r"(tmp2), "=r"(tmp3) : "l"(src)); return uint4{tmp0, tmp1, tmp2, tmp3}; +#endif } __always_inline __device__ void store_nc(uint1* __restrict__ dst, const uint1& value) { +#ifdef __HIP_PLATFORM_AMD__ + *dst = value; +#else uint32_t tmp = value.x; asm volatile("st.global.wt.b32 [%0],%1;" ::"l"(dst), "r"(tmp)); +#endif } __always_inline __device__ void store_nc(uint2* __restrict__ dst, const uint2& value) { +#ifdef __HIP_PLATFORM_AMD__ + *dst = value; +#else uint32_t tmp0 = value.x; uint32_t tmp1 = value.y; asm volatile("st.global.wt.v2.b32 [%0],{%1,%2};" ::"l"(dst), "r"(tmp0), "r"(tmp1)); +#endif } __always_inline __device__ void store_nc(uint4* __restrict__ dst, const uint4& value) { +#ifdef __HIP_PLATFORM_AMD__ + *dst = value; +#else uint32_t tmp0 = value.x; uint32_t tmp1 = value.y; uint32_t tmp2 = value.z; uint32_t tmp3 = value.w; asm volatile("st.global.wt.v4.b32 [%0],{%1,%2,%3,%4};" ::"l"(dst), "r"(tmp0), "r"(tmp1), "r"(tmp2), "r"(tmp3)); +#endif } __always_inline __device__ void wait_flag_clear(const int32_t* __restrict__ flag_ptr) { diff --git a/python/freetoken/kernel/fast_index_copy.py b/python/freetoken/kernel/fast_index_copy.py index 05b6a4f8..1aaa1303 100644 --- a/python/freetoken/kernel/fast_index_copy.py +++ b/python/freetoken/kernel/fast_index_copy.py @@ -22,42 +22,6 @@ def _skip_fast_index_copy_enabled() -> bool: return os.getenv(SKIP_FAST_INDEX_COPY_ENV, "").strip().lower() in _TRUE_VALUES -def _is_rocm() -> bool: - return getattr(torch.version, "hip", None) is not None - - -def _rocm_index_copy_fallback( - dst: torch.Tensor, - dst_indices: torch.Tensor, - src: torch.Tensor, - src_indices: torch.Tensor, - num_indices: torch.Tensor | None = None, -) -> None: - """Correctness-first ROCm fallback for the CUDA-specific copy JIT. - - The native fast-index-copy header still contains NVIDIA inline PTX and CUDA - DLPack device matchers. Until that kernel has a HIP implementation, keep - ROCm functional by gathering only the requested source rows and moving that - bounded selection to the destination device. CUDA continues to use the - existing JIT unchanged. - """ - count = dst_indices.numel() if num_indices is None else int(num_indices.item()) - assert 0 <= count <= dst_indices.numel() - assert count <= src_indices.numel() - if count == 0: - return - - src_index = src_indices[:count].to(device=src.device, dtype=torch.long) - dst_index = dst_indices[:count].to(device=dst.device, dtype=torch.long) - rows = src.index_select(0, src_index) - if rows.device != dst.device: - rows = rows.to( - device=dst.device, - non_blocking=src.device.type == "cpu" and src.is_pinned(), - ) - dst.index_copy_(0, dst_index, rows) - - @lru_cache(maxsize=None) def _jit_update_flag_module() -> Module: return load_jit( @@ -150,14 +114,6 @@ def fast_index_copy_jit( dst = dst.as_strided(size=(dst.size(0), num_dst_feature), stride=(num_dst_feature, 1)) src = src.as_strided(size=(src.size(0), num_src_feature), stride=(num_src_feature, 1)) - if _is_rocm(): - if priority is not None: - raise NotImplementedError( - "ROCm fast-index-copy fallback does not implement high/normal priority scheduling" - ) - _rocm_index_copy_fallback(dst, dst_indices, src, src_indices, num_indices) - return - feature_size = dst.size(-1) * dst.element_size() num_block = num_block or DEFAULT_NUM_BLOCKS worker_threads = worker_threads or _default_worker_threads(feature_size) diff --git a/python/freetoken/kernel/triton/activation.py b/python/freetoken/kernel/triton/activation.py index 2c38b533..0b7c945c 100644 --- a/python/freetoken/kernel/triton/activation.py +++ b/python/freetoken/kernel/triton/activation.py @@ -20,8 +20,9 @@ import triton.language as tl from triton.language.extra import libdevice from triton.language.extra.cuda import gdc_wait, gdc_launch_dependents +from triton.language import target_info -from freetoken.utils.arch import is_sm90_supported +from freetoken.utils.arch import is_rocm, is_sm90_supported SILU = 0 GELU = 1 @@ -48,6 +49,8 @@ def _pdl_supported() -> bool: @triton.jit def _fast_tanh(x): + if target_info.is_hip(): + return libdevice.tanh(x) # PTX tanh.approx.f32 — single HW op, matches flashinfer math::tanh. return tl.inline_asm_elementwise( "tanh.approx.f32 $0, $1;", "=f,f", [x], @@ -57,6 +60,8 @@ def _fast_tanh(x): @triton.jit def _fast_ex2(x): + if target_info.is_hip(): + return libdevice.exp2(x) # PTX ex2.approx.f32 — matches __expf fast path used by flashinfer silu. return tl.inline_asm_elementwise( "ex2.approx.f32 $0, $1;", "=f,f", [x], @@ -134,8 +139,9 @@ def _act_and_mul( block_d = min(triton.next_power_of_2(d), 1024 if M >= 4096 else 512) num_stages = 2 if block_d == 1024 else 3 _act_and_mul_kernel[grid]( - o2, x2, d, alpha, limit, ACT=kind, ENABLE_PDL=pdl, launch_pdl=pdl, + o2, x2, d, alpha, limit, ACT=kind, ENABLE_PDL=pdl, BLOCK_D=block_d, num_warps=4, num_stages=num_stages, + **({} if is_rocm() else {"launch_pdl": pdl}), ) return out diff --git a/python/freetoken/kernel/triton/e4m3_compat.py b/python/freetoken/kernel/triton/e4m3_compat.py index 61d3a0e7..e52095cc 100644 --- a/python/freetoken/kernel/triton/e4m3_compat.py +++ b/python/freetoken/kernel/triton/e4m3_compat.py @@ -59,6 +59,10 @@ def e4m3_native() -> bool: if _native is None: if FORCE_EMU: _native = False + elif torch.version.hip is not None: + # ROCm reports gfx1101 as capability (11, 0), which is not a CUDA + # compute capability and must not select the native fp8e4nv path. + _native = False else: native = {torch.cuda.get_device_capability(i) >= (8, 9) for i in range(torch.cuda.device_count())} diff --git a/python/freetoken/kernel/triton/norm.py b/python/freetoken/kernel/triton/norm.py index 3f95c29f..9071e1df 100644 --- a/python/freetoken/kernel/triton/norm.py +++ b/python/freetoken/kernel/triton/norm.py @@ -30,7 +30,7 @@ import triton.language as tl from triton.language.extra.cuda import gdc_launch_dependents, gdc_wait -from freetoken.utils.arch import is_sm90_supported +from freetoken.utils.arch import is_rocm, is_sm90_supported _HEUR = {"BLOCK": lambda a: triton.next_power_of_2(a["H"])} @@ -144,7 +144,8 @@ def _rmsnorm(input, weight, eps, out, gemma: bool): pdl = contig and is_sm90_supported() _rmsnorm_kernel[(A, B)]( out, input, weight, eps, H, sxa, sxb, soa, sob, - CONTIG=contig, ENABLE_PDL=pdl, launch_pdl=pdl, GEMMA=gemma, + CONTIG=contig, ENABLE_PDL=pdl, GEMMA=gemma, + **({} if is_rocm() else {"launch_pdl": pdl}), num_warps=_num_warps(A * B), num_stages=1, ) return out @@ -172,7 +173,8 @@ def _fused_add_rmsnorm(input, residual, weight, eps, gemma: bool): pdl = contig and is_sm90_supported() _fused_add_rmsnorm_kernel[(A, B)]( input, residual, weight, eps, H, sxa, sxb, sra, srb, - CONTIG=contig, ENABLE_PDL=pdl, launch_pdl=pdl, GEMMA=gemma, + CONTIG=contig, ENABLE_PDL=pdl, GEMMA=gemma, + **({} if is_rocm() else {"launch_pdl": pdl}), num_warps=_num_warps(A * B), num_stages=1, ) diff --git a/setup.py b/setup.py index 8ba0640a..698ad780 100644 --- a/setup.py +++ b/setup.py @@ -9,6 +9,7 @@ ROOT = Path(__file__).parent +KERNEL_INCLUDE = ROOT / "python" / "freetoken" / "kernel" / "csrc" / "include" def _check_toolchain() -> None: @@ -61,6 +62,8 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: runtime_lib = "cudart" extra_compile = ["-O3", "-std=c++17"] +runtime_include_dirs.append(str(KERNEL_INCLUDE)) + _check_toolchain() diff --git a/tests/kernels/test_fast_index_copy_rocm.py b/tests/kernels/test_fast_index_copy_rocm.py deleted file mode 100644 index 37f0d5f6..00000000 --- a/tests/kernels/test_fast_index_copy_rocm.py +++ /dev/null @@ -1,64 +0,0 @@ -from __future__ import annotations - -import pytest -import torch - -import freetoken.kernel.fast_index_copy as fast_copy - - -def test_rocm_fallback_copies_only_requested_rows() -> None: - src = torch.arange(20, dtype=torch.float32).reshape(5, 4).to(torch.bfloat16) - dst = torch.full((4, 4), -1, dtype=torch.bfloat16) - src_indices = torch.tensor([4, 1, 3], dtype=torch.int32) - dst_indices = torch.tensor([2, 0, 3], dtype=torch.int32) - num_indices = torch.tensor([2], dtype=torch.int64) - - fast_copy._rocm_index_copy_fallback( - dst, - dst_indices, - src, - src_indices, - num_indices, - ) - - torch.testing.assert_close(dst[2], src[4], rtol=0, atol=0) - torch.testing.assert_close(dst[0], src[1], rtol=0, atol=0) - torch.testing.assert_close(dst[1], torch.full((4,), -1, dtype=torch.bfloat16), rtol=0, atol=0) - torch.testing.assert_close(dst[3], torch.full((4,), -1, dtype=torch.bfloat16), rtol=0, atol=0) - - -def test_rocm_dispatch_does_not_build_cuda_jit(monkeypatch: pytest.MonkeyPatch) -> None: - src = torch.arange(12, dtype=torch.float32).reshape(3, 4) - dst = torch.zeros((3, 4), dtype=torch.float32) - src_indices = torch.tensor([2, 0], dtype=torch.int32) - dst_indices = torch.tensor([1, 2], dtype=torch.int32) - - monkeypatch.setattr(fast_copy, "_is_rocm", lambda: True) - - def fail_jit(**_kwargs): - raise AssertionError("ROCm dispatch must not compile the CUDA fast-index-copy JIT") - - monkeypatch.setattr(fast_copy, "_jit_fast_index_copy_module", fail_jit) - - fast_copy.fast_index_copy_jit(dst, dst_indices, src, src_indices) - - torch.testing.assert_close(dst[1], src[2], rtol=0, atol=0) - torch.testing.assert_close(dst[2], src[0], rtol=0, atol=0) - - -def test_rocm_priority_mode_fails_closed(monkeypatch: pytest.MonkeyPatch) -> None: - src = torch.zeros((2, 4), dtype=torch.float32) - dst = torch.zeros((2, 4), dtype=torch.float32) - indices = torch.tensor([0], dtype=torch.int32) - - monkeypatch.setattr(fast_copy, "_is_rocm", lambda: True) - - with pytest.raises(NotImplementedError, match="priority scheduling"): - fast_copy.fast_index_copy_jit( - dst, - indices, - src, - indices, - priority="high", - sync_flag=torch.zeros((1,), dtype=torch.int32), - ) From 62bb9623eb3c802ad53063b906374d4cdb8d1b30 Mon Sep 17 00:00:00 2001 From: Yuu <206304251+nekomario28@users.noreply.github.com> Date: Mon, 24 Aug 2026 03:28:27 +0900 Subject: [PATCH 06/10] fix(rocm): preserve CPU MoE implementation --- .../kernel/csrc/cpu_moe/cpu_moe_ext.cpp | 484 +++++++++++++++++- 1 file changed, 480 insertions(+), 4 deletions(-) diff --git a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp index ad397fdd..56ab93df 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp +++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp @@ -1,6 +1,3 @@ -Warning: truncated output (original token count: 25647) -Total output lines: 2150 - // CPU-compute MoE executor for the "cpu" offload backend. // // Decode ships activations to the CPU, computes the routed experts here (reading @@ -829,7 +826,486 @@ float dot_dsfp4_avx512(const uint8_t* packed, const uint8_t* scale, const float* // AVX2: a 32-K block is 16 bytes -> two 8-lane halves (8 even + 8 odd each). __attribute__((target("avx2,fma"))) inline __m256 dsfp4_half_avx2(const uint8_t* pk, const float* xeb, const float* xob, __m256 mag8) { - __m256i wi = _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cas…5647 tokens truncated…h size) pair -- the Python side + __m256i wi = _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast(pk))); + __m256 vlo = e2m1_decode8(_mm256_and_si256(wi, _mm256_set1_epi32(0xF)), mag8); + __m256 vhi = e2m1_decode8(_mm256_srli_epi32(wi, 4), mag8); + return _mm256_fmadd_ps(vlo, _mm256_loadu_ps(xeb), _mm256_mul_ps(vhi, _mm256_loadu_ps(xob))); +} + +__attribute__((target("avx2,fma"))) +float dot_dsfp4_avx2(const uint8_t* packed, const uint8_t* scale, const float* xe, + const float* xo, int K, const float* e2m1, const float* e8m0) { + const __m256 mag8 = _mm256_loadu_ps(e2m1); + __m256 acc0 = _mm256_setzero_ps(), acc1 = _mm256_setzero_ps(); + const int nb = K / 32; + for (int b = 0; b < nb; ++b) { + const uint8_t* pk = packed + (size_t)b * 16; + const float* xeb = xe + (size_t)b * 16; + const float* xob = xo + (size_t)b * 16; + const __m256 sc = _mm256_set1_ps(e8m0[scale[b]]); + acc0 = _mm256_fmadd_ps(dsfp4_half_avx2(pk, xeb, xob, mag8), sc, acc0); + acc1 = _mm256_fmadd_ps(dsfp4_half_avx2(pk + 8, xeb + 8, xob + 8, mag8), sc, acc1); + } + return hsum256(_mm256_add_ps(acc0, acc1)); +} +#endif + +dsdot_fn select_dsdot() { + const IsaTier t = pick_isa(); +#if CPU_MOE_X86 + if (t >= ISA_AVX512) return dot_dsfp4_avx512; + if (t >= ISA_AVX2) return dot_dsfp4_avx2; +#endif + (void)t; + return dot_dsfp4_scalar; +} + +// ------------------------- mxfp4 (gpt-oss) GEMV ----------------------------- +// Transposed split-K layout: blk[Kpairs, N2] (N innermost), scl[Kpairs/16, N2] +// e8m0 per 32-K. Computes out[c] = sum_kb (E2M1[lo]*x[2kb] + E2M1[hi]*x[2kb+1]) +// * 2^(e8m0-127) for a contiguous column tile (blk/scl already offset to col 0 of +// the tile). Vectorized over N (16 columns / __m512), K stays the outer (cache- +// sequential) loop. Used by both gate_up (K=H) and down (K=I). +using mxgemv_fn = void (*)(float*, const uint8_t*, const uint8_t*, const bf16_t*, int, int, + int, const float*, const float*); + +void mxfp4_gemv_scalar(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, + int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { + for (int c = 0; c < ncol; ++c) out[c] = 0.0f; + for (int kb = 0; kb < Kpairs; ++kb) { + const uint8_t* w = blk + (size_t)kb * N2; + const uint8_t* s = scl + (size_t)(kb >> 4) * N2; + const float xl = bf16_to_f32(x[2 * kb]); + const float xh = bf16_to_f32(x[2 * kb + 1]); + for (int c = 0; c < ncol; ++c) { + const uint8_t byte = w[c]; + out[c] += (e2m1[byte & 0xF] * xl + e2m1[byte >> 4] * xh) * e8m0[s[c]]; + } + } +} + +#if CPU_MOE_X86 +__attribute__((target("avx512f"))) +void mxfp4_gemv_avx512(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, + int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { + (void)e8m0; // e8m0[c]=2^(c-127) computed via bit construction (no gather) + const __m512 lut = _mm512_loadu_ps(e2m1); + const __m512i loma = _mm512_set1_epi32(0xF); + // K-outer / N-inner: each kb cache line is read once and all live column chunks + // (up to 4 -> 64 cols) accumulate from registers, so DRAM/L2 stream the tile once. + int c0 = 0; + for (; c0 + 16 <= ncol; c0 += 64) { + const int nchunk = std::min(4, (ncol - c0) / 16); + __m512 acc[4]; + for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm512_setzero_ps(); + for (int kblk = 0; kblk < Kpairs; kblk += 16) { // 16 K-pairs = 32 K = one scale row + __m512 sc[4]; + for (int ci = 0; ci < nchunk; ++ci) { + __m128i sraw = _mm_loadu_si128(reinterpret_cast( + scl + (size_t)(kblk >> 4) * N2 + c0 + ci * 16)); + sc[ci] = _mm512_castsi512_ps(_mm512_slli_epi32(_mm512_cvtepu8_epi32(sraw), 23)); + } + __m512 blk_acc[4]; + for (int ci = 0; ci < nchunk; ++ci) blk_acc[ci] = _mm512_setzero_ps(); + for (int kk = 0; kk < 16; ++kk) { + const int kb = kblk + kk; + const uint8_t* wbase = blk + (size_t)kb * N2 + c0; + // The transposed layout strides K by N2 bytes; prefetch ahead so the strided + // reads are not exposed to DRAM latency (the HW streamer misses big strides). + constexpr int PFD = 8; + if (kb + PFD < Kpairs) + _mm_prefetch(reinterpret_cast(blk + (size_t)(kb + PFD) * N2 + c0), + _MM_HINT_T0); + const __m512 xl = _mm512_set1_ps(bf16_to_f32(x[2 * kb])); + const __m512 xh = _mm512_set1_ps(bf16_to_f32(x[2 * kb + 1])); + for (int ci = 0; ci < nchunk; ++ci) { + __m512i wi = _mm512_cvtepu8_epi32( + _mm_loadu_si128(reinterpret_cast(wbase + ci * 16))); + __m512 vlo = _mm512_permutexvar_ps(_mm512_and_si512(wi, loma), lut); + __m512 vhi = _mm512_permutexvar_ps(_mm512_and_si512(_mm512_srli_epi32(wi, 4), loma), lut); + blk_acc[ci] = _mm512_fmadd_ps(vlo, xl, blk_acc[ci]); + blk_acc[ci] = _mm512_fmadd_ps(vhi, xh, blk_acc[ci]); + } + } + for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm512_fmadd_ps(blk_acc[ci], sc[ci], acc[ci]); + } + for (int ci = 0; ci < nchunk; ++ci) _mm512_storeu_ps(out + c0 + ci * 16, acc[ci]); + } + for (int c = c0; c < ncol; ++c) { // tail columns (< 16) + float o = 0.0f; + for (int kb = 0; kb < Kpairs; ++kb) { + const uint8_t byte = blk[(size_t)kb * N2 + c]; + uint32_t bits = (uint32_t)scl[(size_t)(kb >> 4) * N2 + c] << 23; + float sc; + std::memcpy(&sc, &bits, 4); + o += (e2m1[byte & 0xF] * bf16_to_f32(x[2 * kb]) + + e2m1[byte >> 4] * bf16_to_f32(x[2 * kb + 1])) * sc; + } + out[c] = o; + } +} + +__attribute__((target("avx2,fma"))) +void mxfp4_gemv_avx2(float* out, const uint8_t* blk, const uint8_t* scl, const bf16_t* x, + int Kpairs, int N2, int ncol, const float* e2m1, const float* e8m0) { + (void)e8m0; // e8m0[s]=2^(s-127) built via s<<23 (no gather) + const __m256 mag8 = _mm256_loadu_ps(e2m1); + int c0 = 0; + for (; c0 + 8 <= ncol; c0 += 32) { // up to 4 chunks of 8 = 32 cols + const int nchunk = std::min(4, (ncol - c0) / 8); + __m256 acc[4]; + for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm256_setzero_ps(); + for (int kblk = 0; kblk < Kpairs; kblk += 16) { // 16 K-pairs = one scale row + __m256 sc[4]; + for (int ci = 0; ci < nchunk; ++ci) { + __m128i sraw = _mm_loadl_epi64(reinterpret_cast( + scl + (size_t)(kblk >> 4) * N2 + c0 + ci * 8)); + sc[ci] = _mm256_castsi256_ps(_mm256_slli_epi32(_mm256_cvtepu8_epi32(sraw), 23)); + } + __m256 blk_acc[4]; + for (int ci = 0; ci < nchunk; ++ci) blk_acc[ci] = _mm256_setzero_ps(); + for (int kk = 0; kk < 16; ++kk) { + const int kb = kblk + kk; + const uint8_t* wbase = blk + (size_t)kb * N2 + c0; + constexpr int PFD = 8; + if (kb + PFD < Kpairs) + _mm_prefetch(reinterpret_cast(blk + (size_t)(kb + PFD) * N2 + c0), + _MM_HINT_T0); + const __m256 xl = _mm256_set1_ps(bf16_to_f32(x[2 * kb])); + const __m256 xh = _mm256_set1_ps(bf16_to_f32(x[2 * kb + 1])); + for (int ci = 0; ci < nchunk; ++ci) { + __m256i wi = _mm256_cvtepu8_epi32( + _mm_loadl_epi64(reinterpret_cast(wbase + ci * 8))); + __m256 vlo = e2m1_decode8(_mm256_and_si256(wi, _mm256_set1_epi32(0xF)), mag8); + __m256 vhi = e2m1_decode8(_mm256_srli_epi32(wi, 4), mag8); + blk_acc[ci] = _mm256_fmadd_ps(vlo, xl, blk_acc[ci]); + blk_acc[ci] = _mm256_fmadd_ps(vhi, xh, blk_acc[ci]); + } + } + for (int ci = 0; ci < nchunk; ++ci) acc[ci] = _mm256_fmadd_ps(blk_acc[ci], sc[ci], acc[ci]); + } + for (int ci = 0; ci < nchunk; ++ci) _mm256_storeu_ps(out + c0 + ci * 8, acc[ci]); + } + for (int c = c0; c < ncol; ++c) { // tail columns (< 8); none when ncol%8==0 + float o = 0.0f; + for (int kb = 0; kb < Kpairs; ++kb) { + const uint8_t byte = blk[(size_t)kb * N2 + c]; + uint32_t bits = (uint32_t)scl[(size_t)(kb >> 4) * N2 + c] << 23; + float sc; + std::memcpy(&sc, &bits, 4); + o += (e2m1[byte & 0xF] * bf16_to_f32(x[2 * kb]) + + e2m1[byte >> 4] * bf16_to_f32(x[2 * kb + 1])) * sc; + } + out[c] = o; + } +} +#endif + +mxgemv_fn select_mxgemv() { + const IsaTier t = pick_isa(); +#if CPU_MOE_X86 + if (t >= ISA_AVX512) return mxfp4_gemv_avx512; + if (t >= ISA_AVX2) return mxfp4_gemv_avx2; +#endif + (void)t; + return mxfp4_gemv_scalar; +} + +// Round a clamped |x|<=448 to nearest float8-e4m3 (RNE), back to fp32. Matches +// torch.float8_e4m3fn / triton .to(float8e4nv). +inline float e4m3_round(float x) { + const float sign = x < 0.0f ? -1.0f : 1.0f; + const float a = std::fabs(x); + if (a == 0.0f) return 0.0f; + if (a >= 448.0f) return sign * 448.0f; + int e; + std::frexp(a, &e); // a in [2^(e-1), 2^e) + float step = std::ldexp(1.0f, e - 4); + const float min_step = std::ldexp(1.0f, -9); // e4m3 subnormal step (2^-9) + if (step < min_step) step = min_step; + float r = std::nearbyint(a / step) * step; + if (r > 448.0f) r = 448.0f; + return sign * r; +} + +// IEEE ceil(log2(v)) for v>0 (matches dsv4 _log2_ceil / fast_round_scale). +inline int ceil_log2_pos(float v) { + uint32_t bits; + std::memcpy(&bits, &v, sizeof(bits)); + const int exp = (int)((bits >> 23) & 0xFF); + const int man = (int)(bits & 0x7FFFFF); + return exp - 127 + (man != 0 ? 1 : 0); +} + +// Split an interleaved bf16 row into fp32 even/odd halves (even[m]=src[2m]). +// bf16->fp32 is exact, so this only reorders -- done once per token/route and +// reused across every output row of the GEMV. +inline void deinterleave_bf16_f32(const bf16_t* src, float* even, float* odd, int K) { + for (int m = 0; m < K / 2; ++m) { + even[m] = bf16_to_f32(src[2 * m]); + odd[m] = bf16_to_f32(src[2 * m + 1]); + } +} + +// DeepSeek-V4 activation FP8 round-trip (bf16 in/out): per 128-block, +// s = 2^ceil(log2(max(|x|,1e-4)/448)); y = round_e4m3(clamp(x/s,+-448)) * s. +void fp8_roundtrip_bf16(const bf16_t* src, bf16_t* dst, int K) { + for (int b0 = 0; b0 < K; b0 += 128) { + const int b1 = std::min(K, b0 + 128); + float amax = 1e-4f; + for (int i = b0; i < b1; ++i) amax = std::max(amax, std::fabs(bf16_to_f32(src[i]))); + const float s = std::ldexp(1.0f, ceil_log2_pos(amax * (1.0f / 448.0f))); + const float inv_s = 1.0f / s; + for (int i = b0; i < b1; ++i) { + float q = bf16_to_f32(src[i]) * inv_s; + q = std::min(448.0f, std::max(-448.0f, q)); + dst[i] = f32_to_bf16(e4m3_round(q) * s); + } + } +} + +// --------------------------------- executor --------------------------------- + +struct CpuMoeExecutor; + +struct MoeTask { + CpuMoeExecutor* exec; + int layer_id; + int num_tokens; + const bf16_t* x; // [num_tokens, H] + const int32_t* ids; // [num_tokens, top_k] (raw expert ids; <0 = skip) + const float* w; // [num_tokens, top_k] + bf16_t* y; // [num_tokens, H] +}; + +// Output-row tiling. Small enough to give every worker independent work even at +// batch size 1; large enough to amortize the atomic work-grab. +// +// Bandwidth notes (Sapphire Rapids 8480+, 13 cores): the two passes already read +// every expert weight byte exactly once per token (each output row block is owned +// by one worker), and x stays hot in L1 across a (token,expert)'s rows -- so the +// kernel is single-read bandwidth-optimal at bs=1 (~205 GB/s vs ~55 GB/s PCIe). +// One worker per *physical* core, pinned, is the sweet spot; SMT oversubscription +// thrashes the spin-barrier. Deferred (not worth it here / for this workload): +// - AMX-bf16: a GEMM tile engine; decode is M=1 GEMV so tiles sit idle. It would +// only pay off in a grouped/batched (dedup) path. +// - expert dedup for bs>1: read each distinct expert once and GEMM its tokens. +// Helps locality+bytes when bs is large; decode batches here are tiny (<=4). +// - NUMA: a single node is assumed. Multi-socket machines would split each +// expert's K dimension per node (banks are already per-row contiguous). +constexpr int IBLK = 32; +constexpr int HBLK = 32; + +// -------------------------------- Q4_0 (W4A8) -------------------------------- +// Native GGUF Q4_0 experts (gemma4 GGUF): per-32 block = fp16 scale d + 16 packed +// bytes; byte j holds element j in its low nibble and j+16 in its high nibble, so a +// block's storage order is [lo0..lo15, hi0..hi15] and w = (nibble - 8) * d. Matches +// the reference dequant (models/gguf/dequant.py) and the packed banks the GPU offload +// path streams. +// +// llama.cpp ggml_vec_dot_q4_0_q8_0: W4A8. The activation is pre-quantized to Q8_0 +// (per-32-block int8 ``aq`` + fp32 scale ``asb``); each block unpacks its 16 bytes to +// 32 int8 weights in [-8,7] (bytes_from_nibbles_32: low nibbles -> elems 0..15, high +// -> 16..31) and runs an integer block dot -- VPDPBUSD (AVX-VNNI) or VPMADDUBSW+VPMADDWD +// (AVX2) with the ggml sign trick |w|*(sign(w)*a)=w*a, or a scalar int loop -- then +// scales the block sum by wd*xd in fp32. No fp weight dequant / shuffle chain. The GPU +// offload path (ggml_moe_a8_vec / MMVQ) is also W4A8, so cpu and hybrid stay close. +using q4dot_fn = float (*)(const uint8_t*, const int8_t*, const float*, int); + +float q4_0_dot_i8_scalar(const uint8_t* w, const int8_t* aq, const float* asb, int K) { + float acc = 0.0f; + const int nb = K / 32; + for (int b = 0; b < nb; ++b) { + const uint8_t* blk = w + (size_t)b * 18; + uint16_t dh; + std::memcpy(&dh, blk, sizeof(dh)); + const uint8_t* q = blk + 2; // 16 nibble bytes + const int8_t* a = aq + (size_t)b * 32; + int isum = 0; + for (int j = 0; j < 16; ++j) { + isum += ((int)(q[j] & 0x0F) - 8) * (int)a[j]; // elem j + isum += ((int)(q[j] >> 4) - 8) * (int)a[16 + j]; // elem 16+j + } + acc += fp16_to_f32(dh) * asb[b] * (float)isum; + } + return acc; +} + +#if CPU_MOE_X86 +// fp16 block scale -> fp32 via HW F16C (single value in lane 0). +__attribute__((target("f16c"))) +static inline float q4_scale(uint16_t h) { + return _mm_cvtss_f32(_mm_cvtph_ps(_mm_cvtsi32_si128((int)h))); +} + +// Unpack one Q4_0 block's 16 bytes -> 32 int8 weights in [-8,7] (elems 0..15 = low +// nibbles, 16..31 = high nibbles). ``eight`` = _mm256_set1_epi8(8). +__attribute__((target("avx2"))) +static inline __m256i q4_unpack32(const uint8_t* blk, __m128i mask, __m256i eight) { + const __m128i qb = _mm_loadu_si128(reinterpret_cast(blk + 2)); + const __m128i lo = _mm_and_si128(qb, mask); + const __m128i hi = _mm_and_si128(_mm_srli_epi16(qb, 4), mask); + return _mm256_sub_epi8(_mm256_set_m128i(hi, lo), eight); +} + +// AVX2 W4A8 (llama.cpp non-VNNI mul_sum_i8_pairs): integer block dot via VPMADDUBSW + +// VPMADDWD (sign trick), scaled by wd*xd. |aw*sa| pair sums <= 8*127*2 < 32767 -> no +// int16 saturation. This is the fast path on AVX2 CPUs without AVX-VNNI (and the +// avx512-tier fallback, since the block dot is 256-bit either way). +__attribute__((target("avx2,fma,f16c"))) +float q4_0_dot_i8_avx2(const uint8_t* w, const int8_t* aq, const float* asb, int K) { + const __m128i mask = _mm_set1_epi8(0x0F); + const __m256i eight = _mm256_set1_epi8(8); + const __m256i ones16 = _mm256_set1_epi16(1); + __m256 accF = _mm256_setzero_ps(); + const int nb = K / 32; + for (int b = 0; b < nb; ++b) { + const uint8_t* blk = w + (size_t)b * 18; + _mm_prefetch(reinterpret_cast(blk) + 512, _MM_HINT_T0); + uint16_t dh; + std::memcpy(&dh, blk, sizeof(dh)); + __m256i wq = q4_unpack32(blk, mask, eight); + __m256i a = _mm256_loadu_si256(reinterpret_cast(aq + (size_t)b * 32)); + __m256i aw = _mm256_sign_epi8(wq, wq); // |wq| (unsigned operand) + __m256i sa = _mm256_sign_epi8(a, wq); // sign(wq) * a (signed operand) + __m256i d32 = _mm256_madd_epi16(_mm256_maddubs_epi16(aw, sa), ones16); // 8 int32 + accF = _mm256_fmadd_ps(_mm256_cvtepi32_ps(d32), _mm256_set1_ps(q4_scale(dh) * asb[b]), accF); + } + return hsum256(accF); +} + +// AVX-VNNI W4A8: one VPDPBUSD per block (the fast path on modern CPUs). +__attribute__((target("avx2,avxvnni,fma,f16c"))) +float q4_0_dot_i8_vnni(const uint8_t* w, const int8_t* aq, const float* asb, int K) { + const __m128i mask = _mm_set1_epi8(0x0F); + const __m256i eight = _mm256_set1_epi8(8); + __m256 accF = _mm256_setzero_ps(); + const int nb = K / 32; + for (int b = 0; b < nb; ++b) { + const uint8_t* blk = w + (size_t)b * 18; + _mm_prefetch(reinterpret_cast(blk) + 512, _MM_HINT_T0); + uint16_t dh; + std::memcpy(&dh, blk, sizeof(dh)); + __m256i wq = q4_unpack32(blk, mask, eight); + __m256i a = _mm256_loadu_si256(reinterpret_cast(aq + (size_t)b * 32)); + __m256i aw = _mm256_sign_epi8(wq, wq); // |wq| (unsigned operand) + __m256i sa = _mm256_sign_epi8(a, wq); // sign(wq) * a (signed operand) + __m256i di = _mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), aw, sa); + // All 32 elems of the block share wd*xd; distribute over di's 8 partial sums and + // reduce at the end (equivalent to scale * block_total). + accF = _mm256_fmadd_ps(_mm256_cvtepi32_ps(di), _mm256_set1_ps(q4_scale(dh) * asb[b]), accF); + } + return hsum256(accF); +} +#endif // CPU_MOE_X86 + +// All tiers are W4A8 (int8 activations pre-quantized to Q8_0). AVX-VNNI is orthogonal to +// the ISA tier (gated by cpu_has_avxvnni() / FREETOKEN_CPU_MOE_NO_VNNI), so it wins when +// present; otherwise the 256-bit VPMADDUBSW kernel covers both the avx2 and avx512 tiers. +q4dot_fn select_q4dot() { + const IsaTier t = pick_isa(); +#if CPU_MOE_X86 + if (cpu_has_avxvnni()) return q4_0_dot_i8_vnni; + if (t >= ISA_AVX2) return q4_0_dot_i8_avx2; +#endif + (void)t; + return q4_0_dot_i8_scalar; +} + +enum WFmt { WF_BF16 = 0, WF_NVFP4 = 1, WF_MXFP4 = 2, WF_DSFP4 = 3, WF_Q4_0 = 4 }; + +// Each ctor pointer arg is the address of a CPU int64 array of length +// num_layers (one base address per layer, built by cpu_executor.py's +// _make_table), not a single flat bank. tbl_at resolves +// tbl[layer_id] once per task/pass; a null table (bank unused by this fmt, ptr +// arg 0) resolves to nullptr without dereferencing. +inline const void* tbl_at(const uint64_t* tbl, int layer_id) { + return tbl ? reinterpret_cast(tbl[layer_id]) : nullptr; +} + +struct CpuMoeExecutor { + int num_threads; + int num_layers, num_experts, top_k; + int H, I; + int act, apply_on_input; + int fmt; // WFmt + bool needs_di = false; // pre-deinterleave activations to fp32 (nvfp4/ds_fp4) + // Per-layer pointer tables (one base address per layer, see tbl_at). gate_up_tbl + // doubles as the bf16 gate_up table and the nvfp4/mxfp4/q4_0/ds_fp4 packed-gate_up + // table (down_tbl likewise for down); which reinterpretation applies is picked by + // fmt at each resolve site (see gemm1_dot/gemm2_dot/do_pass1_mxfp4/do_pass1_dsfp4). + const uint64_t* gate_up_tbl; // bf16: [E,2I,H] rows; else: packed e2m1/mxfp4-blocks + const uint64_t* down_tbl; // bf16: [E,H,I] rows; else: packed e2m1/mxfp4-blocks + const uint64_t* gu_scale_tbl; // nvfp4/mxfp4/ds_fp4: [E,2I,*] block scales + const uint64_t* gu_global_tbl; // nvfp4: [E,2I] fp16 row globals + const uint64_t* dn_scale_tbl; // nvfp4/mxfp4/ds_fp4: [E,H,*] block scales + const uint64_t* dn_global_tbl; // nvfp4: [E,H] fp16 row globals + const uint64_t* gu_bias_tbl; // mxfp4: [E,2I] bf16 biases + const uint64_t* dn_bias_tbl; // mxfp4: [E,H] bf16 biases + float swiglu_alpha; + float swiglu_limit; // +inf == no clamp + dot_fn dot; + nvdot_fn nvdot; + nvi8dot_fn nvi8dot = nullptr; // AVX-VNNI W4A8 nvfp4 dot (nullptr -> use fp32 nvdot) + bool use_vnni = false; // nvfp4 + AVX-VNNI: decode via int8 VPDPBUSD (W4A8) + bool use_q4a8 = false; // q4_0: always W4A8 (llama.cpp Q4_0 x Q8_0); int8 pre-quant + dsdot_fn dsdot; + mxgemv_fn mxgemv; + q4dot_fn q4dot; + // ds_fp4: the caller already FP8-round-tripped the input activations on the GPU + // (same reference grid), so submit() must not repeat it on the host-callback + // thread. That scalar per-element pass is single-threaded ON THE DECODE CRITICAL + // PATH (~0.3ms/layer at H=4096, every worker and the GPU waiting on it); moving + // it to a captured GPU elementwise kernel removes it while keeping the official + // W4A8 numerics bit-exact. Set via set_input_prequant (see cpu_executor.py). + bool input_prequant = false; + // Q4_0 packed-row byte strides (H/32*18 for gate_up over K=H, I/32*18 for down over K=I). + int q4_gu_row_bytes = 0, q4_dn_row_bytes = 0; + float e2m1_lut[16]; + float e4m3_lut[256]; + float e8m0_lut[256]; // mxfp4 block scale: 2^(s-127), s clamped to [0,254] + const char* isa; + + std::vector g_scratch; // [max_tokens * top_k * I] intermediate + std::vector xq_scratch; // [max_tokens * H] ds_fp4 fp8-roundtripped input + // ds_fp4 activations pre-deinterleaved to fp32 (even/odd K) for the row-major dot. + std::vector xe_scratch, xo_scratch; // [max_tokens * H/2] (input) + std::vector ge_scratch, go_scratch; // [max_tokens*top_k*I/2] (intermediate) + // AVX-VNNI W4A8: per-16-block int8 activations [even(8),odd(8)] + per-block scale. + std::vector xi8_scratch, gi8_scratch; // [max_tokens*H], [max_tokens*top_k*I] + std::vector xas_scratch, gas_scratch; // [max_tokens*H/16], [..*top_k*I/16] + std::string isa_str; + + std::vector workers; + std::mutex task_mtx; + std::condition_variable task_cv; + std::mutex sync_mtx; + std::condition_variable sync_cv; + + bool stop = false; + uint64_t cur_gen = 0; + MoeTask* cur_task = nullptr; + std::atomic submitted{0}; + std::atomic completed{0}; + + std::atomic p1_next{0}; + std::atomic p2_next{0}; + std::atomic prt_next{0}; // ds_fp4 intermediate fp8 round-trip phase + int64_t p1_total = 0, p2_total = 0, prt_total = 0; + int n_iblk = 0, n_hblk = 0; + std::atomic done_count{0}; + std::atomic bar_count{0}; + std::atomic bar_sense{0}; + + std::vector owned_tasks; // persistent task descriptors (graph-stable) + std::vector core_ids; // worker tid -> logical CPU to pin to (may be empty) + + // ---- Flag-based GPU<->CPU handshake (replaces the per-layer cudaLaunchHostFunc pair) ---- + // A tiny GPU kernel bumps ready_flags[slot] at submit; this coordinator thread busy-polls + // it, runs the slot's task on the worker pool, and sets done_flags[slot], which a GPU + // spin-wait kernel polls at sync. This removes the ~2x30-50us host-func dispatch round + // trips per MoE layer per decode step that otherwise idle the GPU (~6 ms/step on a + // 75-layer model). One slot per (layer, decode batch size) pair -- the Python side // allocates slots as tasks are created. Flags live in mapped-pinned host memory (UVA: // the same pointers are used by the GPU kernels and by this thread). std::thread coord_thread; From c7a95f726b3d67f7570668d7140a258253160de5 Mon Sep 17 00:00:00 2001 From: zihaomu Date: Mon, 24 Aug 2026 15:08:37 +0800 Subject: [PATCH 07/10] build(rocm): support RDNA4 discovery and modular SDKs --- docs/install.md | 31 +++++++- python/freetoken/kernel/__main__.py | 9 ++- .../csrc/include/freetoken/hip_compat.h | 49 +++++++------ python/freetoken/kernel/utils.py | 72 +++++++++++++++++-- python/freetoken/utils/__init__.py | 2 + python/freetoken/utils/arch.py | 46 ++++++++++-- setup.py | 65 +++++++++++------ tests/kernels/test_pinned_tensor.py | 7 +- tests/utils/test_rocm_arch.py | 53 ++++++++++++++ 9 files changed, 271 insertions(+), 63 deletions(-) create mode 100644 tests/utils/test_rocm_arch.py diff --git a/docs/install.md b/docs/install.md index f5205ab3..4db8a15a 100644 --- a/docs/install.md +++ b/docs/install.md @@ -2,7 +2,9 @@ ## Requirements -- Linux x86_64, NVIDIA GPU, driver r580+ (CUDA 13) +- Linux x86_64 with either: + - NVIDIA GPU, driver r580+ (CUDA 13), or + - AMD RDNA3/RDNA4 GPU (`gfx1100`-`gfx1103`, `gfx1200`, or `gfx1201`) with ROCm 7.14 - Python >= 3.10, with [uv](https://docs.astral.sh/uv/) recommended (plain `pip` + `venv` works too) @@ -15,6 +17,33 @@ uv pip install "freetoken[accel]" CUDA kernels are JIT-compiled on first use, need a CUDA 13 toolkit with `nvcc` on PATH. +### AMD ROCm source install (experimental) + +Use an official ROCm PyTorch image whose PyTorch version satisfies the project's +`torch>=2.11,<2.12` constraint. For RDNA4, the matching ROCm 7.14 image is: + +```bash +VIDEO_GID="$(getent group video | cut -d: -f3)" +RENDER_GID="$(getent group render | cut -d: -f3)" +docker run --rm -it \ + --device=/dev/kfd --device=/dev/dri \ + --group-add="$VIDEO_GID" --group-add="$RENDER_GID" --ipc=host \ + --cap-add=SYS_PTRACE --security-opt seccomp=unconfined \ + -e PYTORCH_ROCM_ARCH=gfx1201 -e FREETOKEN_ROCM_ARCH=gfx1201 \ + -v "$PWD:/workspace/FreeToken" -w /workspace/FreeToken \ + rocm/pytorch:rocm7.14_ubuntu24.04_py3.12_pytorch_release_2.11.0 bash +``` + +Inside the container, preserve the ROCm-enabled PyTorch already supplied by the +image and disable build isolation so it is also used to compile the extensions: + +```bash +python -m pip install --no-build-isolation -e . +``` + +Set both architecture variables to `gfx1200` for RX 9060 family GPUs, or to the +actual target reported by `rocminfo`. + ## Method 2: Install from source ```bash diff --git a/python/freetoken/kernel/__main__.py b/python/freetoken/kernel/__main__.py index 5227443e..457385a5 100644 --- a/python/freetoken/kernel/__main__.py +++ b/python/freetoken/kernel/__main__.py @@ -6,7 +6,7 @@ def generate_clangd(): import subprocess from freetoken.kernel.utils import DEFAULT_INCLUDE - from freetoken.utils import init_logger + from freetoken.utils import get_rocm_gfx_arch, init_logger, is_rocm from tvm_ffi.libinfo import find_dlpack_include_path, find_include_path logger = init_logger(__name__) @@ -14,7 +14,9 @@ def generate_clangd(): include_paths = [find_include_path(), find_dlpack_include_path()] + DEFAULT_INCLUDE # TODO(ROCm): hiprtc JIT cache should be separate from nvcc JIT cache to avoid stale binaries. - try: + if is_rocm(): + arch_flags = ["-xhip", f"--offload-arch={get_rocm_gfx_arch() or 'gfx1201'}"] + else: status = subprocess.run( args=["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"], capture_output=True, @@ -23,9 +25,6 @@ def generate_clangd(): compute_cap = status.stdout.decode("utf-8").strip().split("\n")[0] major, minor = compute_cap.split(".") arch_flags = ["-xcuda", f"--cuda-gpu-arch=sm_{major}{minor}"] - except (subprocess.CalledProcessError, FileNotFoundError): - # TODO(ROCm): parse gfx target from rocm-smi; default to gfx1100 for now. - arch_flags = ["-xhip", "--offload-arch=gfx1100"] compile_flags = ",\n ".join( arch_flags + ["-std=c++20", "-Wall", "-Wextra"] + [f"-isystem{path}" for path in include_paths] diff --git a/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h index 00a1b540..eb7e71e1 100644 --- a/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h +++ b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h @@ -7,26 +7,22 @@ // On NVIDIA platforms the CUDA headers are included as-is and every macro below // resolves to the original CUDA symbol, so there is zero overhead. // -// Supported ROCm targets (RDNA3): +// Supported ROCm targets: // gfx1100 — RX 7900 XTX / XT // gfx1101 — RX 7900 GRE // gfx1102 — RX 7700 / XT // gfx1103 — RX 7600 / XT +// gfx1200 — RX 9060 family +// gfx1201 — RX 9070 family / Radeon AI PRO R9700 -#ifdef __HIP__ +#if defined(__HIP_PLATFORM_AMD__) || defined(USE_ROCM) + +#define FREETOKEN_USE_ROCM 1 // --- HIP runtime headers --- #include #include -#ifndef CUDART_CB -#define CUDART_CB -#endif - -#ifndef __grid_constant__ -#define __grid_constant__ -#endif - // --- API name mapping (CUDA -> HIP) --- // HIP already defines most cuda* names as macros that expand to hip* equivalents // via hip_runtime.h, but a few are missing or differ in signature. Define them @@ -60,14 +56,6 @@ #define cudaHostAlloc hipHostMalloc #endif -#ifndef cudaHostAllocPortable -#define cudaHostAllocPortable hipHostMallocPortable -#endif - -#ifndef cudaHostAllocMapped -#define cudaHostAllocMapped hipHostMallocMapped -#endif - #ifndef cudaHostRegister #define cudaHostRegister hipHostRegister #endif @@ -80,6 +68,14 @@ #define cudaHostRegisterMapped hipHostRegisterMapped #endif +#ifndef cudaHostAllocPortable +#define cudaHostAllocPortable hipHostMallocPortable +#endif + +#ifndef cudaHostAllocMapped +#define cudaHostAllocMapped hipHostMallocMapped +#endif + #ifndef cudaHostGetDevicePointer #define cudaHostGetDevicePointer hipHostGetDevicePointer #endif @@ -115,8 +111,7 @@ #endif #ifndef cudaLaunchKernelEx -// TODO(ROCm): hipLaunchKernelEx is available in newer ROCm; use it when widely shipped. -// For now, fall back to hipLaunchKernel with config extracted manually. +// ROCm 7 exposes the CUDA-compatible extended launch configuration through HIP. #define cudaLaunchKernelEx hipLaunchKernelEx #endif @@ -146,12 +141,22 @@ #define cudaLaunchHostFunc hipLaunchHostFunc #endif +#ifndef CUDART_CB +#define CUDART_CB +#endif + +#ifndef __grid_constant__ +#define __grid_constant__ +#endif + #ifndef dim3 // HIP already provides dim3; this is a no-op guard. #endif -#else // !__HIP__ — NVIDIA CUDA path +#else // NVIDIA CUDA path + +#define FREETOKEN_USE_ROCM 0 #include -#endif // __HIP__ +#endif diff --git a/python/freetoken/kernel/utils.py b/python/freetoken/kernel/utils.py index dfdcd4c7..937a750c 100644 --- a/python/freetoken/kernel/utils.py +++ b/python/freetoken/kernel/utils.py @@ -4,6 +4,7 @@ import os import pathlib import re +from functools import cache from typing import TYPE_CHECKING, List, NamedTuple, Tuple, TypeAlias, Union if TYPE_CHECKING: @@ -21,6 +22,7 @@ DEFAULT_CUDA_CFLAGS = ["-std=c++20", "-O3", "--expt-relaxed-constexpr"] DEFAULT_HIP_CFLAGS = ["-std=c++20", "-O3"] DEFAULT_LDFLAGS = [] +DEFAULT_ROCM_ARCHES = ("gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1200", "gfx1201") def _is_rocm() -> bool: @@ -50,11 +52,65 @@ def _rank(a: str) -> int: def _hip_cflags(extra: List[str]) -> List[str]: """HIP flags for a kernel build on ROCm.""" - # TODO(ROCm): Triton autotune configs need RDNA3-specific tuning (wave count, LDS size). + # TODO(ROCm): Triton autotune configs need RDNA-specific tuning (wave count, LDS size). flags = DEFAULT_HIP_CFLAGS + extra - rocm_arch = os.getenv("FREETOKEN_ROCM_ARCH", "gfx1100;gfx1101;gfx1102;gfx1103") - flags = flags + [f"--offload-arch={rocm_arch}"] - return flags + raw_arches = os.getenv("FREETOKEN_ROCM_ARCH") or os.getenv("PYTORCH_ROCM_ARCH", "") + arches = list(dict.fromkeys(re.findall(r"gfx\d+[a-z]?", raw_arches.lower()))) + if not arches: + from freetoken.utils.arch import get_rocm_gfx_arch + + detected = get_rocm_gfx_arch() + arches = [detected] if detected else list(DEFAULT_ROCM_ARCHES) + return flags + [f"--offload-arch={arch}" for arch in arches] + + +@cache +def _rocm_link_flags() -> List[str]: + """Make ROCm's runtime library discoverable to JIT link commands. + + Traditional ROCm installs provide ``libamdhip64.so`` under ``$ROCM_HOME/lib``. + ROCm 7.14 Python SDK images only provide the versioned soname, while TVM-FFI + still links with ``-lamdhip64``. Supply a cache-local unversioned symlink via + ``LIBRARY_PATH`` without modifying the image's Python environment. + """ + candidates: list[pathlib.Path] = [] + if os.getenv("ROCM_HOME"): + candidates.append(pathlib.Path(os.environ["ROCM_HOME"])) + try: + from torch.utils.cpp_extension import ROCM_HOME + + if ROCM_HOME: + candidates.append(pathlib.Path(ROCM_HOME)) + except ImportError: + pass + spec = importlib.util.find_spec("_rocm_sdk_core") + if spec and spec.submodule_search_locations: + candidates.append(pathlib.Path(next(iter(spec.submodule_search_locations)))) + candidates.append(pathlib.Path("/opt/rocm")) + + for rocm_home in dict.fromkeys(candidates): + library_dir = rocm_home / "lib" + unversioned = library_dir / "libamdhip64.so" + link_dir = library_dir + if not unversioned.exists(): + versioned = sorted(library_dir.glob("libamdhip64.so.*")) + if not versioned: + continue + link_dir = pathlib.Path.home() / ".cache" / "freetoken" / "rocm-lib" + link_dir.mkdir(parents=True, exist_ok=True) + compat_link = link_dir / "libamdhip64.so" + if not compat_link.exists() and not compat_link.is_symlink(): + compat_link.symlink_to(versioned[-1]) + + current = [path for path in os.getenv("LIBRARY_PATH", "").split(":") if path] + os.environ["LIBRARY_PATH"] = ":".join( + dict.fromkeys([str(link_dir), str(library_dir), *current]) + ) + return [f"-Wl,-rpath,{library_dir}"] + + raise RuntimeError("Unable to locate libamdhip64 for ROCm JIT linking") + + CPP_TEMPLATE_TYPE: TypeAlias = Union[int, float, bool] @@ -234,8 +290,10 @@ def load_aot( if _is_rocm(): cuda_cflags = _hip_cflags(extra_cuda_cflags) + runtime_ldflags = _rocm_link_flags() else: cuda_cflags = _cuda_cflags(extra_cuda_cflags) + runtime_ldflags = [] return load( name, @@ -243,7 +301,7 @@ def load_aot( cuda_files=cuda_files, extra_cflags=DEFAULT_CFLAGS + extra_cflags, extra_cuda_cflags=cuda_cflags, - extra_ldflags=DEFAULT_LDFLAGS + extra_ldflags, + extra_ldflags=DEFAULT_LDFLAGS + runtime_ldflags + extra_ldflags, extra_include_paths=DEFAULT_INCLUDE + extra_include_paths, build_directory=build_directory, ) @@ -294,8 +352,10 @@ def load_jit( if _is_rocm(): cuda_cflags = _hip_cflags(extra_cuda_cflags) + runtime_ldflags = _rocm_link_flags() else: cuda_cflags = _cuda_cflags(extra_cuda_cflags) + runtime_ldflags = [] return load_inline( name, @@ -303,7 +363,7 @@ def load_jit( cuda_sources=cuda_sources, extra_cflags=DEFAULT_CFLAGS + extra_cflags, extra_cuda_cflags=cuda_cflags, - extra_ldflags=DEFAULT_LDFLAGS + extra_ldflags, + extra_ldflags=DEFAULT_LDFLAGS + runtime_ldflags + extra_ldflags, extra_include_paths=DEFAULT_INCLUDE + extra_include_paths, build_directory=build_directory, ) diff --git a/python/freetoken/utils/__init__.py b/python/freetoken/utils/__init__.py index 1348a528..c54579a1 100644 --- a/python/freetoken/utils/__init__.py +++ b/python/freetoken/utils/__init__.py @@ -3,6 +3,7 @@ is_rocm, get_rocm_gfx_arch, is_gfx11xx_family, + is_gfx12xx_family, is_sm90_family, is_sm90_supported, is_sm100_family, @@ -41,6 +42,7 @@ "is_rocm", "get_rocm_gfx_arch", "is_gfx11xx_family", + "is_gfx12xx_family", "is_sm90_family", "is_sm90_supported", "is_sm100_family", diff --git a/python/freetoken/utils/arch.py b/python/freetoken/utils/arch.py index a70c8aa3..3bf8fb61 100644 --- a/python/freetoken/utils/arch.py +++ b/python/freetoken/utils/arch.py @@ -2,9 +2,18 @@ import functools import os +import re from typing import Tuple +_GFX_ARCH_RE = re.compile(r"gfx\d+[a-z]?") + + +def _gfx_arch_from(value: object) -> str | None: + match = _GFX_ARCH_RE.search(str(value).lower()) + return match.group(0) if match else None + + @functools.cache def is_rocm() -> bool: """True when torch is built for ROCm (AMD GPU) instead of CUDA.""" @@ -14,15 +23,31 @@ def is_rocm() -> bool: @functools.cache def get_rocm_gfx_arch() -> str | None: - """The gfx target of the current AMD GPU (e.g. \"gfx1100\"), or None.""" + """Return the current AMD GPU target (for example ``gfx1201``). + + Prefer the runtime device because build variables may contain multiple + semicolon-separated targets. Environment variables remain useful for + cross-compilation and systems where no GPU is currently visible. + """ if not is_rocm(): return None - # TODO(ROCm): parse rocm-smi for auto-detection; for now rely on env. - for env_var in ("PYTORCH_ROCM_ARCH", "HCC_AMDGPU_TARGET"): - val = os.getenv(env_var, "") - for gfx in ("gfx1100", "gfx1101", "gfx1102", "gfx1103"): - if gfx in val: - return gfx + + import torch + + if torch.cuda.is_available(): + try: + props = torch.cuda.get_device_properties(torch.cuda.current_device()) + for attr in ("gcnArchName", "arch"): + arch = _gfx_arch_from(getattr(props, attr, "")) + if arch: + return arch + except (AttributeError, RuntimeError): + pass + + for env_var in ("FREETOKEN_ROCM_ARCH", "PYTORCH_ROCM_ARCH", "HCC_AMDGPU_TARGET"): + arch = _gfx_arch_from(os.getenv(env_var, "")) + if arch: + return arch return None @@ -33,6 +58,13 @@ def is_gfx11xx_family() -> bool: return arch is not None and arch.startswith("gfx110") +@functools.cache +def is_gfx12xx_family() -> bool: + """True when the current AMD GPU is RDNA4 (gfx120x).""" + arch = get_rocm_gfx_arch() + return arch is not None and arch.startswith("gfx120") + + @functools.cache def _get_torch_cuda_version() -> Tuple[int, int] | None: import torch diff --git a/setup.py b/setup.py index 698ad780..bac07c6f 100644 --- a/setup.py +++ b/setup.py @@ -5,11 +5,11 @@ from pathlib import Path from setuptools import setup -from torch.utils.cpp_extension import BuildExtension, CUDA_HOME, CppExtension +from torch.utils.cpp_extension import BuildExtension, CUDA_HOME, CppExtension, ROCM_HOME ROOT = Path(__file__).parent -KERNEL_INCLUDE = ROOT / "python" / "freetoken" / "kernel" / "csrc" / "include" +KERNEL_INCLUDE = str(ROOT / "python" / "freetoken" / "kernel" / "csrc" / "include") def _check_toolchain() -> None: @@ -25,15 +25,36 @@ def _is_rocm() -> bool: return getattr(torch.version, "hip", None) is not None -def _rocm_paths() -> tuple[list[str], list[str]]: - rocm_home = Path(os.getenv("ROCM_HOME", "/opt/rocm")) - if not rocm_home.exists(): - raise RuntimeError( - "ROCM_HOME is required to build on ROCm. Set ROCM_HOME to your ROCm install." - ) - include_dirs = [str(rocm_home / "include")] - library_dirs = [str(rocm_home / "lib")] - return include_dirs, library_dirs +def _rocm_paths() -> tuple[list[str], list[str], str]: + candidates: list[Path] = [] + if os.getenv("ROCM_HOME"): + candidates.append(Path(os.environ["ROCM_HOME"])) + if ROCM_HOME: + candidates.append(Path(ROCM_HOME)) + + # ROCm 7.14 PyTorch images ship the SDK as a Python package instead of + # installing it at /opt/rocm. + spec = importlib.util.find_spec("_rocm_sdk_core") + if spec and spec.submodule_search_locations: + candidates.append(Path(next(iter(spec.submodule_search_locations)))) + candidates.append(Path("/opt/rocm")) + + for rocm_home in dict.fromkeys(candidates): + include_dir = rocm_home / "include" + library_dir = rocm_home / "lib" + if not (include_dir / "hip" / "hip_runtime.h").exists(): + continue + if (library_dir / "libamdhip64.so").exists(): + return [str(include_dir)], [str(library_dir)], "amdhip64" + versioned = sorted(library_dir.glob("libamdhip64.so.*")) + if versioned: + return [str(include_dir)], [str(library_dir)], f":{versioned[-1].name}" + + searched = ", ".join(str(path) for path in dict.fromkeys(candidates)) + raise RuntimeError( + "A ROCm SDK with HIP headers and libamdhip64 is required to build on ROCm; " + f"searched: {searched}. Set ROCM_HOME to override." + ) def _cuda_runtime_paths() -> tuple[list[str], list[str]]: @@ -52,18 +73,18 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: IS_ROCM = _is_rocm() if IS_ROCM: - runtime_include_dirs, runtime_library_dirs = _rocm_paths() - runtime_lib = "amdhip64" - # TODO(ROCm): allow override via FREETOKEN_ROCM_ARCH; default to all RDNA3. - rocm_arch = os.getenv("FREETOKEN_ROCM_ARCH", "gfx1100;gfx1101;gfx1102;gfx1103") - extra_compile = ["-O3", "-std=c++17", f"--offload-arch={rocm_arch}"] + runtime_include_dirs, runtime_library_dirs, runtime_lib = _rocm_paths() + runtime_link_args = [f"-Wl,-rpath,{runtime_library_dirs[0]}"] + # These extensions contain host code only. BuildExtension supplies the ROCm + # platform defines to the C++ compiler; offload architecture flags belong on + # HIP device sources and would be rejected by the host compiler here. + extra_compile = ["-O3", "-std=c++17"] else: runtime_include_dirs, runtime_library_dirs = _cuda_runtime_paths() runtime_lib = "cudart" + runtime_link_args = [] extra_compile = ["-O3", "-std=c++17"] -runtime_include_dirs.append(str(KERNEL_INCLUDE)) - _check_toolchain() @@ -74,12 +95,13 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: sources=[ "python/freetoken/kernel/csrc/pinned_tensor.cpp", ], - include_dirs=runtime_include_dirs, + include_dirs=[KERNEL_INCLUDE, *runtime_include_dirs], library_dirs=runtime_library_dirs, libraries=[runtime_lib], extra_compile_args=extra_compile, + extra_link_args=runtime_link_args, ), - # CPU-compute MoE executor for --moe-backend cpu. Links cudart/hip for the + # CPU-compute MoE executor for --moe-backend cpu. Links cudart/amdhip64 for the # cudaLaunchHostFunc submit/sync graph nodes; the bf16 GEMV microkernels # use per-function target attributes (avx512bf16/avx512f) + a runtime # __builtin_cpu_supports dispatch, so the single binary stays portable @@ -89,10 +111,11 @@ def _cuda_runtime_paths() -> tuple[list[str], list[str]]: sources=[ "python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp", ], - include_dirs=runtime_include_dirs, + include_dirs=[KERNEL_INCLUDE, *runtime_include_dirs], library_dirs=runtime_library_dirs, libraries=[runtime_lib], extra_compile_args=extra_compile + ["-pthread"], + extra_link_args=runtime_link_args, ), ], cmdclass={"build_ext": BuildExtension.with_options(use_ninja=True)}, diff --git a/tests/kernels/test_pinned_tensor.py b/tests/kernels/test_pinned_tensor.py index e61108fd..2fee4f25 100644 --- a/tests/kernels/test_pinned_tensor.py +++ b/tests/kernels/test_pinned_tensor.py @@ -122,7 +122,12 @@ def test_host_device_ptr_is_identity_under_uva(): pytest.skip("non-UVA platform: host_device_ptr rejects unregistered memory instead") # Under UVA cudaHostGetDevicePointer degenerates to identity for any host pointer # (no registration validation); rejection of pageable memory only exists on - # non-identity platforms (Windows/WDDM), where the translation is real. + # non-identity CUDA platforms (Windows/WDDM), where the translation is real. + # HIP validates registration even though registered/pinned memory uses the + # identity address on Linux. Calling it with pageable memory also leaves a + # sticky HIP error, so the pinned identity case above is the relevant check. + if torch.version.hip is not None: + return pageable = torch.empty(64, dtype=torch.uint8) ext = _load_pinned_extension() assert ext.host_device_ptr(pageable.data_ptr()) == pageable.data_ptr() diff --git a/tests/utils/test_rocm_arch.py b/tests/utils/test_rocm_arch.py new file mode 100644 index 00000000..f080b1e9 --- /dev/null +++ b/tests/utils/test_rocm_arch.py @@ -0,0 +1,53 @@ +from types import SimpleNamespace + +import torch + +from freetoken.utils import arch + + +def _clear_arch_caches() -> None: + arch.get_rocm_gfx_arch.cache_clear() + arch.is_gfx11xx_family.cache_clear() + arch.is_gfx12xx_family.cache_clear() + + +def test_rocm_arch_prefers_visible_device_over_multi_arch_build_env(monkeypatch): + monkeypatch.setattr(arch, "is_rocm", lambda: True) + monkeypatch.setattr(torch.cuda, "is_available", lambda: True) + monkeypatch.setattr(torch.cuda, "current_device", lambda: 0) + monkeypatch.setattr( + torch.cuda, + "get_device_properties", + lambda _device: SimpleNamespace(gcnArchName="gfx1201:sramecc-:xnack-"), + ) + monkeypatch.setenv("FREETOKEN_ROCM_ARCH", "gfx1100;gfx1200") + _clear_arch_caches() + + assert arch.get_rocm_gfx_arch() == "gfx1201" + assert arch.is_gfx12xx_family() + assert not arch.is_gfx11xx_family() + + _clear_arch_caches() + + +def test_rocm_arch_falls_back_to_cross_compile_env(monkeypatch): + monkeypatch.setattr(arch, "is_rocm", lambda: True) + monkeypatch.setattr(torch.cuda, "is_available", lambda: False) + monkeypatch.setenv("FREETOKEN_ROCM_ARCH", "gfx1200;gfx1201") + _clear_arch_caches() + + assert arch.get_rocm_gfx_arch() == "gfx1200" + + _clear_arch_caches() + + +def test_hip_cflags_emit_one_offload_flag_per_arch(monkeypatch): + from freetoken.kernel.utils import _hip_cflags + + monkeypatch.setenv("FREETOKEN_ROCM_ARCH", "gfx1200;gfx1201") + + flags = _hip_cflags(["-Wno-unused-command-line-argument"]) + + assert "--offload-arch=gfx1200" in flags + assert "--offload-arch=gfx1201" in flags + assert not any(";" in flag for flag in flags) From 45417560beeba896a9b0866e50154d2a7a320b8b Mon Sep 17 00:00:00 2001 From: zihaomu Date: Mon, 24 Aug 2026 15:21:29 +0800 Subject: [PATCH 08/10] fix(rocm): complete modular SDK runtime support --- pyproject.toml | 5 ++- python/freetoken/kernel/__main__.py | 19 ++++++---- .../kernel/csrc/jit/fast_index_copy.cuh | 32 ++++++++--------- python/freetoken/kernel/utils.py | 14 ++++---- tests/utils/test_rocm_arch.py | 36 +++++++++++++++++++ 5 files changed, 75 insertions(+), 31 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 3c0c45ed..d22ae67c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -58,7 +58,10 @@ dependencies = [ "torch>=2.11,<2.12", "tqdm>=4.66,<5", "transformers>=5.5,<6", - "triton==3.6.0; platform_system == 'Linux'", + # CUDA torch 2.11 resolves Triton 3.6; AMD's ROCm 7.14 image supplies its + # gfx1201-enabled Triton 3.7 build. Keep both supported without replacing the + # runtime-specific wheel selected by the PyTorch distribution. + "triton>=3.6,<3.8; platform_system == 'Linux'", "uvicorn>=0.30,<1", ] diff --git a/python/freetoken/kernel/__main__.py b/python/freetoken/kernel/__main__.py index 457385a5..5b66d484 100644 --- a/python/freetoken/kernel/__main__.py +++ b/python/freetoken/kernel/__main__.py @@ -17,13 +17,18 @@ def generate_clangd(): if is_rocm(): arch_flags = ["-xhip", f"--offload-arch={get_rocm_gfx_arch() or 'gfx1201'}"] else: - status = subprocess.run( - args=["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"], - capture_output=True, - check=True, - ) - compute_cap = status.stdout.decode("utf-8").strip().split("\n")[0] - major, minor = compute_cap.split(".") + try: + status = subprocess.run( + args=["nvidia-smi", "--query-gpu=compute_cap", "--format=csv,noheader"], + capture_output=True, + check=True, + ) + compute_cap = status.stdout.decode("utf-8").strip().split("\n")[0] + major, minor = compute_cap.split(".") + except (subprocess.CalledProcessError, FileNotFoundError, ValueError): + import torch + + major, minor = torch.cuda.get_device_capability() arch_flags = ["-xcuda", f"--cuda-gpu-arch=sm_{major}{minor}"] compile_flags = ",\n ".join( arch_flags + ["-std=c++20", "-Wall", "-Wextra"] diff --git a/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh b/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh index fe3f6be4..bf313c52 100644 --- a/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh +++ b/python/freetoken/kernel/csrc/jit/fast_index_copy.cuh @@ -34,7 +34,7 @@ inline constexpr auto get_mem_package() { } __always_inline __device__ auto load_nc(const uint1* __restrict__ src) -> uint1 { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM return *src; #else uint32_t tmp; @@ -44,7 +44,7 @@ __always_inline __device__ auto load_nc(const uint1* __restrict__ src) -> uint1 } __always_inline __device__ auto load_nc(const uint2* __restrict__ src) -> uint2 { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM return *src; #else uint32_t tmp0, tmp1; @@ -54,7 +54,7 @@ __always_inline __device__ auto load_nc(const uint2* __restrict__ src) -> uint2 } __always_inline __device__ auto load_nc(const uint4* __restrict__ src) -> uint4 { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM return *src; #else uint32_t tmp0, tmp1, tmp2, tmp3; @@ -64,7 +64,7 @@ __always_inline __device__ auto load_nc(const uint4* __restrict__ src) -> uint4 } __always_inline __device__ void store_nc(uint1* __restrict__ dst, const uint1& value) { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM *dst = value; #else uint32_t tmp = value.x; @@ -73,7 +73,7 @@ __always_inline __device__ void store_nc(uint1* __restrict__ dst, const uint1& v } __always_inline __device__ void store_nc(uint2* __restrict__ dst, const uint2& value) { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM *dst = value; #else uint32_t tmp0 = value.x; @@ -83,7 +83,7 @@ __always_inline __device__ void store_nc(uint2* __restrict__ dst, const uint2& v } __always_inline __device__ void store_nc(uint4* __restrict__ dst, const uint4& value) { -#ifdef __HIP_PLATFORM_AMD__ +#if FREETOKEN_USE_ROCM *dst = value; #else uint32_t tmp0 = value.x; @@ -99,7 +99,7 @@ __always_inline __device__ void wait_flag_clear(const int32_t* __restrict__ flag auto* flag = reinterpret_cast(const_cast(flag_ptr)); uint32_t sleep_ns = 128; while (atomicAdd(flag, 0) > 0) { -#if __CUDA_ARCH__ >= 700 +#if !FREETOKEN_USE_ROCM && __CUDA_ARCH__ >= 700 __nanosleep(sleep_ns); #endif sleep_ns = sleep_ns < 2048 ? (sleep_ns << 1) : 2048; @@ -171,7 +171,7 @@ inline bool host_ptr_identity() { } inline void* device_alias(void* ptr, DLDevice dev) { - if (dev.device_type == kDLCUDA || host_ptr_identity()) { + if (dev.device_type == kDLCUDA || dev.device_type == kDLROCM || host_ptr_identity()) { return ptr; } void* mapped = nullptr; @@ -293,7 +293,7 @@ inline auto get_sync_flag_ptr( auto flag_dtype = host::SymbolicDType{}; host::TensorMatcher({1}) .with_dtype(flag_dtype) - .with_device(device) + .with_device(device) .verify(sync_flag); return static_cast(sync_flag.data_ptr()); } @@ -368,17 +368,17 @@ struct FastIndexCopyKernel { TensorMatcher({-1, D}) .with_dtype(data_dtype) - .with_device() + .with_device() .verify(src); TensorMatcher({-1, D}) .with_dtype(data_dtype) - .with_device() + .with_device() .verify(dst); TensorMatcher({L}) .with_dtype(indices_dtype) - .with_device(device) + .with_device(device) .verify(src_indices) .verify(dst_indices); @@ -387,7 +387,7 @@ struct FastIndexCopyKernel { const auto num_indices_tensor = num_indices.value(); TensorMatcher({1}) .with_dtype(num_indices_dtype) - .with_device(device) + .with_device(device) .verify(num_indices_tensor); num_indices_data_ptr = static_cast(num_indices_tensor.data_ptr()); @@ -553,14 +553,14 @@ struct MultiIndexCopyKernel { auto indices_dtype = SymbolicDType{}; auto num_indices_dtype = SymbolicDType{}; - TensorMatcher({B}).with_dtype(ptr_dtype).with_device(device) + TensorMatcher({B}).with_dtype(ptr_dtype).with_device(device) .verify(dst_ptrs).verify(src_ptrs).verify(feat_bytes); - TensorMatcher({L}).with_dtype(indices_dtype).with_device(device) + TensorMatcher({L}).with_dtype(indices_dtype).with_device(device) .verify(dst_indices).verify(src_indices); const int64_t* valid_length = nullptr; if (num_indices.has_value()) { - TensorMatcher({1}).with_dtype(num_indices_dtype).with_device(device) + TensorMatcher({1}).with_dtype(num_indices_dtype).with_device(device) .verify(num_indices.value()); valid_length = static_cast(num_indices.value().data_ptr()); } diff --git a/python/freetoken/kernel/utils.py b/python/freetoken/kernel/utils.py index 937a750c..b59a588f 100644 --- a/python/freetoken/kernel/utils.py +++ b/python/freetoken/kernel/utils.py @@ -71,7 +71,7 @@ def _rocm_link_flags() -> List[str]: Traditional ROCm installs provide ``libamdhip64.so`` under ``$ROCM_HOME/lib``. ROCm 7.14 Python SDK images only provide the versioned soname, while TVM-FFI still links with ``-lamdhip64``. Supply a cache-local unversioned symlink via - ``LIBRARY_PATH`` without modifying the image's Python environment. + an explicit linker search path without modifying the Python environment. """ candidates: list[pathlib.Path] = [] if os.getenv("ROCM_HOME"): @@ -100,13 +100,13 @@ def _rocm_link_flags() -> List[str]: link_dir.mkdir(parents=True, exist_ok=True) compat_link = link_dir / "libamdhip64.so" if not compat_link.exists() and not compat_link.is_symlink(): - compat_link.symlink_to(versioned[-1]) + try: + compat_link.symlink_to(versioned[-1]) + except FileExistsError: + # Multiple tensor-parallel ranks may prepare the same cache. + pass - current = [path for path in os.getenv("LIBRARY_PATH", "").split(":") if path] - os.environ["LIBRARY_PATH"] = ":".join( - dict.fromkeys([str(link_dir), str(library_dir), *current]) - ) - return [f"-Wl,-rpath,{library_dir}"] + return [f"-L{link_dir}", f"-Wl,-rpath,{library_dir}"] raise RuntimeError("Unable to locate libamdhip64 for ROCm JIT linking") diff --git a/tests/utils/test_rocm_arch.py b/tests/utils/test_rocm_arch.py index f080b1e9..95529862 100644 --- a/tests/utils/test_rocm_arch.py +++ b/tests/utils/test_rocm_arch.py @@ -1,3 +1,5 @@ +import importlib +import pathlib from types import SimpleNamespace import torch @@ -51,3 +53,37 @@ def test_hip_cflags_emit_one_offload_flag_per_arch(monkeypatch): assert "--offload-arch=gfx1200" in flags assert "--offload-arch=gfx1201" in flags assert not any(";" in flag for flag in flags) + + +def test_rocm_link_flags_support_versioned_modular_sdk(monkeypatch, tmp_path): + import torch.utils.cpp_extension as cpp_extension + + from freetoken.kernel import utils + + sdk = tmp_path / "sdk" + library_dir = sdk / "lib" + library_dir.mkdir(parents=True) + versioned_runtime = library_dir / "libamdhip64.so.7" + versioned_runtime.write_bytes(b"") + real_find_spec = importlib.util.find_spec + + def find_spec(name: str): + if name == "_rocm_sdk_core": + return SimpleNamespace(submodule_search_locations=[str(sdk)]) + return real_find_spec(name) + + monkeypatch.delenv("ROCM_HOME", raising=False) + monkeypatch.setattr(cpp_extension, "ROCM_HOME", None) + monkeypatch.setattr(importlib.util, "find_spec", find_spec) + monkeypatch.setattr(pathlib.Path, "home", lambda: tmp_path) + utils._rocm_link_flags.cache_clear() + + flags = utils._rocm_link_flags() + + compat_dir = tmp_path / ".cache" / "freetoken" / "rocm-lib" + compat_link = compat_dir / "libamdhip64.so" + assert f"-L{compat_dir}" in flags + assert f"-Wl,-rpath,{library_dir}" in flags + assert compat_link.resolve() == versioned_runtime.resolve() + + utils._rocm_link_flags.cache_clear() From 89ad7ab016b3d51ae9e0b1b1adaf9a996c4cacf3 Mon Sep 17 00:00:00 2001 From: zihaomu Date: Mon, 24 Aug 2026 15:09:21 +0800 Subject: [PATCH 09/10] fix(rocm): make TVM-FFI JIT kernels portable to HIP --- .../kernel/csrc/include/freetoken/utils.cuh | 14 ++++++-- python/freetoken/kernel/csrc/jit/index.cu | 6 ++-- python/freetoken/kernel/csrc/jit/store.cu | 6 ++-- tests/kernels/test_jit_index_store.py | 36 +++++++++++++++++++ 4 files changed, 54 insertions(+), 8 deletions(-) create mode 100644 tests/kernels/test_jit_index_store.py diff --git a/python/freetoken/kernel/csrc/include/freetoken/utils.cuh b/python/freetoken/kernel/csrc/include/freetoken/utils.cuh index f21b9585..f46d2af2 100644 --- a/python/freetoken/kernel/csrc/include/freetoken/utils.cuh +++ b/python/freetoken/kernel/csrc/include/freetoken/utils.cuh @@ -45,13 +45,21 @@ namespace PDL { template __always_inline __device__ void wait() { if constexpr (kUsePDL) { +#if FREETOKEN_USE_ROCM + // Programmatic dependent launch is NVIDIA-specific. +#else asm volatile("griddepcontrol.wait;" ::: "memory"); +#endif } } template __always_inline __device__ void launch() { if constexpr (kUsePDL) { +#if FREETOKEN_USE_ROCM + // Programmatic dependent launch is NVIDIA-specific. +#else asm volatile("griddepcontrol.launch_dependents;" :::); +#endif } } @@ -116,8 +124,8 @@ public: } auto with_attr(bool use_pdl) -> LaunchKernel & { -#ifdef __HIP__ - (void)use_pdl; +#if FREETOKEN_USE_ROCM + RuntimeCheck(!use_pdl, "Programmatic dependent launch is unavailable on ROCm"); m_config.numAttrs = 0; #else if (use_pdl) { @@ -144,7 +152,9 @@ private: return config; } cudaLaunchConfig_t m_config; +#if !FREETOKEN_USE_ROCM cudaLaunchAttribute m_attr_cache; +#endif }; } // namespace host diff --git a/python/freetoken/kernel/csrc/jit/index.cu b/python/freetoken/kernel/csrc/jit/index.cu index ca0e1db2..aca58383 100644 --- a/python/freetoken/kernel/csrc/jit/index.cu +++ b/python/freetoken/kernel/csrc/jit/index.cu @@ -114,15 +114,15 @@ struct IndexKernel { TensorMatcher({-1, D}) // .with_dtype(weights_dtype_) - .with_device(device_) + .with_device(device_) .verify(weights); TensorMatcher({L, D}) // .with_dtype(weights_dtype_) - .with_device(device_) + .with_device(device_) .verify(output); TensorMatcher({L}) // .with_dtype(indices_dtype_) - .with_device(device_) + .with_device(device_) .verify(indices); const auto device = device_.unwrap(); diff --git a/python/freetoken/kernel/csrc/jit/store.cu b/python/freetoken/kernel/csrc/jit/store.cu index 8d84d76e..162dfdfe 100644 --- a/python/freetoken/kernel/csrc/jit/store.cu +++ b/python/freetoken/kernel/csrc/jit/store.cu @@ -72,18 +72,18 @@ struct StoreKernel { TensorMatcher({-1, D}) // .with_strides({X, 1}) - .with_device(device_) + .with_device(device_) .with_dtype(dtype_) .verify(k_cache) .verify(v_cache); TensorMatcher({L, D}) // .with_strides({Y, 1}) - .with_device(device_) + .with_device(device_) .with_dtype(dtype_) .verify(k) .verify(v); TensorMatcher({L}) // - .with_device(device_) + .with_device(device_) .with_dtype(indices_dtype_) .verify(indices); diff --git a/tests/kernels/test_jit_index_store.py b/tests/kernels/test_jit_index_store.py new file mode 100644 index 00000000..7590023a --- /dev/null +++ b/tests/kernels/test_jit_index_store.py @@ -0,0 +1,36 @@ +import pytest +import torch + +from freetoken.kernel import indexing, store_cache + + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available(), reason="a CUDA or ROCm GPU is required" +) + + +def test_indexing_jit_matches_torch_on_cold_and_warm_loads(): + weights = torch.arange(8 * 64, dtype=torch.float32, device="cuda").reshape(8, 64) + + for values in ([7, 2, 0], [1, 6, 3]): + indices = torch.tensor(values, dtype=torch.int32, device="cuda") + actual = indexing(weights, indices) + torch.testing.assert_close(actual, weights[indices.long()]) + + +def test_store_jit_matches_torch_on_cold_and_warm_loads(): + k_cache = torch.zeros((8, 64), dtype=torch.float32, device="cuda") + v_cache = torch.zeros_like(k_cache) + indices = torch.tensor([5, 0, 3], dtype=torch.int64, device="cuda") + + for offset in (0.0, 1000.0): + k = torch.arange(3 * 64, dtype=torch.float32, device="cuda").reshape(3, 64) + k = k + offset + v = k + 500.0 + store_cache(k_cache, v_cache, indices, k, v) + torch.testing.assert_close(k_cache[indices], k) + torch.testing.assert_close(v_cache[indices], v) + + untouched = torch.tensor([1, 2, 4, 6, 7], device="cuda") + torch.testing.assert_close(k_cache[untouched], torch.zeros((5, 64), device="cuda")) + torch.testing.assert_close(v_cache[untouched], torch.zeros((5, 64), device="cuda")) From 49591978de5cf20fe1096d9bf8a07a8f5156b7b6 Mon Sep 17 00:00:00 2001 From: zihaomu Date: Mon, 24 Aug 2026 15:15:14 +0800 Subject: [PATCH 10/10] feat(rocm): enable GGUF kernels on RDNA4 --- README.md | 2 +- docs/install.md | 7 +++ python/freetoken/kernel/csrc/gguf/dispatch.h | 16 ++++-- python/freetoken/kernel/gguf.py | 53 ++++++++++++++++++-- tests/kernels/test_gguf_rocm.py | 27 ++++++++++ 5 files changed, 97 insertions(+), 8 deletions(-) create mode 100644 tests/kernels/test_gguf_rocm.py diff --git a/README.md b/README.md index 2a56a086..d2dfaf3e 100644 --- a/README.md +++ b/README.md @@ -21,7 +21,7 @@ FreeToken is an edge-native Mixture-of-Experts (MoE) serving engine designed for - **Semantic-Aware Caching**: Features semantic anchor checkpoints for recurrent state and KV caches, allowing agentic context edits (e.g., tool calls, thinking blocks) to avoid redundant context recomputation. - **Elastic Memory Management**: Supports dynamic, runtime VRAM re-allocation between expert caches and KV memory without engine restarts or weight reloading. - **Broad MoE & Ecosystem Support**: Supports frontier open-weight MoE models (e.g., DeepSeek-V4-Flash, Qwen3.6-35B-A3B, GLM-5.2) across various parameter scales and quantization formats (e.g., MXFP4, NVFP4, FP8, BF16), with Anthropic/OpenAI-compatible APIs for seamless integration with real-world coding and tool-calling agents (e.g., Codex, Claude Code, OpenCode, OpenClaw, DeepSeek Harness). -- **Diverse Consumer Hardware**: Scales across consumer laptops, gaming desktops, and workstation GPUs, with native support for NVIDIA RTX 30, RTX 40, and RTX 50 series GPUs. +- **Diverse Consumer Hardware**: Scales across consumer laptops, gaming desktops, and workstation GPUs, with native support for NVIDIA RTX 30/40/50 GPUs and experimental ROCm source support for AMD RDNA3/RDNA4 GPUs. ## Getting Started diff --git a/docs/install.md b/docs/install.md index 4db8a15a..850558a1 100644 --- a/docs/install.md +++ b/docs/install.md @@ -44,6 +44,13 @@ python -m pip install --no-build-isolation -e . Set both architecture variables to `gfx1200` for RX 9060 family GPUs, or to the actual target reported by `rocminfo`. +The optional native GGUF kernels also require Thrust headers. Install the generic +headers before the first GGUF kernel JIT build: + +```bash +apt-get update && apt-get install -y --no-install-recommends libthrust-dev +``` + ## Method 2: Install from source ```bash diff --git a/python/freetoken/kernel/csrc/gguf/dispatch.h b/python/freetoken/kernel/csrc/gguf/dispatch.h index f42a2163..bb15096b 100644 --- a/python/freetoken/kernel/csrc/gguf/dispatch.h +++ b/python/freetoken/kernel/csrc/gguf/dispatch.h @@ -5,18 +5,28 @@ #pragma once #include +#include #ifndef WARP_SIZE #define WARP_SIZE 32 #endif -// Warp-shuffle wrappers the donor pulls from sgl-kernel's utils.h (CUDA variants). +// HIP's synchronized shuffle API requires a 64-bit mask even on wave32 targets +// such as gfx1201, while CUDA uses a 32-bit mask. +#if defined(__HIP_PLATFORM_AMD__) +#define SGLANG_SHUFFLE_MASK(mask) static_cast(mask) +#else +#define SGLANG_SHUFFLE_MASK(mask) (mask) +#endif + +// Warp-shuffle wrappers the donor pulls from sgl-kernel's utils.h. #ifndef SGLANG_SHFL_XOR_SYNC -#define SGLANG_SHFL_XOR_SYNC(mask, var, lane_mask) __shfl_xor_sync((mask), (var), (lane_mask)) +#define SGLANG_SHFL_XOR_SYNC(mask, var, lane_mask) \ + __shfl_xor_sync(SGLANG_SHUFFLE_MASK(mask), (var), (lane_mask)) #endif #ifndef SGLANG_SHFL_XOR_SYNC_WIDTH #define SGLANG_SHFL_XOR_SYNC_WIDTH(mask, var, lane_mask, width) \ - __shfl_xor_sync((mask), (var), (lane_mask), (width)) + __shfl_xor_sync(SGLANG_SHUFFLE_MASK(mask), (var), (lane_mask), (width)) #endif #define DISPATCH_CASE_FLOAT_TYPES(...) \ diff --git a/python/freetoken/kernel/gguf.py b/python/freetoken/kernel/gguf.py index 04a16560..4d44ae5d 100644 --- a/python/freetoken/kernel/gguf.py +++ b/python/freetoken/kernel/gguf.py @@ -13,6 +13,7 @@ from __future__ import annotations import functools +import hashlib import os import pathlib import shutil @@ -22,6 +23,32 @@ _CSRC = pathlib.Path(__file__).parent / "csrc" / "gguf" +def _staged_rocm_sources() -> pathlib.Path: + """Copy CUDA sources out of the checkout before PyTorch HIPifies them. + + ``torch.utils.cpp_extension.load`` writes generated ``*_hip`` sources next to + the input file. Keeping the staging directory under the extension cache makes + the source checkout stay clean while still allowing normal incremental builds. + """ + cache_root = pathlib.Path( + os.environ.get("TORCH_EXTENSIONS_DIR", pathlib.Path.home() / ".cache" / "torch_extensions") + ) + digest = hashlib.sha256() + digest.update(f"torch={torch.__version__};hip={torch.version.hip}".encode()) + for source in sorted(_CSRC.iterdir()): + if source.is_file() and "_hip." not in source.name and source.suffix != ".hip": + digest.update(source.name.encode()) + digest.update(source.read_bytes()) + staged = cache_root / f"freetoken_gguf_sources_{digest.hexdigest()[:16]}" + shutil.copytree( + _CSRC, + staged, + dirs_exist_ok=True, + ignore=shutil.ignore_patterns("*_hip.*", "*.hip", "__pycache__"), + ) + return staged + + def _host_compiler() -> str | None: """A host compiler nvcc + libtorch headers accept. @@ -47,12 +74,29 @@ def _c_compiler_for(cxx: str) -> str: cc = base.replace("g++", "gcc") return shutil.which(cc) or cc + @functools.cache def _module(): from torch.utils.cpp_extension import load - extra_cuda_cflags = ["-O3", "--expt-relaxed-constexpr"] - host_cxx = _host_compiler() + is_rocm = getattr(torch.version, "hip", None) is not None + extra_cuda_cflags = ["-O3"] + extra_ldflags: list[str] = [] + if is_rocm: + from freetoken.kernel.utils import _rocm_link_flags + + extra_ldflags = _rocm_link_flags() + # Ubuntu's generic Thrust headers otherwise select the CUDA backend and + # try to include cuda_runtime_api.h. GGUF only reaches Thrust through a + # libtorch complex-number header, so the backend-neutral C++ path is + # sufficient for HIP compilation. + extra_cuda_cflags.append("-DTHRUST_DEVICE_SYSTEM=THRUST_DEVICE_SYSTEM_CPP") + csrc = _staged_rocm_sources() + else: + extra_cuda_cflags.append("--expt-relaxed-constexpr") + csrc = _CSRC + + host_cxx = None if is_rocm else _host_compiler() if host_cxx is not None: # Point both nvcc's host pass (-ccbin) and torch's C++ compile (CXX) at a # libtorch/nvcc-compatible compiler. Force (not setdefault): the system @@ -66,9 +110,10 @@ def _module(): # plain `load` of the single source compiles + binds the ggml_* ops. return load( name="freetoken_gguf_kernels", - sources=[str(_CSRC / "gguf_kernel.cu")], - extra_include_paths=[str(_CSRC)], + sources=[str(csrc / "gguf_kernel.cu")], + extra_include_paths=[str(csrc)], extra_cuda_cflags=extra_cuda_cflags, + extra_ldflags=extra_ldflags, verbose=True, ) diff --git a/tests/kernels/test_gguf_rocm.py b/tests/kernels/test_gguf_rocm.py new file mode 100644 index 00000000..52936d32 --- /dev/null +++ b/tests/kernels/test_gguf_rocm.py @@ -0,0 +1,27 @@ +import pytest +import torch + + +pytestmark = pytest.mark.skipif( + not torch.cuda.is_available() or torch.version.hip is None, + reason="a ROCm GPU is required", +) + + +def test_q4_0_dequant_matches_torch_reference(): + from freetoken.kernel.gguf import ggml_dequantize + from freetoken.models.gguf.dequant import GGML_Q4_0, dequantize + + scale = torch.tensor([0.5], dtype=torch.float16).view(torch.uint8) + quants = torch.tensor( + [0x10, 0x32, 0x54, 0x76, 0x98, 0xBA, 0xDC, 0xFE] * 2, + dtype=torch.uint8, + ) + packed_cpu = torch.cat((scale, quants)).reshape(1, 18) + expected = dequantize(packed_cpu, GGML_Q4_0, torch.float32).reshape(1, 32) + + actual = ggml_dequantize( + packed_cpu.to("cuda"), GGML_Q4_0, m=1, n=32, dtype=torch.float32 + ) + + torch.testing.assert_close(actual.cpu(), expected)