Skip to content

Run frontier MoE models on hardware you already own β€” pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦

C

feat: AMD GPU support via HIP/ROCm β€” single-source backend through backend_gpu_compat.h

noobdev-phd52e76144781
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml
index e18f1b3e..500f6649 100644
--- a/.github/workflows/ci.yml
+++ b/.github/workflows/ci.yml
@@ -41,6 +41,27 @@ jobs:
-Xcompiler=-Wall,-Wextra
echo "CUDA syntax check passed"
+ engine-hip-syntax:
+ name: HIP syntax check
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - name: Free runner disk
+ # rocm/dev images are large; hosted runners need the headroom freed
+ # BEFORE the pull (which is why this is not a container: job).
+ run: sudo rm -rf /usr/share/dotnet /usr/local/lib/android /opt/ghc /opt/hostedtoolcache/CodeQL
+ - name: Compile backend_cuda.cu + test binary with hipcc (no GPU)
+ run: |
+ # Tag pinned: `latest` outgrew the runner disk once already. The
+ # gcc-side engine link is skipped: containerized gcc/ld cannot link
+ # ROCm runtime libs (both 22.04 and 24.04 bases); the hipcc-driver
+ # link of the test binary below covers the single-source claim, and
+ # the engine link is exercised on real ROCm hardware (GPU_BACKENDS.md).
+ docker run --rm -v "$PWD":/src -w /src rocm/dev-ubuntu-24.04:6.2 bash -c '
+ apt-get update && apt-get install -y --no-install-recommends make gcc g++ &&
+ make -C c gpu-compile HIP=1 HIP_ARCH=gfx1100'
+ echo "HIP syntax check passed"
+
web:
name: Web UI
runs-on: ubuntu-latest
diff --git a/GPU_BACKENDS.md b/GPU_BACKENDS.md
new file mode 100644
index 00000000..be421bfb
--- /dev/null
+++ b/GPU_BACKENDS.md
@@ -0,0 +1,85 @@
+# GPU backends: CUDA and HIP/ROCm
+
+colibrì's GPU expert backend is **one source file** (`c/backend_cuda.cu`) compiled
+for either vendor through `c/backend_gpu_compat.h` β€” the same one-shim-header
+pattern `compat.h` uses for the Windows port. Compiled by nvcc the shim is a
+pass-through to `cuda_runtime.h` (the NVIDIA path is byte-identical to the
+pre-HIP tree); compiled by hipcc it maps the 14-symbol CUDA runtime surface the
+backend uses onto HIP 1:1. The kernels use only shared syntax
+(`__global__`, `__shared__`, `__syncthreads__`, `<<<>>>`), no vendor intrinsics.
+
+**Rule for contributors:** vendor differences go in `backend_gpu_compat.h`
+only β€” never `#ifdef __HIP__` (or CUDA-specific code) in `backend_cuda.cu`.
+
+## Supported environments
+
+| backend | platform | toolchain | build |
+|---|---|---|---|
+| CUDA (`CUDA=1`) | Linux x86-64 | CUDA toolkit (nvcc), `CUDA_HOME=/usr/local/cuda` default | `make -C c glm CUDA=1 [CUDA_ARCH=native\|sm_XX]` |
+| HIP (`HIP=1`) | Linux x86-64 | ROCm (hipcc), `ROCM_HOME=/opt/rocm` default; tested on ROCm 7.2 | `make -C c glm HIP=1 [HIP_ARCH=native\|gfxXXXX]` |
+
+`CUDA=1` and `HIP=1` are mutually exclusive and both opt-in: the default build
+remains pure, dependency-free CPU. Both are refused on non-Linux with an early
+`$(error)`. `*_ARCH=native` targets the local GPU; pass an explicit arch when
+distributing or on machines with an unsupported iGPU visible to the runtime
+(and mask iGPUs at runtime with `HIP_VISIBLE_DEVICES=<ordinal>` on ROCm).
+
+## Runtime configuration (identical for both vendors)
+
+- `COLI_CUDA=1` + `COLI_GPU=N` (or `COLI_GPUS=0,1,...`) β€” enable, select devices
+- `CUDA_EXPERT_GB=G` β€” VRAM budget for the expert tier (clamped to free VRAM
+ minus projected dense set and 2 GB headroom per device)
+- `CUDA_RELEASE_HOST=1` β€” GPU-tier experts drop their host backing after
+ upload (default on multi-GPU); combined with `PIN=auto`/`PIN_FILL`, VRAM
+ becomes additional pinned capacity at zero RAM cost. The engine
+ rematerializes an expert from disk (`expert_host_ensure`) whenever the CPU
+ path needs one whose host copy was released β€” validated under total GPU
+ failure below.
+- `CUDA_DENSE=1` β€” experimental resident-dense path (unchanged)
+- `COLI_CUDA_TC_W4A16=1` β€” opt-in W4A16 tensor-core path. **NVIDIA-only**:
+ the WMMA kernels are compile-gated (`COLI_GPU_HAS_WMMA` in the compat
+ header) because gfx GPUs report `compute_major >= 7` and a runtime check
+ alone would select empty kernel bodies under HIP. On AMD, all compute uses
+ the portable kernels; rocWMMA matrix-core support is a possible follow-up.
+
+## Validation
+
+### Unit tests (run on GPU hardware)
+
+```sh
+make -C c cuda-test [CUDA_ARCH=...] # NVIDIA
+make -C c hip-test [HIP_ARCH=...] # AMD (same test source)
+```
+
+Covers q8/q4/q2/f32 matmul correctness, multi-device placement/stats, and
+`tensor_update` β€” the standard upstream suite, unchanged, compiled by hipcc.
+(A companion PR adds failure-path tests for the backend; they are
+vendor-neutral and run under `hip-test` identically.)
+
+### CI (no GPU required)
+
+The `engine-hip-syntax` job in `.github/workflows/ci.yml` compiles the
+backend and its test binary with hipcc (`rocm/dev` container pinned to
+`6.2`, `gfx1100`) on every PR, mirroring `engine-cuda-syntax`. Kernel
+*execution* is not possible on hosted runners; that is what `hip-test`
+on real hardware is for (matrix below).
+
+### Hardware test matrix (documented results)
+
+| environment | result |
+|---|---|
+| AMD RX 9070 XT (gfx1201), ROCm 7.2.4, Linux 7.0 | `hip-test` **pass** (all cases above); GLM-5.2 end-to-end runs (0.32 tok/s @ 61% expert hit with CUDA_RELEASE_HOST=1); benchmark series in PR #112 |
+| NVIDIA | compile-verified in CI (`sm_80`); nvcc path is a pass-through include β€” **runtime run of `make cuda-test` on NVIDIA hardware welcomed**, the test source is vendor-neutral |
+
+## Known behavior notes
+
+- GPU float matmuls round differently than the CPU int8-dot (IDOT) kernels:
+ greedy output is **not token-identical** across backends (consistent with
+ the shape-dependence documented in #100), and MTP draft acceptance measures
+ lower on GPU-heavy configs (~40% β†’ ~31% on the PR #112 machine). A
+ numerics-matched integer GPU kernel is the planned follow-up.
+- An earlier revision of this branch carried `CUDA_EXTEND=1` (VRAM tier
+ holding experts beyond the RAM pin). It was superseded by upstream's
+ `PIN=auto` + `PIN_FILL` + `CUDA_RELEASE_HOST`, which achieve the same
+ capacity extension with deeper engine integration; this branch's safety
+ and validation work now targets that mechanism.
diff --git a/c/Makefile b/c/Makefile
index 27902cb2..4264d906 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -154,6 +154,18 @@ NVCCFLAGS ?= -O3 -std=c++17 -arch=$(CUDA_ARCH) -Xcompiler=-W3
else
NVCCFLAGS ?= -O3 -std=c++17 -arch=$(CUDA_ARCH) -Xcompiler=-Wall,-Wextra
endif
+# HIP=1 builds the SAME backend for AMD GPUs via ROCm: backend_cuda.cu is
+# compiled unchanged through backend_gpu_compat.h (one source, two vendors,
+# like compat.h does for Windows). HIP_ARCH=native targets the GPU in this
+# machine; set an explicit arch (e.g. HIP_ARCH=gfx1201) when distributing.
+HIP ?= 0
+ROCM_HOME ?= /opt/rocm
+HIPCC ?= $(ROCM_HOME)/bin/hipcc
+HIP_ARCH ?= native
+HIPCCFLAGS ?= -O3 -std=c++17 -x hip --offload-arch=$(HIP_ARCH) -Wall -Wextra
+GPUCC = $(NVCC)
+GPUFLAGS = $(NVCCFLAGS)
+GPUCC_NAME = nvcc (set CUDA_HOME or NVCC)
# PYTHON is a HOST tool (clean/test-c/test-python run it on the build machine),
# so key it off the host, NOT $(IS_WIN) β€” which is derived from the *target*
# triple ($(CC) -dumpmachine). Otherwise a cross build (make CC=x86_64-w64-
@@ -188,11 +200,26 @@ ifneq ($(IS_WIN),)
# On Windows use CUDA_DLL=1 (runtime DLL), not CUDA=1 (direct link).
$(error On Windows use: make CUDA_DLL=1 cuda-dll (see backend_loader.c))
endif
+ifeq ($(HIP),1)
+$(error choose CUDA=1 or HIP=1, not both)
+endif
CFLAGS += -DCOLI_CUDA
LDFLAGS += -L$(CUDA_HOME)/lib64 -Wl,-rpath,$(CUDA_HOME)/lib64 -lcudart -lstdc++
CUDA_OBJ = backend_cuda.o
endif
+ifeq ($(HIP),1)
+ifeq (,$(LINUX))
+$(error HIP=1 is supported only on Linux)
+endif
+CFLAGS += -DCOLI_CUDA
+LDFLAGS += -L$(ROCM_HOME)/lib -Wl,-rpath,$(ROCM_HOME)/lib -lamdhip64 -lstdc++
+CUDA_OBJ = backend_cuda.o
+GPUCC = $(HIPCC)
+GPUFLAGS = $(HIPCCFLAGS)
+GPUCC_NAME = hipcc (set ROCM_HOME or HIPCC)
+endif
+
# METAL=1 adds an opt-in Apple-GPU backend (macOS only). The shader is compiled at
# runtime, so no Xcode / offline metal compiler is required. Default build unchanged.
METAL ?= 0
@@ -219,7 +246,7 @@ glm: glm$(EXE)
# it ONLY when they change (evaluated here at parse time, so the file's timestamp
# moves exactly when the config moves). glm.exe and the CUDA/loader objects depend
# on it, so they relink on a config change and stay put otherwise. (#306)
-BUILD_CONFIG := $(CC)|$(CFLAGS)|$(LDFLAGS)|CUDA=$(CUDA)|CUDA_DLL=$(CUDA_DLL)|ARCH=$(ARCH)|CUDA_ARCH=$(CUDA_ARCH)|METAL=$(METAL)
+BUILD_CONFIG := $(CC)|$(CFLAGS)|$(LDFLAGS)|CUDA=$(CUDA)|CUDA_DLL=$(CUDA_DLL)|ARCH=$(ARCH)|CUDA_ARCH=$(CUDA_ARCH)|METAL=$(METAL)|HIP=$(HIP)|HIP_ARCH=$(HIP_ARCH)
BUILD_CONFIG_OLD := $(shell cat .build-config 2>/dev/null)
ifneq "$(BUILD_CONFIG)" "$(BUILD_CONFIG_OLD)"
$(shell printf '%s' '$(BUILD_CONFIG)' > .build-config)
@@ -245,9 +272,9 @@ cuda-dll: backend_cuda.cu backend_cuda.h
-L"$(CUDA_HOME)/lib/x64" -lcudart \
backend_cuda.cu -o coli_cuda.dll
-backend_cuda.o: backend_cuda.cu backend_cuda.h .build-config
- @command -v "$(NVCC)" >/dev/null 2>&1 || { echo "nvcc not found: set CUDA_HOME or NVCC" >&2; exit 1; }
- "$(NVCC)" $(NVCCFLAGS) -c backend_cuda.cu -o $@
+backend_cuda.o: backend_cuda.cu backend_cuda.h backend_gpu_compat.h .build-config
+ @command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
+ "$(GPUCC)" $(GPUFLAGS) -c backend_cuda.cu -o $@
backend_metal.o: backend_metal.mm backend_metal.h
$(METALXX) -c backend_metal.mm -o $@
@@ -256,14 +283,23 @@ metal-test: tests/test_backend_metal.mm backend_metal.mm backend_metal.h
$(METALXX) tests/test_backend_metal.mm backend_metal.mm -framework Metal -framework Foundation -o backend_metal_test
./backend_metal_test
-cuda-test: backend_cuda.cu backend_cuda.h tests/test_backend_cuda.cu
- @command -v "$(NVCC)" >/dev/null 2>&1 || { echo "nvcc not found: set CUDA_HOME or NVCC" >&2; exit 1; }
- "$(NVCC)" $(NVCCFLAGS) backend_cuda.cu tests/test_backend_cuda.cu -o backend_cuda_test$(EXE)
+cuda-test: backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/test_backend_cuda.cu
+ @command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
+ "$(GPUCC)" $(GPUFLAGS) backend_cuda.cu tests/test_backend_cuda.cu -o backend_cuda_test$(EXE)
./backend_cuda_test$(EXE)
-cuda-bench: backend_cuda.cu backend_cuda.h tests/bench_tensor_core.cu
- @command -v "$(NVCC)" >/dev/null 2>&1 || { echo "nvcc not found: set CUDA_HOME or NVCC" >&2; exit 1; }
- "$(NVCC)" $(NVCCFLAGS) backend_cuda.cu tests/bench_tensor_core.cu -o backend_cuda_bench$(EXE)
+# convenience alias: kernel correctness on AMD (same test, hipcc toolchain)
+hip-test:
+ $(MAKE) cuda-test HIP=1
+
+# CI: compile the backend and its test binary WITHOUT executing them (for
+# runners with the toolchain but no GPU). Pass CUDA_ARCH/HIP=1+HIP_ARCH.
+gpu-compile: backend_cuda.o
+ "$(GPUCC)" $(GPUFLAGS) backend_cuda.cu tests/test_backend_cuda.cu -o backend_cuda_test$(EXE)
+
+cuda-bench: backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/bench_tensor_core.cu
+ @command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
+ "$(GPUCC)" $(GPUFLAGS) backend_cuda.cu tests/bench_tensor_core.cu -o backend_cuda_bench$(EXE)
./backend_cuda_bench$(EXE)
olmoe$(EXE): olmoe.c st.h json.h compat.h
@@ -362,4 +398,4 @@ clean:
bench: iobench$(EXE)
@if [ -n "$(ARGS)" ]; then ./iobench$(EXE) $(ARGS); else echo "built iobench$(EXE) β€” run: ./iobench$(EXE) <file> <MB> <iters> <threads> <direct 0|1>"; fi
-.PHONY: all glm cuda-test cuda-bench cuda-dll portable test-c test-python test check clean install uninstall bench
+.PHONY: all glm cuda-test hip-test gpu-compile cuda-bench cuda-dll portable test-c test-python test check clean install uninstall bench
diff --git a/c/backend_cuda.cu b/c/backend_cuda.cu
index 9ce142fb..1717c63b 100644
--- a/c/backend_cuda.cu
+++ b/c/backend_cuda.cu
@@ -1,7 +1,6 @@
#include "backend_cuda.h"
-#include <cuda_runtime.h>
-#include <mma.h>
+#include "backend_gpu_compat.h"
#include <cstdio>
#include <cstdlib>
@@ -555,7 +554,7 @@ extern "C" int coli_cuda_shared_mlp_w4a16(ColiCudaTensor *gate,ColiCudaTensor *u
if(!gate||!up||!down||!x||!y||S<1||gate->fmt!=2||up->fmt!=2||down->fmt!=2||
gate->device!=up->device||gate->device!=down->device||gate->I!=up->I||
gate->O!=up->O||down->I!=gate->O||down->O!=gate->I)return 0;
- DeviceContext *ctx=find_ctx(gate->device);if(!select_ctx(ctx)||ctx->compute_major<7)return 0;
+ DeviceContext *ctx=find_ctx(gate->device);if(!select_ctx(ctx)||!COLI_GPU_HAS_WMMA||ctx->compute_major<7)return 0;
int D=gate->I,I=gate->O;size_t xb=(size_t)S*D*sizeof(float),ib=(size_t)S*I*sizeof(float);
if(!reserve(&ctx->x,&ctx->x_cap,xb)||!reserve(&ctx->gate,&ctx->gate_cap,ib)||
!reserve(&ctx->up,&ctx->up_cap,ib)||!reserve(&ctx->y,&ctx->y_cap,xb)||
@@ -635,7 +634,7 @@ extern "C" int coli_cuda_expert_group(ColiCudaTensor *const *gates,
silu_mul<<<(unsigned)(((size_t)total*I+255)/256),256,0,ctx->stream>>>(ctx->gate,ctx->up,(size_t)total*I);
quantize_s4_rows<<<total,256,0,ctx->stream>>>(ctx->qx,ctx->qscale,ctx->gate,total,I);
grouped_s4_wmma<<<dim3((unsigned)((D+63)/64),(unsigned)count),256,0,ctx->stream>>>(ctx->y,ctx->qx,ctx->qscale,dev,I,D,2);
- }else if(all_s4&&ctx->compute_major>=7&&getenv("COLI_CUDA_TC_W4A16")&&
+ }else if(all_s4&&COLI_GPU_HAS_WMMA&&ctx->compute_major>=7&&getenv("COLI_CUDA_TC_W4A16")&&
atoi(getenv("COLI_CUDA_TC_W4A16"))){
/* W4A16 Tensor Core per gruppo: attivazioni fp16 per tile (lossless al
* contrario del path W4A4), un lancio per expert dentro lo stream β€”
diff --git a/c/backend_gpu_compat.h b/c/backend_gpu_compat.h
new file mode 100644
index 00000000..98ec98e0
--- /dev/null
+++ b/c/backend_gpu_compat.h
@@ -0,0 +1,62 @@
+/* backend_gpu_compat.h β€” one GPU backend source, two vendors.
+ * Same pattern as compat.h for Windows: every platform difference lives in
+ * this header and backend_cuda.cu stays untouched. Compiled by nvcc this is
+ * a pass-through to the CUDA runtime (and mma.h for the tensor-core paths);
+ * compiled by hipcc (ROCm, HIP=1) it maps the CUDA runtime surface
+ * backend_cuda.cu uses onto HIP 1:1. The kernel language (__global__,
+ * __shared__, <<<>>>) is shared syntax.
+ *
+ * COLI_GPU_HAS_WMMA: the WMMA tensor-core kernels are guarded by
+ * __CUDA_ARCH__ >= 700 (device side) and by this flag at the host dispatch
+ * sites. Under HIP the flag is 0: gfx GPUs report compute_major >= 7, so a
+ * runtime-only check would select empty kernel bodies. Matrix-core support
+ * via rocWMMA is a possible follow-up; until then HIP always uses the
+ * portable kernels. */
+#ifndef COLIBRI_BACKEND_GPU_COMPAT_H
+#define COLIBRI_BACKEND_GPU_COMPAT_H
+
+#if defined(__HIP_PLATFORM_AMD__) || defined(__HIP__)
+#include <hip/hip_runtime.h>
+#include <hip/hip_fp16.h>
+#define COLI_GPU_HAS_WMMA 0
+#define cudaError_t hipError_t
+#define cudaSuccess hipSuccess
+#define cudaGetErrorString hipGetErrorString
+#define cudaGetLastError hipGetLastError
+#define cudaSetDevice hipSetDevice
+#define cudaGetDeviceCount hipGetDeviceCount
+#define cudaDeviceProp hipDeviceProp_t
+#define cudaGetDeviceProperties hipGetDeviceProperties
+#define cudaMalloc hipMalloc
+#define cudaFree hipFree
+#define cudaMemcpy hipMemcpy
+#define cudaMemcpy2D hipMemcpy2D
+#define cudaMemcpyAsync hipMemcpyAsync
+#define cudaMemcpyHostToDevice hipMemcpyHostToDevice
+#define cudaMemcpyDeviceToHost hipMemcpyDeviceToHost
+#define cudaMemGetInfo hipMemGetInfo
+#define cudaStream_t hipStream_t
+#define cudaStreamCreate hipStreamCreate
+#define cudaStreamCreateWithFlags hipStreamCreateWithFlags
+#define cudaStreamNonBlocking hipStreamNonBlocking
+#define cudaStreamDestroy hipStreamDestroy
+#define cudaStreamSynchronize hipStreamSynchronize
+#define cudaDeviceSynchronize hipDeviceSynchronize
+#define cudaEvent_t hipEvent_t
+#define cudaEventCreate hipEventCreate
+#define cudaEventDestroy hipEventDestroy
+#define cudaEventRecord hipEventRecord
+#define cudaEventSynchronize hipEventSynchronize
+#define cudaEventElapsedTime hipEventElapsedTime
+#define cudaMallocHost hipHostMalloc
+#define cudaFreeHost hipHostFree
+#define cudaMemcpyDeviceToDevice hipMemcpyDeviceToDevice
+#define cudaMemcpyPeer hipMemcpyPeer
+#define cudaMemsetAsync hipMemsetAsync
+#else
+#include <cuda_runtime.h>
+#include <mma.h>
+#define COLI_GPU_HAS_WMMA 1
+#endif
+
+#endif