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: fmt=4 grouped-int4 GEMV support (mm_gemv + host plumbing) + tests

monotophic5407494ed772
diff --git a/c/backend_metal.h b/c/backend_metal.h
index 35c4931c..0c79ca2d 100644
--- a/c/backend_metal.h
+++ b/c/backend_metal.h
@@ -27,16 +27,19 @@ void coli_metal_stats(size_t *tensor_count, size_t *tensor_bytes);
int coli_metal_mem_info(size_t *used_bytes, size_t *total_bytes);
/*
- * y[S,O] = (x[S,I] @ W[O,I]^T) * scale[o].
- * fmt matches QT in glm.c: 0=f32, 1=int8, 2=int4(packed), 3=int2(packed).
- * The first successful call wraps W and its row scales in GPU-visible buffers;
- * later calls reuse them (weights are assumed stable at the same address).
+ * y[S,O] = (x[S,I] @ W[O,I]^T) * scale[o]. fmt=4 (grouped int4) instead folds a
+ * PER-GROUP scale into the accumulation -- see the shader comment in backend_metal.mm.
+ * fmt matches QT in colibri.c: 0=f32, 1=int8, 2=int4(packed), 3=int2(packed),
+ * 4=int4(packed, same layout as 2)+per-group scale (gs = group size along I; scale
+ * array is [O, ceil(I/gs)] floats instead of [O]). gs is ignored for fmt!=4 (pass 0).
+ * The first successful call wraps W and its scales in GPU-visible buffers (sized from
+ * fmt+gs); later calls reuse them (weights are assumed stable at the same address).
* Returns 1 on success, 0 if Metal is unavailable or fmt is invalid.
*/
int coli_metal_matmul(ColiMetalTensor **tensor,
float *y, const float *x,
const void *weights, const float *scales,
- int fmt, int S, int I, int O);
+ int fmt, int S, int I, int O, int gs);
void coli_metal_tensor_free(ColiMetalTensor *tensor);
size_t coli_metal_tensor_bytes(const ColiMetalTensor *tensor);
@@ -68,14 +71,14 @@ void coli_metal_unregister(void *base);
*/
int coli_metal_layer_decode(float *x,
const float *in_ln, const float *post_ln,
- const void *qa_w, const float *qa_s, int qa_fmt, const float *qa_ln,
- const void *qb_w, const float *qb_s, int qb_fmt,
- const void *kva_w, const float *kva_s, int kva_fmt, const float *kva_ln,
+ const void *qa_w, const float *qa_s, int qa_fmt, int qa_gs, const float *qa_ln,
+ const void *qb_w, const float *qb_s, int qb_fmt, int qb_gs,
+ const void *kva_w, const float *kva_s, int kva_fmt, int kva_gs, const float *kva_ln,
const void *kvb_w, const float *kvb_s, int kvb_fmt,
- const void *o_w, const float *o_s, int o_fmt,
- const void *shg_w, const float *shg_s, int shg_fmt,
- const void *shu_w, const float *shu_s, int shu_fmt,
- const void *shd_w, const float *shd_s, int shd_fmt,
+ const void *o_w, const float *o_s, int o_fmt, int o_gs,
+ const void *shg_w, const float *shg_s, int shg_fmt, int shg_gs,
+ const void *shu_w, const float *shu_s, int shu_fmt, int shu_gs,
+ const void *shd_w, const float *shd_s, int shd_fmt, int shd_gs,
const float *router_w, const float *router_bias,
int E, int K, int Ksel, float topp, int normk, float rscale,
float *Lc, float *Rc, int S, int pos_base, int st0,
@@ -83,7 +86,7 @@ int coli_metal_layer_decode(float *x,
float *inrm_out, float *nrm_out, float *sh_out, int *idx_out, float *w_out, int *keff_out);
int coli_metal_gemm(float *y, const float *x, const void *weights, const float *scales,
- int fmt, int S, int I, int O); /* large-batch sync GEMM; 0 -> CPU */
+ int fmt, int S, int I, int O, int gs); /* large-batch sync GEMM; 0 -> CPU. gs: fmt=4 group size (0 otherwise) */
/* Parallel top-8 expert selection (r_top8_par): run ONE top-8 selection kernel standalone
* on host arrays — par=0 the serial r_top8, par=1 the parallel exact-match replica gated
* in the engine by COLI_RTOP8 (default ON; COLI_RTOP8=0 opts out to the serial kernel).
@@ -104,11 +107,11 @@ int coli_metal_rtop8(int par, const float *sig, const float *bias, int S, int E,
void coli_metal_attn_counts(uint64_t *ok, double *wall, double *kernel);
void coli_metal_attn_lat(double *ksched, double *gsched);
int coli_metal_attn_decode(const float *x,
- const void *qa_w, const float *qa_s, int qa_fmt, const float *qa_ln,
- const void *qb_w, const float *qb_s, int qb_fmt,
- const void *kva_w, const float *kva_s, int kva_fmt, const float *kva_ln,
+ const void *qa_w, const float *qa_s, int qa_fmt, int qa_gs, const float *qa_ln,
+ const void *qb_w, const float *qb_s, int qb_fmt, int qb_gs,
+ const void *kva_w, const float *kva_s, int kva_fmt, int kva_gs, const float *kva_ln,
const void *kvb_w, const float *kvb_s, int kvb_fmt,
- const void *o_w, const float *o_s, int o_fmt,
+ const void *o_w, const float *o_s, int o_fmt, int o_gs,
float *Lc, float *Rc, int S, int pos_base, int st0, float eps, float theta, float ascale, float *out);
/* Diagnostics: GPU blocks executed, CPU-fallback blocks, experts run on GPU. */
@@ -129,7 +132,11 @@ int coli_metal_resset_stats(double *flush_s);
* D = hidden size, Iinter = moe intermediate size
* g/u/d[e] = pointers to expert e's gate/up/down quantized weights (in RAM slabs)
* gs/us/ds[e] = pointers to expert e's per-row scales
- * fmt = quant format (shared across experts)
+ * fmt = quant format (shared across experts). NOTE: fmt=4 (grouped int4) is
+ * NOT yet supported here -- gates to {1,2} and returns 0 (CPU fallback)
+ * for fmt=4 experts, same as before this stage. Grouped-int4 gained GPU
+ * support in mm_gemv (coli_metal_matmul/coli_metal_gemm/bind_gemv) only;
+ * extending the batched routed-expert path is future work (see PR_BODY.md).
* xg = packed activations [total_rows, D]; xoff[e] = row offset of expert e
* nr[e] = rows for expert e; rows[]/rw[] map packed rows back to out positions
* out = [S, D] accumulate target
diff --git a/c/backend_metal.mm b/c/backend_metal.mm
index 2894d791..73a0836d 100644
--- a/c/backend_metal.mm
+++ b/c/backend_metal.mm
@@ -9,17 +9,22 @@
// ---- shader: general quantized GEMV, one threadgroup per output element (o,si) ----
// y[si,o] = (sum_i dequant(W[o,i]) * x[si,i]) * scale[o]. fmt: 0=f32 1=i8 2=i4 3=i2.
+// fmt=4 (grouped int4, dev e9b3614 matmul_i4_grouped, #298/#451 CUDA twin): same packed
+// nibble layout as fmt=2, but scale is PER-GROUP (gsz elements of I), buffer(1) holds
+// [O, ceil(I/gsz)] floats indexed scale[o*ng+g] -- so unlike fmt 1-3, the group scale is
+// folded into the accumulation itself (see the fmt==4 branch), not applied once at the end.
static const char *SHADER = R"METAL(
#include <metal_stdlib>
using namespace metal;
kernel void mm_gemv(device const uchar* w [[buffer(0)]], // raw weight bytes
- device const float* scale [[buffer(1)]], // [O]
+ device const float* scale [[buffer(1)]], // [O] (fmt<4) or [O,ceil(I/gsz)] (fmt==4)
device const float* x [[buffer(2)]], // [S,I]
device float* y [[buffer(3)]], // [S,O]
constant int& S [[buffer(4)]], constant int& I [[buffer(5)]],
constant int& O [[buffer(6)]], constant int& fmt [[buffer(7)]],
constant int& NT [[buffer(8)]],
+ constant int& gsz [[buffer(9)]], // fmt==4 group size (ignored otherwise)
uint tg [[threadgroup_position_in_grid]],
uint slane [[thread_index_in_simdgroup]],
uint sgid [[simdgroup_index_in_threadgroup]]) {
@@ -53,6 +58,23 @@ kernel void mm_gemv(device const uchar* w [[buffer(0)]], // raw weight by
for (int i = slane; i < I; i += 32) {
uchar b = wr[i>>2]; int v = (b >> (2*(i&3))) & 0x3; acc += float(v-2) * xr[i];
}
+ } else if (fmt == 4) { // int4 GROUPED: same nibble packing as fmt=2,
+ // one f32 scale per gsz-element group along I.
+ // Each lane owns one packed byte (2 elements) per
+ // 64-lane stride -> memory access stays coalesced,
+ // and a group never splits a byte (gsz is even).
+ int rb = (I+1)/2; int ng = (I+gsz-1)/gsz;
+ device const uchar* wr = w + (long)o * rb;
+ device const float* scl = scale + (long)o * ng;
+ for (int i = slane*2; i < I; i += 64) {
+ uchar b = wr[i>>1];
+ int g0 = i / gsz; float sc0 = scl[g0];
+ acc += float(int(b&0xF)-8) * xr[i] * sc0;
+ if (i+1 < I) {
+ int g1 = (i+1) / gsz; float sc1 = (g1==g0) ? sc0 : scl[g1];
+ acc += float(int(b>>4)-8) * xr[i+1] * sc1;
+ }
+ }
} else { // f32
device const float* wr = (device const float*)(w) + (long)o * I;
device const float4* w4 = (device const float4*)wr;
@@ -60,7 +82,8 @@ kernel void mm_gemv(device const uchar* w [[buffer(0)]], // raw weight by
for (int i = I8*8 + slane; i < I; i += 32) acc += wr[i] * xr[i];
}
acc = simd_sum(acc);
- if (slane == 0) y[row] = acc * scale[o];
+ // fmt==4 already folded the per-group scale into acc above -- do not scale again.
+ if (slane == 0) y[row] = (fmt == 4) ? acc : acc * scale[o];
}
// Batched bindless expert GEMV: each row gr belongs to expert erow[gr], whose weight and
@@ -401,8 +424,14 @@ static size_t fmt_bytes(int fmt, int I, int O) {
if (fmt == 1) return (size_t)O * I;
if (fmt == 2) return (size_t)O * ((I+1)/2);
if (fmt == 3) return (size_t)O * ((I+3)/4);
+ if (fmt == 4) return (size_t)O * ((I+1)/2); // grouped int4: identical packed-nibble layout to fmt=2
return (size_t)O * I * sizeof(float);
}
+// Grouped-int4 (fmt=4) scale-array size: one f32 per gsz-element group, per row -> O*ceil(I/gsz).
+static size_t fmt_scale_bytes(int fmt, int I, int O, int gs) {
+ if (fmt == 4) return (size_t)O * ((I + gs - 1) / gs) * sizeof(float);
+ return (size_t)O * sizeof(float);
+}
// Wrap host memory zero-copy if page-aligned, else copy into a shared buffer.
static id<MTLBuffer> wrap(const void *p, size_t n) {
@@ -560,15 +589,15 @@ extern "C" int coli_metal_mem_info(size_t *used, size_t *total) {
extern "C" int coli_metal_matmul(ColiMetalTensor **tp, float *y, const float *x,
const void *weights, const float *scales,
- int fmt, int S, int I, int O) {
- if (!g_dev || fmt < 0 || fmt > 3) return 0;
+ int fmt, int S, int I, int O, int gs) {
+ if (!g_dev || fmt < 0 || fmt > 4) return 0;
@autoreleasepool {
ColiMetalTensor *t = *tp;
if (!t) {
t = new ColiMetalTensor();
t->fmt = fmt; t->I = I; t->O = O; t->wbytes = fmt_bytes(fmt, I, O);
t->w = wrap(weights, t->wbytes);
- t->s = wrap(scales, (size_t)O * sizeof(float));
+ t->s = wrap(scales, fmt_scale_bytes(fmt, I, O, gs));
*tp = t;
g_tensor_count++; g_tensor_bytes += t->wbytes;
}
@@ -582,7 +611,7 @@ extern "C" int coli_metal_matmul(ColiMetalTensor **tp, float *y, const float *x,
int NT=S*O;
[e setBytes:&S length:4 atIndex:4]; [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 setBytes:&NT length:4 atIndex:8]; [e setBytes:&gs length:4 atIndex:9];
[e dispatchThreadgroups:MTLSizeMake(((size_t)NT+3)/4,1,1) threadsPerThreadgroup:MTLSizeMake(128,1,1)];
[e endEncoding]; [cb commit]; [cb waitUntilCompleted];
memcpy(y, [by contents], (size_t)S*O*sizeof(float));
@@ -605,7 +634,9 @@ static void attn_scratch_init(){
}
// y[S,O] = quantized-weight(w) applied to xin[S,I]. Weights are registered (page-aligned,
// zero-copy) at model load; resolve to (buffer,offset). Returns false to fall back to CPU.
-static bool bind_gemv(id<MTLComputeCommandEncoder> e, const void* w, const float* s, int fmt, int I, int O,
+// gs: fmt=4 group size (ignored for fmt!=4; callers pass QT.gs, which is 0 for non-grouped
+// tensors -- harmless, since the shader only reads it when fmt==4).
+static bool bind_gemv(id<MTLComputeCommandEncoder> e, const void* w, const float* s, int fmt, int gs, int I, int O,
id<MTLBuffer> xin, id<MTLBuffer> yout, int S){
uint64_t wa=0,sa=0; id<MTLBuffer> wb=resolve(w,&wa); id<MTLBuffer> sb=resolve(s,&sa);
if(!wb||!sb) return false;
@@ -616,19 +647,22 @@ static bool bind_gemv(id<MTLComputeCommandEncoder> e, const void* w, const float
[e setBuffer:xin offset:0 atIndex:2]; [e setBuffer:yout offset:0 atIndex:3];
int NT=S*O;
[e setBytes:&S length:4 atIndex:4]; [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 setBytes:&NT length:4 atIndex:8]; [e setBytes:&gs length:4 atIndex:9];
[e dispatchThreadgroups:MTLSizeMake(((size_t)NT+3)/4,1,1) threadsPerThreadgroup:MTLSizeMake(128,1,1)];
return true;
}
// Weight-pointer bundle for one layer's attention (+optional layer tail). All pointers
-// must be inside registered allocations.
+// must be inside registered allocations. *_gs: fmt=4 group size for the corresponding
+// weight (0 if that weight isn't grouped). kv_b has none: it never flows through bind_gemv
+// -- a_qabs/a_ctx dequantize it inline with a PER-ROW-only helper (a_deqrow), so a fmt=4
+// kv_b is out of scope for this stage (see PR_BODY.md UNCERTAINTIES).
typedef struct {
- const void *qa_w; const float *qa_s; int qa_fmt; const float *qa_ln;
- const void *qb_w; const float *qb_s; int qb_fmt;
- const void *kva_w; const float *kva_s; int kva_fmt; const float *kva_ln;
+ const void *qa_w; const float *qa_s; int qa_fmt; int qa_gs; const float *qa_ln;
+ const void *qb_w; const float *qb_s; int qb_fmt; int qb_gs;
+ const void *kva_w; const float *kva_s; int kva_fmt; int kva_gs; const float *kva_ln;
const void *kvb_w; const float *kvb_s; int kvb_fmt;
- const void *o_w; const float *o_s; int o_fmt;
+ const void *o_w; const float *o_s; int o_fmt; int o_gs;
} AttnW;
// Encode the fused attention chain into encoder e. Input: ax_ holds the NORMED x [S,AH].
@@ -651,10 +685,10 @@ static bool encode_attention(id<MTLComputeCommandEncoder> e, const AttnW *W,
[e setBuffer:acomp_ offset:0 atIndex:0]; [e setBytes:&off length:4 atIndex:1]; [e setBytes:&ss length:4 atIndex:2];
[e setBuffer:dst offset:doff atIndex:3]; [e setBytes:&n length:4 atIndex:4]; [e setBytes:&n length:4 atIndex:5];
[e dispatchThreads:MTLSizeMake((size_t)S*n,1,1) threadsPerThreadgroup:MTLSizeMake(64,1,1)]; };
- bind_gemv(e,W->qa_w,W->qa_s,W->qa_fmt,AH,AQLORA,ax_,aqr_,S);
- bind_gemv(e,W->kva_w,W->kva_s,W->kva_fmt,AH,AKVL+AROPE,ax_,acomp_,S); BAR();
+ bind_gemv(e,W->qa_w,W->qa_s,W->qa_fmt,W->qa_gs,AH,AQLORA,ax_,aqr_,S);
+ bind_gemv(e,W->kva_w,W->kva_s,W->kva_fmt,W->kva_gs,AH,AKVL+AROPE,ax_,acomp_,S); BAR();
rms(aqr_,0,aqaln_,AQLORA,S); cpy(0,Lb,Loff,AKVL); cpy(AKVL,Rb,Roff,AROPE); BAR();
- bind_gemv(e,W->qb_w,W->qb_s,W->qb_fmt,AQLORA,AHQH,aqr_,aqf_,S); rms(Lb,Loff,akvaln_,AKVL,S); rope(Rb,Roff,0,AROPE,0,1); BAR();
+ bind_gemv(e,W->qb_w,W->qb_s,W->qb_fmt,W->qb_gs,AQLORA,AHQH,aqr_,aqf_,S); rms(Lb,Loff,akvaln_,AKVL,S); rope(Rb,Roff,0,AROPE,0,1); BAR();
rope(aqf_,0,ANOPE,AHQH,AQH,AHEADS); BAR();
[e setComputePipelineState:g_a_qabs]; [e setBuffer:kvbW offset:kvbwoff atIndex:0]; [e setBuffer:kvbS offset:kvbsoff atIndex:1]; [e setBuffer:aqf_ offset:0 atIndex:2]; [e setBuffer:aqabs_ offset:0 atIndex:3];
[e dispatchThreads:MTLSizeMake((size_t)S*AHEADS*AKVL,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)]; BAR();
@@ -667,7 +701,7 @@ static bool encode_attention(id<MTLComputeCommandEncoder> e, const AttnW *W,
[e dispatchThreads:MTLSizeMake((size_t)S*AHEADS*AKVL,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)]; BAR();
[e setComputePipelineState:g_a_ctx]; [e setBuffer:kvbW offset:kvbwoff atIndex:0]; [e setBuffer:kvbS offset:kvbsoff atIndex:1]; [e setBuffer:aclat_ offset:0 atIndex:2]; [e setBuffer:actx_ offset:0 atIndex:3];
[e dispatchThreads:MTLSizeMake((size_t)S*AHEADS*AVH,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)]; BAR();
- bind_gemv(e,W->o_w,W->o_s,W->o_fmt,AHVH,AH,actx_,aout_,S);
+ bind_gemv(e,W->o_w,W->o_s,W->o_fmt,W->o_gs,AHVH,AH,actx_,aout_,S);
return true;
}
// Resolve Lc/Rc + kv_b (+pre-check the projection weights). Returns false -> CPU fallback.
@@ -685,18 +719,18 @@ static bool resolve_attn(const AttnW *W, float *Lc, float *Rc,
}
extern "C" int coli_metal_attn_decode(const float* x,
- const void* qa_w,const float* qa_s,int qa_fmt,const float* qa_ln,
- const void* qb_w,const float* qb_s,int qb_fmt,
- const void* kva_w,const float* kva_s,int kva_fmt,const float* kva_ln,
+ const void* qa_w,const float* qa_s,int qa_fmt,int qa_gs,const float* qa_ln,
+ const void* qb_w,const float* qb_s,int qb_fmt,int qb_gs,
+ const void* kva_w,const float* kva_s,int kva_fmt,int kva_gs,const float* kva_ln,
const void* kvb_w,const float* kvb_s,int kvb_fmt,
- const void* o_w,const float* o_s,int o_fmt,
+ const void* o_w,const float* o_s,int o_fmt,int o_gs,
float* Lc,float* Rc,int S,int pos_base,int st0,float eps,float theta,float ascale,float* out){
if(!g_dev) return 0;
if(st0!=0 || S<1 || S>AMAXS) return 0; // partial-KV / S>4 -> CPU
int T=pos_base+S;
@autoreleasepool {
attn_scratch_init();
- AttnW W={qa_w,qa_s,qa_fmt,qa_ln,qb_w,qb_s,qb_fmt,kva_w,kva_s,kva_fmt,kva_ln,kvb_w,kvb_s,kvb_fmt,o_w,o_s,o_fmt};
+ AttnW W={qa_w,qa_s,qa_fmt,qa_gs,qa_ln,qb_w,qb_s,qb_fmt,qb_gs,kva_w,kva_s,kva_fmt,kva_gs,kva_ln,kvb_w,kvb_s,kvb_fmt,o_w,o_s,o_fmt,o_gs};
id<MTLBuffer> Lb,Rb,kvbW,kvbS; size_t loff,roff,kvbwoff,kvbsoff;
if(!resolve_attn(&W,Lc,Rc,&Lb,&loff,&Rb,&roff,&kvbW,&kvbwoff,&kvbS,&kvbsoff)) return 0;
ascore_=ensure(ascore_,&ascore_cap,(size_t)S*AHEADS*T*4);
@@ -723,14 +757,14 @@ extern "C" int coli_metal_attn_decode(const float* x,
// idx/w/keff (routing). Returns 0 -> CPU fallback (whole layer falls back).
extern "C" int coli_metal_layer_decode(float *x,
const float *in_ln, const float *post_ln,
- const void* qa_w,const float* qa_s,int qa_fmt,const float* qa_ln,
- const void* qb_w,const float* qb_s,int qb_fmt,
- const void* kva_w,const float* kva_s,int kva_fmt,const float* kva_ln,
+ const void* qa_w,const float* qa_s,int qa_fmt,int qa_gs,const float* qa_ln,
+ const void* qb_w,const float* qb_s,int qb_fmt,int qb_gs,
+ const void* kva_w,const float* kva_s,int kva_fmt,int kva_gs,const float* kva_ln,
const void* kvb_w,const float* kvb_s,int kvb_fmt,
- const void* o_w,const float* o_s,int o_fmt,
- const void* shg_w,const float* shg_s,int shg_fmt,
- const void* shu_w,const float* shu_s,int shu_fmt,
- const void* shd_w,const float* shd_s,int shd_fmt,
+ const void* o_w,const float* o_s,int o_fmt,int o_gs,
+ const void* shg_w,const float* shg_s,int shg_fmt,int shg_gs,
+ const void* shu_w,const float* shu_s,int shu_fmt,int shu_gs,
+ const void* shd_w,const float* shd_s,int shd_fmt,int shd_gs,
const float *router_w, const float *router_bias,
int E, int K, int Ksel, float topp, int normk, float rscale,
float *Lc, float *Rc, int S, int pos_base, int st0,
@@ -741,7 +775,7 @@ extern "C" int coli_metal_layer_decode(float *x,
int T=pos_base+S; const int SI=2048;
@autoreleasepool {
attn_scratch_init();
- AttnW W={qa_w,qa_s,qa_fmt,qa_ln,qb_w,qb_s,qb_fmt,kva_w,kva_s,kva_fmt,kva_ln,kvb_w,kvb_s,kvb_fmt,o_w,o_s,o_fmt};
+ AttnW W={qa_w,qa_s,qa_fmt,qa_gs,qa_ln,qb_w,qb_s,qb_fmt,qb_gs,kva_w,kva_s,kva_fmt,kva_gs,kva_ln,kvb_w,kvb_s,kvb_fmt,o_w,o_s,o_fmt,o_gs};
id<MTLBuffer> Lb,Rb,kvbW,kvbS; size_t loff,roff,kvbwoff,kvbsoff;
if(!resolve_attn(&W,Lc,Rc,&Lb,&loff,&Rb,&roff,&kvbW,&kvbwoff,&kvbS,&kvbsoff)) return 0;
uint64_t ina=0,pna=0,rwa=0,rba=0,d;
@@ -778,8 +812,8 @@ extern "C" int coli_metal_layer_decode(float *x,
[e dispatchThreads:MTLSizeMake((size_t)S*AH,1,1) threadsPerThreadgroup:MTLSizeMake(256,1,1)]; BAR();
copyrow(axr_,anrm_,AH); BAR(); rmsw(anrm_,pnB,pnoff,AH,S); BAR();
// 4) shared expert gate/up + router (all read anrm_, independent)
- bind_gemv(e,shg_w,shg_s,shg_fmt,AH,SI,anrm_,ash1_,S);
- bind_gemv(e,shu_w,shu_s,shu_fmt,AH,SI,anrm_,ash2_,S);
+ bind_gemv(e,shg_w,shg_s,shg_fmt,shg_gs,AH,SI,anrm_,ash1_,S);
+ bind_gemv(e,shu_w,shu_s,shu_fmt,shu_gs,AH,SI,anrm_,ash2_,S);
{ int NT=S*E, D=AH; [e setComputePipelineState:g_r_router];
[e setBuffer:rwB offset:rwoff atIndex:0]; [e setBuffer:anrm_ offset:0 atIndex:1]; [e setBuffer:asig_ offset:0 atIndex:2];
[e setBytes:&E length:4 atIndex:3]; [e setBytes:&D length:4 atIndex:4]; [e setBytes:&NT length:4 atIndex:5];
@@ -806,7 +840,7 @@ extern "C" int coli_metal_layer_decode(float *x,
else [e dispatchThreads:MTLSizeMake(S,1,1) threadsPerThreadgroup:MTLSizeMake(S,1,1)]; }
BAR();
// 6) shared down
- bind_gemv(e,shd_w,shd_s,shd_fmt,SI,AH,ash1_,ashout_,S);
+ bind_gemv(e,shd_w,shd_s,shd_fmt,shd_gs,SI,AH,ash1_,ashout_,S);
double tc=mnow();
[e endEncoding]; [cb commit]; [cb waitUntilCompleted];
if(cb.status==MTLCommandBufferStatusError){ fprintf(stderr,"[metal] layer cmdbuf error: %s\n", cb.error?[[cb.error localizedDescription]UTF8String]:"?"); return 0; }
@@ -827,8 +861,8 @@ extern "C" int coli_metal_layer_decode(float *x,
// registered (zero-copy); x/y go through grow-only shared scratch. Returns 0 -> CPU fallback.
static id<MTLBuffer> g_gx, g_gy; static size_t g_gx_cap, g_gy_cap;
extern "C" int coli_metal_gemm(float *y, const float *x, const void *wp, const float *sp,
- int fmt, int S, int I, int O) {
- if (!g_dev || (fmt!=1 && fmt!=2)) return 0;
+ int fmt, int S, int I, int O, int gs) {
+ if (!g_dev || (fmt!=1 && fmt!=2 && fmt!=4)) return 0;
@autoreleasepool {
uint64_t wa=0,sa=0; id<MTLBuffer> wb=resolve(wp,&wa), sb=resolve(sp,&sa);
if(!wb||!sb) return 0;
@@ -841,6 +875,7 @@ extern "C" int coli_metal_gemm(float *y, const float *x, const void *wp, const f
[e setBuffer:wb offset:woff atIndex:0]; [e setBuffer:sb offset:soff atIndex:1];
[e setBytes:&I length:4 atIndex:5];
[e setBytes:&O length:4 atIndex:6]; [e setBytes:&fmt length:4 atIndex:7];
+ [e setBytes:&gs length:4 atIndex:9]; /* loop-invariant, like I/O/fmt: group size for fmt=4 (0 = per-row) */
// 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
diff --git a/c/colibri.c b/c/colibri.c
index 82eeac21..e5c3fcc2 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -547,9 +547,9 @@ static void matmul_i4_grouped_pair(float *yg, float *yu, const float *x,
* (~+12% perplexity), measured. Every other prefill matmul keeps IDOT as before. */
static void matmul_qt_ex(float *y, const float *x, QT *w, int S, int allow_idot){
#ifdef COLI_METAL
- if(g_metal_enabled && S>=g_metal_gemm_min && !spec_pinned() && (w->fmt==1||w->fmt==2) && !omp_in_parallel()){
+ if(g_metal_enabled && S>=g_metal_gemm_min && !spec_pinned() && (w->fmt==1||w->fmt==2||w->fmt==4) && !omp_in_parallel()){
const void *wp = w->fmt==1 ? (const void*)w->q8 : (const void*)w->q4;
- if(coli_metal_gemm(y,x,wp,w->s,w->fmt,S,w->I,w->O)) return;
+ if(coli_metal_gemm(y,x,wp,w->s,w->fmt,S,w->I,w->O,w->gs)) return;
}
#endif
#ifdef COLI_CUDA
@@ -2374,11 +2374,11 @@ static void attention_rows(Model *m, Layer *l, int layer, float *x, int S, int p
}
#define WP_(q) ((q).fmt==1?(const void*)(q).q8:(const void*)(q).q4)
int ok = coli_metal_attn_decode(x,
- WP_(l->q_a), l->q_a.s, l->q_a.fmt, l->q_a_ln,
- WP_(l->q_b), l->q_b.s, l->q_b.fmt,
- WP_(l->kv_a), l->kv_a.s, l->kv_a.fmt, l->kv_a_ln,
+ WP_(l->q_a), l->q_a.s, l->q_a.fmt, l->q_a.gs, l->q_a_ln,
+ WP_(l->q_b), l->q_b.s, l->q_b.fmt, l->q_b.gs,
+ WP_(l->kv_a), l->kv_a.s, l->kv_a.fmt, l->kv_a.gs, l->kv_a_ln,
WP_(l->kv_b), l->kv_b.s, l->kv_b.fmt,
- WP_(l->o), l->o.s, l->o.fmt,
+ WP_(l->o), l->o.s, l->o.fmt, l->o.gs,
m->Lc[layer], m->Rc[layer], S, pos_base, m->kv_start[layer], c->eps, c->theta, c->attn_scale, out);
#undef WP_
if(ok){ m->t_attn += now_s()-ta0; return; }
@@ -4207,14 +4207,14 @@ static void layer_forward_rows(Model *m, Layer *l, int li, float *x, int S, int
double ta0=now_s();
#define WP_(q) ((q).fmt==1?(const void*)(q).q8:(const void*)(q).q4)
int ok = coli_metal_layer_decode(x, l->in_ln, l->post_ln,
- WP_(l->q_a), l->q_a.s, l->q_a.fmt, l->q_a_ln,
- WP_(l->q_b), l->q_b.s, l->q_b.fmt,
- WP_(l->kv_a), l->kv_a.s, l->kv_a.fmt, l->kv_a_ln,
+ WP_(l->q_a), l->q_a.s, l->q_a.fmt, l->q_a.gs, l->q_a_ln,
+ WP_(l->q_b), l->q_b.s, l->q_b.fmt, l->q_b.gs,
+ WP_(l->kv_a), l->kv_a.s, l->kv_a.fmt, l->kv_a.gs, l->kv_a_ln,
WP_(l->kv_b), l->kv_b.s, l->kv_b.fmt,
- WP_(l->o), l->o.s, l->o.fmt,
- WP_(l->sh_gate), l->sh_gate.s, l->sh_gate.fmt,
- WP_(l->sh_up), l->sh_up.s, l->sh_up.fmt,
- WP_(l->sh_down), l->sh_down.s, l->sh_down.fmt,
+ WP_(l->o), l->o.s, l->o.fmt, l->o.gs,
+ WP_(l->sh_gate), l->sh_gate.s, l->sh_gate.fmt, l->sh_gate.gs,
+ WP_(l->sh_up), l->sh_up.s, l->sh_up.fmt, l->sh_up.gs,
+ WP_(l->sh_down), l->sh_down.s, l->sh_down.fmt, l->sh_down.gs,
l->router, l->router_bias,
c->n_experts, c->topk, Ksel, tp, c->norm_topk, c->routed_scale,
m->Lc[li], m->Rc[li], S, pos_base, m->kv_start[li],
diff --git a/c/tests/test_backend_metal.mm b/c/tests/test_backend_metal.mm
index bff0444b..30daee93 100644
--- a/c/tests/test_backend_metal.mm
+++ b/c/tests/test_backend_metal.mm
@@ -1,5 +1,8 @@
// Kernel-correctness test for the Metal backend: coli_metal_matmul vs CPU reference
// (dequant->f32 MAC * per-row scale) for f32/int8/int4/int2 across real GLM shapes.
+// fmt=4 (grouped int4, dev e9b3614 matmul_i4_grouped / CUDA #298 twin) gets its own
+// reference (cpu_ref_grouped) and harness (run_grouped) below -- unlike fmt 1-3 the
+// group scale is per-GROUP, not per-row, so it can't share cpu_ref's [O] scale layout.
#include "../backend_metal.h"
#include <cstdio>
#include <cstdlib>
@@ -7,7 +10,7 @@
#include <cmath>
#include <vector>
-enum { F32=0, I8=1, I4=2, I2=3 };
+enum { F32=0, I8=1, I4=2, I2=3, I4G=4 };
static void cpu_ref(int fmt, const void *W, const float *s, const float *x,
float *y, int S, int I, int O) {
@@ -41,7 +44,7 @@ static int run(int fmt, int O, int I, int S, const char *name) {
for(auto&v:x) v=((rand()%2000)-1000)/1000.f;
cpu_ref(fmt, Wp, s.data(), x.data(), yr.data(), S, I, O);
ColiMetalTensor *t=nullptr;
- if (!coli_metal_matmul(&t, yg.data(), x.data(), Wp, s.data(), fmt, S, I, O)) {
+ if (!coli_metal_matmul(&t, yg.data(), x.data(), Wp, s.data(), fmt, S, I, O, 0)) {
printf(" %-22s FAIL (matmul returned 0)\n", name); return 1; }
double maxabs=0, ymax=0;
for(size_t i=0;i<(size_t)S*O;i++){ maxabs=fmax(maxabs,fabs(yg[i]-yr[i])); ymax=fmax(ymax,fabs(yr[i])); }
@@ -52,6 +55,84 @@ static int run(int fmt, int O, int I, int S, const char *name) {
return ok?0:1;
}
+// ---- fmt=4 (grouped int4): own CPU reference + harness -----------------------------
+// cpu_ref's [O] per-row scale layout can't express fmt=4's [O,ceil(I/gs)] per-group
+// scale, so this is a separate reference rather than a branch of cpu_ref. Mirrors
+// quant.h's matmul_i4_grouped exactly (same nibble decode, same group indexing i/gs)
+// and accumulates in DOUBLE, matching the convention tests/test_i4_grouped.c already
+// established as the fmt=4 oracle for the CUDA port (#298) -- reusing it here means the
+// Metal kernel is checked against the same "known exact" reference, not a third one.
+static void cpu_ref_grouped(const uint8_t *q4, const float *scale, const float *x,
+ double *y, double *mag, int S, int I, int O, int gs) {
+ int rb=(I+1)/2, ng=(I+gs-1)/gs;
+ for (int o=0;o<O;o++){
+ const uint8_t *w = q4 + (size_t)o*rb;
+ const float *scl = scale + (size_t)o*ng;
+ for (int s=0;s<S;s++){
+ const float *xs = x + (size_t)s*I; double a=0, m=0;
+ for (int i=0;i<I;i++){
+ uint8_t b = w[i>>1]; int nib = (i&1) ? (int)(b>>4) : (int)(b&0xF);
+ double term = (double)xs[i] * (double)(nib-8) * (double)scl[i/gs];
+ a += term; m += fabs(term);
+ }
+ y[(size_t)s*O+o] = a; mag[(size_t)s*O+o] = m;
+ }
+ }
+}
+
+// Tolerance: magnitude-relative (error / sum of |terms|), NOT the ymax-relative-max-
+// abs-error convention run() above uses. Reason: a dot product over many groups can
+// land near zero from signed-term cancellation, and a fixed-point-ish absolute GPU/CPU
+// rounding difference then reads as a huge relative error against the (near-zero)
+// RESULT -- that is the accumulator's precision, not a kernel defect. Comparing against
+// the sum of |terms| instead means a wrong scale index or wrong group boundary is still
+// caught as an O(1) relative error (it shifts the result by a fraction of the terms),
+// while cancellation noise is not misreported as a bug. This is the exact convention
+// tests/test_i4_grouped.c uses for the same kernel's CPU-side oracle (see its
+// `ref_grouped`/`mag` comment) -- reused here for a GPU oracle of the same format.
+// 1e-4 (vs. test_i4_grouped.c's 1e-6) because the GPU sums in a different order --
+// byte-pair-strided across 32 SIMD lanes then simd_sum -- than the scalar double
+// reference; that's the same 1e-4 slack run()'s f32-vs-f32 comparisons already carry
+// for fmt 1-3 above, just applied to a magnitude-relative rather than max-relative base.
+static int run_grouped(int O, int I, int gs, int S, int outlier, const char *name) {
+ int rb=(I+1)/2, ng=(I+gs-1)/gs;
+ std::vector<uint8_t> W((size_t)O*rb);
+ std::vector<float> scale((size_t)O*ng), x((size_t)S*I), yg((size_t)S*O);
+ std::vector<double> yr((size_t)S*O), mag((size_t)S*O);
+ srand(4110 + I*7 + O*3 + gs + S*13 + outlier*97);
+ for (auto &b : W) b = (uint8_t)(rand()&0xFF);
+ // scales span orders of magnitude -- a wrong group index shows up big, not as noise.
+ for (auto &v : scale) v = (0.001f + (rand()%1000)/1000.0f) * ((rand()&1) ? 1.f : -1.f);
+ for (auto &v : x) v = ((rand()%2000)-1000)/1000.0f;
+ if (outlier) {
+ // Tail-clipping regime grouped scales exist for: one huge activation per row,
+ // confined to group 0. A per-row quantizer's single scale would have to stretch to
+ // cover this outlier, crushing every other group's precision; per-group scaling
+ // contains the damage to group 0's scale and leaves the rest of the row exact. This
+ // isn't a property of matmul_i4_grouped's weights (which are the same random bytes
+ // as the non-outlier case) -- it's the activation-side stress the format is FOR, and
+ // it exercises the SAME code path (still just per-group scale lookup + MAC), so a
+ // reconstruction win here is really a check that group boundaries/indices are right
+ // under the shape that would most expose a wrong one.
+ for (int s=0; s<S; s++) x[(size_t)s*I+0] = 50.0f;
+ }
+ cpu_ref_grouped(W.data(), scale.data(), x.data(), yr.data(), mag.data(), S, I, O, gs);
+ ColiMetalTensor *t=nullptr;
+ if (!coli_metal_matmul(&t, yg.data(), x.data(), W.data(), scale.data(), I4G, S, I, O, gs)) {
+ printf(" %-34s FAIL (matmul returned 0)\n", name); return 1; }
+ double worst=0; int bad=0;
+ for (size_t i=0; i<(size_t)S*O; i++) {
+ double d = fabs((double)yg[i] - yr[i]);
+ double rel = mag[i] > 1e-30 ? d/mag[i] : d;
+ if (rel > worst) worst = rel;
+ if (rel > 1e-4) bad++;
+ }
+ int ok = (bad == 0);
+ printf(" %-34s worst_rel=%.2e (I=%d gs=%d ng=%d S=%d) %s\n", name, worst, I, gs, ng, S, ok?"ok":"*** MISMATCH");
+ coli_metal_tensor_free(t);
+ return ok?0:1;
+}
+
static float deq4(const uint8_t* w,int i){ uint8_t b=w[i>>1]; int v=(i&1)?(b>>4):(b&0xF); return (float)(v-8); }
static size_t roundpg(size_t n){ size_t p=16384; return ((n+p-1)/p)*p; }
@@ -115,6 +196,22 @@ static TW t_mkw(int O,int I){ TW t; int rb=(I+1)/2;
for(size_t i=0;i<(size_t)O*rb;i++) t.w[i]=(uint8_t)(rand()&0xFF);
for(int i=0;i<O;i++) t.s[i]=0.01f+(rand()%40)/40000.f;
coli_metal_register(t.w,t.wb); coli_metal_register(t.s,t.sb); return t; }
+// Grouped-int4 (fmt=4) variant of t_mkw: same packed-nibble weight layout, but the
+// scale slab holds O*ceil(I/gs) floats. Used to prove the bind_gemv/AttnW/
+// coli_metal_attn_decode plumbing (not just the standalone GEMV) threads gs correctly.
+static TW t_mkw_g(int O,int I,int gs){ TW t; int rb=(I+1)/2, ng=(I+gs-1)/gs;
+ t.wb=((size_t)O*rb+16383)&~(size_t)16383; t.sb=((size_t)O*(size_t)ng*4+16383)&~(size_t)16383;
+ posix_memalign((void**)&t.w,16384,t.wb); posix_memalign((void**)&t.s,16384,t.sb);
+ for(size_t i=0;i<(size_t)O*rb;i++) t.w[i]=(uint8_t)(rand()&0xFF);
+ for(int i=0;i<O*ng;i++) t.s[i]=(0.001f+(rand()%1000)/1000.f)*((rand()&1)?1.f:-1.f);
+ coli_metal_register(t.w,t.wb); coli_metal_register(t.s,t.sb); return t; }
+// Grouped-int4 CPU reference GEMV, mirroring t_gemv4 but with a per-group scale lookup
+// (same semantics as quant.h's matmul_i4_grouped / cpu_ref_grouped above).
+static void t_gemv4g(float*y,const float*x,const uint8_t*w,const float*sc,int O,int I,int gs){
+ int rb=(I+1)/2, ng=(I+gs-1)/gs;
+ for(int o=0;o<O;o++){ const uint8_t*r=w+(size_t)o*rb; const float* scl=sc+(size_t)o*ng; float a=0;
+ for(int i=0;i<I;i++){ uint8_t b=r[i>>1]; int v=(i&1)?(b>>4):(b&0xF); a+=(float)(v-8)*x[i]*scl[i/gs]; }
+ y[o]=a; } }
static int run_attn(int S, int pos_base, const char* name){
const float eps=1e-5f, theta=10000.f, ascale=1.f/16.f;
srand(4242+S+pos_base);
@@ -160,8 +257,8 @@ static int run_attn(int S, int pos_base, const char* name){
t_gemv4(&ref[(size_t)s*TH],ctx.data(),o.w,o.s,TH,THH*TVH);
}
std::vector<float> got((size_t)S*TH);
- int ok=coli_metal_attn_decode(x.data(), qa.w,qa.s,2,qaln.data(), qb.w,qb.s,2,
- kva.w,kva.s,2,kvaln.data(), kvb.w,kvb.s,2, o.w,o.s,2,
+ int ok=coli_metal_attn_decode(x.data(), qa.w,qa.s,2,0,qaln.data(), qb.w,qb.s,2,0,
+ kva.w,kva.s,2,0,kvaln.data(), kvb.w,kvb.s,2, o.w,o.s,2,0,
Lc,Rc,S,pos_base,0,eps,theta,ascale,got.data());
double ma=0,ym=0; for(size_t i=0;i<ref.size();i++){ ma=fmax(ma,fabs(got[i]-ref[i])); ym=fmax(ym,fabs(ref[i])); }
// also verify the cache write-back (Lc/Rc for the new positions)
@@ -239,6 +336,73 @@ static int run_rtop8(int mode, int S, int E, float topp, int normk, float rscale
return 0;
}
+// Same fused-attention pipeline as run_attn, but q_a is fmt=4 (grouped int4, gs) while
+// q_b/kv_a/kv_b/o stay fmt=2 -- proves the bind_gemv/AttnW/coli_metal_attn_decode
+// plumbing (qa_gs threaded through encode_attention) is wired correctly end-to-end
+// through the SAME fused command buffer real decode uses (attention_rows in colibri.c),
+// not just the standalone coli_metal_matmul entry point run_grouped() above exercises.
+// kv_b is deliberately left fmt=2: it never flows through bind_gemv (a_qabs/a_ctx
+// dequantize it with a per-row-only helper) -- a fmt=4 kv_b is out of scope for this
+// stage (see PR_BODY.md UNCERTAINTIES).
+static int run_attn_grouped(int S, int pos_base, int gs, const char* name){
+ const float eps=1e-5f, theta=10000.f, ascale=1.f/16.f;
+ srand(5150+S+pos_base+gs);
+ TW qa=t_mkw_g(TQL,TH,gs), qb=t_mkw(THH*TQH,TQL), kva=t_mkw(TKVL+TROPE,TH), kvb=t_mkw(THH*TROWSH,TKVL), o=t_mkw(TH,THH*TVH);
+ std::vector<float> qaln(TQL), kvaln(TKVL);
+ for(auto&v:qaln) v=0.5f+(rand()%1000)/1000.f; for(auto&v:kvaln) v=0.5f+(rand()%1000)/1000.f;
+ int T=pos_base+S; size_t lcb=(((size_t)T*TKVL*4)+16383)&~(size_t)16383, rcb=(((size_t)T*TROPE*4)+16383)&~(size_t)16383;
+ float *Lc,*Rc; posix_memalign((void**)&Lc,16384,lcb); posix_memalign((void**)&Rc,16384,rcb);
+ coli_metal_register(Lc,lcb); coli_metal_register(Rc,rcb);
+ for(int t=0;t<pos_base;t++){ for(int i=0;i<TKVL;i++) Lc[(size_t)t*TKVL+i]=((rand()%2000)-1000)/1500.f;
+ for(int i=0;i<TROPE;i++) Rc[(size_t)t*TROPE+i]=((rand()%2000)-1000)/1500.f; }
+ std::vector<float> x((size_t)S*TH); for(auto&v:x) v=((rand()%2000)-1000)/1000.f;
+ std::vector<float> Lr((size_t)T*TKVL), Rr((size_t)T*TROPE);
+ memcpy(Lr.data(),Lc,(size_t)pos_base*TKVL*4); memcpy(Rr.data(),Rc,(size_t)pos_base*TROPE*4);
+ std::vector<float> Q((size_t)S*THH*TQH), ref((size_t)S*TH);
+ for(int s=0;s<S;s++){ int pos=pos_base+s;
+ std::vector<float> qr(TQL), comp(TKVL+TROPE);
+ t_gemv4g(qr.data(),&x[(size_t)s*TH],qa.w,qa.s,TQL,TH,gs); t_rms(qr.data(),qr.data(),qaln.data(),TQL,eps); // <- grouped
+ t_gemv4(&Q[(size_t)s*THH*TQH],qr.data(),qb.w,qb.s,THH*TQH,TQL);
+ for(int h=0;h<THH;h++) t_rope(&Q[(size_t)s*THH*TQH+(size_t)h*TQH+TNOPE],pos,theta);
+ t_gemv4(comp.data(),&x[(size_t)s*TH],kva.w,kva.s,TKVL+TROPE,TH);
+ t_rms(&Lr[(size_t)pos*TKVL],comp.data(),kvaln.data(),TKVL,eps);
+ memcpy(&Rr[(size_t)pos*TROPE],&comp[TKVL],TROPE*4); t_rope(&Rr[(size_t)pos*TROPE],pos,theta);
+ }
+ int rb=(TKVL+1)/2;
+ for(int s=0;s<S;s++){ int pos=pos_base+s; std::vector<float> ctx((size_t)THH*TVH);
+ for(int h=0;h<THH;h++){ int rbase=h*TROWSH;
+ const float* qp=&Q[(size_t)s*THH*TQH+(size_t)h*TQH]; const float* qro=qp+TNOPE;
+ std::vector<float> qabs(TKVL,0);
+ for(int d=0;d<TNOPE;d++){ const uint8_t*r=kvb.w+(size_t)(rbase+d)*rb; float sc=kvb.s[rbase+d];
+ for(int i=0;i<TKVL;i++){ uint8_t b=r[i>>1]; int v=(i&1)?(b>>4):(b&0xF); qabs[i]+=qp[d]*(float)(v-8)*sc; } }
+ std::vector<float> a(pos+1);
+ for(int t=0;t<=pos;t++){ const float*Lt=&Lr[(size_t)t*TKVL]; const float*Rt=&Rr[(size_t)t*TROPE];
+ float v=0; for(int i=0;i<TKVL;i++) v+=qabs[i]*Lt[i]; for(int d=0;d<TROPE;d++) v+=qro[d]*Rt[d]; a[t]=v*ascale; }
+ float mx=-1e30f; for(float v:a) mx=fmaxf(mx,v); float sum=0; for(float&v:a){ v=expf(v-mx); sum+=v; } for(float&v:a) v/=sum;
+ std::vector<float> cl(TKVL,0);
+ for(int t=0;t<=pos;t++){ const float*Lt=&Lr[(size_t)t*TKVL]; for(int i=0;i<TKVL;i++) cl[i]+=a[t]*Lt[i]; }
+ for(int j=0;j<TVH;j++){ const uint8_t*r=kvb.w+(size_t)(rbase+TNOPE+j)*rb; float sc=kvb.s[rbase+TNOPE+j];
+ float v=0; for(int i=0;i<TKVL;i++){ uint8_t b=r[i>>1]; int vv=(i&1)?(b>>4):(b&0xF); v+=cl[i]*(float)(vv-8)*sc; }
+ ctx[(size_t)h*TVH+j]=v; } }
+ t_gemv4(&ref[(size_t)s*TH],ctx.data(),o.w,o.s,TH,THH*TVH);
+ }
+ std::vector<float> got((size_t)S*TH);
+ int ok=coli_metal_attn_decode(x.data(), qa.w,qa.s,4,gs,qaln.data(), qb.w,qb.s,2,0, // <- qa fmt=4/gs
+ kva.w,kva.s,2,0,kvaln.data(), kvb.w,kvb.s,2, o.w,o.s,2,0,
+ Lc,Rc,S,pos_base,0,eps,theta,ascale,got.data());
+ double ma=0,ym=0; for(size_t i=0;i<ref.size();i++){ ma=fmax(ma,fabs(got[i]-ref[i])); ym=fmax(ym,fabs(ref[i])); }
+ double mc=0; for(int s=0;s<S;s++){ int pos=pos_base+s;
+ for(int i=0;i<TKVL;i++) mc=fmax(mc,fabs(Lc[(size_t)pos*TKVL+i]-Lr[(size_t)pos*TKVL+i]));
+ for(int i=0;i<TROPE;i++) mc=fmax(mc,fabs(Rc[(size_t)pos*TROPE+i]-Rr[(size_t)pos*TROPE+i])); }
+ double nerr=ma/(ym+1e-9);
+ int pass = ok && nerr<2e-4 && mc<1e-4;
+ printf(" %-24s nerr=%.2e cache=%.2e %s\n", name, nerr, mc, pass?"ok":"*** MISMATCH");
+ auto freew=[&](TW&t){ coli_metal_unregister(t.w); coli_metal_unregister(t.s); free(t.w); free(t.s); };
+ freew(qa); freew(qb); freew(kva); freew(kvb); freew(o);
+ coli_metal_unregister(Lc); coli_metal_unregister(Rc); free(Lc); free(Rc);
+ return pass?0:1;
+}
+
int main(void) {
if (!coli_metal_init()) { printf("Metal unavailable (skipping)\n"); return 0; }
printf("Metal backend kernel tests:\n");
@@ -251,6 +415,21 @@ int main(void) {
fail |= run(I8, 2048,6144,4, "int8 gate/up S=4");
fail |= run(I4, 2048,6144,7, "int4 gate/up S=7 (odd)");
fail |= run(I4, 2050,6146,3, "int4 non-mult-4 dims");
+ printf("Metal fmt=4 grouped-int4 tests (coli_metal_matmul vs matmul_i4_grouped semantics):\n");
+ // I multiple of gs=64, S=1 and S>1 (real g64-checkpoint shapes: gate/up I=6144, down I=2048)
+ fail |= run_grouped(2048,6144,64,1,0, "grouped gate/up I=6144(mult64) S=1");
+ fail |= run_grouped(6144,2048,64,1,0, "grouped down I=2048(mult64) S=1");
+ fail |= run_grouped(2048,6144,64,4,0, "grouped gate/up I=6144(mult64) S=4");
+ // I NOT a multiple of gs=64 (partial last group, the glen-clamp off-by-one)
+ fail |= run_grouped(6, 200, 64,2,0, "grouped I=200 (non-mult-64) S=2");
+ fail |= run_grouped(5, 201, 64,3,0, "grouped I=201 (odd, non-mult-64) S=3");
+ // I<=64 degenerate: single group (ng=1), including I<gs
+ fail |= run_grouped(3, 64, 64,1,0, "grouped I=64 (degenerate, ng=1) S=1");
+ fail |= run_grouped(3, 40, 64,1,0, "grouped I=40 (<gs, single partial group) S=1");
+ // random + outlier-heavy rows: one large-magnitude activation per row (the
+ // tail-clipping regime grouped scales exist for), verified end-to-end through the GPU.
+ fail |= run_grouped(5, 512, 64,3,1, "grouped I=512(mult64) outlier-heavy S=3");
+ fail |= run_grouped(5, 201, 64,2,1, "grouped I=201(non-mult-64) outlier-heavy S=2");
printf("Metal batched moe_block tests:\n");
fail |= run_moe({1,1,1,1,1,1,1,1}, "moe decode nb=8");
fail |= run_moe({3,1,4,2,1,5}, "moe ragged nb=6");
@@ -265,18 +444,43 @@ int main(void) {
std::vector<float> x((size_t)S*I), yr((size_t)S*O), yg((size_t)S*O);
for(auto&v:x) v=((rand()%2000)-1000)/1000.f;
cpu_ref(I4,W,Sc,x.data(),yr.data(),S,I,O);
- int ok=coli_metal_gemm(yg.data(),x.data(),W,Sc,2,S,I,O);
+ int ok=coli_metal_gemm(yg.data(),x.data(),W,Sc,2,S,I,O,0);
double ma=0,ym=0; for(size_t i=0;i<yr.size();i++){ ma=fmax(ma,fabs(yg[i]-yr[i])); ym=fmax(ym,fabs(yr[i])); }
int pass = ok && ma/(ym+1e-9)<1e-4;
printf(" gemm S=64 int4 nerr=%.2e %s\n", ma/(ym+1e-9), pass?"ok":"*** MISMATCH");
fail |= !pass;
coli_metal_unregister(W); coli_metal_unregister(Sc); free(W); free(Sc);
}
+ { // registered GROUPED int4 (fmt=4) weights, S=64: coli_metal_gemm vs cpu_ref_grouped
+ // -- covers the matmul_qt_ex prefill dispatch path (colibri.c), the second of the
+ // two directly-named "gemm-test pattern" entry points mm_gemv is reached through.
+ srand(881); int O=2048,I=6144,S=64,gs=64,rb=(I+1)/2,ng=(I+gs-1)/gs;
+ size_t wb=(((size_t)O*rb)+16383)&~(size_t)16383, sbg=(((size_t)O*(size_t)ng*4)+16383)&~(size_t)16383;
+ uint8_t*W; float*Sc; posix_memalign((void**)&W,16384,wb); posix_memalign((void**)&Sc,16384,sbg);
+ for(size_t i=0;i<(size_t)O*rb;i++) W[i]=(uint8_t)(rand()&0xFF);
+ for(int i=0;i<O*ng;i++) Sc[i]=(0.001f+(rand()%1000)/1000.f)*((rand()&1)?1.f:-1.f);
+ coli_metal_register(W,wb); coli_metal_register(Sc,sbg);
+ std::vector<float> x((size_t)S*I), yg((size_t)S*O);
+ std::vector<double> yr((size_t)S*O), mag((size_t)S*O);
+ for(auto&v:x) v=((rand()%2000)-1000)/1000.f;
+ cpu_ref_grouped(W,Sc,x.data(),yr.data(),mag.data(),S,I,O,gs);
+ int ok=coli_metal_gemm(yg.data(),x.data(),W,Sc,4,S,I,O,gs);
+ double worst=0; for(size_t i=0;i<yg.size();i++){ double d=fabs((double)yg[i]-yr[i]); double rel=mag[i]>1e-30?d/mag[i]:d; if(rel>worst) worst=rel; }
+ int pass = ok && worst<1e-4;
+ printf(" gemm S=64 int4-grouped worst_rel=%.2e %s\n", worst, pass?"ok":"*** MISMATCH");
+ fail |= !pass;
+ coli_metal_unregister(W); coli_metal_unregister(Sc); free(W); free(Sc);
+ }
printf("Metal fused attention tests:\n");
fail |= run_attn(1, 0, "attn S=1 pos=0");
fail |= run_attn(1, 37, "attn S=1 pos=37");
fail |= run_attn(4, 12, "attn S=4 pos=12 (MTP)");
fail |= run_attn(3, 0, "attn S=3 pos=0");
+ printf("Metal fused attention tests (fmt=4 grouped q_a, proves bind_gemv gs plumbing):\n");
+ fail |= run_attn_grouped(1, 0, 64, "attn grouped-qa S=1 pos=0");
+ fail |= run_attn_grouped(4, 12, 64, "attn grouped-qa S=4 pos=12 (MTP)");
+ printf("Metal negative control: fmt 1/2/3 unaffected by the fmt=4 shader branch --\n"
+ " see the runs above (int8/int4/int2/f32/moe/gemm/attn cases): all still ok.\n");
printf("Metal top-8 select serial-vs-parallel tests (exact-match contract, E=256):\n");
fail |= run_rtop8(0, 1, 256, 0.0f, 1, 1.0f, "top8 generic S=1");
fail |= run_rtop8(0, 4, 256, 0.0f, 1, 1.0f, "top8 generic S=4");