Skip to content

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

C

feat(cuda): add fmt=8 (fp8-e4m3) decode to the absorb kernels

monotophic9c7ae3871ce7
diff --git a/c/Makefile b/c/Makefile
index 9fedfa79..1ee880c1 100644
--- a/c/Makefile
+++ b/c/Makefile
@@ -784,7 +784,7 @@ backend_loader.o: backend_loader.c backend_cuda.h compat.h .build-config
# shell that has the MSVC environment set (e.g. after vcvars64.bat, or from a
# "x64 Native Tools Command Prompt"). COLI_CUDA_BUILDING_DLL enables
# __declspec(dllexport) so the 15 API symbols are exported.
-cuda-dll: backend_cuda.cu backend_cuda.h
+cuda-dll: backend_cuda.cu backend_cuda.h fp8_format.h
@command -v "$(NVCC)" >/dev/null 2>&1 || { echo "nvcc not found: set CUDA_HOME or NVCC" >&2; exit 1; }
@command -v cl >/dev/null 2>&1 || { echo "cl.exe (MSVC) not in PATH β€” run vcvars64.bat first" >&2; exit 1; }
# The banner is localized ("for x64" / "per x64" / "pour x64"): match the arch token only (#1531).
@@ -814,7 +814,7 @@ cuda-dll: backend_cuda.cu backend_cuda.h
# survives. No path is hardcoded β€” see the HIP SDK contract above.
#
# make hip-dll HIP_DLL=1 HIP_SDK_ROOT=<sdk> HIP_ARCH=gfx1151
-hip-dll: backend_cuda.cu backend_cuda.h backend_gpu_compat.h
+hip-dll: backend_cuda.cu backend_cuda.h fp8_format.h backend_gpu_compat.h
@test -x "$(HIPCC)" || command -v "$(HIPCC)" >/dev/null 2>&1 || { echo "hipcc not found at \"$(HIPCC)\": set HIP_SDK_ROOT=<path>, HIP_BIN_DIR=<path> or HIPCC=<path>" >&2; exit 1; }
@test -d "$(HIP_INCLUDE_DIR)" || { echo "HIP include dir not found: \"$(HIP_INCLUDE_DIR)\" β€” set HIP_INCLUDE_DIR=<path>" >&2; exit 1; }
@test -f "$(HIP_INCLUDE_DIR)/hip/hip_runtime.h" || { echo "hip/hip_runtime.h missing under \"$(HIP_INCLUDE_DIR)\" β€” set HIP_INCLUDE_DIR=<path>" >&2; exit 1; }
@@ -833,7 +833,7 @@ backend_cuda_ink.o: backend_cuda_ink.cu backend_cuda_ink.h .build-config
@command -v "$(NVCC)" >/dev/null 2>&1 || { echo "nvcc not found: set CUDA_HOME or NVCC" >&2; exit 1; }
"$(NVCC)" $(NVCCFLAGS) -c backend_cuda_ink.cu -o $@
-backend_cuda.o: backend_cuda.cu backend_cuda.h backend_gpu_compat.h .build-config
+backend_cuda.o: backend_cuda.cu backend_cuda.h fp8_format.h backend_gpu_compat.h .build-config
@command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
"$(GPUCC)" $(GPUFLAGS) -c backend_cuda.cu -o $@
@@ -956,7 +956,7 @@ rans: $(RANSLIB)
$(RANSLIB): tools/rans_ctypes.c rans.h
$(CC) $(CFLAGS) -fPIC -shared $< -o $@ $(LDFLAGS)
-cuda-test: tests/test_mxfp4_expert_cuda.cu backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/test_backend_cuda.cu tests/test_ragged_attention.cu tests/test_absorb_determinism.cu tests/test_mxfp4_cuda.cu tests/mxfp4_ref.c tests/test_fp8_warp_cuda.cu tests/test_fp8_cuda.cu tests/test_weights_owned_cuda.cu tests/test_cuda_fmt_trap_cuda.cu tests/test_alloc_footprint_cuda.cu tests/test_cuda_init_failure.cu
+cuda-test: tests/test_mxfp4_expert_cuda.cu backend_cuda.cu backend_cuda.h fp8_format.h backend_gpu_compat.h tests/test_backend_cuda.cu tests/test_ragged_attention.cu tests/test_absorb_determinism.cu tests/test_mxfp4_cuda.cu tests/mxfp4_ref.c tests/test_fp8_warp_cuda.cu tests/test_fp8_cuda.cu tests/test_weights_owned_cuda.cu tests/test_cuda_fmt_trap_cuda.cu tests/test_alloc_footprint_cuda.cu tests/test_cuda_init_failure.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) $(ANS_NVCC_LIBS) $(GPU_TEST_LIBS)
./backend_cuda_test$(EXE)
@@ -1067,7 +1067,7 @@ gpu-compile: backend_cuda.o
"$(GPUCC)" $(GPUFLAGS) tests/test_weights_owned_cuda.cu -o weights_owned_test$(EXE) $(ANS_NVCC_LIBS) $(GPU_TEST_LIBS)
"$(GPUCC)" $(GPUFLAGS) tests/test_cuda_fmt_trap_cuda.cu -o cuda_fmt_trap_test$(EXE) $(ANS_NVCC_LIBS) $(GPU_TEST_LIBS)
-cuda-bench: backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/bench_tensor_core.cu
+cuda-bench: backend_cuda.cu backend_cuda.h fp8_format.h backend_gpu_compat.h tests/bench_tensor_core.cu
@command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
"$(GPUCC)" $(GPUFLAGS) backend_cuda.cu tests/bench_tensor_core.cu -o backend_cuda_bench$(EXE) $(ANS_NVCC_LIBS)
./backend_cuda_bench$(EXE)
@@ -1075,7 +1075,7 @@ cuda-bench: backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/bench_tens
# fmt=8 kernel bench: old vs COLI_CUDA_F8_WARP kernels per decode path, census
# expert shapes, JSON on stdout (kernel time only). The build is a separate
# file target so tools/run_f8_bench.sh can keep stdout pure JSON.
-fp8_bench$(EXE): backend_cuda.cu backend_cuda.h backend_gpu_compat.h tests/bench_fp8_cuda.cu
+fp8_bench$(EXE): backend_cuda.cu backend_cuda.h fp8_format.h backend_gpu_compat.h tests/bench_fp8_cuda.cu
@command -v "$(GPUCC)" >/dev/null 2>&1 || { echo "$(GPUCC_NAME) not found" >&2; exit 1; }
"$(GPUCC)" $(GPUFLAGS) tests/bench_fp8_cuda.cu -o fp8_bench$(EXE) $(ANS_NVCC_LIBS)
fp8-bench: fp8_bench$(EXE)
@@ -1550,6 +1550,13 @@ tests/test_fp8_passthrough$(EXE): tests/test_fp8_passthrough.c quant.h fp8_forma
tests/test_cuda_fmt_guard$(EXE): tests/test_cuda_fmt_guard.c backend_cuda.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+# The fmt=8 LUT-gate state machine. Like test_cuda_fmt_guard it links no CUDA
+# object and needs no toolchain: the two decisions live as pure predicates in
+# backend_cuda.h and backend_cuda.cu calls them, so this pins the engine's own
+# logic on a plain CPU build.
+tests/test_cuda_lut_gate$(EXE): tests/test_cuda_lut_gate.c backend_cuda.h
+ $(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
+
tests/test_fp8_load$(EXE): tests/test_fp8_load.c colibri.c oracle.h st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h fp8_format.h idot.h sample.h kv_persist.h telemetry.h
$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)
@@ -2082,6 +2089,13 @@ tests/test_olmoe_dot_i8_16$(EXE): tests/test_olmoe_dot_i8_16.c olmoe.c sse41_ker
tests/test_olmoe_dot_i8_16_sse41$(EXE): tests/test_olmoe_dot_i8_16.c olmoe.c sse41_kernels.h st.h json.h compat.h sample.h tok.h tok_unicode.h tok_unicode_o200k.h omp_tune.h route_trace.h serve_codec.h
$(CC) $(NOCUDA_CFLAGS) -msse4.1 -mno-avx2 -mno-fma $< -o $@ $(NOCUDA_LDFLAGS)
+# layer_cuda_shard_kvb's format-allowlist refusal (see the test's file header). The
+# function only exists under -DCOLI_CUDA, so on a default (CPU) build the binary is a
+# loud SKIP; built with CUDA=1 it links backend_cuda.o ($(CUDA_OBJ)) and exercises the
+# real guard -- no GPU needed, every probed path returns before any device context.
+tests/test_shard_kvb_refuse$(EXE): tests/test_shard_kvb_refuse.c colibri.c st.h uring.h json.h tok.h tok_unicode.h compat.h grammar.h tier.h quant.h fp8_format.h sample.h kv_persist.h telemetry.h $(CUDA_OBJ)
+ $(CC) $(CFLAGS) $< $(CUDA_OBJ) -o $@ $(LDFLAGS)
+
test-c: $(TEST_BINS)
$(PYTHON) tools/run_tests.py $(TEST_BINS)
diff --git a/c/backend_cuda.cu b/c/backend_cuda.cu
index a0c892a5..b7930a0f 100644
--- a/c/backend_cuda.cu
+++ b/c/backend_cuda.cu
@@ -1,7 +1,12 @@
#include "backend_cuda.h"
+#include "fp8_format.h" /* FP8_BLOCK: the shared fmt=8 scale-block edge (see that header) */
#include "backend_gpu_compat.h"
+static_assert(FP8_BLOCK == 128, "fmt=8 on-disk containers carry ceil(dim/128)-edged scale "
+ "grids (mint tool, docs/FORMATS.md); FP8_BLOCK is container format, not a "
+ "tunable -- an edit here is a format change");
+
/* Optional fmt=8 decode candidate (COLI_CUDA_F8_WARP=2): cuda_fp8.h maps
* __nv_cvt_fp8_to_halfraw to an sm_89+ cvt instruction, with a bit-manip
* fallback below 890. CUDA-only; the HIP build keeps the LUT decode. */
@@ -287,13 +292,14 @@ __device__ static inline float mx4_weight_at(const uint8_t *q, int i) {
* branch and the fall-through is a refusal.
*
* It used to be the other way round: int2 was the fall-through, so every format
- * this function does not decode -- fmt=5 (int3-g64), fmt=6 (E8/IQ3), fmt=8
- * (fp8-e4m3), and anything added later -- was read as 2-bit values and returned
- * numbers. Meanwhile the CPU functions doing the same job on the same tensor,
- * qt_addrow and qt_matvec_rows (colibri.c), both exit(1) naming the function and
- * the fmt. Two backends, identical unsupported input, one refusing and one
- * fabricating: that asymmetry is the defect, independent of any particular
- * format's arrival.
+ * this function does not decode -- fmt=5 (int3-g64), fmt=6 (E8/IQ3), and
+ * anything added later -- was read as 2-bit values and returned numbers.
+ * (fmt=8 was in that misread set too, then refused, until it gained its own
+ * explicit branch below for the absorb path.) Meanwhile the CPU functions
+ * doing the same job on the same tensor, qt_addrow and qt_matvec_rows
+ * (colibri.c), both exit(1) naming the function and the fmt. Two backends,
+ * identical unsupported input, one refusing and one fabricating: that
+ * asymmetry is the defect, independent of any particular format's arrival.
*
* WHY __trap() AND NOT A DIAGNOSTIC. This is device code inside a running
* kernel; there is no stderr to name the tensor on and no way to unwind. __trap
@@ -322,6 +328,15 @@ __device__ static float weight_at(const void *weights, int fmt, size_t row, int
const uint8_t *base = static_cast<const uint8_t *>(weights) + row;
if (fmt == 0) return reinterpret_cast<const float *>(base)[i];
if (fmt == 1) return static_cast<float>(reinterpret_cast<const int8_t *>(base)[i]);
+ /* fmt=8 (fp8-e4m3): raw byte, same layout as fmt=1 (row_bytes(8,I)==I), decoded
+ * through the shared c_e4m3 LUT (same table quant_matmul's fmt==8 branch reads,
+ * uploaded once by coli_cuda_fp8_set_lut). Callers gate on the LUT being live
+ * before a fmt=8 tensor ever reaches this function (coli_cuda_tensor_upload
+ * refuses the upload otherwise), so the table is always populated here. Returns
+ * the decoded WEIGHT only, unscaled -- absorb_scale below applies the
+ * per-128x128-block scale, exactly like every other quantized fmt returns
+ * unscaled through this function. */
+ if (fmt == 8) return c_e4m3[base[i]];
const uint8_t *q = base;
if (fmt == 2 || fmt == 4) { /* fmt=4: same nibble layout */
uint8_t v = q[i >> 1];
@@ -335,13 +350,34 @@ __device__ static float weight_at(const void *weights, int fmt, size_t row, int
return 0.0f; /* not reached: __trap() does not return */
}
-/* Scale for output `row`, input element `k`. fmt=4 (grouped int4) stores ng
- * scales per row at scales[row*ng + k/gs]; every other quantized format has
- * one scale per row at scales[row]. Mirrors quant_matmul's fmt==4 branch so the
+/* Scale for output `row`, input element `k`. Three layouts reach this: fmt=4
+ * (grouped int4) stores ng scales per row at scales[row*ng + k/gs]; fmt=8
+ * (fp8-e4m3) stores one scale per 128x128 BLOCK, block-row-major, and is
+ * handled by its own branch below; every OTHER quantized format has one scale
+ * per row at scales[row]. Mirrors quant_matmul's fmt==4 branch so the
* attention absorb kernels apply per-group scales instead of the per-row
* (fmt=2) semantic that crashed #298's g64 kv_b. */
__device__ static float absorb_scale(const float *wscale, int fmt, int gs, int ng, int row, int k) {
if (!fmt) return 1.f;
+ if (fmt == 8) {
+ /* fp8-e4m3: one f32 scale per 128x128 BLOCK, block-row-major
+ * ([ceil(O/128), ceil(I/128)]), exactly quant_matmul's fmt==8 indexing
+ * (scl[i >> 7] on a scale row selected by o >> 7) and matmul_fp8's CPU
+ * reference (quant.h). `ng` here is coli_cuda_tensor_upload's t->ng,
+ * which for fmt=8 is set to ceil(I/128) specifically (not the fmt=4
+ * group count) -- see the upload-time assignment there. `gs` is unused
+ * for fmt=8 (always 0, only fmt=4 sets it), so the block edge is the
+ * fixed FP8_BLOCK constant (fp8_format.h, shared with the CPU side),
+ * not a caller-supplied group size. Rounding note: the GEOMETRY here
+ * matches quant_matmul_f8w/matmul_fp8, but their fp8 accumulation
+ * convention (f32 partial per block, scale once per partial, double
+ * across blocks) is NOT carried into the absorb kernels -- they apply
+ * the scale per element into a float accumulator, matching their own
+ * fmt=4 arm's long-standing behavior; CPU-vs-CUDA absorb divergence
+ * is an accepted, documented class (#510). */
+ int rowBlk = row / FP8_BLOCK, colBlk = k / FP8_BLOCK;
+ return wscale[(size_t)rowBlk * ng + colBlk];
+ }
if (fmt != 4) return wscale[row];
int g = k / gs; if (g >= ng) g = ng - 1; /* tail of the last (partial) group */
return wscale[(size_t)row * ng + g];
@@ -558,9 +594,9 @@ __global__ static void quant_matmul(float *y, const float *x, const void *weight
* the ORIGINAL dense path, kept for COLI_CUDA_F8_WARP=0; the default
* routes fmt=8 to quant_matmul_f8w instead (quant_matmul_launch). */
const uint8_t *wrow = static_cast<const uint8_t *>(weights) + row;
- const float *scl = scales + (size_t)(o >> 7) * (size_t)((I + 127) >> 7);
+ const float *scl = scales + (size_t)(o / FP8_BLOCK) * (size_t)((I + FP8_BLOCK - 1) / FP8_BLOCK);
for (int i = threadIdx.x; i < I; i += blockDim.x)
- sum += xs[i] * c_e4m3[wrow[i]] * scl[i >> 7];
+ sum += xs[i] * c_e4m3[wrow[i]] * scl[i / FP8_BLOCK];
} else {
for (int i = threadIdx.x; i < I; i += blockDim.x)
sum += xs[i] * weight_at(weights, fmt, row, i);
@@ -1272,10 +1308,15 @@ extern "C" int coli_cuda_init(const int *devices, int count) {
}
}
if (g_nctx) {
- int same = count == g_nctx;
- for (int i = 0; same && i < count; i++) same = devices[i] == g_ctx[i].device;
- if (!same) std::fprintf(stderr, "[CUDA] device list change requires shutdown first\n");
- return same;
+ /* Same decision as before, routed through the shared predicate in
+ * backend_cuda.h so a host-side test can pin it without nvcc; the
+ * return value is unchanged (1 for the same set, 0 otherwise). */
+ int live[COLI_CUDA_MAX_DEVICES];
+ for (int i = 0; i < g_nctx; i++) live[i] = g_ctx[i].device;
+ int d = coli_cuda_init_disposition(g_nctx, count, devices, live);
+ if (d == COLI_CUDA_INIT_REFUSE)
+ std::fprintf(stderr, "[CUDA] device list change requires shutdown first\n");
+ return d == COLI_CUDA_INIT_ACCEPT;
}
for (int i = 0; i < count; i++) {
int device = devices[i];
@@ -1356,6 +1397,22 @@ extern "C" void coli_cuda_shutdown(void) {
ctx->group_desc=nullptr; ctx->group_desc_cap=0;
}
g_nctx = 0;
+ /* g_fp8_lut_ready is PROCESS-WIDE while the e4m3 table (c_e4m3, a
+ * __constant__ device symbol whose lifetime is the CUDA primary context,
+ * not this file's host-side DeviceContext structs) is PER-DEVICE. A later
+ * coli_cuda_init may select a device the previous span never published to;
+ * without this reset the upload gate (g_fp8_lut_ready, checked in
+ * coli_cuda_tensor_upload) would still be satisfied from the PREVIOUS
+ * boot and admit fmt=8 tensors whose kernels there decode against an
+ * unwritten (zero) table: silent all-zero weights, the exact
+ * fabricated-numbers failure mode the format gates exist to refuse.
+ * Reset so every boot must publish its own LUT (coli_cuda_fp8_set_lut)
+ * before any fmt=8 upload. Shutdown is the ONLY site that needs to clear
+ * the flag: coli_cuda_init refuses a re-init that names a different
+ * device set (it returns early while g_nctx is non-zero, leaving the
+ * existing contexts and their published table untouched), so the device
+ * set can only WIDEN by passing through here first. */
+ g_fp8_lut_ready = 0;
#ifdef COLI_ANS
if(g_ans_sidecar){std::fclose(g_ans_sidecar);g_ans_sidecar=nullptr;}
#if defined(__linux__)
@@ -1444,7 +1501,9 @@ 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 */
+ /* kernels would read a zero LUT; shared predicate, pinned by
+ * tests/test_cuda_lut_gate.c without a CUDA toolchain */
+ if (!coli_cuda_fp8_gate_admits(fmt, g_fp8_lut_ready)) return 0;
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;
@@ -1455,9 +1514,9 @@ extern "C" int coli_cuda_tensor_upload(ColiCudaTensor **tensor,
t->ng = (I + 31) / 32;
t->scale_count = (size_t)O * t->ng;
}
- 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 (fmt == 8) { /* per-block scales: [ceil(O/FP8_BLOCK), ceil(I/FP8_BLOCK)] (fp8_format.h) */
+ t->ng = (int)fp8_nblk(I);
+ t->scale_count = (size_t)fp8_nblk(O) * (size_t)t->ng;
}
if (!cuda_ok(cudaMalloc(&t->weights, t->weight_bytes), "tensor allocation")) {
coli_cuda_tensor_free(t);
@@ -2278,18 +2337,20 @@ 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.
+ * per-row scales, fmt=4 group scales, and fmt=8 per-128x128-block scales.
+ * Refuse anything else (fmt=5/6/7) 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.) fmt=8 support
+ * funnels through this one predicate for all the absorb host wrappers below,
+ * so none of them needed a separate change.
*
* The admissible set is weight_at's own, taken from the shared predicate rather
- * than restated as `fmt <= 4`: this gate and weight_at's device-side backstop
- * must not be able to drift apart, and the old inequality also admitted
- * NEGATIVE fmt values, which weight_at would then have fallen through on. Same
- * truth table for every fmt a container can actually carry (0..8), so no
- * existing container changes behaviour here. */
+ * than restated as an inequality: this gate and weight_at's device-side
+ * backstop must not be able to drift apart, and the old `fmt <= 4` also
+ * admitted NEGATIVE fmt values, which weight_at would then have fallen through
+ * on. A fmt=8 tensor implies a live e4m3 LUT (upload refuses it otherwise --
+ * see the predicate's caveat note in backend_cuda.h), so no extra gate is
+ * needed here. */
static int absorb_fmt_ok(const ColiCudaTensor *w){
return w && coli_cuda_weight_at_supported(w->fmt);
}
diff --git a/c/backend_cuda.h b/c/backend_cuda.h
index 2579561d..e58dbf95 100644
--- a/c/backend_cuda.h
+++ b/c/backend_cuda.h
@@ -23,7 +23,9 @@ extern "C" {
/* Weight formats the generic per-element device decoder (weight_at,
* backend_cuda.cu) can actually decode: f32, int8-row, int4 nibbles (fmt=2 and
- * the grouped fmt=4, same packing), and int2. Nothing else.
+ * the grouped fmt=4, same packing), int2, and fmt=8 (fp8-e4m3 raw bytes,
+ * decoded through the c_e4m3 LUT -- absorb-path support; absorb_scale supplies
+ * its per-128x128-block scale). Nothing else.
*
* WHY THIS IS A PREDICATE AND NOT A COMMENT. weight_at used to END in the int2
* decode as an unguarded fall-through, so ANY other format handed to it -- a
@@ -42,12 +44,60 @@ extern "C" {
* same arrangement colibri.c uses for metal_fused_fmt_ok.
*
* NOT a statement about which formats the CUDA BACKEND supports: quant_matmul
- * has its own explicit branches for fmt=6 (E8/IQ3), fmt=7 (MXFP4) and fmt=8
- * (fp8-e4m3) that never route through weight_at. This predicate is scoped to
- * weight_at's own dispatch, which is what the absorb and grouped-expert kernels
- * decode through. */
+ * has its own explicit branches for fmt=6 (E8/IQ3) and fmt=7 (MXFP4) that
+ * never route through weight_at (and its own fmt=8 branch for the dense path
+ * -- weight_at's fmt=8 branch serves the absorb kernels, which share the same
+ * c_e4m3 LUT). This predicate is scoped to weight_at's own dispatch, which is
+ * what the absorb and grouped-expert kernels decode through.
+ *
+ * fmt=8 CAVEAT, stated because the truth table alone cannot carry it: a fmt=8
+ * decode additionally requires the e4m3 LUT to have been published to the
+ * configured devices (coli_cuda_fp8_set_lut). The exact mechanism, so the
+ * claim cannot outrun it: coli_cuda_fp8_set_lut copies the table into every
+ * context live AT CALL TIME and sets a process-wide flag; the flag gates
+ * fmt=8 uploads (coli_cuda_tensor_upload refuses until it is set).
+ * coli_cuda_shutdown clears the flag; coli_cuda_init never writes it. That is
+ * enough because init will not rebuild contexts underneath a live set: a
+ * re-init naming the same device set returns success and leaves the contexts,
+ * and the table published to them, untouched, while one naming a different
+ * device set is refused before any context is rebuilt. So the device set
+ * cannot widen past what the last publish covered without going through
+ * shutdown, and no fmt=8 ColiCudaTensor can reach a kernel whose device has
+ * an unwritten table. This predicate
+ * deliberately does not restate that gate: it answers "does weight_at have a
+ * decode branch for this fmt", which is the question the launch-site gates
+ * and the device-side __trap() backstop share. */
static inline int coli_cuda_weight_at_supported(int fmt) {
- return fmt == 0 || fmt == 1 || fmt == 2 || fmt == 3 || fmt == 4;
+ return fmt == 0 || fmt == 1 || fmt == 2 || fmt == 3 || fmt == 4 || fmt == 8;
+}
+
+/* The two decisions the fmt=8 LUT gate rests on, as pure predicates. They live
+ * here rather than inline in backend_cuda.cu so a host-side test can pin them
+ * with no CUDA toolchain and no GPU (tests/test_cuda_lut_gate.c). backend_cuda.cu
+ * calls BOTH at the real decision sites, so the test pins the engine's own
+ * logic rather than a second copy that could drift from it -- which is the
+ * failure this factoring exists to prevent, the gate having no CI reach
+ * otherwise. */
+
+/* Does the upload gate admit this tensor? Only fmt=8 needs the published
+ * table; every other format decodes without one. */
+static inline int coli_cuda_fp8_gate_admits(int fmt, int lut_ready) {
+ return fmt != 8 || lut_ready != 0;
+}
+
+/* What coli_cuda_init must do with a request while a device set may be live.
+ * BUILD: nothing is live, build the contexts. ACCEPT: the same set is already
+ * live -- return success and touch nothing, so the table published to those
+ * contexts stays valid. REFUSE: a different set is live -- refuse before
+ * rebuilding anything, so the set cannot widen past the last publish. */
+enum { COLI_CUDA_INIT_BUILD = 0, COLI_CUDA_INIT_ACCEPT = 1, COLI_CUDA_INIT_REFUSE = -1 };
+static inline int coli_cuda_init_disposition(int nctx, int count,
+ const int *want, const int *live) {
+ int i;
+ if (nctx <= 0) return COLI_CUDA_INIT_BUILD;
+ if (count != nctx) return COLI_CUDA_INIT_REFUSE;
+ for (i = 0; i < count; i++) if (want[i] != live[i]) return COLI_CUDA_INIT_REFUSE;
+ return COLI_CUDA_INIT_ACCEPT;
}
/* Opaque, persistent device copy of one resident quantized tensor. */
diff --git a/c/colibri.c b/c/colibri.c
index 8ffd06bd..9d91c461 100644
--- a/c/colibri.c
+++ b/c/colibri.c
@@ -2278,10 +2278,9 @@ static void layer_cuda_shard_kvb(Layer *l,int H,int Q,int V){
* dereferenced it -- silent, unnamed, and one refactor away from a misread.
* Refuse BY NAME instead, BEFORE any pointer/stride use, and say what happens
* instead: the un-sharded kv_b stays whole on its layer home device, where fmt=8
- * kv_b decode runs the CPU absorb path (qt_addrow/qt_matvec_rows' fmt=8
- * branches below; the CUDA absorb kernels refuse fmt=8 via absorb_fmt_ok's
- * fmt 0..4 allowlist) -- COLI_CUDA_ATTN_SHARD is a no-op for it. Same
- * "refuse rather than misread" discipline as qt_addrow/
+ * kv_b decode runs the absorb path (qt_addrow/qt_matvec_rows' fmt=8 branches, or
+ * the CUDA absorb kernels via absorb_fmt_ok) -- COLI_CUDA_ATTN_SHARD is a no-op
+ * for it. Same "refuse rather than misread" discipline as qt_addrow/
* qt_matvec_rows' guards; notice only (no exit): sharding is an opt-in
* optimization and skipping it is the correct, working behavior. Bounded once
* per process per fmt, never per layer (metal_fmt_gate_notice, the precedent
diff --git a/c/fp8_format.h b/c/fp8_format.h
index 04610efe..d10ea461 100644
--- a/c/fp8_format.h
+++ b/c/fp8_format.h
@@ -1,20 +1,25 @@
/* fmt=8 (fp8-e4m3-b128) block geometry -- the single definition site for the
- * 128x128 scale-block edge. Every consumer reaches these symbols through
- * quant.h, which includes this header where the definitions used to live:
- * matmul_fp8 and the e4m3 dequant plumbing (quant.h), the qt_addrow /
- * qt_matvec_rows / qt_from_disk paths (colibri.c), and the native-FP8
- * reduction (qwen38.c / qwen38_core.h). Kept deliberately tiny (no LUTs, no
- * functions with OpenMP pragmas, no intrinsics) so a translation unit that
- * cannot include quant.h itself can still name the block edge instead of
- * restating 128 / >>7 as literals.
+ * 128x128 scale-block edge, shared by the CPU side (quant.h: matmul_fp8,
+ * e4m3 dequant plumbing; colibri.c: qt_addrow/qt_matvec_rows, qt_from_disk)
+ * and the CUDA backend's three converted sites (backend_cuda.cu:
+ * absorb_scale, quant_matmul's fmt=8 branch, the upload-time ng/scale_count
+ * computation); the f8-warp and f8-group kernels there keep their own
+ * 128 / >>7 literals, pinned against drift by backend_cuda.cu's
+ * static_assert(FP8_BLOCK == 128). Before this header the two backends
+ * agreed by IDENTICAL LITERALS restated in each file, so an edit to one side
+ * could not break the other side's build -- only a full-scale CPU-vs-CUDA
+ * parity run would have noticed. Kept deliberately tiny (no LUTs, no
+ * functions with OpenMP pragmas, no intrinsics) so the CUDA translation unit
+ * can include it without dragging in quant.h.
*
* The in-repo FP8 tests are NOT independent of this constant: the reference
* decoders in test_fp8_passthrough.c, test_fp8_load.c, test_fp8_e2e_loader.c,
- * test_qwen38_native_weights.c and test_qt_addrow.c all index with
- * FP8_BLOCK/fp8_nblk via quant.h, so they move in lockstep with an edit here
- * (only test_backend_metal.mm's ref_fp8_nblk keeps its own literal, on purpose).
- * An edit to FP8_BLOCK is a format change, not a tunable -- those tests
- * cannot catch a wrong edit on their own. */
+ * test_qwen38_native_weights.c, test_qt_addrow.c and test_shard_kvb_refuse.c
+ * all index with FP8_BLOCK/fp8_nblk via quant.h, so they move in lockstep
+ * with an edit here (test_backend_metal.mm's ref_fp8_nblk and
+ * test_backend_cuda.cu's fmt=8 reference keep their own literals, on
+ * purpose). An edit to FP8_BLOCK is a format change, not a tunable -- those
+ * tests cannot catch a wrong edit on their own. */
#ifndef COLI_FP8_FORMAT_H
#define COLI_FP8_FORMAT_H
@@ -22,9 +27,9 @@
#define FP8_BLOCK 128
-/* Blocks covering n elements: ceil(n/FP8_BLOCK). Plain C on purpose --
- * nothing in this header may need decoration or a special front end, so it
- * stays includable from any translation unit. */
+/* Blocks covering n elements: ceil(n/FP8_BLOCK). Host-side helper (device
+ * code uses the FP8_BLOCK macro arithmetic directly -- this is not decorated
+ * for device compilation on purpose, to keep the header plain C). */
static inline int64_t fp8_nblk(int n){ return ((int64_t)n + FP8_BLOCK - 1) / FP8_BLOCK; }
#endif /* COLI_FP8_FORMAT_H */
diff --git a/c/tests/test_backend_cuda.cu b/c/tests/test_backend_cuda.cu
index 049ccf0a..1603048c 100644
--- a/c/tests/test_backend_cuda.cu
+++ b/c/tests/test_backend_cuda.cu
@@ -223,6 +223,106 @@ static int test_fmt6(int dev) {
return 1;
}
+/* ---- fmt=8 (fp8-e4m3) absorb decode -----------------------------------
+ * Exercises weight_at's new fmt=8 branch and absorb_scale's new per-128x128-
+ * block branch (this PR pair) through the REAL attention_absorb kernel and
+ * absorb_fmt_ok gate, against a CPU reference built the same way the fmt=0
+ * absorb block in main() (below) is: independent score/softmax/context
+ * accumulation, only the weight lookup itself changes to an e4m3 block-scale
+ * dequant. Dims are chosen so BOTH the row-block and column-block axes carry
+ * a partial tail block (O=H*(Q+V)=160 -> nblkO=2, rows 128..159 partial;
+ * K=140 -> nblkI=2, cols 128..139 partial) -- the exact geometry the new
+ * branches must index correctly (blkO=row>>7, blkI=k>>7, scale index
+ * blkO*nblkI+blkI). The e4m3 reference decoder is arithmetic (sign/exp/mant,
+ * OCP E4M3-FN policy), not the engine's c_e4m3 LUT, so it cross-checks
+ * coli_cuda_fp8_set_lut's uploaded table rather than assuming it -- same
+ * independence discipline as t8_e4m3_ref's sibling in tests/test_fp8_cuda.cu. */
+static float t8_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 uint32_t t8_rng_state = 0xC001D00Du;
+static uint8_t t8_rnd_byte(void) {
+ t8_rng_state ^= t8_rng_state<<13; t8_rng_state ^= t8_rng_state>>17; t8_rng_state ^= t8_rng_state<<5;
+ uint8_t b = (uint8_t)(t8_rng_state & 0xFF);
+ if ((b & 0x7F) == 0x7F) b &= (uint8_t)~1; /* avoid the two NaN byte patterns */
+ return b;
+}
+static float t8_dequant(const uint8_t *q, const float *scale, int I, int row, int col, int nblkI) {
+ int blkO = row >> 7, blkI = col >> 7;
+ return t8_e4m3_ref(q[(size_t)row*I + col]) * scale[(size_t)blkO*nblkI + blkI];
+}
+
+static int test_fmt8_absorb(int dev) {
+ float lut[256]; for (int i = 0; i < 256; i++) lut[i] = t8_e4m3_ref((uint8_t)i);
+ if (!coli_cuda_fp8_set_lut(lut)) { std::fprintf(stderr,"fmt=8 absorb: set_lut failed\n"); return 0; }
+
+ const int H = 2, Q = 40, V = 40, R = 2, K = 140, T = 3, O = H*(Q+V);
+ const int nblkO = (O+127)/128, nblkI = (K+127)/128, nblk = nblkO*nblkI;
+ uint8_t *w = (uint8_t*)std::malloc((size_t)O*K);
+ for (size_t i = 0; i < (size_t)O*K; i++) w[i] = t8_rnd_byte();
+ float *wscale = (float*)std::malloc((size_t)nblk*sizeof(float));
+ for (int i = 0; i < nblk; i++) wscale[i] = 0.01f + 0.002f*(float)i;
+
+ /* Refusal must have held BEFORE this test ever ran (fmt=8 was invisible to
+ * absorb_fmt_ok on unpatched main) -- upload + launch below is the positive
+ * side of the same predicate this PR widened. */
+ ColiCudaTensor *wt = nullptr;
+ if (!coli_cuda_tensor_upload(&wt, w, wscale, 8, K, O, dev)) {
+ std::fprintf(stderr,"fmt=8 absorb: weight upload rejected\n"); return 0;
+ }
+
+ float *q = (float*)std::malloc((size_t)H*(Q+R)*sizeof(float));
+ float *latent = (float*)std::malloc((size_t)T*K*sizeof(float));
+ float *rope = (float*)std::malloc((size_t)T*R*sizeof(float));
+ for (int i = 0; i < H*(Q+R); i++) q[i] = std::sin((float)(i+1)*0.037f);
+ for (int i = 0; i < T*K; i++) latent[i] = std::sin((float)(i+1)*0.019f)*0.5f;
+ for (int i = 0; i < T*R; i++) rope[i] = std::cos((float)(i+1)*0.041f)*0.3f;
+ float *ctx = (float*)std::malloc((size_t)H*V*sizeof(float));
+ float scale = 1.f/std::sqrt((float)K);
+
+ if (!coli_cuda_attention_absorb(wt, ctx, q, latent, rope, H, Q, R, V, K, T, scale)) {
+ std::fprintf(stderr,"fmt=8 absorb: kernel launch rejected (absorb_fmt_ok gate?)\n"); return 0;
+ }
+
+ int bad = 0;
+ for (int h = 0; h < H; h++) {
+ int rbase = h*(Q+V);
+ float qa[512]; /* K<=512, this attention_absorb's own documented bound */
+ for (int k = 0; k < K; k++) {
+ double a = 0;
+ for (int d = 0; d < Q; d++) a += (double)q[h*(Q+R)+d]*t8_dequant(w,wscale,K,rbase+d,k,nblkI);
+ qa[k] = (float)a;
+ }
+ float scores[T];
+ for (int t = 0; t < T; t++) {
+ double a = 0; for (int k = 0; k < K; k++) a += (double)qa[k]*latent[t*K+k];
+ for (int d = 0; d < R; d++) a += (double)q[h*(Q+R)+Q+d]*rope[t*R+d];
+ scores[t] = (float)a*scale;
+ }
+ float mx = scores[0]; for (int t = 1; t < T; t++) mx = scores[t]>mx?scores[t]:mx;
+ float z = 0; for (int t = 0; t < T; t++) { scores[t] = std::exp(scores[t]-mx); z += scores[t]; }
+ for (int t = 0; t < T; t++) scores[t] /= z;
+ float cl[512];
+ for (int k = 0; k < K; k++) { double a=0; for (int t=0;t<T;t++) a += (double)scores[t]*latent[t*K+k]; cl[k]=(float)a; }
+ for (int v = 0; v < V; v++) {
+ int row = rbase+Q+v;
+ double a = 0; for (int k = 0; k < K; k++) a += (double)cl[k]*t8_dequant(w,wscale,K,row,k,nblkI);
+ float want = (float)a, got = ctx[h*V+v];
+ float rel = std::fabs(want)>1e-4f ? std::fabs(got-want)/std::fabs(want) : std::fabs(got-want);
+ if (rel > 1e-3f) {
+ std::fprintf(stderr,"fmt=8 absorb mismatch h=%d v=%d got=%.6f want=%.6f rel=%.4g\n",h,v,got,want,rel);
+ bad++;
+ }
+ }
+ }
+ coli_cuda_tensor_free(wt);
+ std::free(w); std::free(wscale); std::free(q); std::free(latent); std::free(rope); std::free(ctx);
+ return bad == 0;
+}
+
int main(int argc, char **argv) {
int devices[COLI_CUDA_MAX_DEVICES], ndev = argc > 1 ? argc - 1 : 1;
if (ndev > COLI_CUDA_MAX_DEVICES) return 2;
@@ -455,6 +555,20 @@ int main(int argc, char **argv) {
coli_cuda_stats(-1, &count, &bytes);
if (count || bytes) { std::fprintf(stderr,"fmt=6 leaked tensors\n"); return 1; }
+ /* fmt=8 absorb: same self-contained lifecycle discipline as fmt=6 above,
+ * BOTH halves. The byte half is load-bearing history: an earlier vintage of
+ * this feature found coli_cuda_tensor_free subtracting per-row scale bytes
+ * for a per-block-scaled fmt=8 tensor (upload charged scale_count =
+ * ceil(O/128)*ng, free subtracted O*ng), so the `tensor_bytes >= bytes`
+ * guard silently declined the subtraction and the diagnostic VRAM counter
+ * stuck non-zero forever after freeing ANY fmt=8 tensor. free's accounting
+ * now mirrors upload's charge expression exactly (see the comment in
+ * coli_cuda_tensor_free), and this is the assertion that keeps the two
+ * from drifting apart again for a tracked fmt=8 tensor. */
+ if (!test_fmt8_absorb(d0)) return 1;
+ coli_cuda_stats(-1, &count, &bytes);
+ if (count || bytes) { std::fprintf(stderr,"fmt=8 absorb leaked tensors\n"); return 1; }
+
coli_cuda_shutdown();
std::printf("cuda backend: q8/q4/q2/f32/e8 correctness ok on %d device(s)\n", ndev);
return 0;
diff --git a/c/tests/test_cuda_fmt_guard.c b/c/tests/test_cuda_fmt_guard.c
index 056d6853..85e5fee6 100644
--- a/c/tests/test_cuda_fmt_guard.c
+++ b/c/tests/test_cuda_fmt_guard.c
@@ -36,21 +36,27 @@ static int fails = 0;
#define CHECK(c) do{ if(!(c)){ printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } }while(0)
int main(void) {
- /* Decodable by weight_at's explicit branches. */
+ /* Decodable by weight_at's explicit branches. fmt=8 (fp8-e4m3-b128) joined
+ * this set when the absorb path gained its block-scale decode (weight_at's
+ * fmt==8 branch + absorb_scale's per-128x128-block branch); its decode
+ * additionally needs the e4m3 LUT live on the device, which is an
+ * UPLOAD-time gate (coli_cuda_tensor_upload refuses fmt=8 until
+ * coli_cuda_fp8_set_lut has run), deliberately not part of this truth
+ * table -- see the predicate's own caveat note in backend_cuda.h. */
CHECK(coli_cuda_weight_at_supported(0)); /* f32 */
CHECK(coli_cuda_weight_at_supported(1)); /* int8-row */
CHECK(coli_cuda_weight_at_supported(2)); /* int4 nibbles */
CHECK(coli_cuda_weight_at_supported(3)); /* int2 */
CHECK(coli_cuda_weight_at_supported(4)); /* grouped int4 */
+ CHECK(coli_cuda_weight_at_supported(8)); /* fp8-e4m3-b128 */
/* NOT decodable. Each of these has a real in-tree meaning, and each used to
* be read as int2 by the fall-through. fmt=5 and fmt=6 are the ones that
- * could already reach a CUDA tensor; fmt=8 is the one this branch is about;
- * fmt=7 (MXFP4) has its own quant_matmul branch and never routes here. */
+ * could already reach a CUDA tensor; fmt=7 (MXFP4) has its own quant_matmul
+ * branch and never routes here. */
CHECK(!coli_cuda_weight_at_supported(5)); /* int3-g64 */
CHECK(!coli_cuda_weight_at_supported(6)); /* E8/IQ3 */
CHECK(!coli_cuda_weight_at_supported(7)); /* MXFP4 */
- CHECK(!coli_cuda_weight_at_supported(8)); /* fp8-e4m3-b128 */
/* Out of range in both directions. The negative cases are the ones the
* previous `fmt <= 4` host gate admitted: a descriptor whose fmt field is
@@ -62,10 +68,10 @@ int main(void) {
CHECK(!coli_cuda_weight_at_supported(100)); /* PRIVATE ORDINAL BLOCK base */
CHECK(!coli_cuda_weight_at_supported(1 << 30));
- /* The set is exactly {0,1,2,3,4} and nothing else in a wide sweep -- so a
+ /* The set is exactly {0,1,2,3,4,8} and nothing else in a wide sweep -- so a
* later edit that widens the predicate has to change this line too. */
for (int fmt = -2048; fmt <= 2048; fmt++) {
- int expect = (fmt >= 0 && fmt <= 4);
+ int expect = (fmt >= 0 && fmt <= 4) || fmt == 8;
if (!!coli_cuda_weight_at_supported(fmt) != expect) {
printf("FAIL fmt=%d: supported=%d, expected %d\n",
fmt, coli_cuda_weight_at_supported(fmt), expect);
diff --git a/c/tests/test_cuda_fmt_trap_cuda.cu b/c/tests/test_cuda_fmt_trap_cuda.cu
index 07b2372f..78e22691 100644
--- a/c/tests/test_cuda_fmt_trap_cuda.cu
+++ b/c/tests/test_cuda_fmt_trap_cuda.cu
@@ -31,7 +31,7 @@
* WHAT MAKES THIS TEST BITE RATHER THAN MERELY PASS. Three controls, because an
* exit code that says "the child failed" is worthless if the child fails no
* matter what:
- * 1. IN-PROCESS control: every supported fmt (0,1,2,3,4) is launched in the
+ * 1. IN-PROCESS control: every supported fmt (0,1,2,3,4,8) is launched in the
* parent and must complete cleanly. If weight_at trapped on those, the
* trap would be firing on valid input and this test would fail here.
* 2. CHILD-HARNESS control: the probe list always contains SUPPORTED formats
@@ -56,13 +56,24 @@
* landing in either order: whatever the predicate promises, the silicon must
* deliver, and whatever it refuses, the silicon must refuse.
*
- * The fmt set probed covers both sides of today's truth table (0,3 supported;
- * 5,6,7,8 unsupported container-carriable formats) plus the out-of-range values
- * a corrupt descriptor could present (-1, 9, 1<<30) -- the ones the previous
+ * The fmt set probed covers both sides of today's truth table (0,3,8 supported
+ * -- 8 since the fp8-e4m3 absorb decode widened the predicate; 5,6,7
+ * unsupported container-carriable formats) plus the out-of-range values a
+ * corrupt descriptor could present (-1, 9, 1<<30) -- the ones the previous
* `fmt <= 4` host gate admitted.
*
+ * fmt=8 gets one extra obligation on top of the derived DECODED verdict: its
+ * decoded VALUE is checked against an independent arithmetic e4m3 reference
+ * (a6_e4m3_ref below), because a fresh child process starts with a
+ * zero-initialized c_e4m3 table -- a decode that "returns a number" from a
+ * zero LUT is exactly the fabricated-numbers failure mode this file exists to
+ * refuse. The child publishes the LUT through the real
+ * coli_cuda_init/coli_cuda_fp8_set_lut path first, the same way any real
+ * fmt=8 caller must before upload.
+ *
* make -C c cuda-test CUDA_ARCH=native (runs this among the CUDA tests)
*/
+#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
@@ -95,6 +106,8 @@
#define A6_EXIT_TRAPPED 42 /* the launch aborted -- the refusal fired */
#define A6_EXIT_DECODED 43 /* the kernel returned a value -- no refusal */
#define A6_EXIT_HARNESS 44 /* could not run the probe at all */
+#define A6_EXIT_MISMATCH 45 /* decoded without trapping, but not to the *
+ * value the independent reference expects */
#define A6_PROBE_FLAG "--a6-probe"
@@ -103,6 +116,38 @@
* visible number rather than something that could be mistaken for "no output". */
#define A6_FILL 0xA5
+/* Independent arithmetic e4m3 decoder (sign/exp/mantissa, OCP E4M3-FN: no
+ * infinities, only 0x7F/0xFF are NaN) -- same construction as t8_e4m3_ref in
+ * tests/test_backend_cuda.cu and e4m3_ref in tests/test_fp8_cuda.cu. Scope
+ * of the check, stated exactly: the device table is PUBLISHED FROM this
+ * reference (a6_publish_lut), so the comparison proves the table is nonzero
+ * and that weight_at's c_e4m3[base[i]] indexing is correct -- it cannot
+ * catch a wrong reference (a wrong table built from it would cancel), and
+ * the engine's own E4M3_LUT (quant.h) is not exercised by this harness at
+ * all. A6_FILL (0xA5) is not a NaN byte pattern. */
+static float a6_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;
+}
+
+/* Publish the e4m3 LUT through the engine's own path, so weight_at's fmt=8
+ * branch reads a real table instead of context-fresh zeros. Harmless for every
+ * other fmt (only the fmt==8 branch reads c_e4m3). coli_cuda_fp8_set_lut walks
+ * the engine's context table (g_nctx/g_ctx), which nothing else in this file
+ * populates -- the rest of the file talks to the device directly via the raw
+ * CUDA runtime API, deliberately, to stay independent of the engine's
+ * device-selection plumbing -- so coli_cuda_init(device 0) is called for this
+ * one dependency only. Returns 0 on harness failure. */
+static int a6_publish_lut(void) {
+ int dev0 = 0;
+ if (!coli_cuda_init(&dev0, 1)) return 0;
+ float lut[256];
+ for (int i = 0; i < 256; i++) lut[i] = a6_e4m3_ref((uint8_t)i);
+ return coli_cuda_fp8_set_lut(lut);
+}
+
/* The deliberate bad launch. weight_at is file-static device code; this is the
* only caller in this TU, and it passes fmt straight through as a runtime
* argument so nvcc cannot constant-fold the dispatch away. */
@@ -116,6 +161,16 @@ static int a6_probe_child(int fmt) {
void *w = NULL;
float *out = NULL;
+ /* Fresh execv'd process, fresh CUDA context: c_e4m3 starts zero-initialized
+ * here regardless of what the parent published. Published unconditionally
+ * rather than gated on fmt==8, so this child's setup mirrors a real
+ * caller's -- the engine publishes the LUT once at boot for every process
+ * that might touch fmt=8, not per tensor. */
+ if (!a6_publish_lut()) {
+ printf(" [child fmt=%d] coli_cuda_init/coli_cuda_fp8_set_lut failed\n", fmt);
+ return A6_EXIT_HARNESS;
+ }
+
if (cudaMalloc(&w, 256) != cudaSuccess) {
printf(" [child fmt=%d] cudaMalloc(weights) failed\n", fmt);
return A6_EXIT_HARNESS;
@@ -155,6 +210,24 @@ static int a6_probe_child(int fmt) {
return A6_EXIT_TRAPPED;
}
printf(" [child fmt=%d] weight_at RETURNED %g\n", fmt, (double)v);
+
+ /* fmt=8's extra obligation (see the file header): the decoded value must
+ * match the independent e4m3 reference. Without this, a zero-LUT decode
+ * (or any wrong LUT/indexing) would still count as "DECODED" -- a wrong
+ * number is not meaningfully different from a fabricated one, which is
+ * the exact failure mode this file's __trap() backstop exists to refuse.
+ * The other DECODED fmts in the probe list (0, 3) are already pinned
+ * bit-exact elsewhere (inprocess_supported_control here, the dense-matmul
+ * oracle in tests/test_backend_cuda.cu). */
+ if (fmt == 8) {
+ float want = a6_e4m3_ref((uint8_t)A6_FILL);
+ if (v != want) {
+ printf(" [child fmt=%d] MISMATCH: weight_at(A6_FILL=0x%02X) = %g, "
+ "independent e4m3 reference says %g\n", fmt, A6_FILL,
+ (double)v, (double)want);
+ return A6_EXIT_MISMATCH;
+ }
+ }
return A6_EXIT_DECODED;
}
@@ -210,7 +283,11 @@ static void expect_child(const char *self, int fmt, int want, const char *why) {
printf("ok fmt=%-6d %s (child exit %d)\n", fmt, why, got);
return;
}
- if (got == A6_EXIT_DECODED && want == A6_EXIT_TRAPPED) {
+ if (got == A6_EXIT_MISMATCH && want == A6_EXIT_DECODED) {
+ printf("FAIL fmt=%-6d %s -- decoded without trapping, but not to the "
+ "value the independent e4m3 reference expects (see child output "
+ "above)\n", fmt, why);
+ } else if (got == A6_EXIT_DECODED && want == A6_EXIT_TRAPPED) {
printf("FAIL fmt=%-6d weight_at DECODED a format the host predicate "
"refuses -- the device-side __trap() is not firing (dispatch "
"disagrees with coli_cuda_weight_at_supported)\n", fmt);
@@ -247,7 +324,14 @@ static void inprocess_supported_control(void) {
return;
}
(void)cudaGetLastError();
- for (int fmt = 0; fmt <= 4; fmt++) {
+ /* The full predicate-true set, fmt=8 included -- its LUT is published by
+ * main() before this control runs (a6_publish_lut), so its in-process
+ * decode reads a real table, and its value is checked against the
+ * independent reference right here (the child probes re-check it in a
+ * fresh process, where the LUT must be re-published). */
+ static const int supported[] = {0, 1, 2, 3, 4, 8};
+ for (size_t fi = 0; fi < sizeof supported / sizeof supported[0]; fi++) {
+ int fmt = supported[fi];
if (!coli_cuda_weight_at_supported(fmt)) { /* keeps the two in step */
printf("FAIL fmt=%d is in this loop but the host predicate rejects it\n", fmt);
fails++;
@@ -267,6 +351,12 @@ static void inprocess_supported_control(void) {
fails++;
return; /* the context is poisoned; nothing after this is valid */
}
+ if (fmt == 8 && v != a6_e4m3_ref((uint8_t)A6_FILL)) {
+ printf("FAIL fmt=8 decoded in-process to %g, independent e4m3 "
+ "reference says %g (wrong LUT or wrong indexing)\n",
+ (double)v, (double)a6_e4m3_ref((uint8_t)A6_FILL));
+ fails++;
+ }
printf("ok fmt=%-6d supported: decoded in-process, weight_at = %g\n",
fmt, (double)v);
}
@@ -288,6 +378,13 @@ int main(int argc, char **argv) {
return 1;
}
+ if (!a6_publish_lut()) {
+ printf("cuda fmt trap test: could not publish the e4m3 LUT "
+ "(coli_cuda_init/coli_cuda_fp8_set_lut failed) -- the fmt=8 "
+ "control cannot run\n");
+ return 1;
+ }
+
printf("-- control: supported formats decode (in-process)\n");
inprocess_supported_control();
diff --git a/c/tests/test_cuda_lut_gate.c b/c/tests/test_cuda_lut_gate.c
new file mode 100644
index 00000000..ab6a1d5c
--- /dev/null
+++ b/c/tests/test_cuda_lut_gate.c
@@ -0,0 +1,142 @@
+/* fmt=8 LUT-gate state machine, pinned on the host with no CUDA toolchain.
+ *
+ * Why this exists: the gate that stops a fmt=8 tensor reaching a kernel whose
+ * device has an unwritten e4m3 table is implemented in backend_cuda.cu, which
+ * compiles only under nvcc/hipcc. Every test that exercised it therefore ran
+ * nowhere in CPU CI, and a rebase was able to change the surrounding
+ * init semantics while three sites in the tree went on asserting the old ones.
+ * The two decisions the gate rests on are pure predicates in backend_cuda.h;
+ * backend_cuda.cu calls them at the real sites, so what is pinned below is the
+ * engine's own logic, not a restatement of it.
+ *
+ * What this does NOT pin: that backend_cuda.cu calls the predicates in the
+ * right order, or at all. That needs a CUDA toolchain (tests/test_fp8_cuda.cu
+ * Phase 3 covers it there). What it does pin is the decision table itself and
+ * the one invariant the whole gate rests on:
+ *
+ * no live context set => the LUT flag is clear
+ *
+ * which holds because shutdown is the only writer that clears the flag and it
+ * clears g_nctx in the same breath, and because init refuses to rebuild
+ * contexts underneath a live set.
+ */
+#include <stdio.h>
+#include "../backend_cuda.h"
+
+static int fails;
+
+static void ck(int cond, const char *what) {
+ if (!cond) { printf("FAIL %s\n", what); fails++; }
+}
+
+/* A model of the three public transitions, written in terms of the SAME
+ * predicates the engine calls. `nctx`/`ready` are the engine's two globals. */
+typedef struct { int nctx; int ready; int dev[8]; } Gate;
+
+static int g_init(Gate *g, const int *want, int count) {
+ int d = coli_cuda_init_disposition(g->nctx, count, want, g->dev);
+ if (d == COLI_CUDA_INIT_REFUSE) return 0; /* touches nothing */
+ if (d == COLI_CUDA_INIT_ACCEPT) return 1; /* touches nothing */
+ for (int i = 0; i < count; i++) g->dev[i] = want[i];
+ g->nctx = count; /* flag NOT written here */
+ return 1;
+}
+static void g_set_lut(Gate *g) { if (g->nctx > 0) g->ready = 1; }
+static void g_shutdown(Gate *g) { g->nctx = 0; g->ready = 0; }
+static int g_upload(Gate *g, int fmt) {
+ return g->nctx > 0 && coli_cuda_fp8_gate_admits(fmt, g->ready);
+}
+
+int main(void) {
+ /* --- the disposition table, directly ------------------------------- */
+ {
+ int live1[1] = {0}, want1[1] = {0}, want2[2] = {0, 1}, wantB[1] = {1};
+ ck(coli_cuda_init_disposition(0, 1, want1, live1) == COLI_CUDA_INIT_BUILD,
+ "nothing live -> BUILD");
+ ck(coli_cuda_init_disposition(1, 1, want1, live1) == COLI_CUDA_INIT_ACCEPT,
+ "same set -> ACCEPT");
+ ck(coli_cuda_init_disposition(1, 2, want2, live1) == COLI_CUDA_INIT_REFUSE,
+ "widening set -> REFUSE");
+ ck(coli_cuda_init_disposition(1, 1, wantB, live1) == COLI_CUDA_INIT_REFUSE,
+ "same size, different device -> REFUSE");
+ int live2[2] = {0, 1};
+ ck(coli_cuda_init_disposition(2, 1, want1, live2) == COLI_CUDA_INIT_REFUSE,
+ "narrowing set -> REFUSE");
+ ck(coli_cuda_init_disposition(2, 2, want2, live2) == COLI_CUDA_INIT_ACCEPT,
+ "same two-device set -> ACCEPT");
+ }
+
+ /* --- the upload gate ------------------------------------------------ */
+ for (int fmt = -3; fmt <= 9; fmt++) {
+ if (fmt == 8) continue;
+ ck(coli_cuda_fp8_gate_admits(fmt, 0) && coli_cuda_fp8_gate_admits(fmt, 1),
+ "non-fmt=8 is admitted regardless of the LUT flag");
+ }
+ ck(!coli_cuda_fp8_gate_admits(8, 0), "fmt=8 refused while the LUT is unpublished");
+ ck(coli_cuda_fp8_gate_admits(8, 1), "fmt=8 admitted once the LUT is published");
+
+ /* --- the three lifecycle edges, as sequences ------------------------ */
+ {
+ Gate g = {0, 0, {0}};
+ int d0[1] = {0}, d01[2] = {0, 1};
+
+ ck(g_init(&g, d0, 1) == 1, "first init succeeds");
+ ck(!g_upload(&g, 8), "fmt=8 refused before the first publish");
+ ck(g_upload(&g, 1), "fmt=1 unaffected by the gate");
+ g_set_lut(&g);
+ ck(g_upload(&g, 8), "fmt=8 admitted after publish");
+
+ /* Edge 2: same-set re-init keeps the flag, because it keeps the
+ * contexts the table was published to. */
+ ck(g_init(&g, d0, 1) == 1, "same-set re-init returns success");
+ ck(g.nctx == 1, "same-set re-init leaves the context count alone");
+ ck(g_upload(&g, 8), "fmt=8 still admitted after a same-set re-init");
+
+ /* Edge 3: different-set re-init is refused and changes nothing. */
+ ck(g_init(&g, d01, 2) == 0, "widening re-init is refused");
+ ck(g.nctx == 1, "refused re-init leaves the context set alone");
+ ck(g_upload(&g, 8), "refused re-init leaves the LUT flag alone");
+
+ /* Edge 1: shutdown clears both, and the next span must republish. */
+ g_shutdown(&g);
+ ck(g.nctx == 0 && g.ready == 0, "shutdown clears the set and the flag");
+ ck(g_init(&g, d01, 2) == 1, "after shutdown a WIDER set may be built");
+ ck(!g_upload(&g, 8), "fmt=8 refused on the widened set until it republishes");
+ g_set_lut(&g);
+ ck(g_upload(&g, 8), "fmt=8 admitted on the widened set after republish");
+ }
+
+ /* --- the invariant, over every reachable transition sequence -------- */
+ {
+ /* Exhaustive over sequences of length 6 drawn from
+ * {init{0}, init{0,1}, set_lut, shutdown}: no reachable state may have
+ * a live-free context set and a set flag, and no state may admit fmt=8
+ * without a live set. */
+ int d0[1] = {0}, d01[2] = {0, 1};
+ int idx[6] = {0, 0, 0, 0, 0, 0};
+ long checked = 0;
+ for (;;) {
+ Gate g = {0, 0, {0}};
+ for (int s = 0; s < 6; s++) {
+ switch (idx[s]) {
+ case 0: g_init(&g, d0, 1); break;
+ case 1: g_init(&g, d01, 2); break;
+ case 2: g_set_lut(&g); break;
+ default: g_shutdown(&g); break;
+ }
+ if (g.nctx == 0 && g.ready != 0) { printf("FAIL invariant: no contexts but the LUT flag is set\n"); return 1; }
+ if (g.nctx == 0 && g_upload(&g, 8)) { printf("FAIL invariant: fmt=8 admitted with no live context\n"); return 1; }
+ }
+ checked++;
+ int p = 5;
+ while (p >= 0 && ++idx[p] > 3) { idx[p] = 0; p--; }
+ if (p < 0) break;
+ }
+ if (checked != 4096) { printf("FAIL sequence enumeration covered %ld, expected 4096\n", checked); return 1; }
+ printf("lut-gate invariant holds over %ld transition sequences\n", checked);
+ }
+
+ if (fails) { printf("cuda lut-gate tests: %d FAILED\n", fails); return 1; }
+ printf("cuda lut-gate tests: ok\n");
+ return 0;
+}
diff --git a/c/tests/test_fp8_cuda.cu b/c/tests/test_fp8_cuda.cu
index 87ccecc2..fe374fd0 100644
--- a/c/tests/test_fp8_cuda.cu
+++ b/c/tests/test_fp8_cuda.cu
@@ -335,5 +335,55 @@ int main(void){
}
coli_cuda_shutdown();
}
+
+ /* ---- Phase 3: LUT-gate lifecycle across shutdown/re-init --------------- */
+ { /* g_fp8_lut_ready is process-wide while the e4m3 table is per-device.
+ * SHUTDOWN is the only site that clears it; coli_cuda_init never writes
+ * it. That is sufficient because init refuses to rebuild contexts while
+ * a set is live: a re-init naming the SAME set returns 1 and leaves the
+ * contexts -- and therefore the published table -- untouched, and one
+ * naming a DIFFERENT set is refused outright. So the device set cannot
+ * widen past what the last publish covered without passing through
+ * shutdown, which clears the flag. This block pins all three edges. */
+ int devs[1]={0};
+ enum { LO=4, LI=128 };
+ uint8_t lw[LO*LI]; float ls[1]={1.f};
+ for(size_t i=0;i<sizeof lw;i++) lw[i]=rnd_e4m3();
+ ColiCudaTensor *lt=nullptr;
+
+ /* Edge 1: after shutdown the flag is clear, so a fmt=8 upload is
+ * refused until this span publishes its own table. */
+ if(!coli_cuda_init(devs,1)){ printf("FAIL lifecycle re-init\n"); return 1; }
+ if(coli_cuda_tensor_upload(&lt,lw,ls,8,LI,LO,0)){ printf("FAIL gate open after shutdown (stale ready flag)\n"); return 1; }
+ if(!coli_cuda_fp8_set_lut(lut)){ printf("FAIL lifecycle set_lut\n"); return 1; }
+ if(!coli_cuda_tensor_upload(&lt,lw,ls,8,LI,LO,0)){ printf("FAIL upload after republish\n"); return 1; }
+ coli_cuda_tensor_free(lt); lt=nullptr;
+
+ /* Edge 2: a SAME-SET re-init returns 1 and does NOT disturb the flag,
+ * so the upload still succeeds -- the table it would decode against is
+ * the one already published to these very contexts. Asserting a refusal
+ * here would assert a republish that buys nothing. */
+ if(coli_cuda_init(devs,1)!=1){ printf("FAIL same-set re-init did not return 1\n"); return 1; }
+ if(coli_cuda_device_count()!=1){ printf("FAIL same-set re-init changed the context count\n"); return 1; }
+ if(!coli_cuda_tensor_upload(&lt,lw,ls,8,LI,LO,0)){ printf("FAIL upload refused after a same-set re-init (flag was disturbed)\n"); return 1; }
+ coli_cuda_tensor_free(lt); lt=nullptr;
+
+ /* Edge 3: a DIFFERENT-SET re-init is refused, and leaves both the
+ * context set and the flag alone -- proven by the upload that follows
+ * still succeeding. With one visible device the only reachable
+ * different set is an out-of-range one, which init's validation refuses
+ * a few lines earlier than the device-list comparison; both return 0
+ * without rebuilding, which is the property under test. */
+ { int ndev=0; cudaGetDeviceCount(&ndev);
+ int other[2]={0, ndev>1 ? 1 : ndev}; /* {0,1} on a multi-GPU box, else out of range */
+ if(coli_cuda_init(other,2)!=0){ printf("FAIL different-set re-init was not refused\n"); return 1; }
+ if(coli_cuda_device_count()!=1){ printf("FAIL refused re-init still changed the context set\n"); return 1; }
+ if(!coli_cuda_tensor_upload(&lt,lw,ls,8,LI,LO,0)){ printf("FAIL refused re-init disturbed the LUT flag\n"); return 1; }
+ coli_cuda_tensor_free(lt); lt=nullptr;
+ }
+
+ coli_cuda_shutdown();
+ printf("lut-gate lifecycle: shutdown clears; same-set re-init keeps; different-set re-init refused\n");
+ }
printf("OK\n"); return 0;
}
diff --git a/c/tests/test_shard_kvb_refuse.c b/c/tests/test_shard_kvb_refuse.c
new file mode 100644
index 00000000..ff6cadc4
--- /dev/null
+++ b/c/tests/test_shard_kvb_refuse.c
@@ -0,0 +1,151 @@
+/* layer_cuda_shard_kvb() (colibri.c, COLI_CUDA_ATTN_SHARD) -- the multi-device kv_b
+ * head-shard uploader. Its rb/weights/scale arithmetic is written for exactly fmt=1/2/3/4
+ * (per-row byte strides, per-row or per-group scales); before the guard this file proves,
+ * an fmt=8 (fp8-e4m3-b128) kv_b was ADMITTED and only failed safe BY ACCIDENT: fmt=8
+ * keeps its raw e4m3 bytes in q8 (q4 stays NULL, per the QT struct comment), so the
+ * function selected a NULL weight pointer with an int2 row stride and
+ * coli_cuda_tensor_upload_g's !weights check happened to reject the upload before
+ * anything dereferenced it -- silent, unnamed, and one refactor away from a misread
+ * (fmt=8's per-128x128-BLOCK scale array would ALSO have been sliced with per-row
+ * geometry). This probe pins the explicit refusal that replaced the accident:
+ * (1) an fmt=8 kv_b shard attempt refuses BY NAME on stderr, BEFORE any pointer/stride
+ * use, and the message says what serves fmt=8 instead (the absorb path on the
+ * layer home device);
+ * (2) no shard state is minted (n_kv_b_shard==0, kv_b_shard[] untouched,
+ * kv_b.cuda_eligible unchanged);
+ * (3) the notice is bounded (once per process per fmt, never per layer);
+ * (4) other un-shardable fmts (fmt=6 here) refuse by name too, with their own message;
+ * (5) an allowlisted fmt (fmt=1) is NOT refused -- with no device context initialized
+ * its upload fails silently and no shard is minted, but no refusal line appears,
+ * so the guard is format-targeted, not a blanket gate.
+ * PROOF-OF-BITE: built against the pre-guard colibri.c, (1)/(3)/(4) fail -- the fmt=8
+ * call slid past the format check into the accidental-safe upload rejection with no
+ * message at all. Needs -DCOLI_CUDA (CUDA=1) to compile the function; a CPU-only build
+ * SKIPs loudly instead of pretending to cover it. No GPU work is performed: every path
+ * exercised here returns before any device context exists, so this runs on a CUDA build
+ * host even without a card.
+ * Portable stderr capture: freopen/dup2, same seam as tests/test_kvb_notice.c. */
+#define main coli_glm_main_unused
+#include "../colibri.c"
+#undef main
+
+#include <stdio.h>
+#include <string.h>
+#include <stdlib.h>
+
+#ifndef COLI_CUDA
+int main(void){
+ printf("test_shard_kvb_refuse: SKIP (built without COLI_CUDA -- build with CUDA=1 on a CUDA host to exercise layer_cuda_shard_kvb)\n");
+ return 0;
+}
+#else
+
+#include <unistd.h>
+
+static int fails = 0;
+#define CHECK(c) do{ if(!(c)){ printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #c); fails++; } }while(0)
+
+static int redirect_stderr(const char *path){
+ fflush(stderr);
+ int saved = dup(fileno(stderr));
+ if(saved<0){ printf("FAIL: dup(stderr) failed -- capture seam unusable, aborting\n"); exit(1); }
+ if(!freopen(path, "w+", stderr)){
+ printf("FAIL: freopen(%s) failed -- capture seam unusable, aborting\n", path);
+ exit(1);
+ }
+ return saved;
+}
+static void restore_stderr(int saved, char *buf, size_t bufsz){
+ fflush(stderr);
+ long n = ftell(stderr);
+ if(n<0) n=0;
+ rewind(stderr);
+ size_t want = (size_t)n < bufsz-1 ? (size_t)n : bufsz-1;
+ size_t got = fread(buf, 1, want, stderr);
+ buf[got] = 0;
+ fflush(stderr);
+ dup2(saved, fileno(stderr));
+ close(saved);
+}
+
+static int count_sub(const char *hay, const char *needle){
+ int n=0; const char *p=hay;
+ while((p=strstr(p,needle))){ n++; p++; }
+ return n;
+}
+
+/* kv_b-shaped fixture at H=4, Q=8, V=8 -> O=H*(Q+V)=64; I=200 (nblkI=2, partial column
+ * tail -- the exact scale geometry the shard's per-row slicing would have misread). */
+enum { H=4, Q=8, V=8, O=H*(Q+V), I=200 };
+
+static void mk_layer_fmt8(Layer *l, int8_t *q8, float *s){
+ memset(l,0,sizeof *l);
+ for(int64_t i=0;i<(int64_t)O*I;i++) q8[i]=(int8_t)(i*37+11);
+ int64_t nblk=fp8_nblk(O)*fp8_nblk(I);
+ for(int64_t i=0;i<nblk;i++) s[i]=0.01f+0.001f*(float)i;
+ l->kv_b.fmt=8; l->kv_b.O=O; l->kv_b.I=I; l->kv_b.gs=0;
+ l->kv_b.q8=q8; l->kv_b.s=s; /* q4 stays NULL: the fmt=8 convention */
+ l->kv_b.cuda_eligible=1; l->kv_b.cuda_device=0;
+}
+
+static void run_shard(Layer *l, char *buf, size_t bufsz){
+ int saved = redirect_stderr("tests/tmp_shard_kvb_refuse.stderr");
+ layer_cuda_shard_kvb(l,H,Q,V);
+ restore_stderr(saved, buf, bufsz);
+ remove("tests/tmp_shard_kvb_refuse.stderr");
+}
+
+int main(void){
+ /* pretend a 2-device dense-CUDA setup so the function's early gate passes; no
+ * device context is ever initialized, and none is needed (see file header). */
+ g_cuda_enabled=1; g_cuda_dense=1; g_cuda_ndev=2;
+ g_cuda_devices[0]=0; g_cuda_devices[1]=0;
+
+ static int8_t q8[(int64_t)O*I];
+ static float s[((O+127)/128)*((I+127)/128)];
+ static float srow[O]; /* per-row scales for the allowlisted fmt=1 case */
+ char err[4096];
+ Layer l;
+
+ /* (1)+(2): fmt=8 refuses by name, names the absorb path, mints no shard state */
+ mk_layer_fmt8(&l,q8,s);
+ run_shard(&l,err,sizeof err);
+ CHECK(strstr(err,"layer_cuda_shard_kvb")!=NULL);
+ CHECK(strstr(err,"refus")!=NULL);
+ CHECK(strstr(err,"fmt=8")!=NULL);
+ CHECK(strstr(err,"absorb path")!=NULL); /* says what serves fmt=8 instead */
+ CHECK(l.n_kv_b_shard==0);
+ CHECK(l.kv_b_shard[0]==NULL && l.kv_b_shard[1]==NULL);
+ CHECK(l.kv_b.cuda_eligible==1); /* shard bookkeeping never ran */
+
+ /* (3): bounded -- a second fmt=8 layer (any of the other 60) adds no second line */
+ mk_layer_fmt8(&l,q8,s);
+ run_shard(&l,err,sizeof err);
+ CHECK(count_sub(err,"layer_cuda_shard_kvb")==0);
+ CHECK(l.n_kv_b_shard==0);
+
+ /* (4): fmt=6 (E8/IQ3, single 4-byte scale tag) refuses by name with its own message */
+ memset(&l,0,sizeof l);
+ l.kv_b.fmt=6; l.kv_b.O=O; l.kv_b.I=I; l.kv_b.gs=0;
+ l.kv_b.q4=(uint8_t*)q8; l.kv_b.s=s; /* non-NULL on purpose: only the guard saves it */
+ run_shard(&l,err,sizeof err);
+ CHECK(strstr(err,"layer_cuda_shard_kvb")!=NULL);
+ CHECK(strstr(err,"refus")!=NULL);
+ CHECK(strstr(err,"fmt=6")!=NULL);
+ CHECK(l.n_kv_b_shard==0);
+
+ /* (5): allowlisted fmt=1 is NOT refused -- upload fails silently (no device
+ * context), no shard minted, but no refusal line either */
+ memset(&l,0,sizeof l);
+ for(int i=0;i<O;i++) srow[i]=0.01f;
+ l.kv_b.fmt=1; l.kv_b.O=O; l.kv_b.I=I; l.kv_b.gs=0;
+ l.kv_b.q8=q8; l.kv_b.s=srow;
+ run_shard(&l,err,sizeof err);
+ CHECK(strstr(err,"refus")==NULL);
+ CHECK(l.n_kv_b_shard==0);
+
+ if(fails){ printf("layer_cuda_shard_kvb refusal probe: %d FAILED\n", fails); return 1; }
+ printf("layer_cuda_shard_kvb refusal probe: ok\n");
+ return 0;
+}
+#endif /* COLI_CUDA */
diff --git a/c/tools/repack_fp8_passthrough.py b/c/tools/repack_fp8_passthrough.py
index 3f0ff07c..3e4d656f 100644
--- a/c/tools/repack_fp8_passthrough.py
+++ b/c/tools/repack_fp8_passthrough.py
@@ -112,23 +112,21 @@ when no `.qs` sidecar exists, colibri.c) -- nothing new is exercised on the
read side. `main()` also copies `config.json` (mandatory, colibri.c's
load_cfg) and `generation_config.json` (best-effort) from --indir into
--outdir. Together with kv_b_proj emission below, this makes the tool's
-output a standalone-loadable model directory on its own, with one caveat: the
-CUDA absorb kernels do not yet decode fmt=8, so a kv_b_proj-carrying
-container decodes through the CPU absorb path only -- see below.
+output a standalone-loadable model directory on its own: both halves of the
+engine-side absorb support (CPU and CUDA) exist -- see below.
kv_b_proj (kind "kvb") is now emitted the same way as o_proj/attn: byte-
preserved fp8 weight + renamed `.qs` scale sidecar, stamped (it clears the
collision shape the same way o_proj does -- M1 audit, GLM-5.2's kv_b_proj is
never at the ambiguous [O,I] this tool's `_check_geometry` guards). The
-engine-side half of this two-sided integration now exists on the CPU:
+engine side of this two-sided integration now exists on both backends:
colibri.c's MLA-absorption path (qt_addrow/qt_matvec_rows, called only on
-l->kv_b) carries explicit fmt==8 decode arms, so a container minted here
-loads clean (qt_from_disk resolves the stamp exactly like o_proj's) and
-decodes correctly through the batched (`kvs`-nonNULL) serving path, where
-absorb cannot be bypassed. The CUDA absorb kernels still have no fmt==8
-case (absorb_fmt_ok delegates to coli_cuda_weight_at_supported's fmt 0..4
-allowlist), so fmt=8 kv_b decode stays on the CPU absorb path until that
-lands.
+l->kv_b) carries explicit fmt==8 decode arms, and the CUDA absorb kernels
+decode fmt=8 through weight_at/absorb_scale (admitted by
+coli_cuda_weight_at_supported, uploads gated on the published e4m3 LUT).
+A container minted here loads clean (qt_from_disk resolves the stamp
+exactly like o_proj's) and decodes correctly through the batched
+(`kvs`-nonNULL) serving path, where absorb cannot be bypassed.
METADATA STAMP (reference implementation of the FORMATS-registry FR -- see
docs/FORMATS.md): every output shard's safetensors `__metadata__` carries a