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

Metal: chunk coli_metal_gemm to fix grid-size truncation at large prefill

Doug Sharpa0b929c15305
diff --git a/c/Makefile b/c/Makefile
index 1799b6b5..f626652d 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -311,6 +311,12 @@ 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
+# Standalone large-batch GEMM correctness sweep — reproduces the long-context prefill
+# corruption in seconds (no model). OMP-parallel CPU reference.
+gemm-test: tests/test_gemm_largebatch.mm backend_metal.mm backend_metal.h
+ $(METALXX) $(OMPC) tests/test_gemm_largebatch.mm backend_metal.mm $(OMPL) -framework Metal -framework Foundation -o gemm_largebatch_test
+ ./gemm_largebatch_test
+
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)
diff --git a/c/backend_metal.mm b/c/backend_metal.mm
index 6ec3fb4f..cc05106c 100644
--- a/c/backend_metal.mm
+++ b/c/backend_metal.mm
@@ -839,12 +839,29 @@ extern "C" int coli_metal_gemm(float *y, const float *x, const void *wp, const f
[e useResource:wb usage:MTLResourceUsageRead]; [e useResource:sb usage:MTLResourceUsageRead];
[e setComputePipelineState:g_gemv];
[e setBuffer:wb offset:woff atIndex:0]; [e setBuffer:sb offset:soff atIndex:1];
- [e setBuffer:g_gx offset:0 atIndex:2]; [e setBuffer:g_gy offset:0 atIndex:3];
- int NT=S*O;
- [e setBytes:&S length:4 atIndex:4]; [e setBytes:&I length:4 atIndex:5];
+ [e setBytes:&I length:4 atIndex:5];
[e setBytes:&O length:4 atIndex:6]; [e setBytes:&fmt length:4 atIndex:7];
- [e setBytes:&NT length:4 atIndex:8];
- [e dispatchThreadgroups:MTLSizeMake(((size_t)NT+3)/4,1,1) threadsPerThreadgroup:MTLSizeMake(128,1,1)];
+ // Grid-size cap. One dispatch of NT=S*O output elements launches (NT+3)/4 threadgroups; past
+ // a device grid limit (observed on M-series: kv_b grid ~3.1e7 tg clean at S=4376, ~5.4e7 tg
+ // CORRUPT at S=7478) rows beyond the limit are silently never computed and the output keeps
+ // its prior contents -- fresh-zero standalone (nerr=1.0), stale scratch in-engine (the
+ // nondeterministic long-context corruption). Chunk over rows so each dispatch stays <=2^25
+ // elements (grid <=2^23 tg, ~4x under the observed-clean bound). Chunks write disjoint g_gy
+ // ranges; g_gx/g_gy offsets are 16B-aligned (I,O multiples of 4).
+ // COLI_GEMM_CHUNK=0 disables chunking (one full dispatch = the buggy pre-fix behavior) so the
+ // fix can be A/B'd on a single binary. Default on.
+ static int chunk_on=-1;
+ if(chunk_on<0){ const char*e=getenv("COLI_GEMM_CHUNK"); chunk_on=(e&&e[0]=='0'&&!e[1])?0:1; }
+ const int64_t NT_MAX = chunk_on ? ((int64_t)1<<25) : ((int64_t)1<<62);
+ int CH=(int)(NT_MAX/O); if(CH<1) CH=1; if((int64_t)CH>S) CH=S;
+ for(int r0=0;r0<S;r0+=CH){
+ int ch=(S-r0<CH)?(S-r0):CH; int NT=ch*O;
+ [e setBuffer:g_gx offset:(size_t)r0*I*4 atIndex:2];
+ [e setBuffer:g_gy offset:(size_t)r0*O*4 atIndex:3];
+ [e setBytes:&ch length:4 atIndex:4];
+ [e setBytes:&NT length:4 atIndex:8];
+ [e dispatchThreadgroups:MTLSizeMake(((size_t)NT+3)/4,1,1) threadsPerThreadgroup:MTLSizeMake(128,1,1)];
+ }
[e endEncoding]; [cb commit]; [cb waitUntilCompleted];
if(cb.status==MTLCommandBufferStatusError){ fprintf(stderr,"[metal] gemm cmdbuf error (S=%d O=%d)\n",S,O); return 0; }
memcpy(y,[g_gy contents],(size_t)S*O*4);
diff --git a/c/tests/test_gemm_largebatch.mm b/c/tests/test_gemm_largebatch.mm
new file mode 100644
index 00000000..fbfa6a41
--- /dev/null
+++ b/c/tests/test_gemm_largebatch.mm
@@ -0,0 +1,106 @@
+// Standalone large-batch correctness test for coli_metal_gemm — reproduces the
+// long-context OpenCode prefill corruption WITHOUT the model or a 33-minute run.
+//
+// Isolation established (see INVESTIGATION_LOG_metal_moe_race.md): corruption <=> dense
+// GEMM on GPU (`coli_metal_gemm`), independent of MoE. The engine's existing kernel tests
+// only exercise S<=64, which is why the S>=~2400 fault was never caught.
+//
+// This sweeps S across the clean/corrupt bracket for a few real GLM matmul shapes,
+// compares GPU vs CPU reference, prints the first diverging (row,col), AND runs the GPU
+// twice to report determinism (race vs fixed compute error).
+//
+// Build/run: make gemm-test
+#include "../backend_metal.h"
+#include <cstdio>
+#include <cstdlib>
+#include <cstring>
+#include <cmath>
+#include <vector>
+
+enum { I8=1, I4=2 };
+
+// CPU reference: dequant->f32 MAC * per-row scale. OMP-parallel over output cols so the
+// big shapes stay fast.
+static void cpu_ref(int fmt, const void *W, const float *s, const float *x,
+ float *y, int S, int I, int O) {
+ const int8_t *q8 = (const int8_t*)W; const uint8_t *q4 = (const uint8_t*)W;
+ int rb4=(I+1)/2;
+ #pragma omp parallel for schedule(static)
+ for (int o=0;o<O;o++) for (int si=0;si<S;si++){
+ const float *xr = x + (size_t)si*I; float acc=0;
+ for (int i=0;i<I;i++){
+ float w;
+ if (fmt==I8) w=(float)q8[(size_t)o*I+i];
+ else { uint8_t b=q4[(size_t)o*rb4+(i>>1)]; int v=(i&1)?(b>>4):(b&0xF); w=(float)(v-8); }
+ acc += w*xr[i];
+ }
+ y[(size_t)si*O+o]=acc*s[o];
+ }
+}
+
+static size_t roundpg(size_t n){ size_t p=16384; return ((n+p-1)/p)*p; }
+
+// One (fmt,O,I,S) case: GPU vs CPU + GPU-vs-GPU determinism. Returns 0 = clean.
+static int run_gemm(int fmt, int O, int I, int S, const char *name) {
+ int rb4=(I+1)/2;
+ size_t wn = (fmt==I8)?(size_t)O*I : (size_t)O*rb4;
+ size_t wb = roundpg(wn), sb = roundpg((size_t)O*4);
+ uint8_t *W=nullptr; float *Sc=nullptr;
+ posix_memalign((void**)&W,16384,wb); posix_memalign((void**)&Sc,16384,sb);
+ srand(1234 + S*7 + fmt);
+ for(size_t i=0;i<wn;i++) W[i]=(uint8_t)((fmt==I8)?((rand()%255)-127):(rand()&0xFF));
+ for(int i=0;i<O;i++) Sc[i]=0.01f+(rand()%50)/50000.f;
+ coli_metal_register(W,wb); coli_metal_register(Sc,sb);
+
+ std::vector<float> x((size_t)S*I), yr((size_t)S*O), yg((size_t)S*O), yg2((size_t)S*O);
+ for(auto&v:x) v=((rand()%2000)-1000)/1000.f;
+
+ cpu_ref(fmt, W, Sc, x.data(), yr.data(), S, I, O);
+ int ok1 = coli_metal_gemm(yg.data(), x.data(), W, Sc, fmt, S, I, O);
+ int ok2 = coli_metal_gemm(yg2.data(), x.data(), W, Sc, fmt, S, I, O);
+
+ // GPU vs CPU: max normalized error + first diverging element.
+ double maxabs=0, ymax=0; long badidx=-1;
+ for(size_t i=0;i<(size_t)S*O;i++){
+ double d=fabs((double)yg[i]-yr[i]);
+ if(d>maxabs) maxabs=d;
+ if(fabs(yr[i])>ymax) ymax=fabs(yr[i]);
+ if(badidx<0 && d > 1e-2*(fabs(yr[i])+1e-6)) badidx=(long)i;
+ }
+ double nerr = maxabs/(ymax+1e-9);
+ // GPU vs GPU: determinism.
+ long detdiff=0; for(size_t i=0;i<(size_t)S*O;i++) if(yg[i]!=yg2[i]) detdiff++;
+
+ int clean = ok1 && ok2 && nerr < 1e-3;
+ printf(" %-26s S=%-5d O=%-6d I=%-5d nerr=%.2e det:%s %s",
+ name, S, O, I, nerr,
+ detdiff? "RACE(diff)" : "same",
+ clean? "ok" : "*** CORRUPT");
+ if(badidx>=0) printf(" first-bad row=%ld col=%ld (gpu=%.4g cpu=%.4g)",
+ badidx/O, badidx%O, (double)yg[badidx], (double)yr[badidx]);
+ if(detdiff) printf(" [%ld/%zu gpu elems differ run-to-run]", detdiff, (size_t)S*O);
+ printf("\n");
+
+ coli_metal_unregister(W); coli_metal_unregister(Sc); free(W); free(Sc);
+ return clean?0:1;
+}
+
+int main(void){
+ if(!coli_metal_init()){ printf("Metal unavailable (skipping)\n"); return 0; }
+ printf("coli_metal_gemm large-batch sweep (GPU vs CPU, + determinism):\n");
+ int fail=0;
+ // Real GLM-5.2 matmul shapes. kv_b (O=28672,I=512) has the largest S*O.
+ struct { int O,I; const char*n; } shapes[] = {
+ { 2048, 6144, "gate/up (O2048,I6144)" },
+ { 6144, 2048, "down (O6144,I2048)" },
+ { 28672, 512, "kv_b (O28672,I512)" },
+ };
+ int Ss[] = { 512, 2153, 4376, 7478 }; // clean control / clean bracket / corrupt bracket / worst
+ for(auto &sh : shapes){
+ for(int S : Ss) fail |= run_gemm(I4, sh.O, sh.I, S, sh.n);
+ printf("\n");
+ }
+ printf(fail? "GEMM large-batch: CORRUPTION DETECTED\n" : "GEMM large-batch: all clean\n");
+ coli_metal_shutdown();
+ return fail;
+}