Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
v4: restore model-specific tensor, safetensors and native-quant infrastructure
DrewZ1e7701603571
diff --git a/c/expert_store.h b/c/expert_store.hnew file mode 100644index 00000000..525e8353--- /dev/null+++ b/c/expert_store.h@@ -0,0 +1,99 @@+#ifndef COLIBRI_EXPERT_STORE_H+#define COLIBRI_EXPERT_STORE_H++#include <stddef.h>+#include <stdint.h>+#include <string.h>++#include "tensor.h"++#ifdef __cplusplus+extern "C" {+#endif++typedef struct ColiExpertStore ColiExpertStore;++typedef struct {+ int layer;+ int expert;+} ColiExpertKey;++typedef struct {+ ColiExpertKey key;+ ColiTensorView gate;+ ColiTensorView down;+ ColiTensorView up;+ void *lease;+} ColiExpertView;++typedef struct {+ uint64_t requests;+ uint64_t hits;+ uint64_t misses;+ uint64_t prefetched;+ uint64_t prefetch_hits;+ uint64_t bytes_read;+ uint64_t resident_bytes;+ uint64_t capacity_bytes;+} ColiExpertStoreStats;++/*+ * ExpertStore lease contract:+ *+ * - After a successful lookup(), the caller must call release() exactly once+ * on the same view (same store). Do not copy ColiExpertView; the lease is+ * not shareable. Do not pass a view that already holds an active lease to+ * lookup().+ * - On lookup failure the view is cleared; the caller must not use it and+ * must not call release().+ * - release() clears the entire view. release() on an already-cleared or+ * zero-initialized view is a no-op.+ * - destroy() requires zero active leases (debug builds assert).+ * - Thread-safety is implementation-specific. Callers must not assume that+ * lookup/release/prefetch/stats/destroy are safe to call concurrently on+ * the same store unless the concrete store documents that guarantee.+ * Views must not be used concurrently from multiple threads.+ * - prefetch() is advisory, holds no lease, and must not evict a slot that+ * still has an active lease.+ */+typedef struct {+ /* Returns zero on success. The view remains valid until release(). */+ int (*lookup)(ColiExpertStore *store, ColiExpertKey key,+ ColiExpertView *view);+ void (*release)(ColiExpertStore *store, ColiExpertView *view);+ /* Prefetch is advisory. Unsupported or rejected requests return zero. */+ int (*prefetch)(ColiExpertStore *store, const ColiExpertKey *keys,+ size_t count);+ void (*stats)(const ColiExpertStore *store, ColiExpertStoreStats *stats);+ void (*destroy)(ColiExpertStore *store);+} ColiExpertStoreOps;++struct ColiExpertStore {+ const ColiExpertStoreOps *ops;+ void *state;+};++static inline int coli_expert_lookup(ColiExpertStore *store,+ ColiExpertKey key,+ ColiExpertView *view) {+ if (!store || !store->ops || !store->ops->lookup) {+ if (view) memset(view, 0, sizeof(*view));+ return -1;+ }+ int result = store->ops->lookup(store, key, view);+ if (result != 0 && view) memset(view, 0, sizeof(*view));+ return result;+}++static inline void coli_expert_release(ColiExpertStore *store,+ ColiExpertView *view) {+ if (store && store->ops && store->ops->release)+ store->ops->release(store, view);+ if (view) memset(view, 0, sizeof(*view));+}++#ifdef __cplusplus+}+#endif++#endifdiff --git a/c/json.h b/c/json.hindex ef590536..7ee0c541 100644--- a/c/json.h+++ b/c/json.h@@ -160,4 +160,19 @@ static jval *json_get(jval *o, const char *key) {return NULL;}+static void json_free(jval *v) {+ if (!v) return;+ if (v->t == J_ARR || v->t == J_OBJ) {+ for (int i = 0; i < v->len; i++) {+ json_free(v->kids[i]);+ if (v->t == J_OBJ) free(v->keys[i]);+ }+ free(v->kids);+ free(v->keys);+ } else if (v->t == J_STR) {+ free(v->str);+ }+ free(v);+}+#endifdiff --git a/c/native_quant.c b/c/native_quant.cnew file mode 100644index 00000000..9771c9fc--- /dev/null+++ b/c/native_quant.c@@ -0,0 +1,281 @@+#include "native_quant.h"++#include <float.h>+#include <math.h>+#include <stdlib.h>+#include <string.h>++float coli_e8m0_decode(uint8_t value) {+ if (value == 0xff) return NAN;+ return ldexpf(1.0f, (int)value - 127);+}++float coli_e2m1_decode(uint8_t nibble) {+ static const float values[16] = {+ 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,+ 0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f,+ };+ return values[nibble & 15];+}++float coli_e4m3fn_decode(uint8_t value) {+ int sign = value >> 7;+ int exponent = (value >> 3) & 15;+ int mantissa = value & 7;+ if (exponent == 15 && mantissa == 7) return NAN;+ float number;+ if (!exponent)+ number = ldexpf((float)mantissa, -9);+ else+ number = ldexpf(1.0f + (float)mantissa / 8.0f, exponent - 7);+ return sign ? -number : number;+}++uint8_t coli_e4m3fn_encode(float value) {+ if (isnan(value)) return 0x7f;+ int negative = signbit(value) != 0;+ float magnitude = fabsf(value);+ if (!magnitude) return negative ? 0x80 : 0;+ if (magnitude >= 448.0f) return (uint8_t)((negative ? 0x80 : 0) | 0x7e);++ uint8_t best = 0;+#if FLT_RADIX == 2 && FLT_MANT_DIG == 24 && FLT_MAX_EXP == 128+ /* Exact binary32 round-to-nearest-even conversion in constant time. */+ if (magnitude < 0.015625f) {+ float scaled = magnitude * 512.0f;+ uint8_t rounded = (uint8_t)scaled;+ float fraction = scaled - rounded;+ if (fraction > 0.5f || (fraction == 0.5f && (rounded & 1)))+ rounded++;+ best = rounded;+ } else {+ uint32_t bits;+ memcpy(&bits, &magnitude, sizeof(bits));+ int exponent = (int)((bits >> 23) & 0xff) - 127;+ uint32_t significand = 0x800000u | (bits & 0x7fffffu);+ uint32_t rounded = significand >> 20;+ uint32_t remainder = significand & 0xfffffu;+ if (remainder > 0x80000u ||+ (remainder == 0x80000u && (rounded & 1u)))+ rounded++;+ if (rounded == 16u) {+ rounded = 8u;+ exponent++;+ }+ best = (uint8_t)((exponent + 7) * 8 + (int)rounded - 8);+ }+#else+ float best_distance = FLT_MAX;+ for (uint8_t code = 0; code <= 0x7e; code++) {+ float candidate = coli_e4m3fn_decode(code);+ float distance = fabsf(candidate - magnitude);+ if (distance < best_distance ||+ (distance == best_distance && !(code & 1) && (best & 1))) {+ best = code;+ best_distance = distance;+ }+ }+#endif+ return (uint8_t)(best | (negative ? 0x80 : 0));+}++float coli_bf16_round(float value) {+ uint32_t bits;+ memcpy(&bits, &value, sizeof(bits));+ if ((bits & 0x7f800000u) != 0x7f800000u) {+ uint32_t tie = (bits >> 16) & 1u;+ bits += 0x7fffu + tie;+ }+ bits &= 0xffff0000u;+ memcpy(&value, &bits, sizeof(value));+ return value;+}++float coli_bf16_decode(uint16_t value) {+ uint32_t bits = (uint32_t)value << 16;+ float output;+ memcpy(&output, &bits, sizeof(output));+ return output;+}++void coli_bf16_round_array(float *values, size_t count) {+ if (!values) return;+ for (size_t index = 0; index < count; index++)+ values[index] = coli_bf16_round(values[index]);+}++static int ceil_log2_positive(float value) {+ int exponent;+ float fraction = frexpf(value, &exponent);+ return fraction == 0.5f ? exponent - 1 : exponent;+}++int coli_fp8_activation_qdq_ref(float *output, uint8_t *scales,+ const float *input, size_t length,+ size_t block_size) {+ if (!output || !scales || !input || !length || !block_size)+ return -1;+ for (size_t base = 0; base < length; base += block_size) {+ size_t count = length - base < block_size ? length - base : block_size;+ float maximum = 0.0f;+ for (size_t i = 0; i < count; i++)+ maximum = fmaxf(maximum, fabsf(input[base + i]));+ maximum = fmaxf(maximum, 1e-4f);+ int scale_exponent = ceil_log2_positive(maximum / 448.0f);+ if (scale_exponent < -127) scale_exponent = -127;+ if (scale_exponent > 127) scale_exponent = 127;+ uint8_t encoded_scale = (uint8_t)(scale_exponent + 127);+ float scale = coli_e8m0_decode(encoded_scale);+ scales[base / block_size] = encoded_scale;+ for (size_t i = 0; i < count; i++) {+ float normalized = fmaxf(-448.0f,+ fminf(448.0f, input[base + i] / scale));+ output[base + i] = coli_e4m3fn_decode(+ coli_e4m3fn_encode(normalized)) * scale;+ }+ }+ return 0;+}++int coli_fp4_activation_qdq_ref(float *output, uint8_t *scales,+ const float *input, size_t length,+ size_t block_size) {+ if (!output || !scales || !input || !length || !block_size)+ return -1;+ for (size_t base = 0; base < length; base += block_size) {+ size_t count = length - base < block_size ? length - base : block_size;+ float maximum = 0.0f;+ for (size_t i = 0; i < count; i++)+ maximum = fmaxf(maximum, fabsf(input[base + i]));+ maximum = fmaxf(maximum, 6.0f * ldexpf(1.0f, -126));+ int exponent = ceil_log2_positive(maximum / 6.0f);+ if (exponent < -127) exponent = -127;+ if (exponent > 127) exponent = 127;+ scales[base / block_size] = (uint8_t)(exponent + 127);+ float scale = coli_e8m0_decode(scales[base / block_size]);+ for (size_t i = 0; i < count; i++) {+ float value = fmaxf(-6.0f, fminf(6.0f, input[base + i] / scale));+ int best = 0;+ float distance = fabsf(value - coli_e2m1_decode(0));+ for (int code = 1; code < 16; code++) {+ float candidate = fabsf(value - coli_e2m1_decode((uint8_t)code));+ if (candidate < distance) {+ distance = candidate;+ best = code;+ }+ }+ output[base + i] = coli_e2m1_decode((uint8_t)best) * scale;+ }+ }+ return 0;+}++int coli_hadamard_bf16_ref(float *values, size_t length) {+ if (!values || !length || (length & (length - 1))) return -1;+ for (size_t width = 1; width < length; width *= 2)+ for (size_t base = 0; base < length; base += 2 * width)+ for (size_t i = 0; i < width; i++) {+ float left = values[base + i];+ float right = values[base + width + i];+ values[base + i] = left + right;+ values[base + width + i] = left - right;+ }+ float scale = 1.0f / sqrtf((float)length);+ for (size_t i = 0; i < length; i++)+ values[i] = coli_bf16_round(values[i] * scale);+ return 0;+}++int coli_fp4_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input) {+ if (!output || !weight || !input ||+ weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 1 || weight->block_columns != 32)+ return -1;+ size_t rows = (size_t)weight->rows;+ size_t columns = (size_t)weight->columns;+ size_t packed_stride = columns / 2;+ size_t scale_stride = columns / 32;+ if (weight->data_bytes != rows * packed_stride ||+ weight->scale_bytes != rows * scale_stride)+ return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!activation || !activation_scales) {+ free(activation);+ free(activation_scales);+ return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation);+ free(activation_scales);+ return -1;+ }+ const uint8_t *packed = weight->data;+ const uint8_t *scales = weight->scales;+ for (size_t row = 0; row < rows; row++) {+ float sum = 0.0f;+ for (size_t column = 0; column < columns; column++) {+ uint8_t byte = packed[row * packed_stride + column / 2];+ uint8_t code = column & 1 ? byte >> 4 : byte & 15;+ float scale = coli_e8m0_decode(+ scales[row * scale_stride + column / 32]);+ sum += activation[column] * coli_e2m1_decode(code) * scale;+ }+ output[row] = sum;+ }+ free(activation_scales);+ free(activation);+ return 0;+}++int coli_fp8_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input) {+ if (!output || !weight || !input ||+ weight->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 128 || weight->block_columns != 128)+ return -1;+ size_t rows = (size_t)weight->rows;+ size_t columns = (size_t)weight->columns;+ size_t scale_rows = (rows + 127) / 128;+ size_t scale_columns = columns / 128;+ if (weight->data_bytes != rows * columns ||+ weight->scale_bytes != scale_rows * scale_columns)+ return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(scale_columns);+ if (!activation || !activation_scales) {+ free(activation);+ free(activation_scales);+ return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation);+ free(activation_scales);+ return -1;+ }+ const uint8_t *data = weight->data;+ const uint8_t *scales = weight->scales;+ for (size_t row = 0; row < rows; row++) {+ float sum = 0.0f;+ size_t scale_row = row / 128;+ for (size_t column = 0; column < columns; column++) {+ float value = coli_e4m3fn_decode(data[row * columns + column]);+ float scale = coli_e8m0_decode(+ scales[scale_row * scale_columns + column / 128]);+ sum += activation[column] * value * scale;+ }+ output[row] = sum;+ }+ free(activation_scales);+ free(activation);+ return 0;+}diff --git a/c/native_quant.h b/c/native_quant.hnew file mode 100644index 00000000..e1efeb6c--- /dev/null+++ b/c/native_quant.h@@ -0,0 +1,46 @@+#ifndef COLIBRI_NATIVE_QUANT_H+#define COLIBRI_NATIVE_QUANT_H++#include <stddef.h>+#include <stdint.h>++#include "tensor.h"++#ifdef __cplusplus+extern "C" {+#endif++float coli_e8m0_decode(uint8_t value);+float coli_e2m1_decode(uint8_t nibble);+float coli_e4m3fn_decode(uint8_t value);+uint8_t coli_e4m3fn_encode(float value);+float coli_bf16_round(float value);+float coli_bf16_decode(uint16_t value);+void coli_bf16_round_array(float *values, size_t count);++/* Simulates the official dynamic E4M3 activation quantization with one E8M0+ * power-of-two scale per block. Output contains the dequantized FP32 values. */+int coli_fp8_activation_qdq_ref(float *output, uint8_t *scales,+ const float *input, size_t length,+ size_t block_size);+int coli_fp4_activation_qdq_ref(float *output, uint8_t *scales,+ const float *input, size_t length,+ size_t block_size);+int coli_hadamard_bf16_ref(float *values, size_t length);++/* Correctness-first FP4 matvec. The input is dynamically quantized to E4M3 in+ * blocks of 128, weights are native E2M1 with one E8M0 scale per 32 K, and+ * accumulation is FP32. */+int coli_fp4_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input);++/* Correctness-first FP8 matvec for native 128x128 E4M3 weight blocks with+ * UE8M0 scales and dynamically quantized E4M3 activations. */+int coli_fp8_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input);++#ifdef __cplusplus+}+#endif++#endifdiff --git a/c/native_quant_batch.c b/c/native_quant_batch.cnew file mode 100644index 00000000..e1b3cbf9--- /dev/null+++ b/c/native_quant_batch.c@@ -0,0 +1,112 @@+#include "native_quant_batch.h"++#include <stdint.h>+#include <stdlib.h>++#include "native_quant.h"++static void batch_tables(float fp4[16], float fp8[256], float e8[256]) {+ for (int i = 0; i < 16; i++) fp4[i] = coli_e2m1_decode((uint8_t)i);+ for (int i = 0; i < 256; i++) {+ fp8[i] = coli_e4m3fn_decode((uint8_t)i);+ e8[i] = coli_e8m0_decode((uint8_t)i);+ }+}++int coli_fp8_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch) {+ if (!outputs || !weight || !inputs || batch < 1 || batch > 64 ||+ weight->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 128 || weight->block_columns != 128) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t scale_rows = (rows + 127) / 128;+ size_t scale_columns = columns / 128;+ if (weight->data_bytes != rows * columns ||+ weight->scale_bytes != scale_rows * scale_columns) return -1;+ float *activations = malloc((size_t)batch * columns * sizeof(*activations));+ uint8_t *activation_scales = malloc((size_t)batch * scale_columns);+ if (!activations || !activation_scales) {+ free(activation_scales); free(activations); return -1;+ }+ for (int item = 0; item < batch; item++)+ if (coli_fp8_activation_qdq_ref(+ activations + (size_t)item * columns,+ activation_scales + (size_t)item * scale_columns,+ inputs + (size_t)item * columns, columns, 128) != 0) {+ free(activation_scales); free(activations); return -1;+ }+ float fp4_unused[16], fp8[256], e8[256];+ batch_tables(fp4_unused, fp8, e8);+ const uint8_t *data = weight->data, *scales = weight->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t row = 0; row < weight->rows; row++) {+ float sums[64] = {0};+ size_t row_data = (size_t)row * columns;+ size_t scale_row = (size_t)row / 128;+ for (size_t base = 0; base < columns; base += 128) {+ float scale = e8[scales[scale_row * scale_columns + base / 128]];+ for (size_t offset = 0; offset < 128; offset++) {+ size_t column = base + offset;+ float value = fp8[data[row_data + column]];+ for (int item = 0; item < batch; item++)+ sums[item] += activations[(size_t)item * columns + column] *+ value * scale;+ }+ }+ for (int item = 0; item < batch; item++)+ outputs[(size_t)item * rows + (size_t)row] = sums[item];+ }+ free(activation_scales); free(activations); return 0;+}++int coli_fp4_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch) {+ if (!outputs || !weight || !inputs || batch < 1 || batch > 64 ||+ weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 1 || weight->block_columns != 32) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t packed_stride = columns / 2, scale_stride = columns / 32;+ if (weight->data_bytes != rows * packed_stride ||+ weight->scale_bytes != rows * scale_stride) return -1;+ float *activations = malloc((size_t)batch * columns * sizeof(*activations));+ uint8_t *activation_scales = malloc((size_t)batch * columns / 128);+ if (!activations || !activation_scales) {+ free(activation_scales); free(activations); return -1;+ }+ for (int item = 0; item < batch; item++)+ if (coli_fp8_activation_qdq_ref(+ activations + (size_t)item * columns,+ activation_scales + (size_t)item * columns / 128,+ inputs + (size_t)item * columns, columns, 128) != 0) {+ free(activation_scales); free(activations); return -1;+ }+ float fp4[16], fp8_unused[256], e8[256];+ batch_tables(fp4, fp8_unused, e8);+ const uint8_t *packed = weight->data, *scales = weight->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t row = 0; row < weight->rows; row++) {+ float sums[64] = {0};+ size_t row_data = (size_t)row * packed_stride;+ size_t row_scale = (size_t)row * scale_stride;+ for (size_t base = 0; base < columns; base += 32) {+ float scale = e8[scales[row_scale + base / 32]];+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ uint8_t byte = packed[row_data + column / 2];+ float value = fp4[column & 1 ? byte >> 4 : byte & 15];+ for (int item = 0; item < batch; item++)+ sums[item] += activations[(size_t)item * columns + column] *+ value * scale;+ }+ }+ for (int item = 0; item < batch; item++)+ outputs[(size_t)item * rows + (size_t)row] = sums[item];+ }+ free(activation_scales); free(activations); return 0;+}diff --git a/c/native_quant_batch.h b/c/native_quant_batch.hnew file mode 100644index 00000000..5a97a1e8--- /dev/null+++ b/c/native_quant_batch.h@@ -0,0 +1,13 @@+#ifndef COLIBRI_NATIVE_QUANT_BATCH_H+#define COLIBRI_NATIVE_QUANT_BATCH_H++#include "tensor.h"++/* inputs and outputs are batch-major. Every batch element preserves the exact+ * scalar column accumulation order of the single-token reference kernels. */+int coli_fp8_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch);+int coli_fp4_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch);++#endifdiff --git a/c/native_quant_batch_avx512.c b/c/native_quant_batch_avx512.cnew file mode 100644index 00000000..4a0e051a--- /dev/null+++ b/c/native_quant_batch_avx512.c@@ -0,0 +1,160 @@+#include <immintrin.h>++#define coli_fp8_matmul_batch_ref coli_fp8_matmul_batch_baseline_v6+/* ---- begin inlined native_quant_batch_interleaved_v4.c ---- */+/* Keep the established FP8 path and replace only FP4 batch execution. */+#define coli_fp4_matmul_batch_ref coli_fp4_matmul_batch_baseline_v4+#include "native_quant_batch.c"+#undef coli_fp4_matmul_batch_ref++int coli_fp4_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch) {+ enum { BATCH_MAX = 64, ROW_TILE = 4, SIMD_WIDTH = 8 };+ if (!outputs || !weight || !inputs || batch < 1 || batch > BATCH_MAX ||+ weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 1 || weight->block_columns != 32) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t packed_stride = columns / 2, scale_stride = columns / 32;+ if (weight->data_bytes != rows * packed_stride ||+ weight->scale_bytes != rows * scale_stride) return -1;+ int stride = (batch + SIMD_WIDTH - 1) & -SIMD_WIDTH;++ float *item_activation = malloc(columns * sizeof(*item_activation));+ float *interleaved = calloc(columns * (size_t)stride, sizeof(*interleaved));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!item_activation || !interleaved || !activation_scales) {+ free(activation_scales); free(interleaved); free(item_activation);+ return -1;+ }+ for (int item = 0; item < batch; item++) {+ if (coli_fp8_activation_qdq_ref(+ item_activation, activation_scales,+ inputs + (size_t)item * columns, columns, 128)) {+ free(activation_scales); free(interleaved); free(item_activation);+ return -1;+ }+ for (size_t column = 0; column < columns; column++)+ interleaved[column * (size_t)stride + (size_t)item] =+ item_activation[column];+ }+ free(activation_scales); free(item_activation);++ float fp4[16], e8[256];+ for (int i = 0; i < 16; i++) fp4[i] = coli_e2m1_decode((uint8_t)i);+ for (int i = 0; i < 256; i++) e8[i] = coli_e8m0_decode((uint8_t)i);+ const uint8_t *packed = weight->data, *scales = weight->scales;+ int64_t tiles = (weight->rows + ROW_TILE - 1) / ROW_TILE;+ #pragma omp parallel for schedule(static)+ for (int64_t tile = 0; tile < tiles; tile++) {+ int lanes = (int)(weight->rows - tile * ROW_TILE);+ if (lanes > ROW_TILE) lanes = ROW_TILE;+ size_t row_data[ROW_TILE], row_scale[ROW_TILE];+ float sums[ROW_TILE][BATCH_MAX] = {{0}};+ for (int lane = 0; lane < lanes; lane++) {+ size_t row = (size_t)tile * ROW_TILE + (size_t)lane;+ row_data[lane] = row * packed_stride;+ row_scale[lane] = row * scale_stride;+ }+ for (size_t base = 0; base < columns; base += 32) {+ float block_scales[ROW_TILE];+ for (int lane = 0; lane < lanes; lane++)+ block_scales[lane] =+ e8[scales[row_scale[lane] + base / 32]];+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ const float *activation =+ interleaved + column * (size_t)stride;+ for (int lane = 0; lane < lanes; lane++) {+ uint8_t byte = packed[row_data[lane] + column / 2];+ float value = fp4[column & 1 ? byte >> 4 : byte & 15];+ float scale = block_scales[lane];+ #pragma omp simd+ for (int item = 0; item < stride; item++)+ sums[lane][item] += activation[item] * value * scale;+ }+ }+ }+ for (int lane = 0; lane < lanes; lane++) {+ size_t row = (size_t)tile * ROW_TILE + (size_t)lane;+ for (int item = 0; item < batch; item++)+ outputs[(size_t)item * rows + row] = sums[lane][item];+ }+ }+ free(interleaved);+ return 0;+}+/* ---- end inlined native_quant_batch_interleaved_v4.c ---- */++#undef coli_fp8_matmul_batch_ref++int coli_fp8_matmul_batch_ref(float *outputs, const ColiTensorView *weight,+ const float *inputs, int batch) {+#ifndef __AVX512F__+ return coli_fp8_matmul_batch_baseline_v6(outputs, weight, inputs, batch);+#else+ if (!outputs || !weight || !inputs || batch < 1 || batch > 64 ||+ weight->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 128 || weight->block_columns != 128) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t scale_rows = (rows + 127) / 128;+ size_t scale_columns = columns / 128;+ if (weight->data_bytes != rows * columns ||+ weight->scale_bytes != scale_rows * scale_columns) return -1;++ float *activations = malloc((size_t)batch * columns * sizeof(*activations));+ uint8_t *activation_scales = malloc((size_t)batch * scale_columns);+ if (!activations || !activation_scales) {+ free(activation_scales); free(activations); return -1;+ }+ for (int item = 0; item < batch; item++)+ if (coli_fp8_activation_qdq_ref(+ activations + (size_t)item * columns,+ activation_scales + (size_t)item * scale_columns,+ inputs + (size_t)item * columns, columns, 128)) {+ free(activation_scales); free(activations); return -1;+ }++ float fp8[256], e8[256];+ for (int i = 0; i < 256; i++) {+ fp8[i] = coli_e4m3fn_decode((uint8_t)i);+ e8[i] = coli_e8m0_decode((uint8_t)i);+ }+ const uint8_t *data = weight->data, *scales = weight->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t row = 0; row < weight->rows; row++) {+ float sums[64] = {0};+ size_t row_data = (size_t)row * columns;+ size_t scale_row = (size_t)row / 128;+ for (size_t base = 0; base < columns; base += 128) {+ __m512 scale = _mm512_set1_ps(+ e8[scales[scale_row * scale_columns + base / 128]]);+ for (size_t chunk = 0; chunk < 128; chunk += 16) {+ __m128i packed_codes = _mm_loadu_si128(+ (const __m128i *)(data + row_data + base + chunk));+ __m512i codes = _mm512_cvtepu8_epi32(packed_codes);+ __m512 values = _mm512_i32gather_ps(codes, fp8, 4);+ for (int item = 0; item < batch; item++) {+ __m512 activation = _mm512_loadu_ps(+ activations + (size_t)item * columns + base + chunk);+ __m512 product = _mm512_mul_ps(+ _mm512_mul_ps(activation, values), scale);+ float products[16];+ _mm512_storeu_ps(products, product);+ for (int lane = 0; lane < 16; lane++)+ sums[item] += products[lane];+ }+ }+ }+ for (int item = 0; item < batch; item++)+ outputs[(size_t)item * rows + (size_t)row] = sums[item];+ }+ free(activation_scales); free(activations);+ return 0;+#endif+}diff --git a/c/native_quant_dual.c b/c/native_quant_dual.cnew file mode 100644index 00000000..1190618c--- /dev/null+++ b/c/native_quant_dual.c@@ -0,0 +1,122 @@+#include "native_quant_dual.h"++#include <stdint.h>+#include <stdlib.h>++#include "native_quant.h"++static int dual_same_shape(const ColiTensorView *a, const ColiTensorView *b) {+ return a && b && a->rows == b->rows && a->columns == b->columns &&+ a->block_rows == b->block_rows &&+ a->block_columns == b->block_columns;+}++int coli_fp4_dual_matvec_ref(float *output_a, float *output_b,+ const ColiTensorView *a,+ const ColiTensorView *b,+ const float *input) {+ if (!output_a || !output_b || !input || !dual_same_shape(a, b) ||+ a->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ b->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ a->scale_format != COLI_SCALE_UE8M0 ||+ b->scale_format != COLI_SCALE_UE8M0 || !a->data || !b->data ||+ !a->scales || !b->scales || a->rows < 1 || a->columns < 1 ||+ a->columns % 128 || a->block_rows != 1 || a->block_columns != 32)+ return -1;+ size_t rows = (size_t)a->rows, columns = (size_t)a->columns;+ size_t packed_stride = columns / 2, scale_stride = columns / 32;+ if (a->data_bytes != rows * packed_stride ||+ b->data_bytes != rows * packed_stride ||+ a->scale_bytes != rows * scale_stride ||+ b->scale_bytes != rows * scale_stride) return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation_scales); free(activation); return -1;+ }+ float fp4[16], e8[256];+ for (int i = 0; i < 16; i++) fp4[i] = coli_e2m1_decode((uint8_t)i);+ for (int i = 0; i < 256; i++) e8[i] = coli_e8m0_decode((uint8_t)i);+ const uint8_t *data_a = a->data, *data_b = b->data;+ const uint8_t *scales_a = a->scales, *scales_b = b->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t row = 0; row < a->rows; row++) {+ size_t row_data = (size_t)row * packed_stride;+ size_t row_scale = (size_t)row * scale_stride;+ float sum_a = 0.0f, sum_b = 0.0f;+ for (size_t base = 0; base < columns; base += 32) {+ float scale_a = e8[scales_a[row_scale + base / 32]];+ float scale_b = e8[scales_b[row_scale + base / 32]];+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ uint8_t byte_a = data_a[row_data + column / 2];+ uint8_t byte_b = data_b[row_data + column / 2];+ uint8_t code_a = column & 1 ? byte_a >> 4 : byte_a & 15;+ uint8_t code_b = column & 1 ? byte_b >> 4 : byte_b & 15;+ float x = activation[column];+ sum_a += x * fp4[code_a] * scale_a;+ sum_b += x * fp4[code_b] * scale_b;+ }+ }+ output_a[row] = sum_a; output_b[row] = sum_b;+ }+ free(activation_scales); free(activation); return 0;+}++int coli_fp8_dual_matvec_ref(float *output_a, float *output_b,+ const ColiTensorView *a,+ const ColiTensorView *b,+ const float *input) {+ if (!output_a || !output_b || !input || !dual_same_shape(a, b) ||+ a->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ b->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ a->scale_format != COLI_SCALE_UE8M0 ||+ b->scale_format != COLI_SCALE_UE8M0 || !a->data || !b->data ||+ !a->scales || !b->scales || a->rows < 1 || a->columns < 1 ||+ a->columns % 128 || a->block_rows != 128 ||+ a->block_columns != 128) return -1;+ size_t rows = (size_t)a->rows, columns = (size_t)a->columns;+ size_t scale_rows = (rows + 127) / 128, scale_columns = columns / 128;+ if (a->data_bytes != rows * columns || b->data_bytes != rows * columns ||+ a->scale_bytes != scale_rows * scale_columns ||+ b->scale_bytes != scale_rows * scale_columns) return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(scale_columns);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation_scales); free(activation); return -1;+ }+ float fp8[256], e8[256];+ for (int i = 0; i < 256; i++) {+ fp8[i] = coli_e4m3fn_decode((uint8_t)i);+ e8[i] = coli_e8m0_decode((uint8_t)i);+ }+ const uint8_t *data_a = a->data, *data_b = b->data;+ const uint8_t *scales_a = a->scales, *scales_b = b->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t row = 0; row < a->rows; row++) {+ size_t row_data = (size_t)row * columns;+ size_t scale_row = (size_t)row / 128;+ float sum_a = 0.0f, sum_b = 0.0f;+ for (size_t base = 0; base < columns; base += 128) {+ size_t scale_index = scale_row * scale_columns + base / 128;+ float scale_a = e8[scales_a[scale_index]];+ float scale_b = e8[scales_b[scale_index]];+ for (size_t offset = 0; offset < 128; offset++) {+ size_t column = base + offset;+ float x = activation[column];+ sum_a += x * fp8[data_a[row_data + column]] * scale_a;+ sum_b += x * fp8[data_b[row_data + column]] * scale_b;+ }+ }+ output_a[row] = sum_a; output_b[row] = sum_b;+ }+ free(activation_scales); free(activation); return 0;+}diff --git a/c/native_quant_dual.h b/c/native_quant_dual.hnew file mode 100644index 00000000..c3e07f47--- /dev/null+++ b/c/native_quant_dual.h@@ -0,0 +1,15 @@+#ifndef COLIBRI_NATIVE_QUANT_DUAL_H+#define COLIBRI_NATIVE_QUANT_DUAL_H++#include "tensor.h"++int coli_fp4_dual_matvec_ref(float *output_a, float *output_b,+ const ColiTensorView *weight_a,+ const ColiTensorView *weight_b,+ const float *input);+int coli_fp8_dual_matvec_ref(float *output_a, float *output_b,+ const ColiTensorView *weight_a,+ const ColiTensorView *weight_b,+ const float *input);++#endifdiff --git a/c/native_quant_fp4_rows16.c b/c/native_quant_fp4_rows16.cnew file mode 100644index 00000000..0c1773d9--- /dev/null+++ b/c/native_quant_fp4_rows16.c@@ -0,0 +1,171 @@+#include "native_quant_fp4_rows16.h"++#include <immintrin.h>+#include <stdint.h>+#include <stdlib.h>++static int source_valid(const ColiTensorView *weight) {+ if (!weight || weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 || !weight->data ||+ !weight->scales || weight->rows < 1 || weight->rows % 16 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 1 || weight->block_columns != 32) return 0;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ return weight->data_bytes == rows * columns / 2 &&+ weight->scale_bytes == rows * columns / 32;+}++static int packed_valid(const ColiTensorView *weight) {+ if (!weight || weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 || !weight->data ||+ !weight->scales || weight->rows < 1 || weight->rows % 16 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 16 || weight->block_columns != 32) return 0;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ return weight->data_bytes == rows * columns / 2 &&+ weight->scale_bytes == rows * columns / 32;+}++int coli_fp4_pack_rows16_v10(unsigned char *packed_data,+ unsigned char *packed_scales,+ const ColiTensorView *source) {+ if (!packed_data || !packed_scales || !source_valid(source)) return -1;+ const unsigned char *data = source->data;+ const unsigned char *scales = source->scales;+ size_t rows = (size_t)source->rows, columns = (size_t)source->columns;+ size_t data_stride = columns / 2, scale_stride = columns / 32;+ for (size_t row = 0; row < rows; row++) {+ size_t tile = row / 16, lane = row % 16;+ for (size_t column = 0; column < data_stride; column++)+ packed_data[(tile * data_stride + column) * 16 + lane] =+ data[row * data_stride + column];+ for (size_t column = 0; column < scale_stride; column++)+ packed_scales[(tile * scale_stride + column) * 16 + lane] =+ scales[row * scale_stride + column];+ }+ return 0;+}++#ifdef __AVX512F__+static void decode_tables(__m512 *fp4_table, float e8[256]) {+ float fp4[16];+ for (int i = 0; i < 16; i++) fp4[i] = coli_e2m1_decode((uint8_t)i);+ for (int i = 0; i < 256; i++) e8[i] = coli_e8m0_decode((uint8_t)i);+ *fp4_table = _mm512_loadu_ps(fp4);+}++static __m512 decode_fp4_rows16(const unsigned char *data, int high,+ __m512 fp4_table) {+ __m512i codes = _mm512_cvtepu8_epi32(+ _mm_loadu_si128((const __m128i *)data));+ codes = high ? _mm512_srli_epi32(codes, 4)+ : _mm512_and_si512(codes, _mm512_set1_epi32(15));+ return _mm512_permutexvar_ps(codes, fp4_table);+}++static __m512 decode_scales_rows16(const unsigned char *scales,+ const float e8[256]) {+ __m512i codes = _mm512_cvtepu8_epi32(+ _mm_loadu_si128((const __m128i *)scales));+ return _mm512_i32gather_ps(codes, e8, 4);+}+#endif++int coli_fp4_matvec_rows16_v10(float *output,+ const ColiTensorView *weight,+ const float *input) {+#ifndef __AVX512F__+ (void)output; (void)weight; (void)input; return -1;+#else+ if (!output || !input || !packed_valid(weight)) return -1;+ size_t columns = (size_t)weight->columns;+ size_t data_stride = columns / 2, scale_stride = columns / 32;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128)) {+ free(activation_scales); free(activation); return -1;+ }+ __m512 fp4_table; float e8[256]; decode_tables(&fp4_table, e8);+ const unsigned char *data = weight->data, *scales = weight->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t tile = 0; tile < weight->rows / 16; tile++) {+ __m512 sum = _mm512_setzero_ps();+ for (size_t base = 0; base < columns; base += 32) {+ __m512 scale = decode_scales_rows16(+ scales + ((size_t)tile * scale_stride + base / 32) * 16, e8);+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ const unsigned char *codes = data ++ ((size_t)tile * data_stride + column / 2) * 16;+ __m512 values = decode_fp4_rows16(codes, column & 1, fp4_table);+ __m512 product = _mm512_mul_ps(+ _mm512_mul_ps(_mm512_set1_ps(activation[column]), values),+ scale);+ sum = _mm512_add_ps(sum, product);+ }+ }+ _mm512_storeu_ps(output + (size_t)tile * 16, sum);+ }+ free(activation_scales); free(activation); return 0;+#endif+}++int coli_fp4_dual_matvec_rows16_v10(float *output_a, float *output_b,+ const ColiTensorView *a,+ const ColiTensorView *b,+ const float *input) {+#ifndef __AVX512F__+ (void)output_a; (void)output_b; (void)a; (void)b; (void)input; return -1;+#else+ if (!output_a || !output_b || !input || !packed_valid(a) ||+ !packed_valid(b) || a->rows != b->rows ||+ a->columns != b->columns) return -1;+ size_t columns = (size_t)a->columns;+ size_t data_stride = columns / 2, scale_stride = columns / 32;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128)) {+ free(activation_scales); free(activation); return -1;+ }+ __m512 fp4_table; float e8[256]; decode_tables(&fp4_table, e8);+ const unsigned char *data_a = a->data, *data_b = b->data;+ const unsigned char *scales_a = a->scales, *scales_b = b->scales;+ #pragma omp parallel for schedule(static)+ for (int64_t tile = 0; tile < a->rows / 16; tile++) {+ __m512 sum_a = _mm512_setzero_ps(), sum_b = _mm512_setzero_ps();+ for (size_t base = 0; base < columns; base += 32) {+ const unsigned char *scale_offset_a = scales_a ++ ((size_t)tile * scale_stride + base / 32) * 16;+ const unsigned char *scale_offset_b = scales_b ++ ((size_t)tile * scale_stride + base / 32) * 16;+ __m512 scale_a = decode_scales_rows16(scale_offset_a, e8);+ __m512 scale_b = decode_scales_rows16(scale_offset_b, e8);+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ size_t packed_offset =+ ((size_t)tile * data_stride + column / 2) * 16;+ __m512 values_a = decode_fp4_rows16(+ data_a + packed_offset, column & 1, fp4_table);+ __m512 values_b = decode_fp4_rows16(+ data_b + packed_offset, column & 1, fp4_table);+ __m512 x = _mm512_set1_ps(activation[column]);+ sum_a = _mm512_add_ps(sum_a, _mm512_mul_ps(+ _mm512_mul_ps(x, values_a), scale_a));+ sum_b = _mm512_add_ps(sum_b, _mm512_mul_ps(+ _mm512_mul_ps(x, values_b), scale_b));+ }+ }+ _mm512_storeu_ps(output_a + (size_t)tile * 16, sum_a);+ _mm512_storeu_ps(output_b + (size_t)tile * 16, sum_b);+ }+ free(activation_scales); free(activation); return 0;+#endif+}diff --git a/c/native_quant_fp4_rows16.h b/c/native_quant_fp4_rows16.hnew file mode 100644index 00000000..2455eacb--- /dev/null+++ b/c/native_quant_fp4_rows16.h@@ -0,0 +1,19 @@+#ifndef COLIBRI_NATIVE_QUANT_FP4_ROWS16_H+#define COLIBRI_NATIVE_QUANT_FP4_ROWS16_H++#include "native_quant.h"++int coli_fp4_pack_rows16_v10(unsigned char *packed_data,+ unsigned char *packed_scales,+ const ColiTensorView *source);++int coli_fp4_matvec_rows16_v10(float *output,+ const ColiTensorView *weight,+ const float *input);++int coli_fp4_dual_matvec_rows16_v10(float *output_a, float *output_b,+ const ColiTensorView *a,+ const ColiTensorView *b,+ const float *input);++#endifdiff --git a/c/native_quant_parallel.c b/c/native_quant_parallel.cnew file mode 100644index 00000000..c6dfb3ba--- /dev/null+++ b/c/native_quant_parallel.c@@ -0,0 +1,129 @@+/* Four-row interleaving keeps each output row's scalar accumulation order+ * unchanged while exposing independent accumulator chains to the CPU. */+#define coli_fp4_matvec_ref coli_fp4_matvec_serial_ref+#define coli_fp8_matvec_ref coli_fp8_matvec_serial_ref+#include "native_quant.c"+#undef coli_fp4_matvec_ref+#undef coli_fp8_matvec_ref++enum { ROW_TILE = 4 };++static void build_decode_tables_v4(float fp4[16], float fp8[256],+ float e8[256]) {+ for (int i = 0; i < 16; i++) fp4[i] = coli_e2m1_decode((uint8_t)i);+ for (int i = 0; i < 256; i++) {+ fp8[i] = coli_e4m3fn_decode((uint8_t)i);+ e8[i] = coli_e8m0_decode((uint8_t)i);+ }+}++int coli_fp4_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input) {+ if (!output || !weight || !input ||+ weight->format != COLI_TENSOR_FP4_NATIVE_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 1 || weight->block_columns != 32) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t packed_stride = columns / 2, scale_stride = columns / 32;+ if (weight->data_bytes != rows * packed_stride ||+ weight->scale_bytes != rows * scale_stride) return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(columns / 128);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation_scales); free(activation); return -1;+ }+ float fp4[16], fp8_unused[256], e8[256];+ build_decode_tables_v4(fp4, fp8_unused, e8);+ const uint8_t *packed = weight->data, *scales = weight->scales;+ int64_t tiles = (weight->rows + ROW_TILE - 1) / ROW_TILE;+ #pragma omp parallel for schedule(static)+ for (int64_t tile = 0; tile < tiles; tile++) {+ int count = (int)(weight->rows - tile * ROW_TILE);+ if (count > ROW_TILE) count = ROW_TILE;+ size_t row_data[ROW_TILE], row_scale[ROW_TILE];+ float sums[ROW_TILE] = {0};+ for (int lane = 0; lane < count; lane++) {+ size_t row = (size_t)tile * ROW_TILE + (size_t)lane;+ row_data[lane] = row * packed_stride;+ row_scale[lane] = row * scale_stride;+ }+ for (size_t base = 0; base < columns; base += 32) {+ float block_scales[ROW_TILE];+ for (int lane = 0; lane < count; lane++)+ block_scales[lane] = e8[scales[row_scale[lane] + base / 32]];+ for (size_t offset = 0; offset < 32; offset++) {+ size_t column = base + offset;+ float x = activation[column];+ for (int lane = 0; lane < count; lane++) {+ uint8_t byte = packed[row_data[lane] + column / 2];+ uint8_t code = column & 1 ? byte >> 4 : byte & 15;+ sums[lane] += x * fp4[code] * block_scales[lane];+ }+ }+ }+ for (int lane = 0; lane < count; lane++)+ output[(size_t)tile * ROW_TILE + (size_t)lane] = sums[lane];+ }+ free(activation_scales); free(activation); return 0;+}++int coli_fp8_matvec_ref(float *output, const ColiTensorView *weight,+ const float *input) {+ if (!output || !weight || !input ||+ weight->format != COLI_TENSOR_FP8_E4M3_BLOCK ||+ weight->scale_format != COLI_SCALE_UE8M0 ||+ !weight->data || !weight->scales || weight->rows < 1 ||+ weight->columns < 1 || weight->columns % 128 ||+ weight->block_rows != 128 || weight->block_columns != 128) return -1;+ size_t rows = (size_t)weight->rows, columns = (size_t)weight->columns;+ size_t scale_rows = (rows + 127) / 128, scale_columns = columns / 128;+ if (weight->data_bytes != rows * columns ||+ weight->scale_bytes != scale_rows * scale_columns) return -1;+ float *activation = malloc(columns * sizeof(*activation));+ uint8_t *activation_scales = malloc(scale_columns);+ if (!activation || !activation_scales) {+ free(activation_scales); free(activation); return -1;+ }+ if (coli_fp8_activation_qdq_ref(activation, activation_scales,+ input, columns, 128) != 0) {+ free(activation_scales); free(activation); return -1;+ }+ float fp4_unused[16], fp8[256], e8[256];+ build_decode_tables_v4(fp4_unused, fp8, e8);+ const uint8_t *data = weight->data, *scales = weight->scales;+ int64_t tiles = (weight->rows + ROW_TILE - 1) / ROW_TILE;+ #pragma omp parallel for schedule(static)+ for (int64_t tile = 0; tile < tiles; tile++) {+ int count = (int)(weight->rows - tile * ROW_TILE);+ if (count > ROW_TILE) count = ROW_TILE;+ size_t row_data[ROW_TILE], scale_row[ROW_TILE];+ float sums[ROW_TILE] = {0};+ for (int lane = 0; lane < count; lane++) {+ size_t row = (size_t)tile * ROW_TILE + (size_t)lane;+ row_data[lane] = row * columns;+ scale_row[lane] = row / 128;+ }+ for (size_t base = 0; base < columns; base += 128) {+ float block_scales[ROW_TILE];+ for (int lane = 0; lane < count; lane++)+ block_scales[lane] = e8[scales[scale_row[lane] *+ scale_columns + base / 128]];+ for (size_t offset = 0; offset < 128; offset++) {+ size_t column = base + offset;+ float x = activation[column];+ for (int lane = 0; lane < count; lane++)+ sums[lane] += x * fp8[data[row_data[lane] + column]] *+ block_scales[lane];+ }+ }+ for (int lane = 0; lane < count; lane++)+ output[(size_t)tile * ROW_TILE + (size_t)lane] = sums[lane];+ }+ free(activation_scales); free(activation); return 0;+}diff --git a/c/safetensors_index.c b/c/safetensors_index.cnew file mode 100644index 00000000..b1c9f11a--- /dev/null+++ b/c/safetensors_index.c@@ -0,0 +1,451 @@+#define _GNU_SOURCE+#include "safetensors_index.h"++#include <dirent.h>+#include <errno.h>+#include <fcntl.h>+#include <math.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++#include "compat.h"+#include "json.h"++#define COLI_ST_MAX_SHARDS 512+#define COLI_ST_MAX_HEADER (512ULL << 20)++typedef struct {+ char *path;+ int fd;+ uint64_t size;+} ColiSafetensorsShard;++struct ColiSafetensorsIndex {+ ColiSafetensorsTensor *tensors;+ size_t tensor_count;+ size_t tensor_capacity;+ int *hash;+ size_t hash_capacity;+ ColiSafetensorsShard shards[COLI_ST_MAX_SHARDS];+ size_t shard_count;+};++static int set_error(char *error, size_t size, const char *format, ...) {+ if (error && size) {+ va_list args;+ va_start(args, format);+ vsnprintf(error, size, format, args);+ va_end(args);+ }+ return -1;+}++static uint64_t hash_name(const char *text) {+ uint64_t hash = 1469598103934665603ULL;+ while (*text) {+ hash ^= (unsigned char)*text++;+ hash *= 1099511628211ULL;+ }+ return hash;+}++static int compare_paths(const void *left, const void *right) {+ const char *const *a = (const char *const *)left;+ const char *const *b = (const char *const *)right;+ return strcmp(*a, *b);+}++static int has_safetensors_suffix(const char *name) {+ const char *suffix = strrchr(name, '.');+ return suffix && !strcmp(suffix, ".safetensors");+}++static int dtype_from_name(const char *name, ColiSafetensorsDType *dtype) {+ static const struct {+ const char *name;+ ColiSafetensorsDType dtype;+ } formats[] = {+ {"BF16", COLI_ST_BF16}, {"F16", COLI_ST_F16},+ {"F32", COLI_ST_F32}, {"U8", COLI_ST_U8},+ {"I8", COLI_ST_I8}, {"I64", COLI_ST_I64},+ {"F8_E4M3", COLI_ST_F8_E4M3},+ {"F8_E8M0", COLI_ST_F8_E8M0},+ };+ for (size_t i = 0; i < sizeof(formats) / sizeof(formats[0]); i++) {+ if (!strcmp(name, formats[i].name)) {+ *dtype = formats[i].dtype;+ return 0;+ }+ }+ return -1;+}++static int dtype_width(ColiSafetensorsDType dtype, uint64_t *width) {+ switch (dtype) {+ case COLI_ST_U8:+ case COLI_ST_I8:+ case COLI_ST_F8_E4M3:+ case COLI_ST_F8_E8M0:+ *width = 1;+ return 0;+ case COLI_ST_BF16:+ case COLI_ST_F16:+ *width = 2;+ return 0;+ case COLI_ST_F32:+ *width = 4;+ return 0;+ case COLI_ST_I64:+ *width = 8;+ return 0;+ }+ return -1;+}++const char *coli_st_dtype_name(ColiSafetensorsDType dtype) {+ switch (dtype) {+ case COLI_ST_BF16: return "BF16";+ case COLI_ST_F16: return "F16";+ case COLI_ST_F32: return "F32";+ case COLI_ST_U8: return "U8";+ case COLI_ST_I8: return "I8";+ case COLI_ST_I64: return "I64";+ case COLI_ST_F8_E4M3: return "F8_E4M3";+ case COLI_ST_F8_E8M0: return "F8_E8M0";+ }+ return "UNKNOWN";+}++static int append_tensor(ColiSafetensorsIndex *index,+ const ColiSafetensorsTensor *tensor) {+ if (index->tensor_count == index->tensor_capacity) {+ size_t capacity = index->tensor_capacity ? index->tensor_capacity * 2 : 4096;+ void *allocation = realloc(index->tensors, capacity * sizeof(*index->tensors));+ if (!allocation) return -1;+ index->tensors = (ColiSafetensorsTensor *)allocation;+ index->tensor_capacity = capacity;+ }+ index->tensors[index->tensor_count++] = *tensor;+ return 0;+}++static int json_nonnegative_integer(const jval *value, double upper_exclusive,+ uint64_t *result) {+ if (!value || value->t != J_NUM || !isfinite(value->num) ||+ value->num < 0.0 || value->num >= upper_exclusive ||+ floor(value->num) != value->num)+ return -1;+ *result = (uint64_t)value->num;+ return 0;+}++static int index_shard(ColiSafetensorsIndex *index, const char *path,+ char *error, size_t error_size) {+ struct stat status;+ int result = -1;+ int fd = -1;+ char *header = NULL;+ char *arena = NULL;+ jval *root = NULL;++ if (index->shard_count >= COLI_ST_MAX_SHARDS)+ return set_error(error, error_size, "too many safetensors shards");++ fd = open(path, COMPAT_O_RDONLY);+ if (fd < 0) {+ result = set_error(error, error_size, "cannot open %s: %s",+ path, strerror(errno));+ goto cleanup;+ }+ if (fstat(fd, &status) != 0) {+ result = set_error(error, error_size, "cannot stat %s: %s",+ path, strerror(errno));+ goto cleanup;+ }+ if (status.st_size < 8) {+ result = set_error(error, error_size, "invalid safetensors header: %s", path);+ goto cleanup;+ }++ uint64_t shard_size = (uint64_t)status.st_size;+ uint64_t header_length = 0;+ if (pread(fd, &header_length, 8, 0) != 8 || header_length < 2 ||+ header_length > shard_size - 8 || header_length > COLI_ST_MAX_HEADER) {+ result = set_error(error, error_size, "invalid safetensors header: %s", path);+ goto cleanup;+ }++ header = (char *)malloc((size_t)header_length + 1);+ if (!header) {+ result = set_error(error, error_size, "out of memory reading %s", path);+ goto cleanup;+ }+ if (pread(fd, header, (size_t)header_length, 8) != (ssize_t)header_length) {+ result = set_error(error, error_size, "short safetensors header: %s", path);+ goto cleanup;+ }+ header[header_length] = 0;++ root = json_parse(header, &arena);+ if (!root || root->t != J_OBJ) {+ result = set_error(error, error_size,+ "safetensors header is not an object: %s", path);+ goto cleanup;+ }++ int shard = (int)index->shard_count;+ uint64_t data_start = 8 + header_length;+ for (int i = 0; i < root->len; i++) {+ const char *name = root->keys[i];+ if (!name) {+ result = set_error(error, error_size, "invalid tensor name in %s", path);+ goto cleanup;+ }+ if (!strcmp(name, "__metadata__")) continue;+ jval *metadata = root->kids[i];+ jval *dtype_value = json_get(metadata, "dtype");+ jval *offsets = json_get(metadata, "data_offsets");+ jval *shape = json_get(metadata, "shape");+ ColiSafetensorsTensor tensor;+ memset(&tensor, 0, sizeof(tensor));+ if (!metadata || metadata->t != J_OBJ ||+ !dtype_value || dtype_value->t != J_STR || !dtype_value->str ||+ !offsets || offsets->t != J_ARR || offsets->len != 2 ||+ !shape || shape->t != J_ARR ||+ shape->len > COLI_ST_MAX_RANK ||+ dtype_from_name(dtype_value->str, &tensor.dtype) != 0) {+ result = set_error(error, error_size,+ "unsupported tensor metadata: %s in %s", name, path);+ goto cleanup;+ }++ uint64_t start = 0, end = 0;+ if (json_nonnegative_integer(offsets->kids[0], ldexp(1.0, 64), &start) != 0 ||+ json_nonnegative_integer(offsets->kids[1], ldexp(1.0, 64), &end) != 0 ||+ start > end || end > shard_size - data_start) {+ result = set_error(error, error_size,+ "invalid offsets for %s in %s", name, path);+ goto cleanup;+ }++ tensor.rank = shape->len;+ tensor.numel = 1;+ for (int dimension = 0; dimension < shape->len; dimension++) {+ uint64_t extent = 0;+ if (json_nonnegative_integer(shape->kids[dimension],+ ldexp(1.0, 63), &extent) != 0 ||+ (extent && tensor.numel > UINT64_MAX / extent)) {+ result = set_error(error, error_size,+ "invalid shape for %s in %s", name, path);+ goto cleanup;+ }+ tensor.shape[dimension] = (int64_t)extent;+ tensor.numel *= extent;+ }++ uint64_t width = 0;+ if (dtype_width(tensor.dtype, &width) != 0 ||+ tensor.numel > UINT64_MAX / width ||+ end - start != tensor.numel * width) {+ result = set_error(error, error_size,+ "tensor byte size does not match dtype and shape: %s in %s",+ name, path);+ goto cleanup;+ }++ tensor.name = strdup(name);+ if (!tensor.name) {+ result = set_error(error, error_size, "out of memory indexing %s", path);+ goto cleanup;+ }+ tensor.shard = shard;+ tensor.offset = data_start + start;+ tensor.nbytes = end - start;+ if (append_tensor(index, &tensor) != 0) {+ free((char *)tensor.name);+ result = set_error(error, error_size, "out of memory indexing %s", path);+ goto cleanup;+ }+ }++ char *stored_path = strdup(path);+ if (!stored_path) {+ result = set_error(error, error_size, "out of memory storing %s", path);+ goto cleanup;+ }+ index->shards[shard].path = stored_path;+ index->shards[shard].fd = fd;+ index->shards[shard].size = shard_size;+ index->shard_count++;+ fd = -1;+ result = 0;++cleanup:+ json_free(root);+ free(arena);+ free(header);+ if (fd >= 0) close(fd);+ return result;+}++static int build_hash(ColiSafetensorsIndex *index, char *error, size_t error_size) {+ size_t capacity = 1;+ while (capacity < index->tensor_count * 2) capacity <<= 1;+ index->hash = (int *)malloc(capacity * sizeof(*index->hash));+ if (!index->hash)+ return set_error(error, error_size, "out of memory building tensor index");+ index->hash_capacity = capacity;+ for (size_t i = 0; i < capacity; i++) index->hash[i] = -1;+ for (size_t i = 0; i < index->tensor_count; i++) {+ size_t slot = (size_t)hash_name(index->tensors[i].name) & (capacity - 1);+ while (index->hash[slot] >= 0) {+ if (!strcmp(index->tensors[index->hash[slot]].name,+ index->tensors[i].name))+ return set_error(error, error_size, "duplicate tensor: %s",+ index->tensors[i].name);+ slot = (slot + 1) & (capacity - 1);+ }+ index->hash[slot] = (int)i;+ }+ return 0;+}++int coli_st_index_open(ColiSafetensorsIndex **out, const char *directory,+ char *error, size_t error_size) {+ if (!out || !directory)+ return set_error(error, error_size, "invalid safetensors index arguments");+ *out = NULL;+ DIR *stream = opendir(directory);+ if (!stream)+ return set_error(error, error_size, "cannot open %s: %s", directory, strerror(errno));+ char **paths = NULL;+ size_t path_count = 0, path_capacity = 0;+ struct dirent *entry;+ while ((entry = readdir(stream))) {+ if (!has_safetensors_suffix(entry->d_name)) continue;+ if (path_count == path_capacity) {+ size_t capacity = path_capacity ? path_capacity * 2 : 16;+ void *allocation = realloc(paths, capacity * sizeof(*paths));+ if (!allocation) {+ closedir(stream);+ free(paths);+ return set_error(error, error_size, "out of memory listing %s", directory);+ }+ paths = (char **)allocation;+ path_capacity = capacity;+ }+ size_t length = strlen(directory) + strlen(entry->d_name) + 2;+ paths[path_count] = (char *)malloc(length);+ if (!paths[path_count]) {+ closedir(stream);+ for (size_t i = 0; i < path_count; i++) free(paths[i]);+ free(paths);+ return set_error(error, error_size, "out of memory listing %s", directory);+ }+ snprintf(paths[path_count++], length, "%s/%s", directory, entry->d_name);+ }+ closedir(stream);+ if (!path_count) {+ free(paths);+ return set_error(error, error_size, "no safetensors shards in %s", directory);+ }+ qsort(paths, path_count, sizeof(*paths), compare_paths);+ ColiSafetensorsIndex *index = (ColiSafetensorsIndex *)calloc(1, sizeof(*index));+ if (!index) {+ for (size_t i = 0; i < path_count; i++) free(paths[i]);+ free(paths);+ return set_error(error, error_size, "out of memory opening %s", directory);+ }+ int result = 0;+ for (size_t i = 0; i < path_count; i++) {+ if (index_shard(index, paths[i], error, error_size) != 0) {+ result = -1;+ break;+ }+ }+ for (size_t i = 0; i < path_count; i++) free(paths[i]);+ free(paths);+ if (!result) result = build_hash(index, error, error_size);+ if (result) {+ coli_st_index_close(index);+ return -1;+ }+ *out = index;+ return 0;+}++void coli_st_index_close(ColiSafetensorsIndex *index) {+ if (!index) return;+ for (size_t i = 0; i < index->tensor_count; i++)+ free((char *)index->tensors[i].name);+ for (size_t i = 0; i < index->shard_count; i++) {+ if (index->shards[i].fd >= 0) close(index->shards[i].fd);+ free(index->shards[i].path);+ }+ free(index->hash);+ free(index->tensors);+ free(index);+}++size_t coli_st_tensor_count(const ColiSafetensorsIndex *index) {+ return index ? index->tensor_count : 0;+}++size_t coli_st_shard_count(const ColiSafetensorsIndex *index) {+ return index ? index->shard_count : 0;+}++const char *coli_st_shard_path(const ColiSafetensorsIndex *index, int shard) {+ return index && shard >= 0 && (size_t)shard < index->shard_count+ ? index->shards[shard].path : NULL;+}++const ColiSafetensorsTensor *coli_st_find(const ColiSafetensorsIndex *index,+ const char *name) {+ if (!index || !name || !index->hash_capacity) return NULL;+ size_t slot = (size_t)hash_name(name) & (index->hash_capacity - 1);+ while (index->hash[slot] >= 0) {+ const ColiSafetensorsTensor *tensor = &index->tensors[index->hash[slot]];+ if (!strcmp(tensor->name, name)) return tensor;+ slot = (slot + 1) & (index->hash_capacity - 1);+ }+ return NULL;+}++int coli_st_read_at(const ColiSafetensorsIndex *index, int shard,+ uint64_t offset, size_t length, void *destination) {+ if (!index || !destination || shard < 0 || (size_t)shard >= index->shard_count ||+ offset > index->shards[shard].size ||+ length > index->shards[shard].size - offset)+ return -1;+ unsigned char *output = (unsigned char *)destination;+ size_t done = 0;+ while (done < length) {+ ssize_t count = pread(index->shards[shard].fd, output + done,+ length - done, (off_t)(offset + done));+ if (count < 0 && errno == EINTR) continue;+ if (count <= 0) return -1;+ done += (size_t)count;+ }+ return 0;+}++int coli_st_read_tensor(const ColiSafetensorsIndex *index,+ const ColiSafetensorsTensor *tensor, void *destination) {+ return tensor ? coli_st_read_at(index, tensor->shard, tensor->offset,+ (size_t)tensor->nbytes, destination) : -1;+}++int coli_st_prefetch_at(const ColiSafetensorsIndex *index, int shard,+ uint64_t offset, size_t length) {+ if (!index || shard < 0 || (size_t)shard >= index->shard_count ||+ offset > index->shards[shard].size ||+ length > index->shards[shard].size - offset)+ return -1;+ return posix_fadvise(index->shards[shard].fd, (off_t)offset,+ (off_t)length, POSIX_FADV_WILLNEED);+}diff --git a/c/safetensors_index.h b/c/safetensors_index.hnew file mode 100644index 00000000..519c7492--- /dev/null+++ b/c/safetensors_index.h@@ -0,0 +1,57 @@+#ifndef COLIBRI_SAFETENSORS_INDEX_H+#define COLIBRI_SAFETENSORS_INDEX_H++#include <stddef.h>+#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++#define COLI_ST_MAX_RANK 8++typedef enum {+ COLI_ST_BF16 = 0,+ COLI_ST_F16,+ COLI_ST_F32,+ COLI_ST_U8,+ COLI_ST_I8,+ COLI_ST_I64,+ COLI_ST_F8_E4M3,+ COLI_ST_F8_E8M0+} ColiSafetensorsDType;++typedef struct {+ const char *name;+ ColiSafetensorsDType dtype;+ int shard;+ uint64_t offset;+ uint64_t nbytes;+ uint64_t numel;+ int rank;+ int64_t shape[COLI_ST_MAX_RANK];+} ColiSafetensorsTensor;++typedef struct ColiSafetensorsIndex ColiSafetensorsIndex;++int coli_st_index_open(ColiSafetensorsIndex **out, const char *directory,+ char *error, size_t error_size);+void coli_st_index_close(ColiSafetensorsIndex *index);+size_t coli_st_tensor_count(const ColiSafetensorsIndex *index);+size_t coli_st_shard_count(const ColiSafetensorsIndex *index);+const char *coli_st_shard_path(const ColiSafetensorsIndex *index, int shard);+const ColiSafetensorsTensor *coli_st_find(const ColiSafetensorsIndex *index,+ const char *name);+int coli_st_read_tensor(const ColiSafetensorsIndex *index,+ const ColiSafetensorsTensor *tensor, void *destination);+int coli_st_read_at(const ColiSafetensorsIndex *index, int shard,+ uint64_t offset, size_t length, void *destination);+int coli_st_prefetch_at(const ColiSafetensorsIndex *index, int shard,+ uint64_t offset, size_t length);+const char *coli_st_dtype_name(ColiSafetensorsDType dtype);++#ifdef __cplusplus+}+#endif++#endifdiff --git a/c/tensor.h b/c/tensor.hnew file mode 100644index 00000000..aebb67a6--- /dev/null+++ b/c/tensor.h@@ -0,0 +1,47 @@+#ifndef COLIBRI_TENSOR_H+#define COLIBRI_TENSOR_H++#include <stddef.h>+#include <stdint.h>++#ifdef __cplusplus+extern "C" {+#endif++/* Storage/execution formats understood by a model backend. A view describes+ * bytes owned by a model or ExpertStore; it never owns or frees those bytes. */+typedef enum {+ COLI_TENSOR_F32 = 0,+ COLI_TENSOR_Q8_ROW,+ COLI_TENSOR_Q4_ROW,+ COLI_TENSOR_Q2_ROW,+ COLI_TENSOR_FP8_E4M3_BLOCK,+ COLI_TENSOR_FP4_NATIVE_BLOCK,+ COLI_TENSOR_INT8_BLOCK,+ COLI_TENSOR_INT4_BLOCK+} ColiTensorFormat;++typedef enum {+ COLI_SCALE_NONE = 0,+ COLI_SCALE_F32,+ COLI_SCALE_UE8M0+} ColiScaleFormat;++typedef struct {+ ColiTensorFormat format;+ ColiScaleFormat scale_format;+ const void *data;+ const void *scales;+ size_t data_bytes;+ size_t scale_bytes;+ int64_t rows;+ int64_t columns;+ uint32_t block_rows;+ uint32_t block_columns;+} ColiTensorView;++#ifdef __cplusplus+}+#endif++#endifdiff --git a/c/tensor_io.c b/c/tensor_io.cnew file mode 100644index 00000000..93485637--- /dev/null+++ b/c/tensor_io.c@@ -0,0 +1,105 @@+#include "tensor_io.h"++#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++#include "native_quant.h"++static int set_error(char *error, size_t size, const char *format, ...) {+ if (error && size) {+ va_list arguments;+ va_start(arguments, format);+ vsnprintf(error, size, format, arguments);+ va_end(arguments);+ }+ return -1;+}++int coli_tensor_load_fp8(ColiOwnedTensor *output,+ const ColiSafetensorsIndex *index,+ const char *prefix, char *error, size_t error_size) {+ if (!output || !index || !prefix)+ return set_error(error, error_size, "invalid FP8 tensor arguments");+ memset(output, 0, sizeof(*output));+ size_t length = strlen(prefix) + sizeof(".weight");+ char *name = malloc(length);+ if (!name) return set_error(error, error_size, "out of memory building tensor name");+ snprintf(name, length, "%s.weight", prefix);+ const ColiSafetensorsTensor *weight = coli_st_find(index, name);+ snprintf(name, length, "%s.scale", prefix);+ const ColiSafetensorsTensor *scale = coli_st_find(index, name);+ free(name);+ if (!weight || !scale || weight->dtype != COLI_ST_F8_E4M3 ||+ scale->dtype != COLI_ST_F8_E8M0 || weight->rank != 2 || scale->rank != 2 ||+ scale->shape[0] != (weight->shape[0] + 127) / 128 ||+ scale->shape[1] != (weight->shape[1] + 127) / 128)+ return set_error(error, error_size, "invalid native FP8 tensor: %s", prefix);+ output->data_allocation = malloc((size_t)weight->nbytes);+ output->scale_allocation = malloc((size_t)scale->nbytes);+ if (!output->data_allocation || !output->scale_allocation) {+ coli_owned_tensor_free(output);+ return set_error(error, error_size, "out of memory loading FP8 tensor: %s", prefix);+ }+ if (coli_st_read_tensor(index, weight, output->data_allocation) != 0 ||+ coli_st_read_tensor(index, scale, output->scale_allocation) != 0) {+ coli_owned_tensor_free(output);+ return set_error(error, error_size, "cannot read FP8 tensor: %s", prefix);+ }+ output->view = (ColiTensorView){+ COLI_TENSOR_FP8_E4M3_BLOCK, COLI_SCALE_UE8M0,+ output->data_allocation, output->scale_allocation,+ (size_t)weight->nbytes, (size_t)scale->nbytes,+ weight->shape[0], weight->shape[1], 128, 128+ };+ return 0;+}++void coli_owned_tensor_free(ColiOwnedTensor *tensor) {+ if (!tensor) return;+ free(tensor->data_allocation);+ free(tensor->scale_allocation);+ memset(tensor, 0, sizeof(*tensor));+}++int coli_tensor_load_f32(ColiFloatTensor *output,+ const ColiSafetensorsIndex *index,+ const char *name, char *error, size_t error_size) {+ if (!output || !index || !name)+ return set_error(error, error_size, "invalid float tensor arguments");+ memset(output, 0, sizeof(*output));+ const ColiSafetensorsTensor *tensor = coli_st_find(index, name);+ if (!tensor || (tensor->dtype != COLI_ST_F32 && tensor->dtype != COLI_ST_BF16))+ return set_error(error, error_size, "missing BF16/F32 tensor: %s", name);+ void *raw = malloc((size_t)tensor->nbytes);+ output->data = malloc((size_t)tensor->numel * sizeof(*output->data));+ if (!raw || !output->data) {+ free(raw);+ coli_float_tensor_free(output);+ return set_error(error, error_size, "out of memory loading tensor: %s", name);+ }+ if (coli_st_read_tensor(index, tensor, raw) != 0) {+ free(raw);+ coli_float_tensor_free(output);+ return set_error(error, error_size, "cannot read tensor: %s", name);+ }+ if (tensor->dtype == COLI_ST_F32)+ memcpy(output->data, raw, (size_t)tensor->nbytes);+ else {+ const uint16_t *values = raw;+ for (uint64_t index_value = 0; index_value < tensor->numel; index_value++)+ output->data[index_value] = coli_bf16_decode(values[index_value]);+ }+ free(raw);+ output->count = tensor->numel;+ output->rank = tensor->rank;+ memcpy(output->shape, tensor->shape, sizeof(output->shape));+ return 0;+}++void coli_float_tensor_free(ColiFloatTensor *tensor) {+ if (!tensor) return;+ free(tensor->data);+ memset(tensor, 0, sizeof(*tensor));+}diff --git a/c/tensor_io.h b/c/tensor_io.hnew file mode 100644index 00000000..a0a86747--- /dev/null+++ b/c/tensor_io.h@@ -0,0 +1,41 @@+#ifndef COLIBRI_TENSOR_IO_H+#define COLIBRI_TENSOR_IO_H++#include <stddef.h>+#include <stdint.h>++#include "safetensors_index.h"+#include "tensor.h"++#ifdef __cplusplus+extern "C" {+#endif++typedef struct {+ ColiTensorView view;+ void *data_allocation;+ void *scale_allocation;+} ColiOwnedTensor;++typedef struct {+ float *data;+ uint64_t count;+ int rank;+ int64_t shape[COLI_ST_MAX_RANK];+} ColiFloatTensor;++int coli_tensor_load_fp8(ColiOwnedTensor *output,+ const ColiSafetensorsIndex *index,+ const char *prefix, char *error, size_t error_size);+void coli_owned_tensor_free(ColiOwnedTensor *tensor);++int coli_tensor_load_f32(ColiFloatTensor *output,+ const ColiSafetensorsIndex *index,+ const char *name, char *error, size_t error_size);+void coli_float_tensor_free(ColiFloatTensor *tensor);++#ifdef __cplusplus+}+#endif++#endifdiff --git a/c/tests/test_expert_store_ops.c b/c/tests/test_expert_store_ops.cnew file mode 100644index 00000000..23c25e05--- /dev/null+++ b/c/tests/test_expert_store_ops.c@@ -0,0 +1,106 @@+#include "../expert_store.h"++#include <stdio.h>+#include <string.h>++typedef struct {+ int held;+ unsigned active_leases;+ ColiExpertStoreStats stats;+} MockState;++static int mock_lookup(ColiExpertStore *store, ColiExpertKey key,+ ColiExpertView *view) {+ static const unsigned char weights[4] = {1, 2, 3, 4};+ MockState *state = (MockState *)store->state;+ if (state->held || !view) return -1;+ memset(view, 0, sizeof(*view));+ view->key = key;+ view->gate.format = COLI_TENSOR_FP4_NATIVE_BLOCK;+ view->gate.scale_format = COLI_SCALE_UE8M0;+ view->gate.data = weights;+ view->gate.data_bytes = sizeof(weights);+ view->lease = state;+ state->held = 1;+ state->active_leases++;+ state->stats.requests++;+ state->stats.misses++;+ state->stats.bytes_read += sizeof(weights);+ return 0;+}++static void mock_release(ColiExpertStore *store, ColiExpertView *view) {+ MockState *state = (MockState *)store->state;+ if (view && view->lease == state) {+ state->held = 0;+ if (state->active_leases) state->active_leases--;+ view->lease = NULL;+ }+}++static int mock_prefetch(ColiExpertStore *store, const ColiExpertKey *keys,+ size_t count) {+ MockState *state = (MockState *)store->state;+ (void)keys;+ state->stats.prefetched += count;+ return (int)count;+}++static void mock_stats(const ColiExpertStore *store,+ ColiExpertStoreStats *stats) {+ *stats = ((const MockState *)store->state)->stats;+}++static void mock_destroy(ColiExpertStore *store) {+ MockState *state = (MockState *)store->state;+ if (state->active_leases != 0)+ fprintf(stderr, "destroy with active leases=%u\n", state->active_leases);+}++static int view_is_cleared(const ColiExpertView *view) {+ static const ColiExpertView zero;+ return memcmp(view, &zero, sizeof(*view)) == 0;+}++int main(void) {+ static const ColiExpertStoreOps ops = {+ mock_lookup, mock_release, mock_prefetch, mock_stats, mock_destroy+ };+ MockState state = {0};+ ColiExpertStore store = {&ops, &state};+ ColiExpertView view;+ ColiExpertView other;+ ColiExpertKey key = {7, 19};+ ColiExpertStoreStats stats;++ if (coli_expert_lookup(&store, key, &view) != 0) return 1;+ if (view.key.layer != 7 || view.key.expert != 19) return 1;+ if (view.gate.format != COLI_TENSOR_FP4_NATIVE_BLOCK) return 1;+ if (view.gate.scale_format != COLI_SCALE_UE8M0) return 1;++ /* A second lookup while the store is busy must fail and clear *other*. */+ memset(&other, 0x5a, sizeof(other));+ if (coli_expert_lookup(&store, key, &other) == 0) return 1;+ if (!view_is_cleared(&other)) return 1;+ if (view.lease != &state || !state.held) return 1;++ coli_expert_release(&store, &view);+ if (state.held || state.active_leases) return 1;+ if (!view_is_cleared(&view)) return 1;++ /* Double release and release of a zero view are no-ops. */+ coli_expert_release(&store, &view);+ memset(&other, 0, sizeof(other));+ coli_expert_release(&store, &other);+ if (!view_is_cleared(&other)) return 1;++ if (store.ops->prefetch(&store, &key, 1) != 1) return 1;+ store.ops->stats(&store, &stats);+ if (stats.requests != 1 || stats.misses != 1 ||+ stats.prefetched != 1 || stats.bytes_read != 4) return 1;++ store.ops->destroy(&store);+ if (state.active_leases != 0) return 1;+ puts("expert store ops tests: ok");+ return 0;+}diff --git a/c/tests/test_native_quant.c b/c/tests/test_native_quant.cnew file mode 100644index 00000000..630132d0--- /dev/null+++ b/c/tests/test_native_quant.c@@ -0,0 +1,102 @@+#include "../native_quant.h"++#include <math.h>+#include <stdint.h>+#include <stdio.h>+#include <string.h>++static int close_enough(float left, float right) {+ return fabsf(left - right) <= 1e-6f * fmaxf(1.0f, fabsf(right));+}++int main(void) {+ if (coli_bf16_round(1.00390625f) != 1.0f ||+ coli_bf16_round(1.01171875f) != 1.015625f)+ return 1;+ static const float fp4[16] = {+ 0.0f, 0.5f, 1.0f, 1.5f, 2.0f, 3.0f, 4.0f, 6.0f,+ 0.0f, -0.5f, -1.0f, -1.5f, -2.0f, -3.0f, -4.0f, -6.0f,+ };+ for (int i = 0; i < 16; i++)+ if (!close_enough(coli_e2m1_decode((uint8_t)i), fp4[i])) return 1;+ if (!close_enough(coli_e8m0_decode(0x7e), 0.5f) ||+ !close_enough(coli_e8m0_decode(0x7f), 1.0f) ||+ !close_enough(coli_e8m0_decode(0x80), 2.0f) ||+ !isnan(coli_e8m0_decode(0xff))) return 1;++ static const float representable[] = {+ 0.0f, 0.001953125f, 0.5f, 1.0f, 1.5f, 6.0f,+ 224.0f, 448.0f, -0.5f, -6.0f, -448.0f,+ };+ for (size_t i = 0; i < sizeof(representable) / sizeof(representable[0]); i++) {+ uint8_t encoded = coli_e4m3fn_encode(representable[i]);+ if (!close_enough(coli_e4m3fn_decode(encoded), representable[i])) return 1;+ }++ float input[128], qdq[128];+ uint8_t activation_scale;+ for (int i = 0; i < 128; i++) input[i] = 1.0f;+ if (coli_fp8_activation_qdq_ref(qdq, &activation_scale, input, 128, 128) != 0)+ return 1;+ if (activation_scale != 119) return 1; /* 2^-8 */+ for (int i = 0; i < 128; i++)+ if (!close_enough(qdq[i], 1.0f)) return 1;++ float fp4_input[32], fp4_qdq[32];+ uint8_t fp4_scale;+ for (int i = 0; i < 32; i++) fp4_input[i] = 1.0f;+ if (coli_fp4_activation_qdq_ref(fp4_qdq, &fp4_scale,+ fp4_input, 32, 32) != 0 ||+ fp4_scale != 125) return 1; /* 2^-2 */+ for (int i = 0; i < 32; i++)+ if (!close_enough(fp4_qdq[i], 1.0f)) return 1;++ /* Tiny valid heads can end in a partial activation block. */+ float partial_input[20], partial_fp8[20], partial_fp4[20];+ uint8_t partial_fp8_scale, partial_fp4_scale;+ for (int i = 0; i < 20; i++) partial_input[i] = 1.0f;+ if (coli_fp8_activation_qdq_ref(partial_fp8, &partial_fp8_scale,+ partial_input, 20, 64) != 0 ||+ partial_fp8_scale != 119 ||+ coli_fp4_activation_qdq_ref(partial_fp4, &partial_fp4_scale,+ partial_input, 20, 32) != 0 ||+ partial_fp4_scale != 125) return 1;+ for (int i = 0; i < 20; i++)+ if (!close_enough(partial_fp8[i], 1.0f) ||+ !close_enough(partial_fp4[i], 1.0f)) return 1;++ float hadamard[4] = {1.0f, 2.0f, 3.0f, 4.0f};+ static const float hadamard_expected[4] = {5.0f, -1.0f, -2.0f, 0.0f};+ if (coli_hadamard_bf16_ref(hadamard, 4) != 0) return 1;+ for (int i = 0; i < 4; i++)+ if (!close_enough(hadamard[i], hadamard_expected[i])) return 1;++ uint8_t weights[64];+ uint8_t scales[4];+ memset(weights, 0x44, sizeof(weights)); /* two +2.0 E2M1 values */+ memset(scales, 0x7e, sizeof(scales)); /* 0.5 */+ ColiTensorView view = {+ COLI_TENSOR_FP4_NATIVE_BLOCK, COLI_SCALE_UE8M0,+ weights, scales, sizeof(weights), sizeof(scales),+ 1, 128, 1, 32+ };+ float output;+ if (coli_fp4_matvec_ref(&output, &view, input) != 0 ||+ !close_enough(output, 128.0f)) return 1;++ uint8_t fp8_weights[128 * 128];+ uint8_t fp8_scales[1] = {0x7f};+ memset(fp8_weights, 0x38, sizeof(fp8_weights)); /* E4M3 1.0 */+ ColiTensorView fp8_view = {+ COLI_TENSOR_FP8_E4M3_BLOCK, COLI_SCALE_UE8M0,+ fp8_weights, fp8_scales, sizeof(fp8_weights), sizeof(fp8_scales),+ 128, 128, 128, 128+ };+ float fp8_output[128];+ if (coli_fp8_matvec_ref(fp8_output, &fp8_view, input) != 0)+ return 1;+ for (int i = 0; i < 128; i++)+ if (!close_enough(fp8_output[i], 128.0f)) return 1;+ puts("native quant tests: ok");+ return 0;+}diff --git a/c/tests/test_safetensors_index.c b/c/tests/test_safetensors_index.cnew file mode 100644index 00000000..40909f20--- /dev/null+++ b/c/tests/test_safetensors_index.c@@ -0,0 +1,202 @@+#define _GNU_SOURCE+#include "../safetensors_index.h"++#include <fcntl.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <sys/stat.h>+#include <unistd.h>++#define TEST_ST_MAX_HEADER (512ULL << 20)++static int write_all(int fd, const void *data, size_t length) {+ const unsigned char *bytes = (const unsigned char *)data;+ while (length) {+ ssize_t count = write(fd, bytes, length);+ if (count <= 0) return -1;+ bytes += count;+ length -= (size_t)count;+ }+ return 0;+}++static int write_fixture(const char *path, const char *header,+ const void *payload, size_t payload_size) {+ uint64_t header_length = (uint64_t)strlen(header);+ int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);+ if (fd < 0) return -1;+ int result = write_all(fd, &header_length, sizeof(header_length)) ||+ write_all(fd, header, (size_t)header_length) ||+ (payload_size && write_all(fd, payload, payload_size));+ close(fd);+ return result ? -1 : 0;+}++static int write_declared_length(const char *path, uint64_t header_length,+ uint64_t file_size) {+ int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);+ if (fd < 0) return -1;+ int result = write_all(fd, &header_length, sizeof(header_length));+ if (!result && ftruncate(fd, (off_t)file_size) != 0) result = -1;+ close(fd);+ return result ? -1 : 0;+}++static int expect_rejected(const char *directory, const char *label) {+ ColiSafetensorsIndex *index = NULL;+ char error[256] = {0};+ if (coli_st_index_open(&index, directory, error, sizeof(error)) == 0) {+ fprintf(stderr, "%s: malformed fixture was accepted\n", label);+ coli_st_index_close(index);+ return -1;+ }+ if (index) {+ fprintf(stderr, "%s: failed open returned a live index\n", label);+ coli_st_index_close(index);+ return -1;+ }+ if (!error[0]) {+ fprintf(stderr, "%s: failed open did not report an error\n", label);+ return -1;+ }+ return 0;+}++static int check_valid_fixture(const char *directory) {+ ColiSafetensorsIndex *index = NULL;+ char error[256] = {0};+ if (coli_st_index_open(&index, directory, error, sizeof(error)) != 0) {+ fprintf(stderr, "%s\n", error);+ return -1;+ }+ int result = 0;+ if (coli_st_shard_count(index) != 1 || coli_st_tensor_count(index) != 3)+ result = -1;+ const ColiSafetensorsTensor *weight = coli_st_find(index, "expert.fp4");+ const ColiSafetensorsTensor *scale = coli_st_find(index, "expert.scale");+ if (!weight || !scale || weight->dtype != COLI_ST_I8 ||+ scale->dtype != COLI_ST_F8_E8M0)+ result = -1;+ if (weight && (weight->rank != 2 || weight->shape[0] != 2 ||+ weight->shape[1] != 1 || weight->nbytes != 2 ||+ weight->numel != 2))+ result = -1;+ unsigned char bytes[4] = {0};+ if (weight && (coli_st_read_tensor(index, weight, bytes) != 0 ||+ bytes[0] != 5 || bytes[1] != 6))+ result = -1;+ if (weight && scale &&+ (coli_st_read_at(index, scale->shard, weight->offset, 4, bytes) != 0 ||+ memcmp(bytes, "\5\6\7\10", 4)))+ result = -1;+ if (strcmp(coli_st_dtype_name(COLI_ST_F8_E4M3), "F8_E4M3"))+ result = -1;+ coli_st_index_close(index);+ return result;+}++int main(void) {+ static const char valid_header[] =+ "{\"dense.fp8\":{\"dtype\":\"F8_E4M3\",\"shape\":[2,2],"+ "\"data_offsets\":[0,4]},"+ "\"expert.fp4\":{\"dtype\":\"I8\",\"shape\":[2,1],"+ "\"data_offsets\":[4,6]},"+ "\"expert.scale\":{\"dtype\":\"F8_E8M0\",\"shape\":[2,1],"+ "\"data_offsets\":[6,8]}}";+ static const unsigned char valid_payload[] = {1, 2, 3, 4, 5, 6, 7, 8};+ static const unsigned char one_byte[] = {0};+ static const unsigned char mismatch_payload[4096] = {0};+ static const struct {+ const char *label;+ const char *header;+ } malformed[] = {+ {"root-not-object", "[]"},+ {"metadata-not-object", "{\"w\":[]}"},+ {"dtype-not-string", "{\"w\":{\"dtype\":12,\"shape\":[1],\"data_offsets\":[0,1]}}"},+ {"offsets-not-array", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":{}}}"},+ {"offsets-wrong-length", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0]}}"},+ {"offsets-not-numbers", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[\"a\",1]}}"},+ {"negative-offset", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[-1,1]}}"},+ {"fractional-offset", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0.5,1]}}"},+ {"nan-offset", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,NaN]}}"},+ {"infinite-offset", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,1e309]}}"},+ {"offset-past-file", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1],\"data_offsets\":[0,2]}}"},+ {"shape-not-array", "{\"w\":{\"dtype\":\"U8\",\"shape\":{},\"data_offsets\":[0,1]}}"},+ {"negative-shape", "{\"w\":{\"dtype\":\"U8\",\"shape\":[-1],\"data_offsets\":[0,1]}}"},+ {"fractional-shape", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1.5],\"data_offsets\":[0,1]}}"},+ {"shape-out-of-range", "{\"w\":{\"dtype\":\"U8\",\"shape\":[9223372036854775808],\"data_offsets\":[0,1]}}"},+ {"shape-product-overflow", "{\"w\":{\"dtype\":\"U8\",\"shape\":[4294967296,4294967296],\"data_offsets\":[0,1]}}"},+ {"rank-too-large", "{\"w\":{\"dtype\":\"U8\",\"shape\":[1,1,1,1,1,1,1,1,1],\"data_offsets\":[0,1]}}"},+ };++ /* Native MinGW binaries do not resolve the MSYS /tmp mount. */+ char directory[] = "colibri-st-XXXXXX";+ char path[256];+ int failures = 0;+ if (!mkdtemp(directory)) return 1;+ snprintf(path, sizeof(path), "%s/model-00001-of-00001.safetensors", directory);++ if (write_fixture(path, valid_header, valid_payload, sizeof(valid_payload)) != 0) {+ failures++;+ } else {+ /* Repetition makes this test useful under ASan/LSan. */+ for (int i = 0; i < 64; i++) {+ if (check_valid_fixture(directory) != 0) {+ fprintf(stderr, "valid fixture failed on iteration %d\n", i);+ failures++;+ break;+ }+ }+ }++ if (write_declared_length(path, 64, 8) != 0 ||+ expect_rejected(directory, "header-past-file") != 0)+ failures++;+ if (write_declared_length(path, TEST_ST_MAX_HEADER + 1,+ TEST_ST_MAX_HEADER + 9) != 0 ||+ expect_rejected(directory, "header-over-limit") != 0)+ failures++;++ for (size_t i = 0; i < sizeof(malformed) / sizeof(malformed[0]); i++) {+ if (write_fixture(path, malformed[i].header, one_byte, sizeof(one_byte)) != 0 ||+ expect_rejected(directory, malformed[i].label) != 0)+ failures++;+ }++ static const struct {+ const char *label;+ const char *header;+ size_t payload_size;+ } size_mismatches[] = {+ {"f32-byte-size-mismatch",+ "{\"w\":{\"dtype\":\"F32\",\"shape\":[1],\"data_offsets\":[0,4096]}}",+ 4096},+ {"bf16-byte-size-mismatch",+ "{\"w\":{\"dtype\":\"BF16\",\"shape\":[4096],\"data_offsets\":[0,2]}}",+ 2},+ {"i64-byte-size-mismatch",+ "{\"w\":{\"dtype\":\"I64\",\"shape\":[1],\"data_offsets\":[0,4]}}",+ 4},+ {"fp8-byte-size-mismatch",+ "{\"w\":{\"dtype\":\"F8_E4M3\",\"shape\":[2],\"data_offsets\":[0,1]}}",+ 1},+ };+ for (size_t i = 0;+ i < sizeof(size_mismatches) / sizeof(size_mismatches[0]); i++) {+ if (write_fixture(path, size_mismatches[i].header, mismatch_payload,+ size_mismatches[i].payload_size) != 0 ||+ expect_rejected(directory, size_mismatches[i].label) != 0)+ failures++;+ }++ unlink(path);+ rmdir(directory);+ if (failures) {+ fprintf(stderr, "safetensors index tests: %d failure(s)\n", failures);+ return 1;+ }+ puts("safetensors index tests: ok");+ return 0;+}diff --git a/c/tests/test_tensor_io.c b/c/tests/test_tensor_io.cnew file mode 100644index 00000000..bf042c8b--- /dev/null+++ b/c/tests/test_tensor_io.c@@ -0,0 +1,82 @@+#define _GNU_SOURCE+#include "../tensor_io.h"++#include <fcntl.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>+#include <unistd.h>++static int write_all(int fd, const void *data, size_t length) {+ const unsigned char *bytes = data;+ while (length) {+ ssize_t count = write(fd, bytes, length);+ if (count <= 0) return -1;+ bytes += count;+ length -= (size_t)count;+ }+ return 0;+}++static int write_fixture(const char *path) {+ static const char header[] =+ "{\"linear.weight\":{\"dtype\":\"F8_E4M3\",\"shape\":[128,128],\"data_offsets\":[0,16384]},"+ "\"linear.scale\":{\"dtype\":\"F8_E8M0\",\"shape\":[1,1],\"data_offsets\":[16384,16385]},"+ "\"norm.weight\":{\"dtype\":\"BF16\",\"shape\":[2],\"data_offsets\":[16385,16389]}}";+ uint64_t header_length = sizeof(header) - 1;+ unsigned char *payload = calloc(16389, 1);+ if (!payload) return -1;+ memset(payload, 0x38, 16384);+ payload[16384] = 0x7f;+ uint16_t norm[2] = {0x3f80, 0x4000};+ memcpy(payload + 16385, norm, sizeof(norm));+ int fd = open(path, O_CREAT | O_TRUNC | O_WRONLY, 0600);+ if (fd < 0) { free(payload); return -1; }+ int result = write_all(fd, &header_length, sizeof(header_length)) ||+ write_all(fd, header, (size_t)header_length) ||+ write_all(fd, payload, 16389);+ close(fd);+ free(payload);+ return result ? -1 : 0;+}++int main(int argc, char **argv) {+ /* Native MinGW binaries do not resolve the MSYS /tmp mount. */+ char directory[] = "colibri-tensor-io-XXXXXX";+ char path[256], error[256];+ if (!mkdtemp(directory)) return 1;+ snprintf(path, sizeof(path), "%s/model.safetensors", directory);+ if (write_fixture(path) != 0) return 1;+ ColiSafetensorsIndex *index = NULL;+ if (coli_st_index_open(&index, directory, error, sizeof(error)) != 0) return 1;+ ColiOwnedTensor linear;+ ColiFloatTensor norm;+ if (coli_tensor_load_fp8(&linear, index, "linear", error, sizeof(error)) != 0 ||+ coli_tensor_load_f32(&norm, index, "norm.weight", error, sizeof(error)) != 0)+ return 1;+ if (linear.view.rows != 128 || linear.view.columns != 128 ||+ ((const uint8_t *)linear.view.data)[0] != 0x38 ||+ norm.count != 2 || norm.data[0] != 1.0f || norm.data[1] != 2.0f)+ return 1;+ coli_float_tensor_free(&norm);+ coli_owned_tensor_free(&linear);+ coli_st_index_close(index);+ unlink(path);+ rmdir(directory);++ if (argc > 1) {+ if (coli_st_index_open(&index, argv[1], error, sizeof(error)) != 0) return 1;+ if (coli_tensor_load_fp8(&linear, index, "layers.0.attn.wq_a",+ error, sizeof(error)) != 0 ||+ coli_tensor_load_f32(&norm, index, "layers.0.attn_norm.weight",+ error, sizeof(error)) != 0) return 1;+ if (linear.view.rows != 1024 || linear.view.columns != 4096 ||+ norm.count != 4096) return 1;+ coli_float_tensor_free(&norm);+ coli_owned_tensor_free(&linear);+ coli_st_index_close(index);+ }+ puts("tensor I/O tests: ok");+ return 0;+}