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

cuda: fmt=8 (fp8-e4m3) kernels β€” dense matmul + expert groups, block-scale aware

kreuzzelgdbb4b0251776
diff --git a/c/backend_cuda.cu b/c/backend_cuda.cu
index 2efc557c..a33aa546 100644
--- a/c/backend_cuda.cu
+++ b/c/backend_cuda.cu
@@ -145,6 +145,7 @@ __host__ __device__ static size_t row_bytes(int fmt, int I) {
if (fmt == 3) return (size_t)(I + 3) / 4;
if (fmt == 4) return (size_t)(I + 1) / 2; /* grouped int4: nibbles like fmt 2 */
if (fmt == 6) return (size_t)(((int64_t)I + COLI_E8_QK - 1) / COLI_E8_QK) * COLI_E8_BBYTES;
+ if (fmt == 8) return (size_t)I; /* fp8-e4m3: raw bytes, layout of fmt=1 */
return 0;
}
@@ -152,6 +153,14 @@ __host__ __device__ static size_t row_bytes(int fmt, int I) {
* has a single source of truth and cannot drift from the CPU decoder. */
__constant__ uint8_t c_e8_grid[256][4];
+/* The fmt=8 e4m3 decode table, uploaded once per device from quant.h's
+ * E4M3_LUT β€” same single-source-of-truth arrangement as c_e8_grid. Uploads of
+ * fmt=8 tensors are refused until it is published (g_fp8_lut_ready): a kernel
+ * reading the zero-initialized table would compute silent zeros, the exact
+ * failure mode this format's dispatch work exists to prevent. */
+__constant__ float c_e4m3[256];
+static int g_fp8_lut_ready;
+
/* A super-block is 98 bytes, so nothing inside it is guaranteed 4- or 2-byte
* aligned: assemble the words byte-wise instead of dereferencing. */
__device__ __forceinline__ uint32_t e8_ld_u32(const uint8_t *p){
@@ -246,6 +255,17 @@ __global__ static void quant_matmul(float *y, const float *x, const void *weight
if (g >= ng) g = ng - 1; /* tail elements in the last (partial) group */
sum += xs[i] * weight_at(weights, fmt, row, i) * scl[g];
}
+ } else if (fmt == 8) {
+ /* fp8-e4m3 (matmul_fp8): one byte per weight (layout of fmt=1), one f32
+ * scale per 128x128 BLOCK of [O,I] β€” scales[(o/128)*ceil(I/128) + i/128].
+ * The block edge is a fixed property of the format (FP8_BLOCK), so the
+ * geometry derives from I alone and gs/ng are ignored: this branch is
+ * correct no matter which call site launched it. NaN bytes decode to NaN
+ * through the LUT and propagate, same policy as the CPU path. */
+ const uint8_t *wrow = static_cast<const uint8_t *>(weights) + row;
+ const float *scl = scales + (size_t)(o >> 7) * (size_t)((I + 127) >> 7);
+ for (int i = threadIdx.x; i < I; i += blockDim.x)
+ sum += xs[i] * c_e4m3[wrow[i]] * scl[i >> 7];
} else {
for (int i = threadIdx.x; i < I; i += blockDim.x)
sum += xs[i] * weight_at(weights, fmt, row, i);
@@ -259,7 +279,7 @@ __global__ static void quant_matmul(float *y, const float *x, const void *weight
__syncthreads();
}
if (!threadIdx.x)
- y[(size_t)s * O + o] = (fmt && fmt != 4 && fmt != 6) ? partial[0] * scales[o] : partial[0];
+ y[(size_t)s * O + o] = (fmt && fmt != 4 && fmt != 6 && fmt != 8) ? partial[0] * scales[o] : partial[0];
}
/* fmt=6 activation rotation, y = Q^T x for Q = D*H/sqrt(n) (#452). One block per
@@ -576,6 +596,43 @@ __global__ static void grouped_down_g4(float *y,const float *x,const GroupDesc *
if(!threadIdx.x)y[(size_t)(d.offset+s)*D+o]=p[0];
}
+/* fmt=8 fp8-e4m3 variants: same structure as the g4 kernels, but one byte per
+ * weight (decoded through c_e4m3) and the scale is per 128x128 BLOCK of the
+ * member's [O,I] matrix β€” sc[(o/128)*ceil(I/128) + i/128]. The block edge is a
+ * property of the format, so the geometry derives from the dims alone; these
+ * kernels require every member to be fmt=8 (no ride-along: a per-row member's
+ * scales are [O], which this indexing would read out of bounds). */
+__global__ static void grouped_hidden_f8_dual(float *gate,float *up,const float *x,
+ const GroupDesc *desc,int I,int D){
+ int o=blockIdx.x,s=blockIdx.y,c=blockIdx.z;GroupDesc d=desc[c];if(s>=d.rows)return;
+ const uint8_t *gr=(const uint8_t*)d.g+(size_t)o*D;
+ const uint8_t *ur=(const uint8_t*)d.u+(size_t)o*D;
+ int nblk=(D+127)>>7;
+ const float *gsc=d.gs+(size_t)(o>>7)*nblk;
+ const float *usc=d.us+(size_t)(o>>7)*nblk;
+ const float *xs=x+(size_t)(d.offset+s)*D;float ga=0,ua=0;
+ for(int i=threadIdx.x;i<D;i+=blockDim.x){float xv=xs[i];int b=i>>7;
+ ga+=xv*c_e4m3[gr[i]]*gsc[b];ua+=xv*c_e4m3[ur[i]]*usc[b];}
+ __shared__ float gp[256],upv[256];gp[threadIdx.x]=ga;upv[threadIdx.x]=ua;__syncthreads();
+ for(int n=128;n;n>>=1){if(threadIdx.x<n){gp[threadIdx.x]+=gp[threadIdx.x+n];upv[threadIdx.x]+=upv[threadIdx.x+n];}__syncthreads();}
+ /* same fused epilogue as the w4/g4 duals: scales applied in the
+ * accumulation, silu(gate)*up lands in gate[], up[] is never written */
+ if(!threadIdx.x){size_t z=(size_t)(d.offset+s)*I+o;
+ float g=gp[0],u=upv[0];
+ gate[z]=(g/(1.0f+expf(-g)))*u;(void)up;}
+}
+__global__ static void grouped_down_f8(float *y,const float *x,const GroupDesc *desc,int D,int I){
+ int o=blockIdx.x,s=blockIdx.y,c=blockIdx.z;GroupDesc d=desc[c];if(s>=d.rows)return;
+ const uint8_t *row=(const uint8_t*)d.d+(size_t)o*I;
+ int nblk=(I+127)>>7;
+ const float *dsc=d.ds+(size_t)(o>>7)*nblk;
+ const float *xs=x+(size_t)(d.offset+s)*I;float sum=0;
+ for(int i=threadIdx.x;i<I;i+=blockDim.x)sum+=xs[i]*c_e4m3[row[i]]*dsc[i>>7];
+ __shared__ float p[256];p[threadIdx.x]=sum;__syncthreads();
+ for(int n=128;n;n>>=1){if(threadIdx.x<n)p[threadIdx.x]+=p[threadIdx.x+n];__syncthreads();}
+ if(!threadIdx.x)y[(size_t)(d.offset+s)*D+o]=p[0];
+}
+
__global__ static void attention_absorb_kernel(float *ctx,const float *q,const float *latent,
const float *rope,const void *weights,const float *wscale,
int fmt,int H,int Q,int R,int V,int K,int T,float scale,
@@ -770,6 +827,19 @@ extern "C" int coli_cuda_e8_set_grid(const void *grid) {
return 1;
}
+/* Publish quant.h's E4M3_LUT the same way β€” one source of truth for the fmt=8
+ * decode on CPU and GPU. Until this succeeds, fmt=8 uploads are refused. */
+extern "C" int coli_cuda_fp8_set_lut(const float *lut) {
+ if (!lut || g_nctx < 1) return 0;
+ for (int i = 0; i < g_nctx; i++) {
+ if (!select_ctx(&g_ctx[i])) return 0;
+ if (!cuda_ok(cudaMemcpyToSymbol(c_e4m3, lut, sizeof(c_e4m3)), "e4m3 LUT upload"))
+ return 0;
+ }
+ g_fp8_lut_ready = 1;
+ return 1;
+}
+
extern "C" int coli_cuda_init(const int *devices, int count) {
#if defined(__HIP_PLATFORM_AMD__) || defined(__HIP__)
/* #509: the ROCm runtime (comgr, MIOpen, roctracer) reads $TEMP as a temp-dir
@@ -934,12 +1004,17 @@ extern "C" int coli_cuda_tensor_upload(ColiCudaTensor **tensor,
/* fmt=6 keeps its scales inside each 98-byte block, so it is the one
* quantized format that legitimately arrives with scales == NULL. */
if (!rb || (fmt && fmt != 6 && !scales)) return 0;
+ if (fmt == 8 && !g_fp8_lut_ready) return 0; /* kernels would read a zero LUT */
ColiCudaTensor *t = static_cast<ColiCudaTensor *>(std::calloc(1, sizeof(*t)));
if (!t) return 0;
t->fmt = fmt; t->I = I; t->O = O; t->device = device; t->weight_bytes = rb * (size_t)O;
t->gs = (fmt==4 && g_upload_gs>0) ? g_upload_gs : 0;
t->ng = t->gs ? (I + t->gs - 1) / t->gs : 1;
t->scale_count = t->gs ? (size_t)O * (size_t)t->ng : (size_t)O;
+ if (fmt == 8) { /* per-128x128-block scales: [ceil(O/128), ceil(I/128)] */
+ t->ng = (I + 127) / 128;
+ t->scale_count = (size_t)((O + 127) / 128) * (size_t)t->ng;
+ }
if (!cuda_ok(cudaMalloc(&t->weights, t->weight_bytes), "tensor allocation") ||
!cuda_ok(cudaMemcpy(t->weights, weights, t->weight_bytes, cudaMemcpyHostToDevice), "tensor upload")) {
coli_cuda_tensor_free(t);
@@ -1268,7 +1343,7 @@ extern "C" int coli_cuda_expert_group(ColiCudaTensor *const *gates,
if (!first) return 0;
int device=first->device,D=first->I,I=first->O,total=0,max_rows=0;
GroupDesc host[64]; if(count>64) return 0;
- int all_s4=1,all_q4=1,any_g4=0,any_e8=0,all_e8=1;
+ int all_s4=1,all_q4=1,any_g4=0,any_e8=0,all_e8=1,any_f8=0,all_f8=1;
for(int c=0;c<count;c++){
ColiCudaTensor *g=gates[c],*u=ups[c],*d=downs[c];
if(!g||!u||!d||rows[c]<1||g->device!=device||u->device!=device||d->device!=device||
@@ -1282,10 +1357,12 @@ extern "C" int coli_cuda_expert_group(ColiCudaTensor *const *gates,
any_g4|=g->fmt==4||u->fmt==4||d->fmt==4;
any_e8|=g->fmt==6||u->fmt==6||d->fmt==6;
all_e8&=g->fmt==6&&u->fmt==6&&d->fmt==6;
+ any_f8|=g->fmt==8||u->fmt==8||d->fmt==8;
+ all_f8&=g->fmt==8&&u->fmt==8&&d->fmt==8;
total+=rows[c]; if(rows[c]>max_rows) max_rows=rows[c];
}
- /* Mixed E8 groups cannot use either homogeneous grouped kernel. */
- if(any_e8&&!all_e8){
+ /* Mixed E8/FP8 groups cannot use a homogeneous grouped kernel. */
+ if((any_e8&&!all_e8)||(any_f8&&!all_f8)){
int off=0;
for(int c=0;c<count;c++){
if(!coli_cuda_expert_mlp(gates[c],ups[c],downs[c],
@@ -1333,6 +1410,11 @@ extern "C" int coli_cuda_expert_group(ColiCudaTensor *const *gates,
grouped_hidden_e8_dual<<<hg,256,0,ctx->stream>>>(ctx->gate,ctx->x,dev,I,D);
if(!e8_rot_rows_dev(ctx->gate,total,I,ctx->stream))return 0;
grouped_down_e8<<<og,256,0,ctx->stream>>>(ctx->y,ctx->gate,dev,D,I);
+ }else if(all_f8){
+ /* fp8-e4m3 groups: silu fused in the dual epilogue, like the w4/g4 duals. */
+ dim3 hg((unsigned)I,(unsigned)max_rows,(unsigned)count),og((unsigned)D,(unsigned)max_rows,(unsigned)count);
+ grouped_hidden_f8_dual<<<hg,256,0,ctx->stream>>>(ctx->gate,ctx->up,ctx->x,dev,I,D);
+ grouped_down_f8<<<og,256,0,ctx->stream>>>(ctx->y,ctx->gate,dev,D,I);
}else if(tc){
size_t qb=(size_t)(total+7)*(size_t)(D>I?D:I)/2;
if(!reserve_bytes((void**)&ctx->qx,&ctx->qx_cap,qb)||
@@ -1453,7 +1535,7 @@ extern "C" int coli_cuda_expert_group_issue(ColiCudaTensor *const *gates,
ColiCudaTensor *first=gates[0];
if (!first) return 0;
int device=first->device,D=first->I,I=first->O,total=0,max_rows=0,all_s4=1,any_e8=0,all_e8=1,
- all_q4=1,any_g4=0;
+ all_q4=1,any_g4=0,any_f8=0,all_f8=1;
GroupDesc host[64];
for(int c=0;c<count;c++){
ColiCudaTensor *g=gates[c],*u=ups[c],*d=downs[c];
@@ -1468,9 +1550,12 @@ extern "C" int coli_cuda_expert_group_issue(ColiCudaTensor *const *gates,
all_q4&=(g->fmt==2||g->fmt==4)&&(u->fmt==2||u->fmt==4)&&(d->fmt==2||d->fmt==4)&&
!(g->gs&1)&&!(u->gs&1)&&!(d->gs&1); /* even gs: a packed byte never straddles groups */
any_g4|=g->fmt==4||u->fmt==4||d->fmt==4;
+ any_f8|=g->fmt==8||u->fmt==8||d->fmt==8;
+ all_f8&=g->fmt==8&&u->fmt==8&&d->fmt==8;
total+=rows[c]; if(rows[c]>max_rows) max_rows=rows[c];
}
if(any_e8&&!all_e8) return 0;
+ if(any_f8&&!all_f8) return 0; /* mixed FP8: no homogeneous kernel, sync path has the per-expert loop */
if(total>8) return 0; /* decode-scale only */
DeviceContext *ctx=find_ctx(device); if(!ctx||ctx->group_pending||!select_ctx(ctx)) return 0;
if(!prepare_group_weights(ctx,gates,ups,downs,count,host)) return 0;
@@ -1493,6 +1578,14 @@ extern "C" int coli_cuda_expert_group_issue(ColiCudaTensor *const *gates,
grouped_hidden_e8_dual<<<hg,256,0,ctx->stream>>>(ctx->gate,ctx->x,dev,I,D);
if(!e8_rot_rows_dev(ctx->gate,total,I,ctx->stream))return 0;
grouped_down_e8<<<og,256,0,ctx->stream>>>(ctx->y,ctx->gate,dev,D,I);
+ }else if(all_f8){
+ /* fp8-e4m3 groups on the async decode path: same kernels as the sync
+ * dispatch, silu fused in the dual epilogue. */
+ GroupDesc *dev=(GroupDesc*)ctx->group_desc;
+ dim3 hg((unsigned)I,(unsigned)max_rows,(unsigned)count);
+ dim3 og((unsigned)D,(unsigned)max_rows,(unsigned)count);
+ grouped_hidden_f8_dual<<<hg,256,0,ctx->stream>>>(ctx->gate,ctx->up,ctx->x,dev,I,D);
+ grouped_down_f8<<<og,256,0,ctx->stream>>>(ctx->y,ctx->gate,dev,D,I);
}else if(all_s4&&(!getenv("COLI_CUDA_W4_PACKED")||atoi(getenv("COLI_CUDA_W4_PACKED")))){
GroupDesc *dev=(GroupDesc*)ctx->group_desc;
dim3 hg((unsigned)I,(unsigned)max_rows,(unsigned)count);
@@ -1558,11 +1651,19 @@ extern "C" const float *coli_cuda_expert_group_take(int device) {
}
+/* The absorb kernels decode `w` through weight_at + absorb_scale, which know
+ * per-row and fmt=4 group scales only. Refuse anything else (fmt=5/6/8) rather
+ * than mis-decode it β€” the caller keeps its CPU attention path. (`proj`
+ * tensors are exempt: they run through quant_matmul, which dispatches every
+ * format it uploads.) A dedicated block-scale absorb for fmt=8 is follow-up
+ * work, same shape as routing fmt=4 through the grouped kernels was. */
+static int absorb_fmt_ok(const ColiCudaTensor *w){ return w && w->fmt <= 4; }
+
extern "C" int coli_cuda_attention_absorb(ColiCudaTensor *w,float *ctx,const float *q,
const float *latent,const float *rope,int H,int Q,
int R,int V,int K,int T,float scale){
if (fault_injected()) return 0;
- if(!w||!ctx||!q||!latent||!rope||H<1||Q<1||R<1||V<1||K<1||K>512||T<1||T>4096||
+ if(!absorb_fmt_ok(w)||!ctx||!q||!latent||!rope||H<1||Q<1||R<1||V<1||K<1||K>512||T<1||T>4096||
w->I!=K||w->O!=H*(Q+V))return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
size_t qb=(size_t)H*(Q+R)*sizeof(float),lb=(size_t)T*K*sizeof(float);
@@ -1584,7 +1685,7 @@ extern "C" int coli_cuda_attention_absorb(ColiCudaTensor *w,float *ctx,const flo
static int attention_absorb_batch_run(ColiCudaTensor *w,ColiCudaTensor *proj,float *out,
const float *q,const float *latent,const float *rope,int S,int H,int Q,int R,int V,
int K,int T,float scale){
- if(!w||!out||!q||!latent||!rope||S<1||H<1||Q<1||R<1||V<1||K<1||K>512||
+ if(!absorb_fmt_ok(w)||!out||!q||!latent||!rope||S<1||H<1||Q<1||R<1||V<1||K<1||K>512||
T<S||T>8192||w->I!=K||w->O!=H*(Q+V))return 0;
if(proj&&(proj->device!=w->device||proj->I!=H*V))return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
@@ -1630,7 +1731,7 @@ extern "C" int coli_cuda_attention_project_ragged(ColiCudaTensor *w,ColiCudaTens
float *out,const float *q,const void *const *keys,
const float *const *latent,const float *const *rope,
const int *lengths,int S,int H,int Q,int R,int V,int K,int T,float scale){
- if(!w||!proj||!out||!q||!keys||!latent||!rope||!lengths||S<1||S>512||T<1||T>8192||
+ if(!absorb_fmt_ok(w)||!proj||!out||!q||!keys||!latent||!rope||!lengths||S<1||S>512||T<1||T>8192||
H<1||Q<1||R<1||V<1||K<1||K>512||w->I!=K||w->O!=H*(Q+V)||
proj->device!=w->device||proj->I!=H*V)return 0;
DeviceContext *dc=find_ctx(w->device);
@@ -2052,7 +2153,7 @@ extern "C" int coli_cuda_attention_project_batch_dev(ColiCudaTensor *w,ColiCudaT
float *out,const float *q_dev,const float *latent_dev,const float *rope_dev,
int S,int H,int Q,int R,int V,int K,int T,float scale){
if (fault_injected()) return 0;
- if(!w||!proj||!out||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
+ if(!absorb_fmt_ok(w)||!proj||!out||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
K<1||K>512||T<S||T>8192||w->I!=K||w->O!=H*(Q+V)||
proj->device!=w->device||proj->I!=H*V)return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
@@ -2116,7 +2217,7 @@ extern "C" int coli_cuda_attention_project_batch_dev_out(ColiCudaTensor *w,ColiC
float *out_dev,const float *q_dev,const float *latent_dev,const float *rope_dev,
int S,int H,int Q,int R,int V,int K,int T,float scale){
if (fault_injected()) return 0;
- if(!w||!proj||!out_dev||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
+ if(!absorb_fmt_ok(w)||!proj||!out_dev||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
K<1||K>512||T<S||T>8192||w->I!=K||w->O!=H*(Q+V)||
proj->device!=w->device||proj->I!=H*V)return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
@@ -2138,7 +2239,7 @@ extern "C" int coli_cuda_attention_absorb_batch_dev(ColiCudaTensor *w,float *ctx
const float *q_dev,const float *latent_dev,const float *rope_dev,
int S,int H,int Q,int R,int V,int K,int T,float scale){
if (fault_injected()) return 0;
- if(!w||!ctx_dev||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
+ if(!absorb_fmt_ok(w)||!ctx_dev||!q_dev||!latent_dev||!rope_dev||S<1||H<1||Q<1||R<1||V<1||
K<1||K>512||T<S||T>8192||w->I!=K||w->O!=H*(Q+V))return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
size_t shared=(size_t)(2*K+T+256)*sizeof(float);
@@ -2153,7 +2254,7 @@ extern "C" int coli_cuda_attention_absorb_kvdev(ColiCudaTensor *w,float *ctx,con
const float *latent_dev,const float *rope_dev,int H,int Q,int R,int V,int K,int T,
float scale){
if (fault_injected()) return 0;
- if(!w||!ctx||!q||!latent_dev||!rope_dev||H<1||Q<1||R<1||V<1||K<1||K>512||T<1||T>8192||
+ if(!absorb_fmt_ok(w)||!ctx||!q||!latent_dev||!rope_dev||H<1||Q<1||R<1||V<1||K<1||K>512||T<1||T>8192||
w->I!=K||w->O!=H*(Q+V))return 0;
DeviceContext *dc=find_ctx(w->device);if(!select_ctx(dc))return 0;
size_t qb=(size_t)H*(Q+R)*sizeof(float),cb=(size_t)H*V*sizeof(float);
diff --git a/c/backend_cuda.h b/c/backend_cuda.h
index 9e2fc86a..8e3412bb 100644
--- a/c/backend_cuda.h
+++ b/c/backend_cuda.h
@@ -41,6 +41,11 @@ COLI_CUDA_DLLEXPORT void coli_cuda_group_stats(uint64_t *calls, uint64_t *expert
* backend keeps no copy of the table so it cannot drift from the CPU decoder. */
COLI_CUDA_DLLEXPORT int coli_cuda_e8_set_grid(const void *grid);
+/* Publish the fmt=8 e4m3 decode table (quant.h's E4M3_LUT, 256 f32) the same
+ * way. Must be called after coli_cuda_init; fmt=8 uploads are refused until it
+ * succeeds, because kernels would decode against a zero-initialized table. */
+COLI_CUDA_DLLEXPORT int coli_cuda_fp8_set_lut(const float *lut);
+
/* Upload without executing, so capacity failures happen during model startup. */
COLI_CUDA_DLLEXPORT int coli_cuda_tensor_upload_g(ColiCudaTensor **tensor,
const void *weights, const float *scales,
diff --git a/c/backend_loader.c b/c/backend_loader.c
index 434a4a8c..07e7b605 100644
--- a/c/backend_loader.c
+++ b/c/backend_loader.c
@@ -54,6 +54,7 @@ typedef int (*fn_tensor_upload)(ColiCudaTensor **tensor, const void *
const float *scales, int fmt, int I, int O, int device);
typedef int (*fn_tensor_upload_g)(ColiCudaTensor **tensor, const void *weights, const float *scales, int fmt, int I, int O, int device, int gs);
typedef int (*fn_e8_set_grid)(const void *grid);
+typedef int (*fn_fp8_set_lut)(const float *lut);
typedef int (*fn_matmul)(ColiCudaTensor **tensor, float *y, const float *x,
const void *weights, const float *scales,
int fmt, int S, int I, int O, int device, int gs);
@@ -118,6 +119,7 @@ static struct {
fn_tensor_upload tensor_upload;
fn_tensor_upload_g tensor_upload_g;
fn_e8_set_grid e8_set_grid;
+ fn_fp8_set_lut fp8_set_lut;
fn_matmul matmul;
fn_tensor_free tensor_free;
fn_tensor_bytes tensor_bytes;
@@ -232,6 +234,7 @@ static int coli_cuda_load(void){
RESOLVE(tensor_upload, fn_tensor_upload)
RESOLVE(tensor_upload_g, fn_tensor_upload_g)
RESOLVE_OPT(e8_set_grid, fn_e8_set_grid)
+ RESOLVE_OPT(fp8_set_lut, fn_fp8_set_lut)
RESOLVE(matmul, fn_matmul)
RESOLVE(tensor_free, fn_tensor_free)
RESOLVE(tensor_bytes, fn_tensor_bytes)
@@ -369,6 +372,11 @@ int coli_cuda_e8_set_grid(const void *grid){
return g_cuda.e8_set_grid(grid);
}
+int coli_cuda_fp8_set_lut(const float *lut){
+ if(!g_cuda.available || !g_cuda.fp8_set_lut) return 0; /* fmt=8 stays CPU-side */
+ return g_cuda.fp8_set_lut(lut);
+}
+
int coli_cuda_matmul(ColiCudaTensor **tensor, float *y, const float *x,
const void *weights, const float *scales,
int fmt, int S, int I, int O, int device, int gs){
diff --git a/c/colibri.c b/c/colibri.c
index aa8bc12c..696b0f8f 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -528,6 +528,7 @@ static void cuda_disabled_note(void){
CUDA_DISABLED_LOUD_AT);
}
static int g_cuda_e8_ready; /* codebook published to the devices (see cuda_boot) */
+static int g_cuda_fp8_ready; /* e4m3 LUT published to the devices (see cuda_boot) */
#endif
#ifdef COLI_VULKAN
/* Drop a QT's Vulkan-resident copy (slot reused for a different expert). */
@@ -557,16 +558,11 @@ static int vk_matmul_pair_qt(QT *a, float *ya, QT *b, float *yb, const float *x,
static int qt_cuda_upload(QT *t){
if(t->fmt==5) return 0; /* int3-g64: no CUDA kernel yet β€” tensor stays CPU-side */
if(t->fmt==6 && !g_cuda_e8_ready) return 0; /* E8 without its codebook would decode garbage */
- if(t->fmt==8) return 0; /* fp8-e4m3 passthrough: no CUDA kernel yet either (matches the
- * fmt=5/6 idiom above; matmul_qt_ex's own caller-side fmt exclusion
- * already keeps this from being reached with cuda_eligible tensors
- * in the exact-kernel path, but row_bytes()/weight_at() in
- * backend_cuda.cu have no fmt=8 case either -- explicit early-
- * return here so a future caller doesn't have to rediscover that by
- * tracing through to the CUDA source. UNVERIFIED at runtime: no CUDA
- * toolchain on this macOS build host to compile-check. */
+ if(t->fmt==8 && !g_cuda_fp8_ready) return 0; /* same idiom: fp8 without its e4m3 LUT stays
+ * CPU-side (an old DLL without the symbol
+ * leaves the flag 0, exactly like fmt=6) */
const void *weights = t->fmt==0 ? (const void*)t->qf
- : t->fmt==1 ? (const void*)t->q8 : (const void*)t->q4;
+ : (t->fmt==1||t->fmt==8) ? (const void*)t->q8 : (const void*)t->q4;
if(t->fmt==4) /* grouped int4 (#334): scales are [O, ceil(I/gs)] β€” the plain
* upload would truncate them to O floats and the group kernels
* would read garbage. An old DLL without the _g symbol returns 0
@@ -582,7 +578,7 @@ static int qt_cuda_upload_compressed(QT *t){
#endif
static int qt_cuda_update(QT *t){
const void *weights=t->fmt==0?(const void*)t->qf:
- t->fmt==1?(const void*)t->q8:(const void*)t->q4;
+ (t->fmt==1||t->fmt==8)?(const void*)t->q8:(const void*)t->q4;
return coli_cuda_tensor_update(t->cuda,weights,t->s);
}
static double g_ovl_issue,g_ovl_cpu,g_ovl_take,g_ovl_mark; /* Inc.4 overlap-window split (OVL report) */
@@ -859,17 +855,15 @@ static void matmul_qt_ex(float *y, const float *x, QT *w, int S, int allow_idot)
}
#endif
#ifdef COLI_CUDA
- /* fmt=8 excluded exactly like fmt=5/6: the CUDA backend's row_bytes()/weight_at()
- * (backend_cuda.cu) have no case for it and fall through to `return 0` / undefined
- * weight_at() behavior. row_bytes()==0 already makes coli_cuda_tensor_upload_g
- * refuse (defensive fail-closed), but that path is reached only after paying an
- * upload attempt and printing a "disabled after an error" message every load;
- * excluding it here up front is the same fmt=5/6 idiom, silent and immediate.
- * UNVERIFIED on this build (no CUDA toolchain on macOS to compile-check; traced
- * from backend_cuda.cu source only). */
- if(g_cuda_enabled && w->cuda_eligible && !w->cuda_failed && w->fmt!=5 && w->fmt!=8 && !omp_in_parallel()){
+ /* fmt=5 excluded like fmt=6-without-codebook: the CUDA backend has no int3
+ * kernel. fmt=8 flows once its e4m3 LUT is published (g_cuda_fp8_ready,
+ * cuda_boot): quant_matmul dispatches it by format, deriving the 128x128
+ * block-scale geometry from the dims alone. Without the LUT (old DLL) it is
+ * excluded up front β€” same silent-and-immediate idiom as fmt=5. */
+ if(g_cuda_enabled && w->cuda_eligible && !w->cuda_failed && w->fmt!=5 &&
+ (w->fmt!=8 || g_cuda_fp8_ready) && !omp_in_parallel()){
const void *weights = w->fmt==0 ? (const void*)w->qf
- : w->fmt==1 ? (const void*)w->q8 : (const void*)w->q4;
+ : (w->fmt==1||w->fmt==8) ? (const void*)w->q8 : (const void*)w->q4;
if(coli_cuda_matmul(&w->cuda,y,x,weights,w->s,w->fmt,S,w->I,w->O,w->cuda_device,w->gs)) return;
w->cuda_failed=1;
if(g_cuda_disabled_n < 8) /* keep the detail for the first few, then the summary */
@@ -9054,6 +9048,8 @@ int main(int argc, char **argv){
* the backend never keeps a second copy that could drift (#452). An older
* DLL without the symbol leaves this 0 and fmt=6 tensors stay CPU-side. */
g_cuda_e8_ready=coli_cuda_e8_set_grid(e8_grid);
+ /* fmt=8 decodes against quant.h's E4M3_LUT β€” same arrangement. */
+ g_cuda_fp8_ready=coli_cuda_fp8_set_lut(E4M3_LUT);
}
g_cuda_dense=getenv("CUDA_DENSE")?atoi(getenv("CUDA_DENSE")):0;
#endif
diff --git a/c/tests/test_fp8_cuda.cu b/c/tests/test_fp8_cuda.cu
new file mode 100644
index 00000000..c3965dc9
--- /dev/null
+++ b/c/tests/test_fp8_cuda.cu
@@ -0,0 +1,225 @@
+/* fmt=8 (fp8-e4m3) CUDA kernel oracle.
+ *
+ * Phase 1 feeds random e4m3 bytes + [ceil(O/128), ceil(I/128)] block scales
+ * through grouped_hidden_f8_dual / grouped_down_f8 and checks against a CPU
+ * reference that replicates matmul_fp8's semantics (LUT decode, one f32 scale
+ * per 128x128 block, float accumulate within a block, double across blocks).
+ * Dims are chosen so both the row- and column-block axes have a partial tail
+ * block. The dual hidden kernel fuses silu into its epilogue (gate[] holds
+ * silu(g)*u, up[] is never written), same contract as the w4/g4 duals.
+ *
+ * The e4m3 reference decoder is computed arithmetically here (sign/exp/mant,
+ * OCP E4M3-FN: no infinities, only 0x7F/0xFF are NaN), so it cross-checks the
+ * engine-supplied LUT rather than assuming it. NaN bytes are excluded from the
+ * random draw: the format's NaN policy is propagation, which a bitwise/relative
+ * compare cannot express.
+ *
+ * Phase 2 goes through the public API: the upload gate must REFUSE fmt=8
+ * before coli_cuda_fp8_set_lut publishes the decode table (a kernel against
+ * the zero-initialized table would compute silent zeros), then accept it.
+ * After that: coli_cuda_matmul (dense quant_matmul branch) vs the reference,
+ * coli_cuda_expert_group (sync) vs the reference, and issue/take (async) vs
+ * sync, which must match bit for bit.
+ *
+ * Build: nvcc -O2 -std=c++17 -arch=native tests/test_fp8_cuda.cu -o tests/test_fp8
+ */
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <cuda_runtime.h>
+
+#include "../backend_cuda.cu"
+
+static float e4m3_ref(uint8_t b){
+ int s=b>>7, e=(b>>3)&15, m=b&7;
+ if(e==15&&m==7) return NAN; /* E4M3-FN: only NaN, no inf */
+ float v = e ? ldexpf(1.f+m/8.f, e-7) : ldexpf(m/8.f, -6);
+ return s ? -v : v;
+}
+
+static uint8_t rnd_e4m3(void){ /* any byte except the two NaNs */
+ uint8_t b=(uint8_t)(rand()&255);
+ if((b&0x7F)==0x7F) b&=(uint8_t)~1;
+ return b;
+}
+
+/* matmul_fp8's accumulation, one output element: float within a 128-block,
+ * double across blocks, block scale applied on the block subtotal. */
+static void cpu_gemv_f8(const uint8_t *q,const float *sc,int K,int O,
+ const float *x,float *y){
+ int nblk=(K+127)/128;
+ for(int o=0;o<O;o++){
+ const uint8_t *w=q+(size_t)o*K;
+ const float *scl=sc+(size_t)(o/128)*nblk;
+ double a=0;
+ for(int b=0;b*128<K;b++){
+ int base=b*128, len=K-base<128?K-base:128; float acc=0;
+ for(int i=base;i<base+len;i++) acc+=e4m3_ref(w[i])*x[i];
+ a+=(double)acc*scl[b];
+ }
+ y[o]=(float)a;
+ }
+}
+
+#define COUNT 3
+int main(void){
+ srand(8);
+ const int D=320, I=192; /* hidden [I,D]: 2x3 blocks; down [D,I]: 3x2 */
+ const int nbD=(D+127)/128, nbI=(I+127)/128;
+ const int hs_n=nbI*nbD, ds_n=nbD*nbI; /* block-scale counts, tails included */
+ float lut[256]; for(int i=0;i<256;i++) lut[i]=e4m3_ref((uint8_t)i);
+
+ /* ---- Phase 1: raw kernels vs reference --------------------------------- */
+ cudaDeviceProp prop; cudaGetDeviceProperties(&prop,0);
+ printf("[CUDA] device 0: %s, %.1f GB VRAM, sm_%d%d\n",prop.name,
+ prop.totalGlobalMem/1e9,prop.major,prop.minor);
+ if(cudaMemcpyToSymbol(c_e4m3,lut,sizeof(lut))!=cudaSuccess){ printf("FAIL lut\n"); return 1; }
+
+ int rows[COUNT]={1,2,1}, total=4, bad=0, trials=50;
+ for(int t=0;t<trials;t++){
+ uint8_t *hg[COUNT],*hu[COUNT],*hd[COUNT]; float *hgs[COUNT],*hus[COUNT],*hds[COUNT];
+ GroupDesc host[COUNT]; int off=0;
+ for(int c=0;c<COUNT;c++){
+ hg[c]=(uint8_t*)malloc((size_t)I*D); hu[c]=(uint8_t*)malloc((size_t)I*D);
+ hd[c]=(uint8_t*)malloc((size_t)D*I);
+ hgs[c]=(float*)malloc(hs_n*4); hus[c]=(float*)malloc(hs_n*4); hds[c]=(float*)malloc(ds_n*4);
+ for(size_t i=0;i<(size_t)I*D;i++){ hg[c][i]=rnd_e4m3(); hu[c][i]=rnd_e4m3(); }
+ for(size_t i=0;i<(size_t)D*I;i++) hd[c][i]=rnd_e4m3();
+ for(int i=0;i<hs_n;i++){ hgs[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12);
+ hus[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12); }
+ for(int i=0;i<ds_n;i++) hds[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12);
+ void *dg,*du,*dd,*dgs,*dus,*dds;
+ cudaMalloc(&dg,(size_t)I*D); cudaMalloc(&du,(size_t)I*D); cudaMalloc(&dd,(size_t)D*I);
+ cudaMalloc(&dgs,hs_n*4); cudaMalloc(&dus,hs_n*4); cudaMalloc(&dds,ds_n*4);
+ cudaMemcpy(dg,hg[c],(size_t)I*D,cudaMemcpyHostToDevice);
+ cudaMemcpy(du,hu[c],(size_t)I*D,cudaMemcpyHostToDevice);
+ cudaMemcpy(dd,hd[c],(size_t)D*I,cudaMemcpyHostToDevice);
+ cudaMemcpy(dgs,hgs[c],hs_n*4,cudaMemcpyHostToDevice);
+ cudaMemcpy(dus,hus[c],hs_n*4,cudaMemcpyHostToDevice);
+ cudaMemcpy(dds,hds[c],ds_n*4,cudaMemcpyHostToDevice);
+ host[c]={dg,du,dd,(const float*)dgs,(const float*)dus,(const float*)dds,
+ 8,8,8,rows[c],off,0,0,0};
+ off+=rows[c];
+ }
+ float *xs=(float*)malloc((size_t)total*D*4);
+ for(size_t i=0;i<(size_t)total*D;i++) xs[i]=(rand()/(float)RAND_MAX-.5f)*2.f;
+ void *ddesc,*dx,*dgate,*dup,*dy;
+ cudaMalloc(&ddesc,sizeof(host)); cudaMalloc(&dx,(size_t)total*D*4);
+ cudaMalloc(&dgate,(size_t)total*I*4); cudaMalloc(&dup,(size_t)total*I*4);
+ cudaMalloc(&dy,(size_t)total*D*4);
+ cudaMemcpy(ddesc,host,sizeof(host),cudaMemcpyHostToDevice);
+ cudaMemcpy(dx,xs,(size_t)total*D*4,cudaMemcpyHostToDevice);
+ dim3 hgd((unsigned)I,2,COUNT),ogd((unsigned)D,2,COUNT);
+ grouped_hidden_f8_dual<<<hgd,256>>>((float*)dgate,(float*)dup,(const float*)dx,
+ (const GroupDesc*)ddesc,I,D);
+ grouped_down_f8<<<ogd,256>>>((float*)dy,(const float*)dgate,(const GroupDesc*)ddesc,D,I);
+ if(cudaDeviceSynchronize()!=cudaSuccess){ printf("FAIL cuda\n"); return 1; }
+ float *gate=(float*)malloc((size_t)total*I*4),*y=(float*)malloc((size_t)total*D*4);
+ cudaMemcpy(gate,dgate,(size_t)total*I*4,cudaMemcpyDeviceToHost);
+ cudaMemcpy(y,dy,(size_t)total*D*4,cudaMemcpyDeviceToHost);
+ for(int c=0;c<COUNT;c++){
+ for(int s=0;s<rows[c];s++){
+ float rg[512],ru[512],rh[512],ry[512];
+ const float *xr=xs+(size_t)(host[c].offset+s)*D;
+ cpu_gemv_f8(hg[c],hgs[c],D,I,xr,rg);
+ cpu_gemv_f8(hu[c],hus[c],D,I,xr,ru);
+ for(int o=0;o<I;o++) rh[o]=(rg[o]/(1.f+expf(-rg[o])))*ru[o];
+ for(int o=0;o<I;o++){
+ float got=gate[(size_t)(host[c].offset+s)*I+o];
+ if(fabsf(got-rh[o])>1e-3f*(fabsf(rh[o])+1e-3f)) bad++;
+ }
+ cpu_gemv_f8(hd[c],hds[c],I,D,rh,ry);
+ for(int o=0;o<D;o++){
+ float got=y[(size_t)(host[c].offset+s)*D+o];
+ if(fabsf(got-ry[o])>1e-3f*(fabsf(ry[o])+1e-3f)) bad++;
+ }
+ }
+ }
+ for(int c=0;c<COUNT;c++){ cudaFree((void*)host[c].g);cudaFree((void*)host[c].u);cudaFree((void*)host[c].d);
+ cudaFree((void*)host[c].gs);cudaFree((void*)host[c].us);cudaFree((void*)host[c].ds);
+ free(hg[c]);free(hu[c]);free(hd[c]);free(hgs[c]);free(hus[c]);free(hds[c]); }
+ cudaFree(ddesc);cudaFree(dx);cudaFree(dgate);cudaFree(dup);cudaFree(dy);
+ free(xs);free(gate);free(y);
+ }
+ printf("fp8 oracle: %d trials x %d experts (128-blocks + row/col tails), %d mismatches\n",
+ trials,COUNT,bad);
+ if(bad){ printf("FAIL\n"); return 1; }
+
+ /* ---- Phase 2: public API β€” LUT gate, dense matmul, sync group, async ---- */
+ {
+ int devs[1]={0};
+ if(!coli_cuda_init(devs,1)){ printf("FAIL cuda init\n"); return 1; }
+ uint8_t *hw=(uint8_t*)malloc((size_t)I*D); float *hsc=(float*)malloc(hs_n*4);
+ for(size_t i=0;i<(size_t)I*D;i++) hw[i]=rnd_e4m3();
+ for(int i=0;i<hs_n;i++) hsc[i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12);
+ ColiCudaTensor *tt=nullptr;
+ /* The gate must hold until the LUT is published: a zero table would
+ * make every fmt=8 matmul a silent zero. */
+ if(coli_cuda_tensor_upload(&tt,hw,hsc,8,D,I,0)){ printf("FAIL gate open before LUT\n"); return 1; }
+ if(!coli_cuda_fp8_set_lut(lut)){ printf("FAIL set_lut\n"); return 1; }
+ if(!coli_cuda_tensor_upload(&tt,hw,hsc,8,D,I,0)){ printf("FAIL upload\n"); return 1; }
+
+ int api_bad=0;
+ { /* dense: quant_matmul's fmt=8 branch */
+ const int S=2;
+ float *x=(float*)malloc((size_t)S*D*4),*y=(float*)malloc((size_t)S*I*4),ry[512];
+ for(size_t i=0;i<(size_t)S*D;i++) x[i]=(rand()/(float)RAND_MAX-.5f)*2.f;
+ if(!coli_cuda_matmul(&tt,y,x,hw,hsc,8,S,D,I,0,0)){ printf("FAIL dense matmul\n"); return 1; }
+ for(int s=0;s<S;s++){
+ cpu_gemv_f8(hw,hsc,D,I,x+(size_t)s*D,ry);
+ for(int o=0;o<I;o++)
+ if(fabsf(y[(size_t)s*I+o]-ry[o])>1e-3f*(fabsf(ry[o])+1e-3f)) api_bad++;
+ }
+ free(x);free(y);
+ }
+ int rows2[COUNT]={1,2,1}, total2=4;
+ ColiCudaTensor *tg[COUNT]={},*tu[COUNT]={},*td[COUNT]={};
+ uint8_t *hg[COUNT],*hu[COUNT],*hd[COUNT]; float *hgs[COUNT],*hus[COUNT],*hds[COUNT];
+ for(int c=0;c<COUNT;c++){
+ hg[c]=(uint8_t*)malloc((size_t)I*D); hu[c]=(uint8_t*)malloc((size_t)I*D);
+ hd[c]=(uint8_t*)malloc((size_t)D*I);
+ hgs[c]=(float*)malloc(hs_n*4); hus[c]=(float*)malloc(hs_n*4); hds[c]=(float*)malloc(ds_n*4);
+ for(size_t i=0;i<(size_t)I*D;i++){ hg[c][i]=rnd_e4m3(); hu[c][i]=rnd_e4m3(); }
+ for(size_t i=0;i<(size_t)D*I;i++) hd[c][i]=rnd_e4m3();
+ for(int i=0;i<hs_n;i++){ hgs[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12);
+ hus[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12); }
+ for(int i=0;i<ds_n;i++) hds[c][i]=ldexpf(1.f+rand()/(float)RAND_MAX,-12);
+ if(!coli_cuda_tensor_upload(&tg[c],hg[c],hgs[c],8,D,I,0)||
+ !coli_cuda_tensor_upload(&tu[c],hu[c],hus[c],8,D,I,0)||
+ !coli_cuda_tensor_upload(&td[c],hd[c],hds[c],8,I,D,0)){
+ printf("FAIL expert upload\n"); return 1; }
+ }
+ float *x=(float*)malloc((size_t)total2*D*4),*ysync=(float*)malloc((size_t)total2*D*4);
+ for(size_t i=0;i<(size_t)total2*D;i++) x[i]=(rand()/(float)RAND_MAX-.5f)*2.f;
+ if(!coli_cuda_expert_group(tg,tu,td,rows2,COUNT,ysync,x)){ printf("FAIL sync group\n"); return 1; }
+ if(!coli_cuda_expert_group_issue(tg,tu,td,rows2,COUNT,x)){ printf("FAIL async issue\n"); return 1; }
+ const float *yasync=coli_cuda_expert_group_take(0);
+ if(!yasync){ printf("FAIL async take\n"); return 1; }
+ int off=0;
+ for(int c=0;c<COUNT;c++){
+ for(int s=0;s<rows2[c];s++){
+ float rg[512],ru[512],rh[512],ry[512];
+ const float *xr=x+(size_t)(off+s)*D;
+ cpu_gemv_f8(hg[c],hgs[c],D,I,xr,rg);
+ cpu_gemv_f8(hu[c],hus[c],D,I,xr,ru);
+ for(int o=0;o<I;o++) rh[o]=(rg[o]/(1.f+expf(-rg[o])))*ru[o];
+ cpu_gemv_f8(hd[c],hds[c],I,D,rh,ry);
+ for(int o=0;o<D;o++){
+ size_t z=(size_t)(off+s)*D+o;
+ if(fabsf(ysync[z]-ry[o])>1e-3f*(fabsf(ry[o])+1e-3f)) api_bad++;
+ if(yasync[z]!=ysync[z]) api_bad++; /* async == sync, bitwise */
+ }
+ }
+ off+=rows2[c];
+ }
+ printf("fp8 API: LUT gate + dense vs oracle + sync group vs oracle + async vs sync, %d mismatches\n",api_bad);
+ coli_cuda_tensor_free(tt);
+ for(int c=0;c<COUNT;c++){ coli_cuda_tensor_free(tg[c]);coli_cuda_tensor_free(tu[c]);coli_cuda_tensor_free(td[c]);
+ free(hg[c]);free(hu[c]);free(hd[c]);free(hgs[c]);free(hus[c]);free(hds[c]); }
+ free(x);free(ysync);free(hw);free(hsc);
+ coli_cuda_shutdown();
+ if(api_bad){ printf("FAIL\n"); return 1; }
+ }
+ printf("OK\n"); return 0;
+}