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

Add packed affine Metal GEMV path

Léon Avic Simmonsf118f5452b72
diff --git a/THIRD_PARTY_NOTICES.md b/THIRD_PARTY_NOTICES.md
index ca473c78..bfdbec41 100644
--- a/THIRD_PARTY_NOTICES.md
+++ b/THIRD_PARTY_NOTICES.md
@@ -32,6 +32,17 @@ executes an unmodified vLLM checkout (commit
`ffd46bfab2128bb84146050e98b51a617c6575ab`) as a behavioural oracle for the
native port; no vLLM code is vendored.
+## Swiftlet MLX affine Metal GEMV
+
+The MLX affine Q4/Q8 kernels in `c/backend_metal.mm` are adapted from
+`gemv_affine_fast` and `gemv_affine_fast8` in Swiftlet:
+https://github.com/leonickson1/Swiftlet at commit
+`b3a04676748c7597800c5bcc8b80a32508f9f43d`.
+
+Swiftlet is licensed under Apache License 2.0. The kernels were modified for
+Colibri's checked descriptor, batched dispatch, buffer ownership, and fallback
+contract. This repository's `LICENSE` contains the applicable Apache 2.0 text.
+
## DeepGEMM sm120 headers (fetched, not vendored: `c/third_party/deepgemm/`)
The DeepSeek V4 CUDA tier's DeepGEMM flavour (`make cuda-dsv4-dg-dll`,
diff --git a/c/Makefile b/c/Makefile
index 5c9d7e7a..db5fed18 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -961,10 +961,10 @@ cuda-dsv4-dg-dll: backend_cuda_dsv4.cu backend_cuda_dsv4.h dsv4.def $(DEEPGEMM_S
dsv4-cuda-loader-test: tests/test_dsv4_decode_cuda.c backend_loader_dsv4.c backend_cuda_dsv4.h
$(CC) $(CFLAGS) tests/test_dsv4_decode_cuda.c backend_loader_dsv4.c -o dsv4_decode_loader_test$(EXE)
./dsv4_decode_loader_test$(EXE)
-backend_metal.o: backend_metal.mm backend_metal.h
+backend_metal.o: backend_metal.mm backend_metal.h affine_quant.h
$(METALXX) -c backend_metal.mm -o $@
-metal-test: tests/test_backend_metal.mm backend_metal.mm backend_metal.h
+metal-test: tests/test_backend_metal.mm backend_metal.mm backend_metal.h affine_quant.h
$(METALXX) tests/test_backend_metal.mm backend_metal.mm -framework Metal -framework Foundation -o backend_metal_test
./backend_metal_test
@@ -991,7 +991,7 @@ glm53-metal-check: backend_metal.o tests/test_glm53_clamped_metal.c tests/test_g
# 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
+gemm-test: tests/test_gemm_largebatch.mm backend_metal.mm backend_metal.h affine_quant.h
$(METALXX) $(OMPC) tests/test_gemm_largebatch.mm backend_metal.mm $(OMPL) -framework Metal -framework Foundation -o gemm_largebatch_test
./gemm_largebatch_test
@@ -1784,7 +1784,7 @@ tests/test_native_quant$(EXE): tests/test_native_quant.c sse41_kernels.h deepsee
# Portable MLX affine Q4/Q8 format contract and CPU oracle. This stays
# separate from QT fmt=4, whose signed-int4 scale-only layout is incompatible.
-tests/test_affine_quant$(EXE): tests/test_affine_quant.c affine_quant.h
+tests/test_affine_quant$(EXE): tests/test_affine_quant.c affine_quant.h backend_metal.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
tests/test_edge_runtime$(EXE): tests/test_edge_runtime.c edge_runtime.c edge_runtime.h
diff --git a/c/backend_metal.h b/c/backend_metal.h
index 4fd5a334..a9dfe881 100644
--- a/c/backend_metal.h
+++ b/c/backend_metal.h
@@ -4,6 +4,8 @@
#include <stddef.h>
#include <stdint.h>
+#include "affine_quant.h"
+
#ifdef __cplusplus
extern "C" {
#endif
@@ -22,7 +24,9 @@ typedef struct ColiMetalTensor ColiMetalTensor;
int coli_metal_init(void);
void coli_metal_shutdown(void);
int coli_metal_available(void);
-/* Bytes of unified memory in use by wrapped tensors, and their count. */
+/* Resident handle count and bytes. Existing QT handles retain weight-only byte
+ * accounting; affine handles include their weight, scale, and bias buffers.
+ */
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);
@@ -70,7 +74,57 @@ int coli_metal_matmul(ColiMetalTensor **tensor,
const void *weights, const float *scales,
int fmt, int S, int I, int O, int gs);
+/* Returns whether a validated MLX affine descriptor and batch fit the Metal
+ * shader's uint32 indexing ABI. This predicate is portable and does not query
+ * hardware; coli_metal_affine_available() additionally requires initialized
+ * Q4/Q8 pipelines on a device with 32-lane simdgroups.
+ */
+static inline int
+coli_metal_affine_dispatch_supported(const ColiAffineQuantizedView *view,
+ int batch) {
+ size_t elements, groups;
+ if (batch <= 0 || coli_affine_validate(view) != COLI_AFFINE_OK)
+ return 0;
+ if (view->output_dim > UINT32_MAX || view->input_dim > UINT32_MAX ||
+ view->group_size > UINT32_MAX)
+ return 0;
+ groups = view->input_dim / view->group_size;
+ if (!coli_affine_size_mul(view->output_dim, groups, &elements) ||
+ elements > UINT32_MAX)
+ return 0;
+ if (!coli_affine_size_mul((size_t)batch, view->input_dim, &elements) ||
+ elements > UINT32_MAX)
+ return 0;
+ if (!coli_affine_size_mul((size_t)batch, view->output_dim, &elements) ||
+ elements > UINT32_MAX)
+ return 0;
+ return 1;
+}
+
+/* Dedicated MLX affine path. This does not use or extend Colibri's QT fmt
+ * namespace: `view` names unsigned uint32-packed Q4/Q8 plus scale and bias.
+ * The first successful call wraps the three stable buffers in `tensor`, as
+ * coli_metal_matmul does for its existing weight formats. Returns 0 for CPU
+ * fallback when validation, capability, allocation, or execution fails.
+ */
+typedef enum {
+ COLI_METAL_AFFINE_CAP_NOT_INITIALIZED = 0,
+ COLI_METAL_AFFINE_CAP_PIPELINE_UNAVAILABLE = 1,
+ COLI_METAL_AFFINE_CAP_SIMD_WIDTH_UNSUPPORTED = 2,
+ COLI_METAL_AFFINE_CAP_READY = 3
+} ColiMetalAffineCapability;
+
+/* Reports why the runtime affine path is unavailable so tests and callers can
+ * distinguish an optional hardware-width fallback from a pipeline failure.
+ */
+ColiMetalAffineCapability coli_metal_affine_capability(void);
+int coli_metal_affine_available(void);
+int coli_metal_matmul_affine(ColiMetalTensor **tensor,
+ float *y, const float *x, int batch,
+ const ColiAffineQuantizedView *view);
+
void coli_metal_tensor_free(ColiMetalTensor *tensor);
+/* Weight payload bytes only, preserving the established QT API contract. */
size_t coli_metal_tensor_bytes(const ColiMetalTensor *tensor);
/*
diff --git a/c/backend_metal.mm b/c/backend_metal.mm
index 3b767e2b..22671d51 100644
--- a/c/backend_metal.mm
+++ b/c/backend_metal.mm
@@ -156,6 +156,107 @@ kernel void mm_gemv(device const uchar* w [[buffer(0)]], // raw weight by
if (slane == 0) y[row] = (fmt == 0 || fmt == 4 || fmt == 8) ? acc : acc * scale[o];
}
+// MLX affine packed GEMV, adapted from Swiftlet's gemv_affine_fast Q4/Q8
+// kernels (Apache-2.0, commit b3a04676748c7597800c5bcc8b80a32508f9f43d).
+// Modified here for Colibri's batched standalone API and checked descriptor.
+// This is a separate representation from mm_gemv fmt=4: q is unsigned and
+// every group reconstructs weights as scale*q + bias.
+struct AffineGemvParams {
+ uint output_dim;
+ uint input_dim;
+ uint group_size;
+ uint scalar_format; // ColiAffineScalarFormat: 0=f32, 1=f16, 2=bf16
+ uint batch;
+};
+
+inline uint affine_load_u32(device const uchar *p, ulong offset) {
+ return uint(p[offset]) | (uint(p[offset+1]) << 8) |
+ (uint(p[offset+2]) << 16) | (uint(p[offset+3]) << 24);
+}
+
+inline float affine_load_scalar(device const uchar *p, uint index, uint format) {
+ if (format == 0) return as_type<float>(affine_load_u32(p, ulong(index)*4));
+ ulong offset = ulong(index)*2;
+ ushort value = ushort(p[offset]) | (ushort(p[offset+1]) << 8);
+ if (format == 1) return float(as_type<half>(value));
+ return as_type<float>(uint(value) << 16);
+}
+
+kernel void mm_affine_q4(device const float *x [[buffer(0)]],
+ device const uchar *weights [[buffer(1)]],
+ device const uchar *scales [[buffer(2)]],
+ device const uchar *biases [[buffer(3)]],
+ device float *y [[buffer(4)]],
+ constant AffineGemvParams &p [[buffer(5)]],
+ uint2 position [[thread_position_in_grid]],
+ uint lane [[thread_index_in_simdgroup]]) {
+ uint flat_row=position.y, total=p.batch*p.output_dim;
+ if (flat_row >= total) return;
+ uint sample=flat_row/p.output_dim, row=flat_row%p.output_dim;
+ uint packed_cols=p.input_dim/8, groups=p.input_dim/p.group_size;
+ uint words_per_group=p.group_size/8;
+ device const uint *wr=(device const uint*)(weights + ulong(row)*packed_cols*4);
+ float acc=0.f;
+ for (uint group=lane; group<groups; group+=32) {
+ float qdot=0.f, xsum=0.f;
+ uint word_base=group*words_per_group;
+ uint xbase=sample*p.input_dim + group*p.group_size;
+ for (uint wi=0; wi<words_per_group; wi++) {
+ uint word=wr[word_base+wi], xo=xbase+wi*8;
+ qdot += float(word & 0xFu)*x[xo]
+ + float((word >> 4) & 0xFu)*x[xo+1]
+ + float((word >> 8) & 0xFu)*x[xo+2]
+ + float((word >> 12) & 0xFu)*x[xo+3]
+ + float((word >> 16) & 0xFu)*x[xo+4]
+ + float((word >> 20) & 0xFu)*x[xo+5]
+ + float((word >> 24) & 0xFu)*x[xo+6]
+ + float((word >> 28) & 0xFu)*x[xo+7];
+ xsum += x[xo]+x[xo+1]+x[xo+2]+x[xo+3]
+ + x[xo+4]+x[xo+5]+x[xo+6]+x[xo+7];
+ }
+ uint scalar_index=row*groups+group;
+ acc += affine_load_scalar(scales,scalar_index,p.scalar_format)*qdot
+ + affine_load_scalar(biases,scalar_index,p.scalar_format)*xsum;
+ }
+ acc=simd_sum(acc);
+ if (lane == 0) y[flat_row]=acc;
+}
+
+kernel void mm_affine_q8(device const float *x [[buffer(0)]],
+ device const uchar *weights [[buffer(1)]],
+ device const uchar *scales [[buffer(2)]],
+ device const uchar *biases [[buffer(3)]],
+ device float *y [[buffer(4)]],
+ constant AffineGemvParams &p [[buffer(5)]],
+ uint2 position [[thread_position_in_grid]],
+ uint lane [[thread_index_in_simdgroup]]) {
+ uint flat_row=position.y, total=p.batch*p.output_dim;
+ if (flat_row >= total) return;
+ uint sample=flat_row/p.output_dim, row=flat_row%p.output_dim;
+ uint packed_cols=p.input_dim/4, groups=p.input_dim/p.group_size;
+ uint words_per_group=p.group_size/4;
+ device const uint *wr=(device const uint*)(weights + ulong(row)*packed_cols*4);
+ float acc=0.f;
+ for (uint group=lane; group<groups; group+=32) {
+ float qdot=0.f, xsum=0.f;
+ uint word_base=group*words_per_group;
+ uint xbase=sample*p.input_dim + group*p.group_size;
+ for (uint wi=0; wi<words_per_group; wi++) {
+ uint word=wr[word_base+wi], xo=xbase+wi*4;
+ qdot += float(word & 0xFFu)*x[xo]
+ + float((word >> 8) & 0xFFu)*x[xo+1]
+ + float((word >> 16) & 0xFFu)*x[xo+2]
+ + float((word >> 24) & 0xFFu)*x[xo+3];
+ xsum += x[xo]+x[xo+1]+x[xo+2]+x[xo+3];
+ }
+ uint scalar_index=row*groups+group;
+ acc += affine_load_scalar(scales,scalar_index,p.scalar_format)*qdot
+ + affine_load_scalar(biases,scalar_index,p.scalar_format)*xsum;
+ }
+ acc=simd_sum(acc);
+ if (lane == 0) y[flat_row]=acc;
+}
+
// Batched bindless expert GEMV: each row gr belongs to expert erow[gr], whose weight and
// scale live at gpuAddresses waddr[e]/saddr[e] (zero-copy in the RAM slab). fmt 1=i8, 2=i4
// per-row, 4=i4 grouped (scale layout [O][ng], ng=ceil(K/qgs) -- same convention as mm_gemv
@@ -592,12 +693,23 @@ kernel void kda_state(
struct ColiMetalTensor {
id<MTLBuffer> w; // weights (wrapped, zero-copy when page-aligned)
id<MTLBuffer> s; // scales
- int fmt, I, O; size_t wbytes;
+ id<MTLBuffer> b; // affine bias (nil for existing QT formats)
+ int fmt, scalar_fmt, affine;
+ size_t I, O, group_size, wbytes, resident_bytes;
+ const void *host_w, *host_s, *host_b;
};
+static void tensor_destroy(ColiMetalTensor *t) {
+ if (!t) return;
+ t->w=nil; t->s=nil; t->b=nil;
+ delete t;
+}
+
static id<MTLDevice> g_dev;
static id<MTLCommandQueue> g_queue;
static id<MTLComputePipelineState> g_gemv, g_moe_gemv, g_moe_silu, g_moe_silu_clamped, g_moe_fwht;
+static id<MTLComputePipelineState> g_affine_q4, g_affine_q8;
+static int g_affine_width_ok;
// fmt=6: sign-bit buffers for the GPU FWHT, one per tile size, cached forever (a
// handful of sizes). The xorshift64* draw replicates quant.h e8_signs exactly —
@@ -842,6 +954,7 @@ extern "C" int coli_metal_init(void) {
g_moe_fwht = [g_dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@"moe_fwht"] error:&err];
auto P=[&](const char*n){ return [g_dev newComputePipelineStateWithFunction:[lib newFunctionWithName:@(n)] error:&err]; };
g_moe_silu_clamped=P("moe_silu_clamped");
+ g_affine_q4=P("mm_affine_q4"); g_affine_q8=P("mm_affine_q8");
g_a_rms=P("a_rmsnorm"); g_a_rope=P("a_rope"); g_a_copy=P("a_copy");
g_a_qabs=P("a_qabs"); g_a_score=P("a_score"); g_a_smax=P("a_smax"); g_a_clat=P("a_clat"); g_a_ctx=P("a_ctx");
g_a_add=P("a_add"); g_r_router=P("r_router"); g_r_top8=P("r_top8"); g_r_top8p=P("r_top8_par");
@@ -849,6 +962,17 @@ extern "C" int coli_metal_init(void) {
g_kda_state=P("kda_state");
g_kda_conv_silu=P("kda_conv_silu"); g_kda_l2_norm=P("kda_l2_norm");
if(!g_a_add||!g_r_router||!g_r_top8||!g_r_top8p||!g_kv_rope||!g_kv_clear||!g_kda_state||!g_kda_conv_silu||!g_kda_l2_norm){ fprintf(stderr,"[metal] tail pipelines failed\n"); g_dev=nil; return 0; }
+ if (!g_affine_q4 || !g_affine_q8) {
+ fprintf(stderr,"[metal] MLX affine GEMV disabled: pipeline creation failed\n");
+ g_affine_width_ok = 0;
+ } else {
+ g_affine_width_ok = [g_affine_q4 threadExecutionWidth] == 32 &&
+ [g_affine_q8 threadExecutionWidth] == 32;
+ if (!g_affine_width_ok)
+ fprintf(stderr,"[metal] MLX affine GEMV disabled: simd width Q4=%lu Q8=%lu, expected 32\n",
+ (unsigned long)[g_affine_q4 threadExecutionWidth],
+ (unsigned long)[g_affine_q8 threadExecutionWidth]);
+ }
// r_top8_par's reduction hardcodes SIMD width 32 (shuffle-down offsets 16..1, one
// 32-thread threadgroup per row). True on all Apple Silicon shipped to date, but a
// non-32-width device would reduce wrongly AND race multiple lane-0 writers, so this
@@ -968,9 +1092,21 @@ extern "C" void coli_metal_shutdown(void) {
}
#endif
g_resset_obj=nil; g_resset_enabled=false; g_resset_dirty=false;
- g_gemv=nil; g_queue=nil; g_dev=nil; g_tensor_count=g_tensor_bytes=0;
+ g_gemv=nil; g_affine_q4=nil; g_affine_q8=nil; g_affine_width_ok=0;
+ g_queue=nil; g_dev=nil; g_tensor_count=g_tensor_bytes=0;
}
extern "C" int coli_metal_available(void) { return g_dev != nil; }
+extern "C" ColiMetalAffineCapability coli_metal_affine_capability(void) {
+ if (!g_dev) return COLI_METAL_AFFINE_CAP_NOT_INITIALIZED;
+ if (!g_affine_q4 || !g_affine_q8)
+ return COLI_METAL_AFFINE_CAP_PIPELINE_UNAVAILABLE;
+ if (!g_affine_width_ok)
+ return COLI_METAL_AFFINE_CAP_SIMD_WIDTH_UNSUPPORTED;
+ return COLI_METAL_AFFINE_CAP_READY;
+}
+extern "C" int coli_metal_affine_available(void) {
+ return coli_metal_affine_capability() == COLI_METAL_AFFINE_CAP_READY;
+}
extern "C" void coli_metal_stats(size_t *c, size_t *b) { if(c)*c=g_tensor_count; if(b)*b=g_tensor_bytes; }
extern "C" int coli_metal_mem_info(size_t *used, size_t *total) {
if (!g_dev) return 0;
@@ -999,13 +1135,18 @@ extern "C" int coli_metal_matmul(ColiMetalTensor **tp, float *y, const float *x,
}
@autoreleasepool {
ColiMetalTensor *t = *tp;
+ if (t && t->affine) return 0;
if (!t) {
t = new ColiMetalTensor();
- t->fmt = fmt; t->I = I; t->O = O; t->wbytes = fmt_bytes(fmt, I, O);
+ t->fmt = fmt; t->scalar_fmt = 0; t->affine = 0;
+ t->I = I; t->O = O; t->group_size = (size_t)gs;
+ t->host_w = weights; t->host_s = scales; t->host_b = NULL;
+ t->wbytes = fmt_bytes(fmt, I, O); t->resident_bytes = t->wbytes;
+ t->b = nil;
t->w = wrap(weights, t->wbytes);
{ size_t sb=fmt_scale_bytes(fmt, I, O, gs); t->s=sb?wrap(scales,sb):0; }
*tp = t;
- g_tensor_count++; g_tensor_bytes += t->wbytes;
+ g_tensor_count++; g_tensor_bytes += t->resident_bytes;
}
id<MTLBuffer> bx = [g_dev newBufferWithBytes:x length:(size_t)S*I*sizeof(float) options:MTLResourceStorageModeShared];
id<MTLBuffer> by = [g_dev newBufferWithLength:(size_t)S*O*sizeof(float) options:MTLResourceStorageModeShared];
@@ -1025,6 +1166,100 @@ extern "C" int coli_metal_matmul(ColiMetalTensor **tp, float *y, const float *x,
return 1;
}
+struct AffineGemvParamsHost {
+ uint32_t output_dim;
+ uint32_t input_dim;
+ uint32_t group_size;
+ uint32_t scalar_format;
+ uint32_t batch;
+};
+static_assert(sizeof(AffineGemvParamsHost) == 5*sizeof(uint32_t),
+ "Metal affine parameter layout drift");
+
+extern "C" int coli_metal_matmul_affine(ColiMetalTensor **tp,
+ float *y, const float *x, int batch,
+ const ColiAffineQuantizedView *view) {
+ if (!tp || !y || !x || !coli_metal_affine_available() ||
+ !coli_metal_affine_dispatch_supported(view,batch))
+ return 0;
+ @autoreleasepool {
+ const unsigned bits=coli_affine_bits(view->format), per_word=32u/bits;
+ const size_t groups=view->input_dim/view->group_size;
+ const size_t wbytes=view->output_dim*(view->input_dim/per_word)*sizeof(uint32_t);
+ const size_t scalar_bytes=view->output_dim*groups*
+ coli_affine_scalar_size(view->scalar_format);
+ if (scalar_bytes > (SIZE_MAX-wbytes)/2)
+ return 0;
+ const size_t resident_bytes=wbytes+2*scalar_bytes;
+ ColiMetalTensor *t=*tp;
+ if (t && (!t->affine || t->fmt != (int)view->format ||
+ t->scalar_fmt != (int)view->scalar_format ||
+ t->I != view->input_dim || t->O != view->output_dim ||
+ t->group_size != view->group_size ||
+ t->host_w != view->weights || t->host_s != view->scales ||
+ t->host_b != view->biases))
+ return 0;
+ const bool fresh=t==NULL;
+ if (fresh) {
+ id<MTLBuffer> bw=wrap(view->weights,wbytes);
+ id<MTLBuffer> bs=wrap(view->scales,scalar_bytes);
+ id<MTLBuffer> bb=wrap(view->biases,scalar_bytes);
+ if (!bw || !bs || !bb) return 0;
+ t=new ColiMetalTensor();
+ t->w=bw; t->s=bs; t->b=bb;
+ t->fmt=(int)view->format; t->scalar_fmt=(int)view->scalar_format;
+ t->affine=1; t->I=view->input_dim; t->O=view->output_dim;
+ t->group_size=view->group_size; t->wbytes=wbytes;
+ t->resident_bytes=resident_bytes;
+ t->host_w=view->weights; t->host_s=view->scales; t->host_b=view->biases;
+ }
+
+ const size_t input_bytes=(size_t)batch*view->input_dim*sizeof(float);
+ const size_t output_bytes=(size_t)batch*view->output_dim*sizeof(float);
+ id<MTLBuffer> bx=[g_dev newBufferWithBytes:x length:input_bytes
+ options:MTLResourceStorageModeShared];
+ id<MTLBuffer> by=[g_dev newBufferWithLength:output_bytes
+ options:MTLResourceStorageModeShared];
+ if (!bx || !by) {
+ if (fresh) tensor_destroy(t);
+ return 0;
+ }
+ AffineGemvParamsHost p = {
+ (uint32_t)view->output_dim, (uint32_t)view->input_dim,
+ (uint32_t)view->group_size, (uint32_t)view->scalar_format,
+ (uint32_t)batch
+ };
+ id<MTLCommandBuffer> cb=[g_queue commandBuffer];
+ id<MTLComputeCommandEncoder> e=[cb computeCommandEncoder];
+ if (!cb || !e) {
+ if (fresh) tensor_destroy(t);
+ return 0;
+ }
+ [e setComputePipelineState:(view->format == COLI_AFFINE_MLX_Q4 ?
+ g_affine_q4 : g_affine_q8)];
+ [e setBuffer:bx offset:0 atIndex:0]; [e setBuffer:t->w offset:0 atIndex:1];
+ [e setBuffer:t->s offset:0 atIndex:2]; [e setBuffer:t->b offset:0 atIndex:3];
+ [e setBuffer:by offset:0 atIndex:4]; [e setBytes:&p length:sizeof(p) atIndex:5];
+ [e dispatchThreads:MTLSizeMake(32,(NSUInteger)batch*view->output_dim,1)
+ threadsPerThreadgroup:MTLSizeMake(32,1,1)];
+ [e endEncoding]; [cb commit]; [cb waitUntilCompleted];
+ if (cb.status != MTLCommandBufferStatusCompleted) {
+ fprintf(stderr,"[metal] affine GEMV command buffer failed (status=%ld): %s\n",
+ (long)cb.status,
+ cb.error ? [[cb.error localizedDescription] UTF8String] : "?");
+ if (fresh) tensor_destroy(t);
+ return 0;
+ }
+ memcpy(y,[by contents],output_bytes);
+ if (fresh) {
+ *tp=t;
+ g_tensor_count++;
+ g_tensor_bytes+=t->resident_bytes;
+ }
+ }
+ return 1;
+}
+
// ---- fused decode attention scratch (GLM-5.2 dims) ----
enum { AH=6144, AHEADS=64, AQLORA=2048, AKVL=512, AROPE=64, AVH=256, AQH=256, ANOPE=192, AROWSH=448, AHQH=AHEADS*AQH, AHVH=AHEADS*AVH, AMAXS=4 };
static id<MTLBuffer> ax_,aqr_,aqf_,acomp_,aqabs_,ascore_,aclat_,actx_,aout_,aqaln_,akvaln_; static size_t ascore_cap;
@@ -1408,8 +1643,8 @@ extern "C" int coli_metal_rtop8(int par, const float *sig, const float *bias, in
extern "C" void coli_metal_tensor_free(ColiMetalTensor *t) {
if (!t) return;
- g_tensor_count--; g_tensor_bytes -= t->wbytes;
- t->w = nil; t->s = nil; delete t;
+ g_tensor_count--; g_tensor_bytes -= t->resident_bytes;
+ tensor_destroy(t);
}
extern "C" size_t coli_metal_tensor_bytes(const ColiMetalTensor *t) { return t ? t->wbytes : 0; }
diff --git a/c/tests/test_affine_quant.c b/c/tests/test_affine_quant.c
index 939802b3..35db0601 100644
--- a/c/tests/test_affine_quant.c
+++ b/c/tests/test_affine_quant.c
@@ -1,4 +1,4 @@
-#include "../affine_quant.h"
+#include "../backend_metal.h"
#include <math.h>
#include <stdint.h>
@@ -124,6 +124,11 @@ static int run_parity(ColiAffineFormat format,
bits, (int)scalar_format, coli_affine_status_string(status));
return 1;
}
+ if (!coli_metal_affine_dispatch_supported(&view, BATCH)) {
+ fprintf(stderr, "valid Metal dispatch rejected bits=%u scalar=%d\n",
+ bits, (int)scalar_format);
+ return 1;
+ }
status = coli_affine_matmul_ref(output, input, BATCH, &view);
if (status != COLI_AFFINE_OK) {
fprintf(stderr, "affine matmul failed bits=%u scalar=%d: %s\n",
@@ -195,6 +200,31 @@ static int test_validation(void) {
COLI_AFFINE_OVERFLOW);
#undef EXPECT_STATUS
if (output != 123.0f) return 1;
+
+ if (!coli_metal_affine_dispatch_supported(&view, 1) ||
+ coli_metal_affine_dispatch_supported(&view, 0) ||
+ coli_metal_affine_dispatch_supported(&view, -1))
+ return 1;
+ view.format = (ColiAffineFormat)99;
+ if (coli_metal_affine_dispatch_supported(&view, 1)) return 1;
+ view.format = COLI_AFFINE_MLX_Q4;
+#if SIZE_MAX > UINT32_MAX
+ view.output_dim = (size_t)UINT32_MAX + 1u;
+ view.weight_bytes = view.scale_bytes = view.bias_bytes = SIZE_MAX;
+ if (coli_affine_validate(&view) != COLI_AFFINE_OK ||
+ coli_metal_affine_dispatch_supported(&view, 1))
+ return 1;
+ view.output_dim = UINT32_MAX;
+ if (coli_affine_validate(&view) != COLI_AFFINE_OK ||
+ coli_metal_affine_dispatch_supported(&view, 2))
+ return 1;
+ view.output_dim = UINT32_C(65536);
+ view.input_dim = UINT32_C(1048576);
+ view.group_size = 8;
+ if (coli_affine_validate(&view) != COLI_AFFINE_OK ||
+ coli_metal_affine_dispatch_supported(&view, 1))
+ return 1;
+#endif
return 0;
}
diff --git a/c/tests/test_backend_metal.mm b/c/tests/test_backend_metal.mm
index 54c07586..165e673e 100644
--- a/c/tests/test_backend_metal.mm
+++ b/c/tests/test_backend_metal.mm
@@ -9,6 +9,7 @@
#include <cstdlib>
#include <cstring>
#include <cmath>
+#include <algorithm>
#include <vector>
enum { F32=0, I8=1, I4=2, I2=3, I4G=4, FP8=8 };
@@ -102,6 +103,103 @@ static int run_f32_noscale(int O, int I, int S, const char *name) {
return ok?0:1;
}
+static uint16_t affine_f16(float value) {
+ uint32_t bits; memcpy(&bits,&value,sizeof(bits));
+ uint32_t sign=(bits>>16)&0x8000u, mantissa=bits&0x7fffffu;
+ int exponent=(int)((bits>>23)&0xffu)-127+15;
+ if(exponent<=0) return (uint16_t)sign;
+ if(exponent>=31) return (uint16_t)(sign|0x7c00u);
+ return (uint16_t)(sign|((uint32_t)exponent<<10)|(mantissa>>13));
+}
+
+static void affine_store_scalar(std::vector<uint8_t>& bytes, size_t index,
+ ColiAffineScalarFormat format, float value) {
+ uint32_t bits; memcpy(&bits,&value,sizeof(bits));
+ if(format==COLI_AFFINE_SCALAR_F32){
+ bytes[index*4]=(uint8_t)bits; bytes[index*4+1]=(uint8_t)(bits>>8);
+ bytes[index*4+2]=(uint8_t)(bits>>16); bytes[index*4+3]=(uint8_t)(bits>>24);
+ } else {
+ uint16_t encoded=format==COLI_AFFINE_SCALAR_F16 ? affine_f16(value)
+ : (uint16_t)(bits>>16);
+ bytes[index*2]=(uint8_t)encoded; bytes[index*2+1]=(uint8_t)(encoded>>8);
+ }
+}
+
+static int run_affine(ColiAffineFormat format, ColiAffineScalarFormat scalar_format,
+ int S, const char *name) {
+ enum { O=48, I=2048, GROUP=32 }; // 64 groups exercises lane's group+32 stride.
+ unsigned bits=coli_affine_bits(format), per_word=32u/bits;
+ size_t packed_words=I/per_word, scalar_count=(size_t)O*(I/GROUP);
+ size_t scalar_size=coli_affine_scalar_size(scalar_format);
+ std::vector<uint32_t> weights((size_t)O*packed_words);
+ std::vector<uint8_t> scales(scalar_count*scalar_size), biases(scalar_count*scalar_size);
+ std::vector<float> x((size_t)S*I), expected((size_t)S*O), actual((size_t)S*O);
+ uint32_t state=0x12345678u+(uint32_t)bits*17u+(uint32_t)scalar_format;
+ for(auto &word:weights){ state=state*1664525u+1013904223u; word=state; }
+ for(size_t i=0;i<scalar_count;i++){
+ float scale=(float)((int)(i%7)-3)*0.03125f;
+ float bias=(float)((int)(i%5)-2)*0.015625f;
+ affine_store_scalar(scales,i,scalar_format,scale);
+ affine_store_scalar(biases,i,scalar_format,bias);
+ }
+ for(size_t i=0;i<x.size();i++) x[i]=(float)((int)((i*11+3)%31)-15)*0.0625f;
+ ColiAffineQuantizedView view = {
+ weights.data(), scales.data(), biases.data(), weights.size()*sizeof(uint32_t),
+ scales.size(), biases.size(), O, I, GROUP, format, scalar_format
+ };
+ if(coli_affine_matmul_ref(expected.data(),x.data(),(size_t)S,&view)!=COLI_AFFINE_OK){
+ printf(" %-38s FAIL (CPU reference refused descriptor)\n",name); return 1;
+ }
+ auto relative_error=[&](){
+ double maxabs=0.0, ymax=0.0;
+ for(size_t i=0;i<actual.size();i++){
+ if(!std::isfinite(actual[i]) || !std::isfinite(expected[i]))
+ return (double)INFINITY;
+ maxabs=fmax(maxabs,fabs((double)actual[i]-expected[i]));
+ ymax=fmax(ymax,fabs((double)expected[i]));
+ }
+ return maxabs/(ymax+1e-9);
+ };
+ size_t count_before=0, bytes_before=0;
+ coli_metal_stats(&count_before,&bytes_before);
+ ColiMetalTensor *tensor=nullptr;
+ int submitted=coli_metal_matmul_affine(&tensor,actual.data(),x.data(),S,&view);
+ double first_nerr=submitted?relative_error():INFINITY;
+ size_t count_published=0, bytes_published=0;
+ coli_metal_stats(&count_published,&bytes_published);
+ const size_t weight_bytes=weights.size()*sizeof(uint32_t);
+ const size_t resident_bytes=weight_bytes+scales.size()+biases.size();
+ int published=submitted && tensor && count_published==count_before+1 &&
+ bytes_published==bytes_before+resident_bytes &&
+ coli_metal_tensor_bytes(tensor)==weight_bytes;
+
+ for(size_t i=0;i<x.size();i++) x[i]=-x[i]+(float)((int)(i%3)-1)*0.015625f;
+ int ref_reuse=coli_affine_matmul_ref(expected.data(),x.data(),(size_t)S,&view)==COLI_AFFINE_OK;
+ std::fill(actual.begin(),actual.end(),NAN);
+ int reused=published && ref_reuse &&
+ coli_metal_matmul_affine(&tensor,actual.data(),x.data(),S,&view);
+ double reuse_nerr=reused?relative_error():INFINITY;
+
+ ColiAffineQuantizedView mismatch=view;
+ mismatch.group_size=64;
+ int mismatch_valid=coli_affine_validate(&mismatch)==COLI_AFFINE_OK;
+ int mismatch_rejected=reused && mismatch_valid &&
+ !coli_metal_matmul_affine(&tensor,actual.data(),x.data(),S,&mismatch);
+ size_t count_reused=0, bytes_reused=0;
+ coli_metal_stats(&count_reused,&bytes_reused);
+ int stats_stable=count_reused==count_published && bytes_reused==bytes_published;
+
+ coli_metal_tensor_free(tensor);
+ size_t count_after=0, bytes_after=0;
+ coli_metal_stats(&count_after,&bytes_after);
+ int restored=count_after==count_before && bytes_after==bytes_before;
+ int ok=submitted && first_nerr<1e-4 && reused && reuse_nerr<1e-4 &&
+ mismatch_rejected && stats_stable && restored;
+ printf(" %-38s nerr=%.2e/%.2e S=%d groups=%d %s\n",
+ name,first_nerr,reuse_nerr,S,I/GROUP,ok?"ok":"*** MISMATCH");
+ 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
@@ -778,16 +876,30 @@ static int run_silu_mul(size_t n, const char *name) {
}
int main(void) {
- if (!coli_metal_init()) { printf("Metal unavailable (skipping)\n"); return 0; }
+ id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
+ if (!dev) { printf("Metal device unavailable (skipping)\n"); return 0; }
+ if (!coli_metal_init()) {
+ printf("Metal backend initialization failed on device %s\n",
+ [[dev name] UTF8String]);
+ return 1;
+ }
+ ColiMetalAffineCapability affine_capability=coli_metal_affine_capability();
+ if (affine_capability!=COLI_METAL_AFFINE_CAP_READY &&
+ affine_capability!=COLI_METAL_AFFINE_CAP_SIMD_WIDTH_UNSUPPORTED) {
+ printf("Metal MLX affine packed GEMV setup: FAIL (capability=%d)\n",
+ (int)affine_capability);
+ coli_metal_shutdown();
+ return 1;
+ }
/* GitHub Actions Apple Silicon runners expose Metal through the Apple
* Paravirtual device, where Metal submissions never complete (hangs -- the
* #947 CI observation). The shader compile above (coli_metal_init) still
* runs, keeping this suite's compile coverage -- the class of bug #940
* shipped -- while GPU execution is honestly skipped here. (#947 review) */
- id<MTLDevice> dev = MTLCreateSystemDefaultDevice();
- if (dev && [[dev name] containsString:@"Apple Paravirtual device"]) {
+ if ([[dev name] containsString:@"Apple Paravirtual device"]) {
printf("SKIPPED: paravirtual device (%s) -- compile-only\n",
[[dev name] UTF8String]);
+ coli_metal_shutdown();
return 0;
}
printf("Metal standalone op tests (MAE / maxAbs error vs CPU reference):\n");
@@ -871,6 +983,22 @@ int main(void) {
fail |= run_f32_noscale(128, 7168, 1, "f32 no-scale fa O=128 I=7168 (non-page-mult)");
fail |= run_f32_noscale(96, 7168, 1, "f32 no-scale bp O=96 I=7168 (non-page-mult)");
fail |= run_f32_noscale(128, 7168, 4, "f32 no-scale fa O=128 I=7168 S=4 (prefill)");
+ if (affine_capability==COLI_METAL_AFFINE_CAP_READY) {
+ printf("Metal MLX affine packed GEMV tests:\n");
+ const char *scalar_name[] = {"f32","f16","bf16"};
+ for(int format=COLI_AFFINE_MLX_Q4;format<=COLI_AFFINE_MLX_Q8;format++)
+ for(int scalar=COLI_AFFINE_SCALAR_F32;scalar<=COLI_AFFINE_SCALAR_BF16;scalar++){
+ char name[64]; snprintf(name,sizeof(name),"affine Q%d/%s batched",
+ (int)coli_affine_bits((ColiAffineFormat)format),scalar_name[scalar]);
+ fail |= run_affine((ColiAffineFormat)format,(ColiAffineScalarFormat)scalar,3,name);
+ }
+ } else if (affine_capability==COLI_METAL_AFFINE_CAP_SIMD_WIDTH_UNSUPPORTED) {
+ printf("Metal MLX affine packed GEMV tests: SKIPPED (requires 32-lane simdgroups)\n");
+ } else {
+ printf("Metal MLX affine packed GEMV tests: FAIL (affine pipelines unavailable, capability=%d)\n",
+ (int)affine_capability);
+ fail=1;
+ }
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");