diff --git a/docs/install.md b/docs/install.md index f5205ab3b..4db8a15a3 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/docs/models.md b/docs/models.md index e4850a124..16c5c8358 100644 --- a/docs/models.md +++ b/docs/models.md @@ -31,6 +31,19 @@ for them; other checkpoints of the same architectures work too. `offload`, upgraded to `hybrid` when a cached `ft bench bw` profile recommends it. +### CPU/Hybrid MoE graph compatibility + +CPU and hybrid MoE have the same execution semantics on CUDA and ROCm, but use +backend-specific GPU/CPU synchronization. CUDA retains its mapped-pinned, +per-slot flag handshake. ROCm 7.14 uses HIP signal memory and explicit Graph +batch-memory-op nodes whose storage follows the CPU executor's lifetime. + +At startup, FreeToken verifies the ROCm path with a real graph capture, +instantiate, and replay probe. If that probe fails, FreeToken disables CUDA +Graph for CPU/hybrid MoE and continues on the correct eager path. Set +`FREETOKEN_CPU_MOE_FLAG_SYNC=0` to explicitly disable the native flag handshake; +on ROCm this also selects the graph-off eager path. + ## Notes - `ft checkpoint` conversion is optional — it pre-converts a checkpoint into diff --git a/pyproject.toml b/pyproject.toml index 8bd653f87..d22ae67cc 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", @@ -57,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/engine/engine.py b/python/freetoken/engine/engine.py index 22c4a6c7e..20ac6eb4d 100644 --- a/python/freetoken/engine/engine.py +++ b/python/freetoken/engine/engine.py @@ -15,10 +15,18 @@ from freetoken.moe import create_moe_backend, is_offload_moe_backend from freetoken.moe.expert_banks import load_expert_banks from freetoken.moe.offload_cache import OffloadMoeCache, attach_offload_moe_cache -from freetoken.utils import align_ceil, init_logger, is_sm90_family, is_sm100_family, mem_GB, torch_dtype +from freetoken.utils import ( + align_ceil, + init_logger, + is_rocm, + is_sm90_family, + is_sm100_family, + mem_GB, + torch_dtype, +) from .config import EngineConfig -from .graph import GraphRunner, get_free_memory +from .graph import GraphRunner, _determine_cuda_graph_bs, get_free_memory from .sample import BatchSamplingArgs, Sampler from freetoken.kvcache import create_kv_pool, resolve_pool_class from freetoken.kvcache.base import CacheRebuildRejected @@ -30,6 +38,52 @@ logger = init_logger(__name__) +def _cuda_graph_disabled(config: EngineConfig) -> bool: + return config.cuda_graph_bs == [] or ( + config.cuda_graph_bs is None and config.cuda_graph_max_bs == 0 + ) + + +def _auto_hybrid_allowed_before_rocm_probe(config: EngineConfig) -> bool: + """Auto cannot verify the HIP replay handshake before constructing an executor.""" + return not is_rocm() or _cuda_graph_disabled(config) + + +def _disable_unsafe_rocm_cpu_moe_graph(config: EngineConfig, executor) -> bool: + """Disable graph capture when ROCm CPU/Hybrid MoE lacks a replay-safe handshake. + + This runs after the executor's real capture/replay capability probe and before + ``GraphRunner`` is constructed. An empty explicit batch list is the canonical graph-off + setting; max_bs is cleared too so later rebuilds cannot silently turn capture back on. + """ + if ( + not is_rocm() + or executor is None + or executor.graph_capture_safe + or _cuda_graph_disabled(config) + ): + return False + object.__setattr__(config, "cuda_graph_bs", []) + object.__setattr__(config, "cuda_graph_max_bs", 0) + logger.warning_rank0( + "ROCm CPU/Hybrid MoE stream-memory synchronization did not pass capture/replay; " + "disabling CUDA Graph and continuing in the correct eager path" + ) + return True + + +def _cpu_moe_flag_slots_per_layer(config: EngineConfig, free_memory: int) -> int: + """Cover every configured graph batch size while retaining eager headroom.""" + from freetoken.moe.cpu_executor import _FLAG_SLOTS_PER_LAYER + + graph_batch_sizes = _determine_cuda_graph_bs( + cuda_graph_bs=config.cuda_graph_bs, + cuda_graph_max_bs=config.cuda_graph_max_bs, + free_memory=free_memory, + ) + return max(_FLAG_SLOTS_PER_LAYER, len(set(graph_batch_sizes))) + + def _require_offload_cache_size(cache_size: int, num_experts: int) -> None: """The offload MoE cache needs at least one slot per expert per layer. A too-small size (e.g. a bare offload run with moe_cache_size unset and auto disabled) must fail loudly.""" @@ -313,6 +367,7 @@ def __init__(self, config: EngineConfig): self.tp_cpu_group = self._init_communication(config) free_min, free_max = self._sync_get_memory() init_free_memory = free_max # startup KV sizing keeps cross-rank MAX (unchanged) + self._init_free_memory = init_free_memory self._baseline_free = free_min # rebuild baseline: cross-rank MIN, deterministic across ranks logger.info_rank0(f"Free memory before loading model: {mem_GB(init_free_memory)}") @@ -333,6 +388,10 @@ def __init__(self, config: EngineConfig): self.cpu_moe_executor = None if is_offload_moe_backend(config.moe_backend): self._init_offload_moe_cache(config) + # cpu/hybrid and offload + --moe-cpu-layers all attach the same executor. + # Auto may select hybrid from a bandwidth profile before GPU init; at this point + # it is safe only if the native handshake was verified or graphs are disabled. + _disable_unsafe_rocm_cpu_moe_graph(config, self.cpu_moe_executor) if hasattr(self.model, "prepare_for_runtime"): self.model.prepare_for_runtime() @@ -683,8 +742,20 @@ def _init_cpu_moe_executor(self, config: EngineConfig, cache, layers) -> None: f"(MoE layer {type(sample).__name__} is missing {required})." ) # Decode batches never exceed max_running_req, but CUDA-graph padding can - # round a batch up to the largest captured size; cover both. - max_tokens = max(config.max_running_req, config.cuda_graph_max_bs or 0, 1) + # round a batch up to the largest explicitly captured size. Derive both + # scratch capacity and handshake slots from the same resolved list that + # GraphRunner will use (explicit cuda_graph_bs takes precedence over max_bs). + graph_batch_sizes = _determine_cuda_graph_bs( + cuda_graph_bs=config.cuda_graph_bs, + cuda_graph_max_bs=config.cuda_graph_max_bs, + free_memory=self._init_free_memory, + ) + max_tokens = max( + config.max_running_req, + config.cuda_graph_max_bs or 0, + max(graph_batch_sizes, default=0), + 1, + ) # gpt-oss mxfp4 carries clamped-swiglu scalars; other formats use the defaults. executor = CpuMoeExecutor( cache, @@ -694,6 +765,9 @@ def _init_cpu_moe_executor(self, config: EngineConfig, cache, layers) -> None: num_threads=config.moe_cpu_threads, max_tokens=max_tokens, device=self.device, + flag_slots_per_layer=_cpu_moe_flag_slots_per_layer( + config, self._init_free_memory + ), swiglu_alpha=getattr(sample, "hidden_act_alpha", 1.702), swiglu_limit=getattr(sample, "swiglu_limit", None), ) @@ -1363,7 +1437,17 @@ def override(attr: str, value: Any): # this is dangerous, use with caution from freetoken.moe.cpu_executor import compiled_extension_supports _act = getattr(model_config, "hidden_act", "silu") - if not _cpu_moe_act_ok: + if not _auto_hybrid_allowed_before_rocm_probe(config): + # The capability probe needs a constructed CPU executor, which auto + # selection does not have yet. Keep auto fail-closed on ROCm when graph + # capture is enabled; explicit cpu/hybrid still probes the native path, + # while graph-off auto configurations may safely use eager hybrid. + logger.info_rank0( + "benchbw profile recommends hybrid, but ROCm CUDA Graph is enabled " + "and the native flag handshake has not been verified yet; staying " + "on offload" + ) + elif not _cpu_moe_act_ok: logger.info_rank0( f"benchbw profile recommends hybrid, but the CPU MoE executor does not " f"support this model's expert activation " diff --git a/python/freetoken/kernel/__main__.py b/python/freetoken/kernel/__main__.py index 7be541a67..5b66d484d 100644 --- a/python/freetoken/kernel/__main__.py +++ b/python/freetoken/kernel/__main__.py @@ -6,27 +6,32 @@ 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__) 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. + if is_rocm(): + arch_flags = ["-xhip", f"--offload-arch={get_rocm_gfx_arch() or 'gfx1201'}"] + else: + 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( - [ - "-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 b49cebbb4..93d032215 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 3037ad8d7..8293e3a6e 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/cpu_moe/cpu_moe_ext.cpp b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp index 880e8637a..f0f0f0550 100644 --- a/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp +++ b/python/freetoken/kernel/csrc/cpu_moe/cpu_moe_ext.cpp @@ -16,11 +16,12 @@ // (AVX-512-BF16 dpbf16 -> AVX-512F widening -> AVX2+FMA -> scalar). #include +#include #include -#include +#include #include +#include #include -#include #include #include #include @@ -29,7 +30,7 @@ #include #include -#include +#include #include #if defined(__linux__) @@ -558,15 +559,237 @@ float dot_nvfp4_i8_avx512vnni(const uint8_t* packed, const uint8_t* scale, float #endif // ===================================================================================== -// CUDA stream memory operations (driver API, resolved via dlopen -- no link-time or -// toolchain dependence). The GPU side of the flag handshake: submit = WRITE_VALUE -// (done[slot]=0 then ready[slot]=1), sync = WAIT_VALUE(done[slot] >= 1). The wait is -// executed by the GPU front-end (no SM-resident kernel), so GPU "utilization" stays -// truthful during CPU compute windows -- a resident spin kernel pinned it at 99%, -// which laptop CPU/GPU dynamic power schedulers answered by clamping the CPU's max -// frequency (GEMV workers -1.5x: the reported edge regression). Availability is -// probed functionally at startup (memops_probe); anything unsupported (Windows WDDM, -// vGPU, old drivers) falls back to the cudaLaunchHostFunc path. +// CUDA/HIP stream memory operations. The GPU side of the flag handshake is: +// submit = WRITE_VALUE(done=0), WRITE_VALUE(ready=slot+1); sync = WAIT_VALUE(done>=1). +// The wait runs on the GPU front end rather than occupying an SM. CUDA uses mapped +// pinned arrays and resolves the driver entry points at runtime. ROCm uses two shared +// 64-bit signals allocated with hipMallocSignalMemory (HIP requires that allocation +// type for WAIT addresses) and writes the task slot into the single ready signal. +// +// HIP's ordinary hipStreamWrite/WaitValue and hipStreamBatchMemOp calls execute while +// a stream is being captured but, as of ROCm 7.14, are not themselves recorded in the +// graph. During capture we therefore add explicit batch-memory-op graph nodes and splice +// them into the stream's current dependency set. The ROCm capability probe below does +// a real capture + instantiate + replay with a host handshake; eager enqueue alone is +// deliberately insufficient to enable the path. + +#if FREETOKEN_USE_ROCM && defined(HIP_VERSION_MAJOR) && defined(HIP_VERSION_MINOR) && \ + ((HIP_VERSION_MAJOR > 7) || (HIP_VERSION_MAJOR == 7 && HIP_VERSION_MINOR >= 14)) +#define FREETOKEN_HAS_HIP_GRAPH_MEMOPS 1 +#else +#define FREETOKEN_HAS_HIP_GRAPH_MEMOPS 0 +#endif + +#if FREETOKEN_USE_ROCM + +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS +static hipError_t hip_add_capture_memop_node( + hipStream_t stream, hipStreamBatchMemOpParams* ops, unsigned int count) { + if (ops == nullptr || count == 0) return hipErrorInvalidValue; + hipStreamCaptureStatus status = hipStreamCaptureStatusNone; + hipGraph_t graph = nullptr; + const hipGraphNode_t* dependencies = nullptr; + size_t dependency_count = 0; + hipError_t rc = hipStreamGetCaptureInfo_v2( + stream, &status, nullptr, &graph, &dependencies, &dependency_count); + if (rc != hipSuccess) return rc; + if (status != hipStreamCaptureStatusActive || graph == nullptr) + return hipErrorIllegalState; + + hipCtx_t context = nullptr; +#if defined(__GNUC__) +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + rc = hipCtxGetCurrent(&context); +#if defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + if (rc != hipSuccess) return rc; + + hipBatchMemOpNodeParams params{}; + params.ctx = context; + params.count = count; + params.paramArray = ops; + hipGraphNode_t node = nullptr; + rc = hipGraphAddBatchMemOpNode( + &node, graph, dependencies, dependency_count, ¶ms); + if (rc != hipSuccess) return rc; + return hipStreamUpdateCaptureDependencies( + stream, &node, 1, hipStreamSetCaptureDependencies); +} + +static hipError_t hip_alloc_signal(uint64_t** out) { + void* storage = nullptr; + hipError_t rc = hipExtMallocWithFlags( + &storage, sizeof(uint64_t), hipMallocSignalMemory); + if (rc == hipSuccess) { + *out = static_cast(storage); + __atomic_store_n(*out, 0ULL, __ATOMIC_RELEASE); + } + return rc; +} + +static void hip_free_signal(uint64_t* signal) { + if (signal != nullptr) (void)hipFree(signal); +} + +static bool hipmemops_probe(uintptr_t /*stream*/, uintptr_t /*scratch_addr*/) { + int device = 0; + int can_wait = 0; + if (hipGetDevice(&device) != hipSuccess || + hipDeviceGetAttribute(&can_wait, hipDeviceAttributeCanUseStreamWaitValue, device) != + hipSuccess || + can_wait == 0) + return false; + + uint64_t* ready = nullptr; + uint64_t* done = nullptr; + hipStream_t probe_stream = nullptr; + hipGraph_t graph = nullptr; + hipGraphExec_t graph_exec = nullptr; + hipError_t rc = hip_alloc_signal(&ready); + if (rc == hipSuccess) rc = hip_alloc_signal(&done); + if (rc == hipSuccess) rc = hipStreamCreateWithFlags(&probe_stream, hipStreamNonBlocking); + + hipStreamBatchMemOpParams submit_ops[2]{}; + submit_ops[0].writeValue.operation = hipStreamMemOpWriteValue64; + submit_ops[0].writeValue.address = reinterpret_cast(done); + submit_ops[0].writeValue.value64 = 0; + submit_ops[1].writeValue.operation = hipStreamMemOpWriteValue64; + submit_ops[1].writeValue.address = reinterpret_cast(ready); + submit_ops[1].writeValue.value64 = 1; + hipStreamBatchMemOpParams sync_op{}; + sync_op.waitValue.operation = hipStreamMemOpWaitValue64; + sync_op.waitValue.address = reinterpret_cast(done); + sync_op.waitValue.value64 = 1; + sync_op.waitValue.flags = hipStreamWaitValueGte; + + if (rc == hipSuccess) + rc = hipStreamBeginCapture(probe_stream, hipStreamCaptureModeRelaxed); + if (rc == hipSuccess) + rc = hip_add_capture_memop_node(probe_stream, submit_ops, 2); + if (rc == hipSuccess) + rc = hip_add_capture_memop_node(probe_stream, &sync_op, 1); + if (rc == hipSuccess) rc = hipStreamEndCapture(probe_stream, &graph); + if (rc == hipSuccess) + rc = hipGraphInstantiate(&graph_exec, graph, nullptr, nullptr, 0); + + bool served = false; + std::thread responder; + if (rc == hipSuccess) { + __atomic_store_n(ready, 0ULL, __ATOMIC_RELEASE); + __atomic_store_n(done, 0ULL, __ATOMIC_RELEASE); + responder = std::thread([&] { + const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(2); + while (std::chrono::steady_clock::now() < deadline) { + if (__atomic_load_n(ready, __ATOMIC_ACQUIRE) == 1ULL) { + __atomic_store_n(ready, 0ULL, __ATOMIC_RELEASE); + served = true; + break; + } + std::this_thread::yield(); + } + // Always release the graph wait, including on probe failure, so startup cannot + // wedge indefinitely on a beta runtime implementation. + __atomic_store_n(done, 1ULL, __ATOMIC_RELEASE); + }); + rc = hipGraphLaunch(graph_exec, probe_stream); + if (rc == hipSuccess) rc = hipStreamSynchronize(probe_stream); + } + if (responder.joinable()) responder.join(); + const bool ok = rc == hipSuccess && served && + __atomic_load_n(done, __ATOMIC_ACQUIRE) == 1ULL; + + if (graph_exec != nullptr) (void)hipGraphExecDestroy(graph_exec); + if (graph != nullptr) (void)hipGraphDestroy(graph); + if (probe_stream != nullptr) (void)hipStreamDestroy(probe_stream); + hip_free_signal(ready); + hip_free_signal(done); + return ok; +} + +static void hipmemop_throw(hipError_t rc, const char* what) { + if (rc != hipSuccess) { + throw std::runtime_error( + std::string("CPU MoE HIP flag handshake: ") + what + " failed: " + + hipGetErrorString(rc)); + } +} + +static void cumemop_submit(uintptr_t stream, uintptr_t done_addr, uintptr_t ready_addr, + int64_t slot, uintptr_t capture_ops_addr = 0) { + auto hip_stream = reinterpret_cast(stream); + auto* done = reinterpret_cast(done_addr); + auto* ready = reinterpret_cast(ready_addr); + hipStreamCaptureStatus status = hipStreamCaptureStatusNone; + hipError_t rc = hipStreamIsCapturing(hip_stream, &status); + hipmemop_throw(rc, "submit capture-status query"); + if (status != hipStreamCaptureStatusActive) { + hipmemop_throw( + hipStreamWriteValue64(hip_stream, done, 0, hipStreamWriteValueDefault), + "hipStreamWriteValue64(done)"); + hipmemop_throw( + hipStreamWriteValue64( + hip_stream, ready, static_cast(slot + 1), + hipStreamWriteValueDefault), + "hipStreamWriteValue64(ready)"); + return; + } + + auto* capture_ops = reinterpret_cast(capture_ops_addr); + if (capture_ops == nullptr) { + throw std::runtime_error( + "CPU MoE HIP graph memops require executor-owned parameter storage"); + } + hipmemop_throw(hip_add_capture_memop_node(hip_stream, capture_ops, 2), + "submit graph batch-memory-op"); +} + +static void cumemop_sync(uintptr_t stream, uintptr_t done_addr, int64_t /*slot*/, + uintptr_t capture_ops_addr = 0) { + auto hip_stream = reinterpret_cast(stream); + auto* done = reinterpret_cast(done_addr); + hipStreamCaptureStatus status = hipStreamCaptureStatusNone; + hipError_t rc = hipStreamIsCapturing(hip_stream, &status); + hipmemop_throw(rc, "sync capture-status query"); + if (status != hipStreamCaptureStatusActive) { + hipmemop_throw( + hipStreamWaitValue64( + hip_stream, done, 1, hipStreamWaitValueGte, UINT64_MAX), + "hipStreamWaitValue64(done)"); + return; + } + + auto* capture_ops = reinterpret_cast(capture_ops_addr); + if (capture_ops == nullptr) { + throw std::runtime_error( + "CPU MoE HIP graph memops require executor-owned parameter storage"); + } + hipmemop_throw(hip_add_capture_memop_node(hip_stream, capture_ops, 1), + "sync graph batch-memory-op"); +} + +#else // ROCm headers older than the graph batch-memory-op API + +static bool hipmemops_probe(uintptr_t, uintptr_t) { return false; } +static void cumemop_submit(uintptr_t, uintptr_t, uintptr_t, int64_t, uintptr_t = 0) { + throw std::runtime_error( + "CPU MoE HIP flag handshake requires ROCm 7.14 graph batch-memory-op APIs"); +} +static void cumemop_sync(uintptr_t, uintptr_t, int64_t, uintptr_t = 0) { + throw std::runtime_error( + "CPU MoE HIP flag handshake requires ROCm 7.14 graph batch-memory-op APIs"); +} + +#endif // FREETOKEN_HAS_HIP_GRAPH_MEMOPS + +static bool cumemops_probe(uintptr_t stream, uintptr_t scratch_addr) { + return hipmemops_probe(stream, scratch_addr); +} + +#else // CUDA + #if defined(_WIN32) #include static void* cumemop_dlopen() { return (void*)::LoadLibraryA("nvcuda.dll"); } @@ -636,7 +859,7 @@ static void cumemop_check(int rc, const char* what) { } static void cumemop_submit(uintptr_t stream, uintptr_t done_addr, uintptr_t ready_addr, - int64_t slot) { + int64_t slot, uintptr_t /*capture_ops_addr*/ = 0) { auto* s = reinterpret_cast(stream); // Order matters and is preserved by the front end: reset done BEFORE raising ready, // so the coordinator's completion write for THIS step can never be wiped. @@ -648,13 +871,16 @@ static void cumemop_submit(uintptr_t stream, uintptr_t done_addr, uintptr_t read "cuStreamWriteValue64(ready)"); } -static void cumemop_sync(uintptr_t stream, uintptr_t done_addr, int64_t slot) { +static void cumemop_sync(uintptr_t stream, uintptr_t done_addr, int64_t slot, + uintptr_t /*capture_ops_addr*/ = 0) { cumemop_check(g_cu_wait64(reinterpret_cast(stream), (unsigned long long)(done_addr + (size_t)slot * 8), 1ULL, kCuWaitValueGeq), "cuStreamWaitValue64(done)"); } +#endif // FREETOKEN_USE_ROCM + struct DotChoice { dot_fn fn; const char* name; @@ -1301,17 +1527,28 @@ struct CpuMoeExecutor { 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). + // CUDA uses one mapped-pinned ready/done entry per task slot. HIP signal memory is + // restricted to one 64-bit word per allocation, so ROCm uses a shared ready command + // (slot+1) and shared done flag. Decode layers are serialized by their stream waits, + // therefore only one CPU task can own that pair at a time. std::thread coord_thread; std::atomic coord_stop{false}; - volatile int64_t* ready_flags = nullptr; // GPU increments, this thread polls - volatile int64_t* done_flags = nullptr; // this thread sets, GPU spin-waits + volatile int64_t* ready_flags = nullptr; + volatile int64_t* done_flags = nullptr; + bool shared_flag_signal = false; +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + uint64_t* owned_ready_signal = nullptr; + uint64_t* owned_done_signal = nullptr; + // ROCm 7.14's beta graph API retains hipBatchMemOpNodeParams::paramArray. + // There are only two immutable node shapes per task slot (submit has two ops; + // sync has one shared op), so allocate one canonical array for each shape once + // and let every rebuilt graph reference it. The vector is sized before capture + // starts and never resized, keeping addresses stable without a module-global, + // append-only allocation. These arrays and the signals now share the executor's + // lifetime, which is also the minimum lifetime required by captured CPU-MoE nodes. + std::vector> hip_graph_submit_ops; + std::array hip_graph_sync_ops{}; +#endif int coord_num_slots = 0; std::vector flag_task; // slot -> task (registered lazily) std::vector flag_served; // slot -> completed dispatch count (tests/debug) @@ -1532,6 +1769,12 @@ struct CpuMoeExecutor { ~CpuMoeExecutor() { coord_stop.store(true); if (coord_thread.joinable()) coord_thread.join(); +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + hip_free_signal(owned_ready_signal); + hip_free_signal(owned_done_signal); + owned_ready_signal = nullptr; + owned_done_signal = nullptr; +#endif { std::lock_guard lk(task_mtx); stop = true; @@ -1979,11 +2222,72 @@ struct CpuMoeExecutor { return (slot >= 0 && slot < static_cast(flag_served.size())) ? flag_served[slot] : 0; } + uintptr_t flag_ready_address() const { + return reinterpret_cast(ready_flags); + } + + uintptr_t flag_done_address() const { + return reinterpret_cast(done_flags); + } + + int64_t flag_ready_value(int slot) const { + if (ready_flags == nullptr) return 0; + if (shared_flag_signal) { + const int64_t command = flag_load_acquire(&ready_flags[0]); + return command == slot + 1 ? 1 : 0; + } + return flag_load_acquire(&ready_flags[slot]); + } + + int64_t flag_done_value(int slot) const { + if (done_flags == nullptr) return 0; + return flag_load_acquire(&done_flags[shared_flag_signal ? 0 : slot]); + } + + std::vector pending_flag_slots() const { + std::vector pending; + if (ready_flags == nullptr || done_flags == nullptr) return pending; + if (shared_flag_signal) { + const int64_t command = flag_load_acquire(&ready_flags[0]); + if (command > 0 && command <= coord_num_slots && + flag_load_acquire(&done_flags[0]) == 0) + pending.push_back(static_cast(command - 1)); + return pending; + } + for (int slot = 0; slot < coord_num_slots; ++slot) { + if (flag_load_acquire(&ready_flags[slot]) != 0 && + flag_load_acquire(&done_flags[slot]) == 0) + pending.push_back(slot); + } + return pending; + } + + void poison_flag(int slot) { + if (done_flags != nullptr) + flag_store_release(&done_flags[shared_flag_signal ? 0 : slot], 1); + } + + void launch_flag_coordinator(int pin_core) { + coord_stop.store(false); + coord_thread = std::thread([this, pin_core] { +#if CPU_MOE_HAS_AFFINITY + if (pin_core >= 0) { + cpu_set_t set; + CPU_ZERO(&set); + CPU_SET(pin_core, &set); + pthread_setaffinity_np(pthread_self(), sizeof(set), &set); + } +#endif + coordinator_loop(); + }); + } + // Start the busy-poll coordinator over the mapped-pinned flag arrays. ``pin_core`` >= 0 // pins the coordinator to that logical CPU (the worker auto-sizing reserves it), so its // polling never migrates onto / contends with a GEMV worker's core. void start_flag_coordinator(uintptr_t ready_ptr, uintptr_t done_ptr, int num_slots, int pin_core) { + shared_flag_signal = false; ready_flags = reinterpret_cast(ready_ptr); done_flags = reinterpret_cast(done_ptr); coord_num_slots = num_slots; @@ -1992,18 +2296,102 @@ struct CpuMoeExecutor { if (static_cast(flag_task.size()) < num_slots) flag_task.resize(num_slots, nullptr); } flag_served.assign(num_slots, 0); - coord_stop.store(false); - coord_thread = std::thread([this, pin_core] { -#if CPU_MOE_HAS_AFFINITY - if (pin_core >= 0) { - cpu_set_t set; - CPU_ZERO(&set); - CPU_SET(pin_core, &set); - pthread_setaffinity_np(pthread_self(), sizeof(set), &set); - } + launch_flag_coordinator(pin_core); + } + + void start_shared_signal_coordinator(int num_slots, int pin_core) { +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + if (num_slots <= 0) + throw std::invalid_argument("CPU MoE HIP flag slot count must be positive"); + if (owned_ready_signal != nullptr || owned_done_signal != nullptr || + !hip_graph_submit_ops.empty()) + throw std::logic_error( + "CPU MoE HIP flag coordinator is already initialized"); + hipError_t rc = hip_alloc_signal(&owned_ready_signal); + if (rc == hipSuccess) rc = hip_alloc_signal(&owned_done_signal); + if (rc != hipSuccess) { + hip_free_signal(owned_ready_signal); + hip_free_signal(owned_done_signal); + owned_ready_signal = nullptr; + owned_done_signal = nullptr; + throw std::runtime_error( + std::string("CPU MoE HIP signal allocation failed: ") + hipGetErrorString(rc)); + } + shared_flag_signal = true; + ready_flags = reinterpret_cast(owned_ready_signal); + done_flags = reinterpret_cast(owned_done_signal); + coord_num_slots = num_slots; + hip_graph_submit_ops.clear(); + hip_graph_submit_ops.resize(num_slots); + for (int slot = 0; slot < num_slots; ++slot) { + auto& ops = hip_graph_submit_ops[slot]; + ops[0].writeValue.operation = hipStreamMemOpWriteValue64; + ops[0].writeValue.address = reinterpret_cast(owned_done_signal); + ops[0].writeValue.value64 = 0; + ops[1].writeValue.operation = hipStreamMemOpWriteValue64; + ops[1].writeValue.address = reinterpret_cast(owned_ready_signal); + ops[1].writeValue.value64 = static_cast(slot + 1); + } + hip_graph_sync_ops[0] = {}; + hip_graph_sync_ops[0].waitValue.operation = hipStreamMemOpWaitValue64; + hip_graph_sync_ops[0].waitValue.address = + reinterpret_cast(owned_done_signal); + hip_graph_sync_ops[0].waitValue.value64 = 1; + hip_graph_sync_ops[0].waitValue.flags = hipStreamWaitValueGte; + { + std::lock_guard lk(flag_task_mtx); + if (static_cast(flag_task.size()) < num_slots) flag_task.resize(num_slots, nullptr); + } + flag_served.assign(num_slots, 0); + launch_flag_coordinator(pin_core); +#else + (void)num_slots; + (void)pin_core; + throw std::runtime_error( + "CPU MoE HIP signal allocation requires ROCm 7.14 graph memops"); +#endif + } + + void submit_flag_memop(uintptr_t stream, uintptr_t done_addr, + uintptr_t ready_addr, int64_t slot) { + uintptr_t capture_ops_addr = 0; +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + if (shared_flag_signal) { + if (slot < 0 || slot >= static_cast(hip_graph_submit_ops.size())) + throw std::out_of_range("CPU MoE HIP flag slot is out of range"); + if (done_addr != reinterpret_cast(owned_done_signal) || + ready_addr != reinterpret_cast(owned_ready_signal)) + throw std::invalid_argument( + "CPU MoE HIP memops must use this executor's signal memory"); + capture_ops_addr = + reinterpret_cast(hip_graph_submit_ops[slot].data()); + } +#endif + cumemop_submit(stream, done_addr, ready_addr, slot, capture_ops_addr); + } + + void sync_flag_memop(uintptr_t stream, uintptr_t done_addr, int64_t slot) { + uintptr_t capture_ops_addr = 0; +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + if (shared_flag_signal) { + if (slot < 0 || slot >= static_cast(hip_graph_submit_ops.size())) + throw std::out_of_range("CPU MoE HIP flag slot is out of range"); + if (done_addr != reinterpret_cast(owned_done_signal)) + throw std::invalid_argument( + "CPU MoE HIP memops must use this executor's signal memory"); + capture_ops_addr = reinterpret_cast(hip_graph_sync_ops.data()); + } +#endif + cumemop_sync(stream, done_addr, slot, capture_ops_addr); + } + + size_t graph_memop_param_count() const { +#if FREETOKEN_HAS_HIP_GRAPH_MEMOPS + return hip_graph_submit_ops.size() * 2 + + (hip_graph_submit_ops.empty() ? 0 : hip_graph_sync_ops.size()); +#else + return 0; #endif - coordinator_loop(); - }); } void coordinator_loop() { @@ -2026,13 +2414,19 @@ struct CpuMoeExecutor { bool dozing = false; while (!coord_stop.load(std::memory_order_relaxed)) { bool any = false; - for (int L = 0; L < coord_num_slots; ++L) { + const int begin = shared_flag_signal + ? static_cast(flag_load_acquire(&ready_flags[0]) - 1) + : 0; + const int end = shared_flag_signal ? begin + 1 : coord_num_slots; + for (int L = begin; L < end; ++L) { + if (L < 0 || L >= coord_num_slots) continue; // Binary handshake (memop-compatible: the GPU-side WAIT compares against an // immediate baked at graph capture, so the protocol resets per step instead of // counting). Acquire: everything the GPU made visible before setting ready -- // the D2H input copies -- is visible to the worker pool after this read. - if (flag_load_acquire(&ready_flags[L]) != 0) { - flag_store_release(&ready_flags[L], 0); // consume this step's doorbell + volatile int64_t* ready = &ready_flags[shared_flag_signal ? 0 : L]; + if (flag_load_acquire(ready) != 0) { + flag_store_release(ready, 0); // consume this step's doorbell MoeTask* t; { std::lock_guard lk(flag_task_mtx); @@ -2043,7 +2437,7 @@ struct CpuMoeExecutor { sync(); } // Release: the workers' y stores are visible before the GPU sees done. - flag_store_release(&done_flags[L], 1); + flag_store_release(&done_flags[shared_flag_signal ? 0 : L], 1); if (L < static_cast(flag_served.size())) ++flag_served[L]; any = true; } @@ -2077,7 +2471,8 @@ struct CpuMoeExecutor { // caught mid-shutdown exits its sync kernel now instead of owning the watchdog // stall. Runs before the destructor's join() returns, while the flag arrays are // still alive on the Python side. - for (int L = 0; L < coord_num_slots; ++L) { + const int done_count = shared_flag_signal ? 1 : coord_num_slots; + for (int L = 0; L < done_count; ++L) { flag_store_release(&done_flags[L], INT64_MAX); } } @@ -2128,18 +2523,46 @@ PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { .def("register_flag_task", &CpuMoeExecutor::register_flag_task, py::arg("slot"), py::arg("task")) .def("flag_served_count", &CpuMoeExecutor::flag_served_count, py::arg("slot")) + .def("flag_ready_address", &CpuMoeExecutor::flag_ready_address) + .def("flag_done_address", &CpuMoeExecutor::flag_done_address) + .def("flag_ready_value", &CpuMoeExecutor::flag_ready_value, py::arg("slot")) + .def("flag_done_value", &CpuMoeExecutor::flag_done_value, py::arg("slot")) + .def("pending_flag_slots", &CpuMoeExecutor::pending_flag_slots) + .def("poison_flag", &CpuMoeExecutor::poison_flag, py::arg("slot")) .def("start_flag_coordinator", &CpuMoeExecutor::start_flag_coordinator, py::arg("ready_ptr"), py::arg("done_ptr"), py::arg("num_slots"), py::arg("pin_core")) + .def("start_shared_signal_coordinator", + &CpuMoeExecutor::start_shared_signal_coordinator, + py::arg("num_slots"), py::arg("pin_core")) + .def("submit_flag_memop", &CpuMoeExecutor::submit_flag_memop, + py::arg("stream"), py::arg("done_addr"), py::arg("ready_addr"), + py::arg("slot")) + .def("sync_flag_memop", &CpuMoeExecutor::sync_flag_memop, + py::arg("stream"), py::arg("done_addr"), py::arg("slot")) + .def("graph_memop_param_count", &CpuMoeExecutor::graph_memop_param_count) .def("set_input_prequant", [](CpuMoeExecutor& e, bool v) { e.input_prequant = v; }, py::arg("value")) .def("isa_name", &CpuMoeExecutor::isa_name); m.def("memops_probe", &cumemops_probe, py::arg("stream"), py::arg("scratch_addr")); - m.def("memop_submit", &cumemop_submit, py::arg("stream"), py::arg("done_addr"), - py::arg("ready_addr"), py::arg("slot")); - m.def("memop_sync", &cumemop_sync, py::arg("stream"), py::arg("done_addr"), + // Preserve the established CUDA-facing module API. ROCm graph capture uses the + // executor methods above so its beta node parameter arrays have executor lifetime; + // eager ROCm calls remain valid here as well. + m.def("memop_submit", + [](uintptr_t stream, uintptr_t done_addr, uintptr_t ready_addr, int64_t slot) { + cumemop_submit(stream, done_addr, ready_addr, slot); + }, + py::arg("stream"), py::arg("done_addr"), py::arg("ready_addr"), py::arg("slot")); + m.def("memop_sync", + [](uintptr_t stream, uintptr_t done_addr, int64_t slot) { + cumemop_sync(stream, done_addr, slot); + }, + py::arg("stream"), py::arg("done_addr"), py::arg("slot")); + m.def("memops_use_shared_signal", []() { + return static_cast(FREETOKEN_HAS_HIP_GRAPH_MEMOPS); + }); // ABI capability marker: the highest ActKind this build implements in the // GENERIC epilogue. CpuMoeExecutor.__init__ probes it before requesting an act // id the epilogue must handle -- a prebuilt .so from before ACT_SWIGLUOAI 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 000000000..1898b4118 --- /dev/null +++ b/python/freetoken/kernel/csrc/include/freetoken/hip_compat.h @@ -0,0 +1,162 @@ +#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: +// 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 + +#if defined(__HIP_PLATFORM_AMD__) || defined(USE_ROCM) + +#define FREETOKEN_USE_ROCM 1 + +// --- 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 hipHostMalloc +#endif + +#ifndef cudaFreeHost +#define cudaFreeHost hipHostFree +#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 cudaHostAllocPortable +#define cudaHostAllocPortable hipHostMallocPortable +#endif + +#ifndef cudaHostAllocMapped +#define cudaHostAllocMapped hipHostMallocMapped +#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 +// ROCm 7 exposes the CUDA-compatible extended launch configuration through HIP. +#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 cudaStreamSynchronize +#define cudaStreamSynchronize hipStreamSynchronize +#endif + +#ifndef cudaLaunchHostFunc +#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 // NVIDIA CUDA path + +#define FREETOKEN_USE_ROCM 0 + +#include + +#endif diff --git a/python/freetoken/kernel/csrc/include/freetoken/utils.cuh b/python/freetoken/kernel/csrc/include/freetoken/utils.cuh index 8e917832c..72a495969 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 & { +#if FREETOKEN_USE_ROCM + (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 bb83c23ed..bf313c525 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 { +#if FREETOKEN_USE_ROCM + 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 { +#if FREETOKEN_USE_ROCM + 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 { +#if FREETOKEN_USE_ROCM + 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) { +#if FREETOKEN_USE_ROCM + *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) { +#if FREETOKEN_USE_ROCM + *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) { +#if FREETOKEN_USE_ROCM + *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) { @@ -75,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; @@ -147,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; @@ -269,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()); } @@ -344,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); @@ -363,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()); @@ -529,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/csrc/pinned_tensor.cpp b/python/freetoken/kernel/csrc/pinned_tensor.cpp index c3947adfa..9355f57aa 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 23ea57351..71bde7342 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/triton/activation.py b/python/freetoken/kernel/triton/activation.py index 2c38b533e..0b7c945c3 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 61d3a0e77..e52095cc4 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 3f95c29f0..9071e1dff 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/python/freetoken/kernel/utils.py b/python/freetoken/kernel/utils.py index 7a0164b59..b59a588f6 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: @@ -19,7 +20,14 @@ 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 = [] +DEFAULT_ROCM_ARCHES = ("gfx1100", "gfx1101", "gfx1102", "gfx1103", "gfx1200", "gfx1201") + + +def _is_rocm() -> bool: + import torch + return getattr(torch.version, "hip", None) is not None def _cuda_cflags(extra: List[str]) -> List[str]: @@ -40,6 +48,69 @@ 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 RDNA-specific tuning (wave count, LDS size). + flags = DEFAULT_HIP_CFLAGS + extra + 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 + an explicit linker search path without modifying the 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(): + try: + compat_link.symlink_to(versioned[-1]) + except FileExistsError: + # Multiple tensor-parallel ranks may prepare the same cache. + pass + + return [f"-L{link_dir}", f"-Wl,-rpath,{library_dir}"] + + raise RuntimeError("Unable to locate libamdhip64 for ROCm JIT linking") + + CPP_TEMPLATE_TYPE: TypeAlias = Union[int, float, bool] @@ -217,13 +288,20 @@ 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) + runtime_ldflags = _rocm_link_flags() + else: + cuda_cflags = _cuda_cflags(extra_cuda_cflags) + runtime_ldflags = [] + 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_ldflags=DEFAULT_LDFLAGS + extra_ldflags, + extra_cuda_cflags=cuda_cflags, + extra_ldflags=DEFAULT_LDFLAGS + runtime_ldflags + extra_ldflags, extra_include_paths=DEFAULT_INCLUDE + extra_include_paths, build_directory=build_directory, ) @@ -272,13 +350,20 @@ 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) + runtime_ldflags = _rocm_link_flags() + else: + cuda_cflags = _cuda_cflags(extra_cuda_cflags) + runtime_ldflags = [] + 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_ldflags=DEFAULT_LDFLAGS + extra_ldflags, + extra_cuda_cflags=cuda_cflags, + 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/moe/cpu_executor.py b/python/freetoken/moe/cpu_executor.py index b96205aa6..9ed53d4db 100644 --- a/python/freetoken/moe/cpu_executor.py +++ b/python/freetoken/moe/cpu_executor.py @@ -1,18 +1,28 @@ """Python wrapper around the ``_cpu_moe`` C++ executor (--moe-backend cpu). Owns the persistent CPU worker pool, the per-batch-size pinned IO buffers, and -the per-(layer, batch-size) host-func task descriptors. ``decode`` issues the -whole CUDA-graph-capturable sequence on the current stream: +the per-(layer, batch-size) task descriptors. ``decode`` issues this sequence on +the current stream: D2H (hidden, topk_ids, topk_weights -> pinned) - -> submit host node (cudaLaunchHostFunc: enqueue MoE task to the pool) - -> sync host node (cudaLaunchHostFunc: spin until the pool drains) + -> submit flag memop (or eager cudaLaunchHostFunc fallback) + -> sync flag memop (or eager cudaLaunchHostFunc fallback) -> H2D (pinned expert output -> GPU) -Buffers and tasks are allocated lazily per batch size. GraphRunner runs an eager -``model.forward()`` at each batch size immediately before capturing it, so the -first (eager) call materializes the stable pinned buffers + task pointers that -the subsequent capture embeds in its host/memcpy nodes. +CUDA and ROCm expose the same ordering and results; only the GPU/CPU handshake +implementation differs. CUDA keeps mapped-pinned ready/done arrays and the +established module-level ``cuStreamWriteValue64``/``cuStreamWaitValue64`` path. +ROCm 7.14 uses executor-owned ``hipMallocSignalMemory`` signals and explicitly +adds batch-memory-op nodes during graph capture. The executor also owns the HIP +node-parameter arrays because captured graphs retain their addresses through +replay. + +Only a ROCm handshake that passes a real capture/instantiate/replay probe is +graph-safe; the Engine disables graph capture and continues eagerly when the +probe fails. Buffers and tasks are allocated lazily per batch size. GraphRunner +runs an eager ``model.forward()`` at each batch size immediately before +capturing it, so the first (eager) call materializes the stable pinned buffers + +task pointers that the subsequent capture embeds in its host/memcpy nodes. """ from __future__ import annotations @@ -32,26 +42,27 @@ # Flag-based GPU<->CPU handshake for hybrid/cpu decode. The default host-func path # (cudaLaunchHostFunc submit+sync per layer) pays ~30-50us of callback dispatch latency # per call with the GPU stream idle -- 2 calls per MoE layer per decode step (~6 ms/step -# on a 75-layer model). Instead the GPU raises a mapped-pinned "ready" flag at submit; a -# persistent CPU coordinator (in _cpu_moe) polls it, runs the layer, and sets a "done" -# flag the GPU waits on at sync -- no host-func round-trip. Both GPU-side operations are -# STREAM MEMORY OPERATIONS (cuStreamWriteValue64 / cuStreamWaitValue64, resolved from the -# driver at runtime): they execute on the GPU front end with no SM-resident kernel, so -# GPU utilization stays truthful during the CPU compute window. (The first cut used a -# spin-wait kernel; that pinned reported utilization at 99% and laptop CPU/GPU dynamic -# power schedulers responded by clamping the CPU frequency -- a net decode regression on -# power-coupled edge devices.) Each (layer, decode batch size) pair gets its own flag -# slot, so every captured decode graph rides the handshake. Where memops are unavailable -# (Windows WDDM, vGPU, old drivers -- functionally probed at startup) or the slot -# capacity is exceeded, decode keeps the host-func path (functional, slower). A Python -# watchdog thread turns a wedged coordinator into a loud RuntimeError (via err[] + +# on a 75-layer model). Instead the GPU raises a backend-specific "ready" signal at +# submit; a persistent CPU coordinator (in _cpu_moe) polls it, runs the layer, and sets +# the "done" signal the GPU waits on at sync -- no host-func round-trip. CUDA uses +# mapped-pinned per-slot arrays with cuStreamWriteValue64/cuStreamWaitValue64; ROCm uses +# executor-owned HIP signal memory and explicit graph batch-memory-op nodes. Both execute +# on the GPU front end with no SM-resident kernel, so GPU utilization stays truthful +# during the CPU compute window. (The first cut used a spin-wait kernel; that pinned +# reported utilization at 99% and laptop CPU/GPU dynamic power schedulers responded by +# clamping the CPU frequency -- a net decode regression on power-coupled edge devices.) +# Each (layer, decode batch size) pair gets a logical slot, so every captured decode graph +# rides the handshake. Where memops are unavailable (Windows WDDM, vGPU, old drivers -- +# functionally probed at startup), CUDA keeps the host-func path (functional, slower); +# ROCm fails closed during capture and the Engine normally selects the eager path. A +# Python watchdog thread turns a wedged coordinator into a loud RuntimeError (via err[] + # raise_if_unhealthy) instead of an indefinite stream stall. # Caveat: the coordinator busy-polls one core while decode traffic flows (idle backoff # otherwise); FREETOKEN_CPU_MOE_FLAG_SYNC=0 opts out entirely. _FLAG_SYNC = os.getenv("FREETOKEN_CPU_MOE_FLAG_SYNC", "1") != "0" -# Flag slots per MoE layer: covers this many distinct decode batch sizes (captured graph -# sizes plus any eager padded sizes); more than that is unheard of, and the overflow -# just keeps the host-func path for the extra combos. +_IS_ROCM = getattr(torch.version, "hip", None) is not None +# Minimum flag slots per MoE layer, retaining eager headroom for small graph sets. The +# Engine raises this to the number of distinct configured graph batch sizes when needed. _FLAG_SLOTS_PER_LAYER = 16 # Activation ids must match ActKind in csrc/cpu_moe/cpu_moe_ext.cpp. Id 3 is the @@ -154,6 +165,7 @@ def __init__( num_threads: int, max_tokens: int, device: torch.device, + flag_slots_per_layer: int = _FLAG_SLOTS_PER_LAYER, swiglu_alpha: float = 1.702, swiglu_limit: float | None = None, ) -> None: @@ -188,6 +200,9 @@ def __init__( self.quant_format = fmt self.device = device self.max_tokens = int(max_tokens) + self._flag_slots_per_layer = int(flag_slots_per_layer) + if self._flag_slots_per_layer < 1: + raise ValueError("flag_slots_per_layer must be positive") self.apply_router_weight_on_input = bool(apply_router_weight_on_input) # The per-layer tensors and their pointer tables must outlive the executor # (C++ holds raw addresses into both). @@ -195,7 +210,9 @@ def __init__( ptrs, (self.H, self.I) = self._resolve_banks(cache.bank_sources, fmt) # Decide the flag handshake up front (env + device + a functional stream-memop - # probe): its coordinator needs a core of its own, which the auto thread sizing + # probe). On ROCm the extension's probe performs a real graph capture + replay, + # not merely an eager enqueue: its coordinator needs a core of its own, which + # the auto thread sizing # below reserves (a coordinator time-slicing against the GEMV workers measurably # destabilizes throughput on fully-subscribed boxes). self._flag_sync = _FLAG_SYNC and device.type == "cuda" @@ -206,11 +223,18 @@ def __init__( if not _cpu_moe.memops_probe( torch.cuda.current_stream().cuda_stream, probe_scratch.data_ptr() ): - logger.info_rank0( - "cpu-moe flag handshake unavailable: CUDA stream memory operations " - "are not supported here (Windows WDDM / vGPU / old driver); using " - "the cudaLaunchHostFunc sync" - ) + if _IS_ROCM: + logger.info_rank0( + "cpu-moe flag handshake unavailable: stream memory operations " + "did not pass the capture/replay probe; using " + "cudaLaunchHostFunc only for eager execution" + ) + else: + logger.info_rank0( + "cpu-moe flag handshake unavailable: CUDA stream memory " + "operations are not supported here (Windows WDDM / vGPU / old " + "driver); using the cudaLaunchHostFunc sync" + ) self._flag_sync = False nthreads, core_ids = resolve_threads_and_affinity(num_threads) @@ -266,19 +290,31 @@ def __init__( # self so the coordinator's pinned pointers stay valid for the executor's # lifetime (flag_sync itself was decided above, before thread sizing). self._ready = self._done = self._err = None + self._shared_flag_signal = bool( + self._flag_sync + and getattr(_cpu_moe, "memops_use_shared_signal", lambda: False)() + ) self._flag_slots: dict[tuple[int, int], int] = {} # (layer_id, bs) -> slot - self._flag_capacity = self.num_layers * _FLAG_SLOTS_PER_LAYER + self._flag_capacity = self.num_layers * self._flag_slots_per_layer if self._flag_sync: - self._ready = alloc_pinned_tensor(self._flag_capacity, dtype=torch.int64) - self._done = alloc_pinned_tensor(self._flag_capacity, dtype=torch.int64) self._err = alloc_pinned_tensor(self._flag_capacity, dtype=torch.int64) - self._ready.zero_() - self._done.zero_() self._err.zero_() - self._ext.start_flag_coordinator( - self._ready.data_ptr(), self._done.data_ptr(), self._flag_capacity, - self._coord_core, - ) + if self._shared_flag_signal: + # HIP wait addresses must come from hipMallocSignalMemory. The C++ + # executor owns the two exact 64-bit allocations so it can stop/join + # the coordinator before freeing them. + self._ext.start_shared_signal_coordinator( + self._flag_capacity, self._coord_core + ) + else: + self._ready = alloc_pinned_tensor(self._flag_capacity, dtype=torch.int64) + self._done = alloc_pinned_tensor(self._flag_capacity, dtype=torch.int64) + self._ready.zero_() + self._done.zero_() + self._ext.start_flag_coordinator( + self._ready.data_ptr(), self._done.data_ptr(), self._flag_capacity, + self._coord_core, + ) self._watchdog_stop = False # The thread target holds a WEAKREF and re-derefs it each tick: a bound # method would strong-reference the executor forever (the loop never ends @@ -317,6 +353,11 @@ def __init__( f"top_k={self.top_k} act={activation} max_tokens={self.max_tokens}" ) + @property + def graph_capture_safe(self) -> bool: + """Whether this executor passed the native stream-memop graph replay probe.""" + return self._flag_sync + def _make_table(self, layers: list[torch.Tensor]) -> torch.Tensor: """Build a CPU int64 tensor of per-layer base addresses for one bank. @@ -550,8 +591,33 @@ def decode_submit( computes only the routes assigned to it. Returns an opaque handle to pass to :meth:`decode_sync`. The output tensor is allocated here so it stays live (and distinct from the interleaved GPU work) across the overlap window.""" + # hipLaunchHostFunc is not replay-safe for this CPU handshake on ROCm. The + # Engine normally disables graphs when the native capture/replay probe failed; + # this is the non-bypassable last line of defence for direct executor use or a + # future configuration path that misses that downgrade. + if ( + _IS_ROCM + and not self._flag_sync + and torch.cuda.is_current_stream_capturing() + ): + raise RuntimeError( + "CPU/Hybrid MoE is not CUDA-graph safe on ROCm when " + "stream-memory synchronization is unavailable" + ) + bs = hidden_states.shape[0] io = self._io_for(bs) + task = self._task_for(layer_id, bs) + slot = self._flag_slots.get((layer_id, bs)) if self._flag_sync else None + if ( + _IS_ROCM + and torch.cuda.is_current_stream_capturing() + and slot is None + ): + raise RuntimeError( + "CPU/Hybrid MoE exhausted its graph-safe ROCm flag slots during " + "CUDA-graph capture" + ) if self._gpu_prequant: # DSV4: apply the reference FP8 round-trip on the GPU (the same kernel the @@ -566,16 +632,24 @@ def decode_submit( io["ids"].copy_(topk_ids.to(torch.int32), non_blocking=True) io["w"].copy_(topk_weights.to(torch.float32), non_blocking=True) - task = self._task_for(layer_id, bs) out = torch.empty_like(hidden_states) - slot = self._flag_slots.get((layer_id, bs)) if self._flag_sync else None if slot is not None: # Front-end memops: done[slot]=0 then ready[slot]=1 (the coordinator's # doorbell). No kernel launched; no host-func round trip. - self._cpu_moe.memop_submit( - torch.cuda.current_stream().cuda_stream, - self._done.data_ptr(), self._ready.data_ptr(), slot, - ) + stream = torch.cuda.current_stream().cuda_stream + if self._shared_flag_signal: + self._ext.submit_flag_memop( + stream, + self._ext.flag_done_address(), + self._ext.flag_ready_address(), + slot, + ) + else: + # Keep CUDA on the established module-level driver-API path. Only + # ROCm needs executor-owned graph parameter storage. + self._cpu_moe.memop_submit( + stream, self._done.data_ptr(), self._ready.data_ptr(), slot + ) else: stream = torch.cuda.current_stream().cuda_stream self._ext.submit_with_cuda_stream(stream, task) @@ -589,9 +663,13 @@ def decode_sync(self, pending: tuple) -> torch.Tensor: if slot is not None: # Front-end WAIT(done[slot] >= 1): blocks this stream's later nodes without # occupying an SM, so GPU utilization stays truthful during the CPU window. - self._cpu_moe.memop_sync( - torch.cuda.current_stream().cuda_stream, self._done.data_ptr(), slot, - ) + stream = torch.cuda.current_stream().cuda_stream + if self._shared_flag_signal: + self._ext.sync_flag_memop( + stream, self._ext.flag_done_address(), slot + ) + else: + self._cpu_moe.memop_sync(stream, self._done.data_ptr(), slot) else: stream = torch.cuda.current_stream().cuda_stream self._ext.sync_with_cuda_stream(stream, task) @@ -610,12 +688,11 @@ def _watchdog_tick(self, suspects: dict) -> None: windows under heavy external load, but a coordinator that made progress in between is alive by definition. ``suspects`` maps slot -> (first_seen, served_at_first_sight) and persists across ticks.""" - stuck = (self._ready == 1) & (self._done == 0) - if not bool(stuck.any()): + pending = set(self._ext.pending_flag_slots()) + if not pending: suspects.clear() return now = time.monotonic() - pending = set(stuck.nonzero().flatten().tolist()) for slot in list(suspects): if slot not in pending: del suspects[slot] @@ -637,7 +714,7 @@ def _watchdog_tick(self, suspects: dict) -> None: for i in dead: self._err[i] = 1 for i in dead: - self._done[i] = 1 # after err: unblock the stream into a checked failure + self._ext.poison_flag(i) # after err: unblock into a checked failure suspects.pop(i, None) def raise_if_unhealthy(self) -> None: @@ -662,7 +739,7 @@ def _watchdog_main(executor_ref) -> None: while True: time.sleep(2.0) executor = executor_ref() - if executor is None or executor._watchdog_stop or executor._ready is None: + if executor is None or executor._watchdog_stop or not executor._flag_sync: return try: executor._watchdog_tick(suspects) diff --git a/python/freetoken/utils/__init__.py b/python/freetoken/utils/__init__.py index 2e4ad15f2..af68bf581 100644 --- a/python/freetoken/utils/__init__.py +++ b/python/freetoken/utils/__init__.py @@ -1,5 +1,7 @@ from .arch import ( is_arch_supported, + is_rocm, + get_rocm_gfx_arch, is_sm90_family, is_sm90_supported, is_sm100_family, @@ -35,6 +37,8 @@ "load_toolcall_anchor_id", "init_logger", "is_arch_supported", + "is_rocm", + "get_rocm_gfx_arch", "is_sm90_family", "is_sm90_supported", "is_sm100_family", diff --git a/python/freetoken/utils/arch.py b/python/freetoken/utils/arch.py index 8c1c6c3d5..304505966 100644 --- a/python/freetoken/utils/arch.py +++ b/python/freetoken/utils/arch.py @@ -1,14 +1,66 @@ from __future__ import annotations 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.""" + import torch + return getattr(torch.version, "hip", None) is not None + + +@functools.cache +def get_rocm_gfx_arch() -> str | 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; in that + fallback mode the first target is returned. The result is process-cached + for FreeToken's one-process-per-GPU execution model, so callers must select + the intended device before the first call. + """ + if not is_rocm(): + return None + + 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 + + @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 cfe41b7d8..bac07c6fb 100644 --- a/setup.py +++ b/setup.py @@ -1,13 +1,15 @@ from __future__ import annotations import importlib.util +import os 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 = str(ROOT / "python" / "freetoken" / "kernel" / "csrc" / "include") def _check_toolchain() -> None: @@ -18,6 +20,43 @@ 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], 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]]: if CUDA_HOME is None: raise RuntimeError( @@ -31,7 +70,21 @@ 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, 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"] + _check_toolchain() @@ -42,12 +95,13 @@ 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=[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 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 @@ -57,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=cuda_include_dirs, - library_dirs=cuda_library_dirs, - libraries=["cudart"], - extra_compile_args=["-O3", "-std=c++17", "-pthread"], + 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/engine/test_cpu_moe_graph_safety.py b/tests/engine/test_cpu_moe_graph_safety.py new file mode 100644 index 000000000..d05de7efc --- /dev/null +++ b/tests/engine/test_cpu_moe_graph_safety.py @@ -0,0 +1,155 @@ +from types import SimpleNamespace + +import pytest + + +@pytest.mark.parametrize("backend", ["cpu", "hybrid", "offload"]) +def test_rocm_unsafe_cpu_executor_disables_graph(monkeypatch, backend): + """The same gate covers cpu/hybrid and offload + moe_cpu_layers.""" + import freetoken.engine.engine as engine + + monkeypatch.setattr(engine, "is_rocm", lambda: True) + config = SimpleNamespace( + moe_backend=backend, + moe_cpu_layers="0" if backend == "offload" else None, + cuda_graph_bs=None, + cuda_graph_max_bs=32, + ) + executor = SimpleNamespace(graph_capture_safe=False) + + assert engine._disable_unsafe_rocm_cpu_moe_graph(config, executor) + assert config.cuda_graph_bs == [] + assert config.cuda_graph_max_bs == 0 + + +def test_rocm_verified_cpu_executor_keeps_graph(monkeypatch): + import freetoken.engine.engine as engine + + monkeypatch.setattr(engine, "is_rocm", lambda: True) + config = SimpleNamespace(cuda_graph_bs=[1, 2, 4], cuda_graph_max_bs=4) + + assert not engine._disable_unsafe_rocm_cpu_moe_graph( + config, SimpleNamespace(graph_capture_safe=True) + ) + assert config.cuda_graph_bs == [1, 2, 4] + assert config.cuda_graph_max_bs == 4 + + +def test_non_rocm_keeps_existing_cuda_host_callback_fallback(monkeypatch): + import freetoken.engine.engine as engine + + monkeypatch.setattr(engine, "is_rocm", lambda: False) + config = SimpleNamespace(cuda_graph_bs=None, cuda_graph_max_bs=16) + + assert not engine._disable_unsafe_rocm_cpu_moe_graph( + config, SimpleNamespace(graph_capture_safe=False) + ) + assert config.cuda_graph_bs is None + assert config.cuda_graph_max_bs == 16 + + +@pytest.mark.parametrize( + ("cuda_graph_bs", "cuda_graph_max_bs", "expected"), + [ + (None, 32, False), + ([1, 2], 2, False), + ([1], 0, False), + ([], 32, True), + (None, 0, True), + ], +) +def test_rocm_auto_hybrid_requires_graph_to_be_disabled( + monkeypatch, cuda_graph_bs, cuda_graph_max_bs, expected +): + import freetoken.engine.engine as engine + + monkeypatch.setattr(engine, "is_rocm", lambda: True) + config = SimpleNamespace( + cuda_graph_bs=cuda_graph_bs, cuda_graph_max_bs=cuda_graph_max_bs + ) + + assert engine._auto_hybrid_allowed_before_rocm_probe(config) is expected + + +def test_cpu_moe_flag_slots_cover_every_graph_batch_size(): + import freetoken.engine.engine as engine + + config = SimpleNamespace(cuda_graph_bs=None, cuda_graph_max_bs=128) + + # [1, 2, 4] plus 8..128 in steps of 8: 19 distinct captured sizes. + assert engine._cpu_moe_flag_slots_per_layer(config, free_memory=0) == 19 + + +def test_cpu_moe_flag_slots_keep_eager_headroom_for_small_graph_sets(): + import freetoken.engine.engine as engine + + config = SimpleNamespace(cuda_graph_bs=[1, 2, 2, 4], cuda_graph_max_bs=128) + + assert engine._cpu_moe_flag_slots_per_layer(config, free_memory=0) == 16 + + +def test_cuda_flag_memops_keep_module_level_api(monkeypatch): + """The ownership refactor must not reroute CUDA through the ROCm-only methods.""" + import freetoken.moe.cpu_executor as cpu_executor + + calls = [] + + class TensorStub: + shape = (1, 8) + + def copy_(self, *args, **kwargs): + return self + + def to(self, *args, **kwargs): + return self + + executor = object.__new__(cpu_executor.CpuMoeExecutor) + executor._flag_sync = True + executor._shared_flag_signal = False + executor._gpu_prequant = False + executor._flag_slots = {(0, 1): 3} + executor._cpu_moe = SimpleNamespace( + memop_submit=lambda *args: calls.append(("submit", args)), + memop_sync=lambda *args: calls.append(("sync", args)), + ) + executor._ext = SimpleNamespace( + submit_flag_memop=lambda *args: pytest.fail("ROCm submit used on CUDA"), + sync_flag_memop=lambda *args: pytest.fail("ROCm sync used on CUDA"), + ) + executor._ready = SimpleNamespace(data_ptr=lambda: 101) + executor._done = SimpleNamespace(data_ptr=lambda: 202) + io = {name: TensorStub() for name in ("x", "ids", "w", "y")} + executor._io_for = lambda bs: io + executor._task_for = lambda layer_id, bs: 303 + executor._io = {1: io} + + monkeypatch.setattr(cpu_executor, "_IS_ROCM", False) + monkeypatch.setattr( + cpu_executor.torch.cuda, + "current_stream", + lambda: SimpleNamespace(cuda_stream=404), + ) + monkeypatch.setattr(cpu_executor.torch, "empty_like", lambda value: TensorStub()) + + tensor = TensorStub() + pending = executor.decode_submit(0, tensor, tensor, tensor) + executor.decode_sync(pending) + + assert calls == [ + ("submit", (404, 202, 101, 3)), + ("sync", (404, 202, 3)), + ] + + +def test_direct_rocm_capture_without_flag_sync_fails_closed(monkeypatch): + import freetoken.moe.cpu_executor as cpu_executor + + monkeypatch.setattr(cpu_executor, "_IS_ROCM", True) + monkeypatch.setattr( + cpu_executor.torch.cuda, "is_current_stream_capturing", lambda: True + ) + executor = object.__new__(cpu_executor.CpuMoeExecutor) + executor._flag_sync = False + + with pytest.raises(RuntimeError, match="not CUDA-graph safe on ROCm"): + executor.decode_submit(0, None, None, None) diff --git a/tests/kernels/test_e4m3_compat.py b/tests/kernels/test_e4m3_compat.py index 8bcb8e581..fa8a1f1d3 100644 --- a/tests/kernels/test_e4m3_compat.py +++ b/tests/kernels/test_e4m3_compat.py @@ -41,6 +41,29 @@ def _native_cc() -> bool: return torch.cuda.get_device_capability() >= (8, 9) +@pytest.mark.skipif(torch.version.hip is None, reason="needs ROCm") +def test_rocm_host_and_compile_time_native_gates_match(): + """The host wrapper and Triton constexpr must choose the same buffer ABI.""" + import triton + import triton.language as tl + + from freetoken.kernel.triton.e4m3_compat import e4m3_native, e4m3_native_cx + + @triton.jit + def gate_kernel(output): + if e4m3_native_cx(): + value = 1 + else: + value = 0 + tl.store(output, value) + + output = torch.empty(1, dtype=torch.int32, device="cuda") + gate_kernel[(1,)](output) + + assert e4m3_native() is False + assert output.item() == int(e4m3_native()) + + # ====================================================================================== # 1. Primitives vs the native fp8 unit (needs sm_89+ hardware for the reference). # ====================================================================================== diff --git a/tests/kernels/test_pinned_tensor.py b/tests/kernels/test_pinned_tensor.py index e61108fd5..2fee4f25c 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/kernels/test_rocm_launch_kwargs.py b/tests/kernels/test_rocm_launch_kwargs.py new file mode 100644 index 000000000..52fac5451 --- /dev/null +++ b/tests/kernels/test_rocm_launch_kwargs.py @@ -0,0 +1,51 @@ +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", +) + + +class _KernelRecorder: + def __init__(self): + self.kwargs = None + + def __getitem__(self, _grid): + def launch(*_args, **kwargs): + self.kwargs = kwargs + + return launch + + +def test_rocm_activation_launch_omits_cuda_pdl_attribute(monkeypatch): + import freetoken.kernel.triton.activation as activation + + recorder = _KernelRecorder() + monkeypatch.setattr(activation, "_act_and_mul_kernel", recorder) + monkeypatch.setattr(activation, "_pdl_supported", lambda: True) + monkeypatch.setattr(activation, "is_rocm", lambda: True) + + activation.silu_and_mul(torch.ones((2, 128), device="cuda")) + + assert recorder.kwargs is not None + assert recorder.kwargs["ENABLE_PDL"] is True + assert "launch_pdl" not in recorder.kwargs + + +def test_rocm_norm_launch_omits_cuda_pdl_attribute(monkeypatch): + import freetoken.kernel.triton.norm as norm + + recorder = _KernelRecorder() + monkeypatch.setattr(norm, "_rmsnorm_kernel", recorder) + monkeypatch.setattr(norm, "is_sm90_supported", lambda: True) + monkeypatch.setattr(norm, "is_rocm", lambda: True) + + x = torch.ones((2, 64), device="cuda") + weight = torch.ones(64, device="cuda") + norm.rmsnorm(x, weight) + + assert recorder.kwargs is not None + assert recorder.kwargs["ENABLE_PDL"] is True + assert "launch_pdl" not in recorder.kwargs diff --git a/tests/moe/test_cpu_moe.py b/tests/moe/test_cpu_moe.py index f496de314..5b58c7d26 100644 --- a/tests/moe/test_cpu_moe.py +++ b/tests/moe/test_cpu_moe.py @@ -4,9 +4,9 @@ GPU decode kernels (bf16/nvfp4/mxfp4/ds_fp4) on identical banks and routing across batch sizes (fp32-accumulate, so the only spread is reduction order -> tight tol). -Part 2 -- CUDA-graph capture/replay: the cudaLaunchHostFunc submit/sync host nodes -end to end (eager decode, capture, replay with *new* data -> result tracks the new -routing, i.e. the dependency flows through the pinned buffers, not baked-in). +Part 2 -- CUDA-graph capture/replay: the native flag handshake end to end (eager +decode, capture, replay with *new* data -> result tracks the new routing, i.e. the +dependency flows through the pinned buffers, not baked-in). """ from __future__ import annotations @@ -502,15 +502,136 @@ def test_cpu_moe_decode_cuda_graph_replay(): assert (layer, bs) in ex._flag_slots, "flag slot expected for the decode task" slot = ex._flag_slots[(layer, bs)] assert ex._ext.flag_served_count(slot) >= 4, "1 eager + 3 replay dispatches expected" - assert int(ex._done[slot]) == 1 and int(ex._ready[slot]) == 0, "handshake at rest" + assert ex._ext.flag_done_value(slot) == 1, "completion flag at rest" + assert ex._ext.flag_ready_value(slot) == 0, "doorbell must be consumed" assert int(ex._err.sum()) == 0, "watchdog must not fire in normal operation" ex.raise_if_unhealthy() print("cpu moe cuda graph replay OK") +@pytest.mark.skipif(getattr(torch.version, "hip", None) is None, reason="ROCm guard") +def test_rocm_cpu_moe_capture_without_flag_sync_fails_closed(monkeypatch): + """ROCm must never capture the known-unsafe hipLaunchHostFunc fallback.""" + import freetoken.moe.cpu_executor as cpu_executor + + monkeypatch.setattr(cpu_executor, "_FLAG_SYNC", False) + cache = _make_cache(1, 4, 64, 32) + dev = torch.device("cuda") + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + executor = cpu_executor.CpuMoeExecutor( + cache, + top_k=2, + activation="silu", + apply_router_weight_on_input=False, + num_threads=2, + max_tokens=1, + device=dev, + ) + hidden = torch.randn(1, 64, device=dev, dtype=torch.bfloat16) + ids = torch.randint(0, 4, (1, 2), device=dev, dtype=torch.int32) + weights = torch.rand(1, 2, device=dev, dtype=torch.float32) + + with pytest.raises(RuntimeError, match="not CUDA-graph safe on ROCm"): + with torch.cuda.graph(torch.cuda.CUDAGraph(), stream=stream): + hidden.add_(0) # keep capture valid when the executor rejects its own nodes + executor.decode(0, hidden, weights, ids) + + +@pytest.mark.skipif(getattr(torch.version, "hip", None) is None, reason="ROCm guard") +def test_rocm_graph_memop_param_storage_is_bounded_across_rebuilds(): + """Rebuilding graphs must reuse executor-owned HIP batch-op parameters. + + ROCm 7.14 retains each graph node's ``paramArray`` pointer. The executor keeps + one immutable submit array per flag slot plus one shared wait array, so graph + rebuilds must neither invalidate those addresses nor append new storage. + """ + from freetoken.moe.cpu_executor import CpuMoeExecutor + + torch.manual_seed(37) + L, E, H, I, top_k, bs = 1, 4, 64, 32, 2, 1 + cache = _make_cache(L, E, H, I) + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + executor = CpuMoeExecutor( + cache, + top_k=top_k, + activation="silu", + apply_router_weight_on_input=False, + num_threads=2, + max_tokens=bs, + device=torch.device("cuda"), + ) + if not executor._flag_sync: + pytest.skip("native ROCm graph handshake unavailable") + + hidden = torch.randn(bs, H, device="cuda", dtype=torch.bfloat16) + ids = torch.randint(0, E, (bs, top_k), device="cuda", dtype=torch.int32) + weights = torch.rand(bs, top_k, device="cuda", dtype=torch.float32) + executor.decode(0, hidden, weights, ids) # materialize the task and flag slot + torch.cuda.synchronize() + + expected_params = 2 * executor._flag_capacity + 1 + assert executor._ext.graph_memop_param_count() == expected_params + for _ in range(16): + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + out = executor.decode(0, hidden, weights, ids) + graph.replay() + torch.cuda.synchronize() + assert torch.isfinite(out).all() + assert executor._ext.graph_memop_param_count() == expected_params + del graph, out + + +@pytest.mark.skipif(getattr(torch.version, "hip", None) is None, reason="ROCm guard") +def test_rocm_graph_memops_support_more_than_sixteen_batch_sizes(): + """Every configured graph size gets a native slot, including size sets > 16.""" + from freetoken.moe.cpu_executor import CpuMoeExecutor + + torch.manual_seed(41) + batch_sizes = list(range(1, 20)) + L, E, H, I, top_k = 1, 4, 64, 32, 2 + cache = _make_cache(L, E, H, I) + stream = torch.cuda.Stream() + torch.cuda.set_stream(stream) + executor = CpuMoeExecutor( + cache, + top_k=top_k, + activation="silu", + apply_router_weight_on_input=False, + num_threads=2, + max_tokens=max(batch_sizes), + device=torch.device("cuda"), + flag_slots_per_layer=len(batch_sizes), + ) + if not executor._flag_sync: + pytest.skip("native ROCm graph handshake unavailable") + + for bs in batch_sizes: + hidden = torch.randn(bs, H, device="cuda", dtype=torch.bfloat16) + ids = torch.randint(0, E, (bs, top_k), device="cuda", dtype=torch.int32) + weights = torch.rand(bs, top_k, device="cuda", dtype=torch.float32) + executor.decode(0, hidden, weights, ids) + torch.cuda.synchronize() + + graph = torch.cuda.CUDAGraph() + with torch.cuda.graph(graph, stream=stream): + out = executor.decode(0, hidden, weights, ids) + graph.replay() + torch.cuda.synchronize() + slot = executor._flag_slots[(0, bs)] + assert executor._ext.flag_served_count(slot) >= 2 + assert torch.isfinite(out).all() + del graph, out + + assert len(executor._flag_slots) == len(batch_sizes) + assert executor._ext.graph_memop_param_count() == 2 * len(batch_sizes) + 1 + + def test_cpu_moe_decode_cuda_graph_replay_mxfp4(): - """gpt-oss mxfp4 path under capture/replay: the host nodes must recompute the + """gpt-oss mxfp4 path under capture/replay: the handshake must recompute the clamped-swiglu+bias GEMV from the freshly written pinned routing on each replay.""" from freetoken.moe.cpu_executor import CpuMoeExecutor from freetoken.moe.fused_mxfp4 import run_mxfp4_splitk_decode_experts as _run_mxfp4_splitk_decode_experts diff --git a/tests/moe/test_cpu_moe_q4_0.py b/tests/moe/test_cpu_moe_q4_0.py index b5ec2f09b..1e7c63cd7 100644 --- a/tests/moe/test_cpu_moe_q4_0.py +++ b/tests/moe/test_cpu_moe_q4_0.py @@ -7,8 +7,8 @@ production bf16 GPU decode kernel on byte-identical banks: both are W4A16, so the only spread is weight bf16-rounding + reduction order -> tight relative tolerance. -Part 2 covers CUDA-graph capture/replay (the cudaLaunchHostFunc submit/sync nodes -must recompute from the freshly written pinned routing on each replay). +Part 2 covers CUDA-graph capture/replay (the native flag handshake must recompute +from the freshly written pinned routing on each replay). """ from __future__ import annotations @@ -148,7 +148,7 @@ def test_cpu_decode_q4_0_matches_ggml_mmvq(): def test_cpu_moe_decode_q4_0_cuda_graph_replay(): - """Q4_0 CPU path under capture/replay: the host nodes must recompute the GEMV from + """Q4_0 CPU path under capture/replay: the handshake must recompute the GEMV from the freshly written pinned routing on each replay (dep flows through pinned buffers).""" from freetoken.moe.cpu_executor import CpuMoeExecutor from freetoken.moe.fused import fused_experts_decode_impl diff --git a/tests/utils/test_rocm_arch.py b/tests/utils/test_rocm_arch.py new file mode 100644 index 000000000..224a61647 --- /dev/null +++ b/tests/utils/test_rocm_arch.py @@ -0,0 +1,85 @@ +import importlib +import pathlib +from types import SimpleNamespace + +import torch + +from freetoken.utils import arch + + +def _clear_arch_caches() -> None: + arch.get_rocm_gfx_arch.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" + + _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) + + +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()