Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
refactor(v4): preserve target-only runtime
DrewZ8245eeae1dd7
diff --git a/c/Makefile b/c/Makefileindex 8e720578..b1ab36aa 100644--- a/c/Makefile+++ b/c/Makefile@@ -281,14 +281,13 @@ TEST_RULES := $(shell sed -n 's|^tests/\(test_[a-z0-9_]*\)\$$(EXE):.*|\1|p' $(f# test_uring is Linux-only. V4 engine tests are appended below only on supported# x86-64 Linux/Windows and aarch64 Linux hosts; the V4 infrastructure tests have# unconditional rules and therefore remain portable gates.-TEST_EXCLUDE = test_uring test_deepseek_v4 test_v4_ownership test_v4_config_dspark_compat+TEST_EXCLUDE = test_uring test_deepseek_v4 test_v4_ownershipTEST_BINS = $(addprefix tests/,$(addsuffix $(EXE),$(filter-out $(TEST_EXCLUDE),$(TEST_RULES))))ifneq (,$(LINUX))TEST_BINS += tests/test_uring$(EXE)endififeq ($(COLI_V4_SUPPORTED),1)-TEST_BINS += tests/test_deepseek_v4$(EXE) tests/test_v4_ownership$(EXE) \- tests/test_v4_config_dspark_compat$(EXE)+TEST_BINS += tests/test_deepseek_v4$(EXE) tests/test_v4_ownership$(EXE)endif# Windows CUDA DLL path: host links the loader, NOT cudart.@@ -391,7 +390,8 @@ endifall: colibri$(EXE)-.PHONY: deepseek-v4 deepseek-v4-oracle deepseek-v4-tiny-check deepseek-v4-clean+.PHONY: deepseek-v4 deepseek-v4-oracle deepseek-v4-tiny-generate \+ deepseek-v4-tiny-check deepseek-v4-cleanifeq ($(COLI_V4_SUPPORTED),1)deepseek-v4:$(MAKE) -f Makefile.deepseek-v4 ARCH=$(ARCH) deepseek-v4@@ -399,7 +399,11 @@ deepseek-v4:deepseek-v4-clean:$(MAKE) -f Makefile.deepseek-v4 deepseek-v4-clean-deepseek-v4-tiny-check:+deepseek-v4-tiny-generate:+ $(PYTHON) tools/make_deepseek_v4_tiny.py \+ --output ./deepseek_v4_tiny --force++deepseek-v4-tiny-check: deepseek-v4-tiny-generate$(MAKE) -f Makefile.deepseek-v4 deepseek-v4-clean$(MAKE) -f Makefile.deepseek-v4 ARCH=$(if $(strip $(ARCH)),$(ARCH),$(PORTABLE_ARCH)) deepseek-v4$(PYTHON) tests/test_deepseek_v4_tiny.py \@@ -415,8 +419,7 @@ deepseek-v4-oracle: deepseek-v4--prompt "$(or $(ORACLE_PROMPT),The capital of France is)" \--validate \--teacher-forcing $(or $(ORACLE_TEACHER_FORCING),32) \- --greedy $(or $(ORACLE_GREEDY),20) \- --check-dspark+ --greedy $(or $(ORACLE_GREEDY),20)elsedeepseek-v4 deepseek-v4-oracle:@echo "$@ is supported only on x86-64/aarch64 Linux and Windows/MSYS2" >&2; exit 1@@ -424,6 +427,8 @@ deepseek-v4-clean:@:deepseek-v4-tiny-check:@echo "SKIP deepseek-v4-tiny-check: V4 runtime requires x86-64/aarch64 Linux or Windows/MSYS2"+deepseek-v4-tiny-generate:+ @echo "SKIP deepseek-v4-tiny-generate: V4 runtime requires x86-64/aarch64 Linux or Windows/MSYS2"endif# phony targets — 'glm' kept for backward compatibility@@ -691,32 +696,26 @@ tests/test_compat_direct$(EXE): tests/test_compat_direct.c compat.htests/test_expert_store_ops$(EXE): tests/test_expert_store_ops.c expert_store.h tensor.h$(CC) $(CFLAGS) $< -o $@ $(LDFLAGS)-tests/test_safetensors_index$(EXE): tests/test_safetensors_index.c safetensors_index.c safetensors_index.h json.h- $(CC) $(CFLAGS) safetensors_index.c $< -o $@ $(LDFLAGS)--tests/test_native_quant$(EXE): tests/test_native_quant.c native_quant.c native_quant.h tensor.h+tests/test_native_quant$(EXE): tests/test_native_quant.c native_quant.c native_quant.h tensor.h quant.h$(CC) $(CFLAGS) native_quant.c $< -o $@ $(LDFLAGS)-tests/test_tensor_io$(EXE): tests/test_tensor_io.c tensor_io.c tensor_io.h native_quant.c native_quant.h safetensors_index.c safetensors_index.h tensor.h json.h- $(CC) $(CFLAGS) safetensors_index.c native_quant.c tensor_io.c $< \- -o $@ $(LDFLAGS)-ifeq ($(COLI_V4_SUPPORTED),1)include Makefile.deepseek-v4.unitsV4_TEST_LINK_OBJS = \+ COLI_V4_UNIT_ST.o \+ COLI_V4_UNIT_CONFIG.o \COLI_V4_UNIT_MATH.o \COLI_V4_UNIT_SPARSE_ATTENTION.o \COLI_V4_UNIT_RESOURCE_PLAN.o \COLI_V4_UNIT_PROMPT.o \$(addsuffix .o,$(V4_TEST_UNITS)) \- safetensors_index.o native_quant.o+ native_quant.otests/test_deepseek_v4$(EXE): tests/test_deepseek_v4.c deepseek_v4.c deepseek_v4.h \- deepseek_v4_dspark.h Makefile.deepseek-v4.units+ Makefile.deepseek-v4.units$(MAKE) -f Makefile.deepseek-v4 ARCH=$(ARCH) deepseek-v4-test-objs \- COLI_V4_UNIT_MATH.o COLI_V4_UNIT_SPARSE_ATTENTION.o \- COLI_V4_UNIT_RESOURCE_PLAN.o COLI_V4_UNIT_PROMPT.o \- safetensors_index.o+ COLI_V4_UNIT_ST.o COLI_V4_UNIT_CONFIG.o COLI_V4_UNIT_MATH.o COLI_V4_UNIT_SPARSE_ATTENTION.o \+ COLI_V4_UNIT_RESOURCE_PLAN.o COLI_V4_UNIT_PROMPT.o$(CC) $(CFLAGS) native_quant.c -c -o native_quant.o$(CC) $(CFLAGS) $< $(V4_TEST_LINK_OBJS) -o $@ -pthread $(LDFLAGS)@@ -725,7 +724,8 @@ V4_OWN_CFLAGS = $(CFLAGS) -DCOLI_V4_TEST_HOOKSV4_OWNERSHIP_OBJS = \$(V4_OWN_DIR)/COLI_V4_UNIT_RUNTIME.o \$(V4_OWN_DIR)/COLI_V4_UNIT_CONFIG.o \- $(V4_OWN_DIR)/safetensors_index.o+ $(V4_OWN_DIR)/COLI_V4_UNIT_ST.o \+ native_quant.o$(V4_OWN_DIR):mkdir -p $(V4_OWN_DIR)@@ -736,21 +736,12 @@ $(V4_OWN_DIR)/COLI_V4_UNIT_RUNTIME.o: deepseek_v4.c deepseek_v4.h deepseek_v4_in$(V4_OWN_DIR)/COLI_V4_UNIT_CONFIG.o: deepseek_v4.c deepseek_v4.h deepseek_v4_internal.h | $(V4_OWN_DIR)$(CC) $(V4_OWN_CFLAGS) -DCOLI_V4_UNIT_CONFIG -c deepseek_v4.c -o $@-$(V4_OWN_DIR)/safetensors_index.o: safetensors_index.c safetensors_index.h | $(V4_OWN_DIR)- $(CC) $(CFLAGS) -c safetensors_index.c -o $@+$(V4_OWN_DIR)/COLI_V4_UNIT_ST.o: deepseek_v4.c deepseek_v4.h deepseek_v4_internal.h st.h | $(V4_OWN_DIR)+ $(CC) $(V4_OWN_CFLAGS) -DCOLI_V4_UNIT_ST -c deepseek_v4.c -o $@tests/test_v4_ownership$(EXE): tests/test_v4_ownership.c $(V4_OWNERSHIP_OBJS)$(CC) $(V4_OWN_CFLAGS) $< $(V4_OWNERSHIP_OBJS) -o $@ -pthread $(LDFLAGS)-COLI_V4_UNIT_CONFIG_DSPARK_COMPAT.o: deepseek_v4_dspark.c deepseek_v4.h \- deepseek_v4_dspark.h deepseek_v4_internal.h Makefile.deepseek-v4- $(MAKE) -f Makefile.deepseek-v4 ARCH=$(ARCH) $@--tests/test_v4_config_dspark_compat$(EXE): \- tests/test_v4_config_dspark_compat.c \- COLI_V4_UNIT_CONFIG_DSPARK_COMPAT.o- $(CC) $(CFLAGS) $< COLI_V4_UNIT_CONFIG_DSPARK_COMPAT.o \- -o $@ $(LDFLAGS)endiftests/test_route_trace$(EXE): tests/test_route_trace.c route_trace.h@@ -804,7 +795,6 @@ test-python: $(RANSLIB)$(PYTHON) -m unittest discover -s tests -p 'test_*.py'test: test-c test-python- $(MAKE) deepseek-v4-tiny-check# --- Efficiency / regression suite (issue: "test the program for inefficiencies") ---# The tiny-model assertions live in test_inefficiency.py and run as part of@@ -835,13 +825,16 @@ check:$(MAKE) portable$(MAKE) test-install: colibri$(EXE) olmoe$(EXE)+install: colibri$(EXE) olmoe$(EXE) $(if $(filter 1,$(COLI_V4_SUPPORTED)),deepseek-v4,)$(INSTALL) -d $(DESTDIR)$(BINDIR)$(INSTALL) -d $(DESTDIR)$(LIBEXECDIR)$(INSTALL) -d $(DESTDIR)$(LIBEXECDIR)/tools$(INSTALL) -m 755 coli $(DESTDIR)$(BINDIR)/coli$(INSTALL) -m 755 colibri$(EXE) $(DESTDIR)$(LIBEXECDIR)/colibri$(EXE)$(INSTALL) -m 755 olmoe$(EXE) $(DESTDIR)$(LIBEXECDIR)/olmoe$(EXE)+ @if [ -f deepseek_v4$(EXE) ]; then \+ $(INSTALL) -m 755 deepseek_v4$(EXE) $(DESTDIR)$(LIBEXECDIR)/deepseek_v4$(EXE); \+ fi$(INSTALL) -m 644 resource_plan.py doctor.py autotune.py openai_server.py version.py $(DESTDIR)$(LIBEXECDIR)/$(INSTALL) -m 644 tools/*.py $(DESTDIR)$(LIBEXECDIR)/tools/@# The dashboard is an optional build artifact (cd web && npm run build), so install@@ -863,6 +856,7 @@ clean:bench: iobench$(EXE)@if [ -n "$(ARGS)" ]; then ./iobench$(EXE) $(ARGS); else echo "built iobench$(EXE) — run: ./iobench$(EXE) <file> <MB> <iters> <threads> <direct 0|1>"; fi-.PHONY: all colibri glm deepseek-v4 deepseek-v4-clean deepseek-v4-oracle deepseek-v4-tiny-check \+.PHONY: all colibri glm deepseek-v4 deepseek-v4-clean deepseek-v4-oracle \+ deepseek-v4-tiny-generate deepseek-v4-tiny-check \iq3 rans fuzz-rans cuda-test hip-test gpu-compile cuda-bench cuda-dll portable \test-c test-python test check clean install uninstall benchdiff --git a/c/Makefile.deepseek-v4 b/c/Makefile.deepseek-v4index af79676b..540003c2 100644--- a/c/Makefile.deepseek-v4+++ b/c/Makefile.deepseek-v4@@ -31,7 +31,6 @@ ARCH ?= x86-64-v3CFLAGS = -D_FILE_OFFSET_BITS=64 -O3 -march=$(ARCH) -fopenmp \-include pthread.h -Wall -Wextra -Wno-unused-parameter \-Wno-misleading-indentation -Wno-unused-function \- -DCOLI_V4_EXPERIMENTAL_PARALLEL_PREFIX_VERIFY \-DCOLI_V4_MAX_PIN_SLOTS_PER_LAYER=16 \-DCOLI_V4_PIN_RAMP_REQUESTS=24LDFLAGS = -lm -fopenmp -static -pthread@@ -42,7 +41,6 @@ ARCH ?= nativeCFLAGS = -O3 -march=$(ARCH) -fopenmp -pthread -include pthread.h \-Wall -Wextra -Wno-unused-parameter \-Wno-misleading-indentation -Wno-unused-function \- -DCOLI_V4_EXPERIMENTAL_PARALLEL_PREFIX_VERIFY \-DCOLI_V4_MAX_PIN_SLOTS_PER_LAYER=16 \-DCOLI_V4_PIN_RAMP_REQUESTS=24LDFLAGS = -lm -fopenmp -pthread@@ -52,15 +50,14 @@ endifinclude Makefile.deepseek-v4.units# native_quant.c / native_quant_batch.c are pulled in by the parallel/avx512 TUs.-SHARED_SOURCES = safetensors_index.c native_quant_parallel.c \+SHARED_SOURCES = native_quant_parallel.c \native_quant_dual.c native_quant_batch_avx512.c \- native_quant_fp4_rows16.c tensor_io.c+ native_quant_fp4_rows16.cSHARED_OBJS = $(SHARED_SOURCES:.c=.o)TARGET_OBJS = $(addsuffix .o,$(V4_TARGET_UNITS))-DSPARK_OBJS = $(addsuffix .o,$(V4_DSPARK_UNITS))TEST_UNIT_OBJS = $(addsuffix .o,$(V4_TEST_UNITS))-V4_OBJS = $(SHARED_OBJS) $(TARGET_OBJS) $(DSPARK_OBJS)+V4_OBJS = $(SHARED_OBJS) $(TARGET_OBJS).PHONY: deepseek-v4 deepseek-v4-clean deepseek-v4-test-objsdeepseek-v4: $(V4_BINARY)@@ -73,16 +70,12 @@ $(SHARED_OBJS): %.o: %.c# These translation units include native_quant.c directly.native_quant_parallel.o native_quant_dual.o native_quant_batch_avx512.o: \- native_quant.c native_quant.h+ native_quant.c native_quant_batch.c native_quant.h quant.h$(TARGET_OBJS) $(TEST_UNIT_OBJS): %.o: deepseek_v4.c deepseek_v4.h \- deepseek_v4_dspark.h deepseek_v4_internal.h+ deepseek_v4_internal.h st.h json.h compat.h$(CC) $(CFLAGS) -D$* -c deepseek_v4.c -o $@-$(DSPARK_OBJS): %.o: deepseek_v4_dspark.c deepseek_v4.h \- deepseek_v4_dspark.h deepseek_v4_internal.h- $(CC) $(CFLAGS) -D$* -c deepseek_v4_dspark.c -o $@-deepseek-v4-test-objs: $(TEST_UNIT_OBJS)deepseek-v4-clean:diff --git a/c/Makefile.deepseek-v4.units b/c/Makefile.deepseek-v4.unitsindex 31e1e0e0..4ef2d4d2 100644--- a/c/Makefile.deepseek-v4.units+++ b/c/Makefile.deepseek-v4.units@@ -1,5 +1,7 @@# Generated by _amalgamate_v4.py — object units for amalgamated sources.V4_TARGET_UNITS = \+ COLI_V4_UNIT_ST \+ COLI_V4_UNIT_CONFIG \COLI_V4_UNIT_LAYER_RESIDENT \COLI_V4_UNIT_RESOURCE_PLAN \COLI_V4_UNIT_HEAD_CACHE \@@ -20,28 +22,9 @@ V4_TARGET_UNITS = \COLI_V4_UNIT_RUNTIME \COLI_V4_UNIT_PROMPT \COLI_V4_UNIT_GENERATE_STATS-V4_DSPARK_UNITS = \- COLI_V4_UNIT_CONFIG_DSPARK_COMPAT \- COLI_V4_UNIT_DSPARK \- COLI_V4_UNIT_DSPARK_MEMORY \- COLI_V4_UNIT_DSPARK_RUNTIME_RESIDENT \- COLI_V4_UNIT_DSPARK_EXPERT_STORE \- COLI_V4_UNIT_DSPARK_ATTENTION \- COLI_V4_UNIT_DSPARK_BLOCK \- COLI_V4_UNIT_DSPARK_FINAL \- COLI_V4_UNIT_DSPARK_RUNNER \- COLI_V4_UNIT_TARGET_HEAD_BATCH \- COLI_V4_UNIT_SPECULATIVE \- COLI_V4_UNIT_DSPARK_HEADS \- COLI_V4_UNIT_DSPARK_CAPTURE \- COLI_V4_UNIT_TARGET_VERIFY \- COLI_V4_UNIT_TARGET_ATTENTION_COMMIT \- COLI_V4_UNIT_TARGET_VERIFY_PREFIX \- COLI_V4_UNIT_DSPARK_VERIFY_WINDOWV4_TEST_UNITS = \COLI_V4_UNIT_KV_CACHE \COLI_V4_UNIT_ATTENTION_CACHE \COLI_V4_UNIT_EXPERT \COLI_V4_UNIT_EXPERT_STORE \- COLI_V4_UNIT_LAYER \- COLI_V4_UNIT_CONFIG+ COLI_V4_UNIT_LAYERdiff --git a/c/deepseek_v4.c b/c/deepseek_v4.cindex 68c52af7..3646c76e 100644--- a/c/deepseek_v4.c+++ b/c/deepseek_v4.c@@ -1,5 +1,190 @@/* Amalgamated deepseek_v4.c — GLM-style source; compile with -DCOLI_V4_UNIT_* per object */-/* Umbrella API: deepseek_v4.h + deepseek_v4_dspark.h (included by units) */+/* Umbrella API: deepseek_v4.h (included by units) */++#ifdef COLI_V4_UNIT_ST+/* Shared st.h adapter and V4 tensor materialization helpers. */+#include "deepseek_v4_internal.h"++#include <dirent.h>+#include <stdarg.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.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_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 *probe = opendir(directory);+ if (!probe)+ return set_error(error, error_size, "cannot open model directory: %s", directory);+ closedir(probe);+ ColiSafetensorsIndex *index = calloc(1, sizeof(*index));+ if (!index)+ return set_error(error, error_size, "out of memory opening: %s", directory);+ st_init(index, directory);+ if (!index->nfd || !index->n) {+ st_destroy(index);+ free(index);+ return set_error(error, error_size, "no safetensors tensors in: %s", directory);+ }+ *out = index;+ return 0;+}++void coli_st_index_close(ColiSafetensorsIndex *index) {+ if (!index) return;+ st_destroy(index);+ free(index);+}++size_t coli_st_tensor_count(const ColiSafetensorsIndex *index) {+ return index ? (size_t)index->n : 0;+}++size_t coli_st_shard_count(const ColiSafetensorsIndex *index) {+ return index ? (size_t)index->nfd : 0;+}++const char *coli_st_shard_path(const ColiSafetensorsIndex *index, int shard) {+ return index && shard >= 0 && shard < index->nfd ? index->paths[shard] : NULL;+}++const ColiSafetensorsTensor *coli_st_find(const ColiSafetensorsIndex *index,+ const char *name) {+ return index && name ? st_find((ColiSafetensorsIndex *)index, name) : NULL;+}++int coli_st_read_at(const ColiSafetensorsIndex *index, int shard,+ uint64_t offset, size_t length, void *destination) {+ return st_read_at_range((ColiSafetensorsIndex *)index, shard, offset,+ length, destination);+}++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) {+ return st_prefetch_at_range((ColiSafetensorsIndex *)index, shard,+ offset, length);+}++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/I8";+ case COLI_ST_I64: return "I64";+ case COLI_ST_F8_E4M3: return "F8_E4M3";+ case COLI_ST_F8_E8M0: return "F8_E8M0";+ default: return "UNKNOWN";+ }+}++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_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_float_tensor_free(ColiFloatTensor *tensor) {+ if (!tensor) return;+ free(tensor->data);+ 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 i = 0; i < (uint64_t)tensor->numel; i++)+ output->data[i] = coli_bf16_decode(values[i]);+ }+ free(raw);+ output->count = (uint64_t)tensor->numel;+ output->rank = tensor->rank;+ memcpy(output->shape, tensor->shape, sizeof(output->shape));+ return 0;+}+#endif /* COLI_V4_UNIT_ST */+#ifdef COLI_V4_UNIT_LAYER_RESIDENT/* ######## deepseek_v4_layer_resident.c ######## */@@ -420,11 +605,9 @@ int coli_v4_resource_plan_compute(}static int resident_tiers_fit(uint64_t available, uint64_t fixed,- uint64_t dense, uint64_t dspark,- uint64_t minimum_experts) {+ uint64_t dense, uint64_t minimum_experts) {uint64_t total;return !add_u64(fixed, dense, &total) &&- !add_u64(total, dspark, &total) &&!add_u64(total, minimum_experts, &total) && total <= available;}@@ -433,47 +616,21 @@ int coli_v4_resident_tier_plan(const ColiDeepSeekV4ResidentTierInputs *inputs,char *error, size_t error_size) {if (!plan || !inputs || !inputs->available_bytes ||- !inputs->dense_bytes || !inputs->minimum_expert_bytes ||- (inputs->has_dspark &&- (!inputs->dspark_streamed_bytes || !inputs->dspark_full_bytes ||- inputs->dspark_full_bytes < inputs->dspark_streamed_bytes)) ||- (!inputs->has_dspark &&- (inputs->dspark_streamed_bytes || inputs->dspark_full_bytes)))+ !inputs->dense_bytes || !inputs->minimum_expert_bytes)return plan_error(error, error_size,"invalid V4 resident-tier inputs");memset(plan, 0, sizeof(*plan));- uint64_t streamed = inputs->has_dspark- ? inputs->dspark_streamed_bytes : 0;if (!resident_tiers_fit(inputs->available_bytes, inputs->fixed_bytes,- 0, streamed, inputs->minimum_expert_bytes))+ 0, inputs->minimum_expert_bytes))return plan_error(error, error_size,"resident V4 tiers leave too little target cache");- if (inputs->has_dspark &&- resident_tiers_fit(inputs->available_bytes, inputs->fixed_bytes,- inputs->dense_bytes, inputs->dspark_full_bytes,+ if (resident_tiers_fit(inputs->available_bytes, inputs->fixed_bytes,+ inputs->dense_bytes,inputs->minimum_expert_bytes)) {plan->dense_resident = 1;- plan->dspark_resident = 1;plan->dense_bytes = inputs->dense_bytes;- plan->dspark_bytes = inputs->dspark_full_bytes;- } else if (resident_tiers_fit(- inputs->available_bytes, inputs->fixed_bytes,- inputs->dense_bytes, streamed,- inputs->minimum_expert_bytes)) {- plan->dense_resident = 1;- plan->dense_bytes = inputs->dense_bytes;- plan->dspark_bytes = streamed;- } else if (inputs->has_dspark &&- resident_tiers_fit(- inputs->available_bytes, inputs->fixed_bytes, 0,- inputs->dspark_full_bytes,- inputs->minimum_expert_bytes)) {- plan->dspark_resident = 1;- plan->dspark_bytes = inputs->dspark_full_bytes;- } else {- plan->dspark_bytes = streamed;}return 0;}@@ -487,7 +644,6 @@ int coli_v4_resident_tier_plan(#include <stdlib.h>#include <string.h>-#include "safetensors_index.h"static int find_head(const char *model_dir, ColiSafetensorsIndex **index,const ColiSafetensorsTensor **head,@@ -571,7 +727,6 @@ int coli_st_read_at_engine(ColiV4Engine *engine,#ifdef COLI_V4_UNIT_EXPERT_STORE_AUTO/* ######## deepseek_v4_expert_store_auto.c ######## */-#include "deepseek_v4_dspark.h"/* ---- begin inlined deepseek_v4_expert_store_auto_v5.c ---- */#include "deepseek_v4_internal.h"@@ -580,8 +735,6 @@ int coli_st_read_at_engine(ColiV4Engine *engine,#include <string.h>#include <time.h>-#include "deepseek_v4_dspark.h"-#include "safetensors_index.h"#define MIB UINT64_C(1048576)#define GIB UINT64_C(1073741824)@@ -595,8 +748,10 @@ static uint64_t expert_record_bytes(const ColiSafetensorsIndex *index) {uint64_t total = 0;for (size_t i = 0; i < sizeof(parts) / sizeof(parts[0]); i++) {const ColiSafetensorsTensor *tensor = coli_st_find(index, parts[i]);- if (!tensor || UINT64_MAX - total < tensor->nbytes) return 0;- total += tensor->nbytes;+ if (!tensor || tensor->nbytes < 0) return 0;+ uint64_t bytes = (uint64_t)tensor->nbytes;+ if (UINT64_MAX - total < bytes) return 0;+ total += bytes;}return total;}@@ -704,49 +859,22 @@ int coli_v4_expert_store_open_planned(v5_dense_inventory(options->model_dir, &dense_bytes,error, error_size)) return -1;- uint64_t dspark_bytes = 0, dspark_full_bytes = 0;- uint64_t dspark_full_experts = 0;- const char *dspark_model = runtime->dspark_model_dir;- ColiV4DSparkMemoryPlan dspark = {0};- if (dspark_model && *dspark_model) {- ColiDeepSeekV4Config ds_config;- ColiDeepSeekV4DSparkManifest manifest;- if (coli_v4_config_load(&ds_config, dspark_model, error, error_size) ||- coli_v4_dspark_memory_plan(dspark_model, &ds_config, &dspark,- error, error_size) ||- coli_v4_dspark_inspect(dspark_model, &ds_config, &manifest,- error, error_size)) return -1;- uint64_t all_stages = 0;- for (int stage = 0; stage < manifest.stage_count; stage++)- all_stages += manifest.common_stage_bytes[stage];- dspark_full_experts = dspark.expert_record_bytes *- (uint64_t)manifest.stage_count * ds_config.n_routed_experts;- dspark_full_bytes = dspark.resident_heads_bytes + all_stages +- dspark_full_experts + dspark.working_bytes;- dspark_bytes = dspark.incremental_reserve_bytes;- }-uint64_t fixed = plan.system_reserve_bytes + plan.runtime_reserve_bytes;- int has_dspark = dspark_model && *dspark_model;ColiDeepSeekV4ResidentTierPlan tiers;ColiDeepSeekV4ResidentTierInputs tier_inputs = {- plan.planner_available_bytes, fixed, dense_bytes, dspark_bytes,- dspark_full_bytes, plan.minimum_expert_bytes, has_dspark,+ plan.planner_available_bytes, fixed, dense_bytes,+ plan.minimum_expert_bytes,};if (coli_v4_resident_tier_plan(&tiers, &tier_inputs,error, error_size)) return -1;dense_bytes = tiers.dense_bytes;- dspark_bytes = tiers.dspark_bytes;runtime->dense_resident = tiers.dense_resident;- runtime->dspark_resident = tiers.dspark_resident;- runtime->dspark_expert_cache_bytes = tiers.dspark_resident- ? dspark_full_experts : 0;- if (dspark_bytes + dense_bytes > plan.planner_available_bytes - fixed) {+ if (dense_bytes > plan.planner_available_bytes - fixed) {snprintf(error, error_size, "resident V4 tiers exceed available RAM");return -1;}uint64_t safe_payload = plan.planner_available_bytes - fixed -- dspark_bytes - dense_bytes;+ dense_bytes;int requested_head = -1;int resident_head = safe_payload >= plan.minimum_expert_bytes +head_bytes + 256 * MIB;@@ -765,21 +893,18 @@ int coli_v4_expert_store_open_planned(if (slots > plan.slots_per_layer) slots = plan.slots_per_layer;if (slots < options->experts_per_layer && slots < 6) slots = 6;plan.expert_cache_bytes = (uint64_t)slots * per_slot;- plan.projected_bytes = fixed + dense_bytes + dspark_bytes ++ runtime->target_expert_cache_bytes = plan.expert_cache_bytes;+ plan.projected_bytes = fixed + dense_bytes +plan.expert_cache_bytes + (resident_head ? head_bytes : 0);if (resident_head && coli_v4_head_cache_load(engine, options->model_dir, error, error_size)) return -1;- const char *dspark_tier = (dspark_model && *dspark_model)- ? (tiers.dspark_resident ? "resident" : "streamed") : "disabled";fprintf(stderr,"ram_tiers available=%.2fGiB dense=%s(%.2fGiB) "- "dspark=%s(%.2fGiB) dspark_experts=%.2fGiB ""target_slots=%d target_cache=%.2fGiB head=%s projected=%.2fGiB\n",plan.planner_available_bytes / (double)GIB,tiers.dense_resident ? "resident" : "streamed",dense_bytes / (double)GIB,- dspark_tier, dspark_bytes / (double)GIB,- dspark_full_experts / (double)GIB, slots,+ slots,plan.expert_cache_bytes / (double)GIB,resident_head ? "resident-bf16" : "streamed-bf16",plan.projected_bytes / (double)GIB);@@ -4747,7 +4872,6 @@ void coli_v4_attention_snapshot_destroy(ColiV4AttentionSnapshot *snapshot) {#include <stdlib.h>#include <string.h>-#include "safetensors_index.h"#ifdef COLI_V4_EXPERIMENTAL_PREFETCH_BATCHint coli_st_prefetch_many(@@ -5664,11 +5788,9 @@ int coli_v4_route_bf16(float *weights, int *indices, const float *hidden,#include <stdlib.h>#include <string.h>-/* Provided by LAYER_RESIDENT / DSPARK heads units. */+/* Provided by LAYER_RESIDENT. */void coli_v4_layer_resident_reference_free(ColiV4Engine *engine,ColiDeepSeekV4LayerWeights *weights);-void coli_v4_dspark_heads_close(ColiV4DSparkHeads *heads);-void coli_v4_dspark_runner_close(ColiV4DSparkRunner *runner);#ifdef COLI_V4_TEST_HOOKSint coli_v4_test_fail_expert_store_open = 0;@@ -5686,20 +5808,6 @@ void coli_v4_engine_detach_session(ColiV4Engine *engine) {engine->active_sessions--;}-void coli_v4_session_take_runner(ColiV4Session *session,- ColiV4DSparkRunner *runner) {- if (!session) return;- if (session->runner && session->runner != runner)- coli_v4_dspark_runner_close(session->runner);- session->runner = runner;-}--void coli_v4_session_clear_runner(ColiV4Session *session) {- if (!session || !session->runner) return;- coli_v4_dspark_runner_close(session->runner);- session->runner = NULL;-}-#ifdef COLI_V4_TEST_HOOKSColiV4Session *coli_v4_test_session_bare_create(ColiV4Engine *engine) {if (!engine) return NULL;@@ -5712,7 +5820,6 @@ ColiV4Session *coli_v4_test_session_bare_create(ColiV4Engine *engine) {void coli_v4_test_session_bare_destroy(ColiV4Session *session) {if (!session) return;- coli_v4_session_clear_runner(session);if (session->engine) {coli_v4_engine_detach_session(session->engine);session->engine = NULL;@@ -5720,9 +5827,6 @@ void coli_v4_test_session_bare_destroy(ColiV4Session *session) {free(session);}-ColiV4DSparkRunner *coli_v4_session_peek_runner(const ColiV4Session *session) {- return session ? session->runner : NULL;-}#endifconst ColiDeepSeekV4Config *coli_v4_engine_config(const ColiV4Engine *engine) {@@ -5751,34 +5855,11 @@ const char *coli_v4_engine_target_model_dir(const ColiV4Engine *engine) {return engine ? engine->runtime.target_model_dir : NULL;}-const char *coli_v4_engine_dspark_model_dir(const ColiV4Engine *engine) {- return engine ? engine->runtime.dspark_model_dir : NULL;-}-void coli_v4_engine_destroy(ColiV4Engine *engine) {if (!engine) return;assert(engine->active_sessions == 0 &&"destroy engine while sessions are still alive");- /* DSpark capture (heads owned by engine; runners must not free them). */- if (engine->dspark_capture.heads) {- coli_v4_dspark_heads_close(engine->dspark_capture.heads);- engine->dspark_capture.heads = NULL;- }- for (int i = 0; i < COLI_V4_DSPARK_MAX_TARGETS; i++) {- free(engine->dspark_capture.states[i]);- engine->dspark_capture.states[i] = NULL;- }- free(engine->dspark_capture.staged_main_x);- engine->dspark_capture.staged_main_x = NULL;- engine->dspark_capture.capacity = 0;- engine->dspark_capture.staged_batch = 0;- engine->dspark_capture.staged_hidden = 0;- memset(&engine->dspark_capture.manifest, 0,- sizeof(engine->dspark_capture.manifest));-- memset(&engine->dspark_verify, 0, sizeof(engine->dspark_verify));-for (int layer = 0; layer < COLI_V4_RESIDENT_MAX_LAYERS; layer++) {if (!engine->dense_resident.ready[layer]) continue;coli_v4_layer_resident_reference_free(@@ -5788,15 +5869,6 @@ void coli_v4_engine_destroy(ColiV4Engine *engine) {engine->dense_resident.index = NULL;engine->dense_resident.total_bytes = 0;- for (int stage = 0; stage < COLI_V4_DSPARK_MAX_STAGES; stage++) {- if (!engine->dspark_resident.ready[stage]) continue;- coli_v4_layer_resident_reference_free(- NULL, &engine->dspark_resident.layers[stage]);- engine->dspark_resident.ready[stage] = 0;- }- engine->dspark_resident.index = NULL;- engine->dspark_resident.total_bytes = 0;-free(engine->head_cache.data);engine->head_cache.data = NULL;if (engine->owns_experts && engine->experts && engine->experts->ops &&@@ -5811,11 +5883,8 @@ void coli_v4_engine_destroy(ColiV4Engine *engine) {}engine->target_index = NULL;engine->runtime.target_model_dir = NULL;- engine->runtime.dspark_model_dir = NULL;free(engine->owned_target_model_dir);engine->owned_target_model_dir = NULL;- free(engine->owned_dspark_model_dir);- engine->owned_dspark_model_dir = NULL;free(engine);}@@ -5836,23 +5905,15 @@ int coli_v4_engine_open(ColiV4Engine **output,}engine->owned_target_model_dir = strdup(options->target_model_dir);- const char *dspark_model_dir = options->no_dspark ? NULL :- (options->dspark_model_dir ? options->dspark_model_dir- : options->target_model_dir);- engine->owned_dspark_model_dir = dspark_model_dir- ? strdup(dspark_model_dir) : NULL;- if (!engine->owned_target_model_dir ||- (dspark_model_dir && !engine->owned_dspark_model_dir)) {+ if (!engine->owned_target_model_dir) {if (error && error_size)- snprintf(error, error_size, "out of memory copying model directories");+ snprintf(error, error_size, "out of memory copying model directory");goto fail;}engine->runtime.target_model_dir = engine->owned_target_model_dir;- engine->runtime.dspark_model_dir = engine->owned_dspark_model_dir;engine->runtime.memory_limit_bytes = options->memory_limit_bytes;engine->runtime.context_tokens =options->context_tokens > 0 ? options->context_tokens : 4096;- engine->runtime.verify_drafts = options->verify_drafts;engine->runtime.repin_interval = options->repin_interval;engine->runtime.pin_slots_per_layer = options->pin_slots_per_layer;@@ -5873,10 +5934,9 @@ int coli_v4_engine_open(ColiV4Engine **output,}if (coli_v4_test_skip_expert_store_open) {engine->summary.dense_resident = engine->runtime.dense_resident;- engine->summary.dspark_resident = engine->runtime.dspark_resident;engine->summary.head_resident = engine->head_cache.data != NULL;engine->summary.expert_cache_bytes =- engine->runtime.dspark_expert_cache_bytes;+ engine->runtime.target_expert_cache_bytes;*output = engine;return 0;}@@ -5894,10 +5954,9 @@ int coli_v4_engine_open(ColiV4Engine **output,goto fail;engine->owns_experts = 1;engine->summary.dense_resident = engine->runtime.dense_resident;- engine->summary.dspark_resident = engine->runtime.dspark_resident;engine->summary.head_resident = engine->head_cache.data != NULL;engine->summary.expert_cache_bytes =- engine->runtime.dspark_expert_cache_bytes;+ engine->runtime.target_expert_cache_bytes;*output = engine;return 0;@@ -5977,7 +6036,7 @@ int coli_v4_prompt_build(char **output, size_t *output_length,#define COLI_V4_GENERATE_MAIN coli_v4_generate_stats_legacy_main#define COLI_V4_GENERATE_HELPERS_ONLY#define spec_print spec_print_diagnostic_legacy-/* ---- begin include tools/deepseek_v4_generate_speculative.c ---- */+/* Target-only generation helpers. */#include <time.h>#define main coli_v4_first_token_legacy_main@@ -5996,8 +6055,6 @@ int coli_v4_prompt_build(char **output, size_t *output_length,#include "deepseek_v4_internal.h"#include "json.h"#include "native_quant.h"-#include "safetensors_index.h"-#include "tensor_io.h"#include "tok.h"static int load_embedding(float *state, const ColiSafetensorsIndex *index,@@ -6269,12 +6326,6 @@ int main(int argc, char **argv) {#undef main#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-static double spec_now(void) {struct timespec value;clock_gettime(CLOCK_MONOTONIC, &value);@@ -6296,18 +6347,6 @@ static int spec_sentence_end(const char *text, int length) {return 0;}-#ifndef COLI_V4_GENERATE_HELPERS_ONLY-static int spec_print(Tok *tokenizer, int token, float logit,- int position, int ordinal, int stop_sentence) {- char piece[1024];- int length = tok_decode(tokenizer, &token, 1, piece, sizeof(piece) - 1);- printf("generated=%d position=%d token=%d logit=%.9g piece=",- ordinal, position, token, logit);- fwrite(piece, 1, (size_t)length, stdout); fputc('\n', stdout); fflush(stdout);- return token == 1 || (stop_sentence && spec_sentence_end(piece, length));-}-#endif-static int target_batch(ColiV4Engine *engine, float **state_ptr, float **next_ptr,ColiDeepSeekV4WindowAttentionState **attention,const ColiSafetensorsIndex *index,@@ -6339,34 +6378,12 @@ static int target_batch(ColiV4Engine *engine, float **state_ptr, float **next_pt"target prefill failed layer=%d offset=%d batch=%d",layer_id, offset, chunk);}- if (!result)- coli_v4_dspark_capture_after_block(engine, &layer, config, next,- batch);coli_v4_layer_free(engine, &layer);if (result) return -1;float *swap = state; state = next; next = swap;}- *state_ptr = state; *next_ptr = next; return 0;-}--static int dspark_prefill_chunks(ColiV4DSparkRunner *runner,- const float *main_x, int hidden_size,- int start_position, int batch,- char *error, size_t error_size) {- if (!runner || !main_x || hidden_size < 1 || start_position < 0 ||- batch < 1) {- if (error && error_size)- snprintf(error, error_size, "invalid chunked DSpark prefill");- return -1;- }- for (int offset = 0; offset < batch; offset += 64) {- int chunk = batch - offset;- if (chunk > 64) chunk = 64;- if (coli_v4_dspark_runner_prefill(- runner, main_x + (size_t)offset * hidden_size,- start_position + offset, chunk, error, error_size))- return -1;- }+ *state_ptr = state;+ *next_ptr = next;return 0;}@@ -6385,189 +6402,14 @@ static int target_token(ColiV4Engine *engine, float **state_ptr, float **next_ptint result = coli_v4_block_window_token_ref(next, attention[layer_id], &layer, config, experts,state, token, position, error, error_size);- if (!result)- coli_v4_dspark_capture_after_block(engine, &layer, config, next, 1);coli_v4_layer_free(engine, &layer);if (result) return -1;float *swap = state; state = next; next = swap;}- *state_ptr = state; *next_ptr = next; return 0;-}--#ifndef COLI_V4_GENERATE_HELPERS_ONLY-static uint64_t env_u64(const char *name, uint64_t fallback) {- const char *text = getenv(name); char *end = NULL;- if (!text || !*text) return fallback;- unsigned long long value = strtoull(text, &end, 10);- return end != text && !*end && value ? (uint64_t)value : fallback;-}--static float env_float(const char *name, float fallback) {- const char *text = getenv(name); char *end = NULL;- if (!text || !*text) return fallback;- float value = strtof(text, &end);- return end != text && !*end && value > 0.0f && value <= 1.0f- ? value : fallback;-}--#ifndef COLI_V4_GENERATE_MAIN-#define COLI_V4_GENERATE_MAIN main-#endif--int COLI_V4_GENERATE_MAIN(int argc, char **argv) {- if (argc < 4 || argc > 6) {- fprintf(stderr, "usage: %s TARGET_MODEL DSPARK_MODEL PROMPT "- "[MAX_NEW_TOKENS] [--stop-sentence]\n", argv[0]);- return 2;- }- int max_new = argc >= 5 ? atoi(argv[4]) : 32;- int stop_sentence = argc == 6 && !strcmp(argv[5], "--stop-sentence");- if (max_new < 1 || (argc == 6 && !stop_sentence)) return 2;-#ifdef _WIN32- _putenv_s("COLI_V4_DSPARK_MODEL", argv[2]);-#else- setenv("COLI_V4_DSPARK_MODEL", argv[2], 1);-#endif- char error[512] = {0}, tokenizer_path[4096];- ColiDeepSeekV4Config config; ColiSafetensorsIndex *index = NULL;- ColiExpertStore *experts = NULL; ColiV4DSparkRunner *runner = NULL;- if (coli_v4_config_load(&config, argv[1], error, sizeof(error)) ||- coli_st_index_open(&index, argv[1], error, sizeof(error)) ||- coli_deepseek_v4_expert_store_open(- &(ColiDeepSeekV4ExpertStoreOptions){argv[1],- config.num_hidden_layers, config.n_routed_experts, 4ULL << 30},- &experts, error, sizeof(error))) {- fprintf(stderr, "%s\n", error); return 1;- }- snprintf(tokenizer_path, sizeof(tokenizer_path), "%s/tokenizer.json", argv[1]);- Tok tokenizer; tok_load(&tokenizer, tokenizer_path);- int prompt_capacity = (int)strlen(argv[3]) + 16;- int *prompt_ids = malloc((size_t)prompt_capacity * sizeof(int));- int *generated = malloc((size_t)(max_new + 64) * sizeof(int));- int prompt_count = tok_encode(&tokenizer, argv[3], strlen(argv[3]),- prompt_ids, prompt_capacity);- if (!prompt_ids || !generated || prompt_count < 1 || prompt_count > 64)- return 1;- size_t hd = (size_t)config.hc_mult * config.hidden_size;- float *state = malloc((size_t)64 * hd * sizeof(float));- float *next = malloc((size_t)64 * hd * sizeof(float));- float *hidden = malloc((size_t)config.hidden_size * sizeof(float));- float *main_x_batch = malloc((size_t)64 * config.hidden_size * sizeof(float));- ColiDeepSeekV4WindowAttentionState **attention = calloc(- config.num_hidden_layers, sizeof(*attention));- if (!state || !next || !hidden || !main_x_batch || !attention) return 1;- for (int layer = 0; layer < config.num_hidden_layers; layer++)- if (coli_v4_window_attention_create(&attention[layer], &config)) return 1;- for (int item = 0; item < prompt_count; item++)- if (load_embedding(state + (size_t)item * hd, index, &config,- prompt_ids[item])) return 1;-- double started = spec_now();- if (target_batch(NULL, &state, &next, attention, index, &config, experts,- prompt_ids, 0, prompt_count, error, sizeof(error)) ||- coli_v4_dspark_capture_main_x(NULL, main_x_batch, prompt_count, &config)) {- fprintf(stderr, "%s\n", error); return 1;- }- if (coli_v4_dspark_runner_open(&runner, NULL, argv[2], argv[1], &config,- 256ULL << 20, error, sizeof(error))) {- fprintf(stderr, "%s\n", error); return 1;- }- if (coli_v4_dspark_runner_use_shared_heads(- runner, coli_v4_dspark_capture_heads(NULL)) ||- dspark_prefill_chunks(runner, main_x_batch, config.hidden_size,- 0, prompt_count, error, sizeof(error))) {- coli_v4_dspark_runner_close(runner);- fprintf(stderr, "%s\n", error); return 1;- }- const float *last = state + (size_t)(prompt_count - 1) * hd;- int current; float current_logit;- if (final_hidden(hidden, last, index, &config, error, sizeof(error)) ||- head_argmax(NULL, hidden, index, &config, ¤t, ¤t_logit)) return 1;- int generated_count = 0, last_processed = prompt_count - 1;- generated[generated_count++] = current;- int done = spec_print(&tokenizer, current, current_logit,- last_processed, generated_count, stop_sentence);- double first_at = spec_now();-- ColiV4SpeculativeController controller;- coli_v4_speculative_controller_init(- &controller, env_u64("COLI_V4_DSPARK_MIN_PROPOSALS", 10),- env_float("COLI_V4_DSPARK_DISABLE_THRESHOLD", 0.35f));- int block = coli_v4_dspark_runner_verify_block_size(runner);- int drafts[64], verified[65]; float draft_logits[64];- while (!done && generated_count < max_new) {- if (!controller.enabled || last_processed == prompt_count - 1) {- int position = last_processed + 1;- if (target_token(NULL, &state, &next, attention, index, &config, experts,- current, position, error, sizeof(error)) ||- final_hidden(hidden, state, index, &config, error, sizeof(error)) ||- head_argmax(NULL, hidden, index, &config, ¤t, ¤t_logit) ||- coli_v4_dspark_capture_main_x(NULL, main_x_batch, 1, &config)) {- fprintf(stderr, "%s\n", error); return 1;- }- last_processed = position; generated[generated_count++] = current;- done = spec_print(&tokenizer, current, current_logit,- last_processed, generated_count, stop_sentence);- continue;- }- const float *main_x = main_x_batch;- if (coli_v4_dspark_runner_draft(- runner, main_x, current, last_processed,- drafts, draft_logits, error, sizeof(error))) {- fprintf(stderr, "%s\n", error); return 1;- }- ColiV4VerificationResult verification;- if (coli_v4_target_verify_greedy_batch(- &verification, verified, 65, NULL, attention, index, &config,- experts, current, drafts, block, last_processed + 1,- error, sizeof(error))) {- fprintf(stderr, "%s\n", error); return 1;- }- coli_v4_speculative_record(&controller, block,- verification.accepted_draft_tokens);- int committed = verification.accepted_draft_tokens + 1;- if (coli_v4_dspark_capture_main_x(NULL, main_x_batch, committed, &config))- return 1;- memmove(main_x_batch,- main_x_batch + (size_t)(committed - 1) * config.hidden_size,- (size_t)config.hidden_size * sizeof(float));- int base_position = last_processed + 1;- last_processed += committed;- fprintf(stderr,- "dspark_verify proposed=%d accepted=%d rate=%.3f enabled=%d\n",- block, verification.accepted_draft_tokens,- coli_v4_speculative_acceptance(&controller), controller.enabled);- for (int i = 0; i < verification.output_count &&- generated_count < max_new && !done; i++) {- current = verified[i]; current_logit = 0.0f;- generated[generated_count++] = current;- done = spec_print(&tokenizer, current, current_logit,- base_position + i, generated_count, stop_sentence);- }- }- double ended = spec_now();- ColiExpertStoreStats stats; experts->ops->stats(experts, &stats);- size_t text_capacity = (size_t)generated_count * 256 + 1;- char *text = malloc(text_capacity);- int text_count = generated_count;- if (text_count && generated[text_count - 1] == 1) text_count--;- int text_length = tok_decode(&tokenizer, generated, text_count,- text, text_capacity - 1);- printf("summary tokens=%d expert_reads=%llu bytes=%llu "- "dspark_rounds=%llu proposed=%llu accepted=%llu rate=%.3f enabled=%d\n",- generated_count, (unsigned long long)stats.misses,- (unsigned long long)stats.bytes_read,- (unsigned long long)controller.rounds,- (unsigned long long)controller.proposed,- (unsigned long long)controller.accepted,- coli_v4_speculative_acceptance(&controller), controller.enabled);- printf("generated_text="); fwrite(text, 1, text_length, stdout);- printf("\ntiming time_to_first_token=%.3fs after_first=%.3fs total=%.3fs\n",- first_at - started, ended - first_at, ended - started);+ *state_ptr = state;+ *next_ptr = next;return 0;}-#endif-/* ---- end include tools/deepseek_v4_generate_speculative.c ---- */#undef spec_print#undef COLI_V4_GENERATE_HELPERS_ONLY@@ -6576,66 +6418,6 @@ int COLI_V4_GENERATE_MAIN(int argc, char **argv) {#include "deepseek_v4_internal.h"#include "deepseek_v4_internal.h"-#ifdef COLI_V4_EXPERIMENTAL_PARALLEL_PREFIX_VERIFY-#include <omp.h>--#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"---typedef struct {- float **state_ptr;- float **next_ptr;- ColiDeepSeekV4WindowAttentionState **attention;- const ColiSafetensorsIndex *index;- const ColiDeepSeekV4Config *config;- ColiExpertStore *experts;- int token;- int position;- int threads;- int target_token;- float target_logit;- float *main_x;- double seconds;- int result;- char error[512];-} ParallelPrefixJob;---static void *parallel_prefix_worker(void *argument) {- ParallelPrefixJob *job = argument;- double began = spec_now();- int previous_threads = omp_get_max_threads();- omp_set_num_threads(job->threads);- float *hidden = malloc((size_t)job->config->hidden_size * sizeof(float));- if (!hidden) {- snprintf(job->error, sizeof(job->error),- "out of memory in parallel target prefix");- job->result = -1;- } else {- job->result = target_token(- NULL, job->state_ptr, job->next_ptr, job->attention, job->index,- job->config, job->experts, job->token, job->position,- job->error, sizeof(job->error));- if (!job->result)- job->result = final_hidden(- hidden, *job->state_ptr, job->index, job->config,- job->error, sizeof(job->error));- if (!job->result)- job->result = head_argmax(- NULL, hidden, job->index, job->config,- &job->target_token, &job->target_logit);- if (!job->result)- job->result = coli_v4_dspark_capture_main_x(- NULL, job->main_x, 1, job->config);- }- free(hidden);- omp_set_num_threads(previous_threads);- job->seconds = spec_now() - began;- return NULL;-}-#endif-static ColiExpertStoreStats stats_subtract(ColiExpertStoreStats end,ColiExpertStoreStats begin) {ColiExpertStoreStats delta = end;@@ -6664,7 +6446,6 @@ static uint64_t state_hash_v70(const float *values, size_t count) {typedef struct {const char *model_dir;- const char *draft_model_dir;const char *prompt;const char *prompt_file;const char *system_prompt;@@ -6687,12 +6468,11 @@ static void v4_cli_usage(FILE *stream, const char *program) {" --max-tokens N maximum generated tokens (default: 128)\n"" --memory-gb GiB cap this process; otherwise use available RAM\n"" --prompt-file PATH read UTF-8 prompt from file (avoids argv encoding issues)\n"- " --draft-model PATH separate DSpark checkpoint (default: MODEL)\n"" --system TEXT optional system message\n"" --thinking enable the official V4 thinking prefix\n"" --raw-prompt bypass the default V4 chat template\n"" --stop-sentence stop after the first sentence terminator\n"- " --no-dspark disable speculative decode (greedy target only)\n"+ " --no-dspark accepted for compatibility; target-only is always greedy\n"" --oracle FILE validate against an oracle JSON fixture\n"" --teacher-forcing N oracle: compare top-1 on N prompt positions\n"" --greedy N oracle: compare N greedy continuation tokens\n"@@ -6758,7 +6538,6 @@ static int v4_cli_parse(int argc, char **argv, V4CliOptions *options) {if (!options || argc < 3) return -1;memset(options, 0, sizeof(*options));options->model_dir = argv[1];- options->draft_model_dir = argv[1];options->max_new_tokens = 128;options->prompt_mode = COLI_V4_PROMPT_CHAT;int argi = 2;@@ -6778,9 +6557,6 @@ static int v4_cli_parse(int argc, char **argv, V4CliOptions *options) {} else if (!strcmp(option, "--prompt-file")) {if (++i == argc || !argv[i][0]) return -1;options->prompt_file = argv[i];- } else if (!strcmp(option, "--draft-model")) {- if (++i == argc || !argv[i][0]) return -1;- options->draft_model_dir = argv[i];} else if (!strcmp(option, "--system")) {if (++i == argc) return -1;options->system_prompt = argv[i];@@ -6863,8 +6639,7 @@ static int v4_oracle_write_json(const char *path, const char *source,}fputs("\",\n \"comparison\": {\n"" \"top1_token\": \"exact\",\n"- " \"logits\": \"not required for coli-self fixtures\",\n"- " \"dspark\": \"greedy tokens must match --no-dspark\"\n"+ " \"logits\": \"not required for coli-self fixtures\"\n"" },\n \"prompt_ids\": [", out);for (int i = 0; i < prompt_count; i++)fprintf(out, "%s%d", i ? ", " : "", prompt_ids[i]);@@ -6892,7 +6667,6 @@ static void v4_attention_free(ColiDeepSeekV4WindowAttentionState **attention,static void session_free_buffers(ColiV4Session *session) {if (!session) return;free(session->text); session->text = NULL; session->text_length = 0;- free(session->main_x_batch); session->main_x_batch = NULL;free(session->hidden); session->hidden = NULL;free(session->next); session->next = NULL;free(session->state); session->state = NULL;@@ -6908,7 +6682,6 @@ static void session_free_attention(ColiV4Session *session) {void coli_v4_session_destroy(ColiV4Session *session) {if (!session) return;- coli_v4_session_clear_runner(session);session_free_attention(session);session_free_buffers(session);if (session->tokenizer_ready) {@@ -6984,14 +6757,12 @@ int coli_v4_session_create(ColiV4Session **output, ColiV4Engine *engine,session->state = malloc(slots * hd * sizeof(float));session->next = malloc(slots * hd * sizeof(float));session->hidden = malloc((size_t)session->config.hidden_size * sizeof(float));- session->main_x_batch =- malloc(slots * (size_t)session->config.hidden_size * sizeof(float));session->prompt_ids =malloc((size_t)(session->max_prompt_tokens + 16) * sizeof(int));session->generated =malloc((size_t)(session->max_new_tokens_cap + 64) * sizeof(int));if (!session->state || !session->next || !session->hidden ||- !session->main_x_batch || !session->prompt_ids || !session->generated) {+ !session->prompt_ids || !session->generated) {coli_v4_session_destroy(session);if (error && error_size)snprintf(error, error_size, "out of memory allocating session buffers");@@ -7049,7 +6820,6 @@ int coli_v4_session_generate(ColiV4Session *session,session->text_length = 0;session->prompt_count = 0;session->generated_count = 0;- coli_v4_session_clear_runner(session);for (int layer = 0; layer < session->config.num_hidden_layers; layer++)coli_v4_window_attention_reset(session->attention[layer]);@@ -7075,7 +6845,6 @@ int coli_v4_session_generate(ColiV4Session *session,float *state = session->state;float *next = session->next;float *hidden = session->hidden;- float *main_x_batch = session->main_x_batch;ColiDeepSeekV4WindowAttentionState **attention = session->attention;int *generated = session->generated;size_t hd = (size_t)config->hc_mult * config->hidden_size;@@ -7094,29 +6863,6 @@ int coli_v4_session_generate(ColiV4Session *session,return -1;session->state = state;session->next = next;- if (!options->no_dspark &&- coli_v4_dspark_capture_main_x(engine, main_x_batch, prompt_count, config)) {- if (error && error_size)- snprintf(error, error_size, "dspark capture main_x failed");- return -1;- }-- ColiV4DSparkRunner *runner = NULL;- if (!options->no_dspark) {- const char *draft = coli_v4_engine_dspark_model_dir(engine);- const char *target = coli_v4_engine_target_model_dir(engine);- if (coli_v4_dspark_runner_open(&runner, session->engine, draft, target,- config, 256ULL << 20, error, error_size))- return -1;- coli_v4_session_take_runner(session, runner);- if (coli_v4_dspark_runner_use_shared_heads(- runner, coli_v4_dspark_capture_heads(engine)))- return -1;- if (dspark_prefill_chunks(runner, main_x_batch, config->hidden_size,- 0, prompt_count, error, error_size))- return -1;- }-const float *last = state + (size_t)(prompt_count - 1) * hd;int current = 0;float current_logit = 0.0f;@@ -7131,71 +6877,22 @@ int coli_v4_session_generate(ColiV4Session *session,generated_count, options->stop_at_sentence);double first_at = spec_now();- ColiV4SpeculativeController controller;- coli_v4_speculative_controller_init(&controller, 10, 0.35f);- if (options->no_dspark) controller.enabled = 0;- int block = runner ? coli_v4_dspark_runner_verify_block_size(runner) : 0;- int drafts[64], verified[65];- float draft_logits[64];-while (!done && generated_count < max_new) {- if (!controller.enabled || last_processed == prompt_count - 1) {- int position = last_processed + 1;- if (target_token(engine, &state, &next, attention, index, config, experts,- current, position, error, error_size))- return -1;- session->state = state;- session->next = next;- if (final_hidden(hidden, state, index, config, error, error_size) ||- head_argmax(engine, hidden, index, config, ¤t, ¤t_logit))- return -1;- if (!options->no_dspark &&- coli_v4_dspark_capture_main_x(engine, main_x_batch, 1, config)) {- if (error && error_size)- snprintf(error, error_size, "dspark capture failed");- return -1;- }- last_processed = position;- generated[generated_count++] = current;- done = session_emit_token(session, on_token, user_data, current,- current_logit, last_processed,- generated_count,- options->stop_at_sentence);- continue;- }- ColiV4VerificationResult verification;- if (coli_v4_dspark_runner_draft(runner, main_x_batch, current,- last_processed, drafts, draft_logits,- error, error_size))+ int position = last_processed + 1;+ if (target_token(engine, &state, &next, attention, index, config, experts,+ current, position, error, error_size))return -1;- if (coli_v4_target_verify_greedy_batch(- &verification, verified, 65, engine, attention, index, config,- experts, current, drafts, block, last_processed + 1, error,- error_size))- return -1;- coli_v4_speculative_record(&controller, block,- verification.accepted_draft_tokens);- int committed = verification.accepted_draft_tokens + 1;- if (coli_v4_dspark_capture_main_x(engine, main_x_batch, committed, config)) {- if (error && error_size)- snprintf(error, error_size, "dspark capture failed");+ session->state = state;+ session->next = next;+ if (final_hidden(hidden, state, index, config, error, error_size) ||+ head_argmax(engine, hidden, index, config, ¤t, ¤t_logit))return -1;- }- memmove(main_x_batch,- main_x_batch + (size_t)(committed - 1) * config->hidden_size,- (size_t)config->hidden_size * sizeof(float));- int base_position = last_processed + 1;- last_processed += committed;- for (int i = 0; i < verification.output_count &&- generated_count < max_new && !done; i++) {- current = verified[i];- current_logit = 0.0f;- generated[generated_count++] = current;- done = session_emit_token(session, on_token, user_data, current,- current_logit, base_position + i,- generated_count,- options->stop_at_sentence);- }+ last_processed = position;+ generated[generated_count++] = current;+ done = session_emit_token(session, on_token, user_data, current,+ current_logit, last_processed,+ generated_count,+ options->stop_at_sentence);}double ended = spec_now();session->state = state;@@ -7220,11 +6917,6 @@ int coli_v4_session_generate(ColiV4Session *session,stats_out->generated_tokens = generated_count;stats_out->eos_stopped = done && generated_count > 0 &&generated[generated_count - 1] == 1;- stats_out->dspark_rounds = controller.rounds;- stats_out->dspark_proposed = controller.proposed;- stats_out->dspark_accepted = controller.accepted;- stats_out->dspark_acceptance =- coli_v4_speculative_acceptance(&controller);stats_out->time_to_first_token_sec = first_at - setup_done;stats_out->decode_sec = ended - first_at;}@@ -7343,7 +7035,6 @@ static void v4_generate_cleanup(ColiV4Session *session,char *prompt_storage,ColiV4Engine *engine,- ColiV4DSparkRunner *runner,ColiDeepSeekV4WindowAttentionState **attention,int layers,int *prompt_ids,@@ -7351,7 +7042,6 @@ static void v4_generate_cleanup(float *state,float *next,float *hidden,- float *main_x_batch,char *text,int *full_ids,int *tf_pred,@@ -7365,11 +7055,9 @@ static void v4_generate_cleanup(prompt_ids = NULL;generated = NULL;attention = NULL;- runner = NULL;state = NULL;next = NULL;hidden = NULL;- main_x_batch = NULL;text = NULL;coli_v4_session_destroy(session);}@@ -7379,20 +7067,264 @@ static void v4_generate_cleanup(free(tf_pred);free(full_ids);free(text);- free(main_x_batch);free(hidden);free(next);free(state);free(generated);free(prompt_ids);v4_attention_free(attention, layers);- if (runner) coli_v4_dspark_runner_close(runner);coli_v4_engine_destroy(engine);free(prompt_storage);}+typedef struct {+ char id[64];+ char *prompt;+ int prompt_bytes;+ int max_tokens;+ float temperature;+ float top_p;+ int extension_bytes;+} V4ServeRequest;++typedef struct {+ ColiV4Session *session;+ const char *request_id;+ int cancelled;+} V4ServeStream;++static double v4_serve_rss_gb(void) {+ struct rusage usage;+ if (getrusage(RUSAGE_SELF, &usage)) return 0.0;+#ifdef __APPLE__+ return usage.ru_maxrss / (1024.0 * 1024.0 * 1024.0);+#else+ return usage.ru_maxrss / (1024.0 * 1024.0);+#endif+}++static int v4_serve_read_request(V4ServeRequest *request,+ const char *active_id) {+ char line[512], command[16], id[64];+ if (!fgets(line, sizeof(line), stdin)) return -1;+ if (sscanf(line, "%15s %63s", command, id) < 2) return 0;+ if (!strcmp(command, "CANCEL") || !strcmp(command, "STOP"))+ return active_id && !strcmp(active_id, id);+ if (strcmp(command, "SUBMIT")) return 0;++ int slot = 0, prompt_bytes = 0, max_tokens = 0, extension_bytes = 0;+ float temperature = 0.0f, top_p = 1.0f;+ int fields = sscanf(line, "%*s %*s %d %d %d %f %f %d",+ &slot, &prompt_bytes, &max_tokens,+ &temperature, &top_p, &extension_bytes);+ if (fields < 5 || slot != 0 || prompt_bytes < 0 ||+ prompt_bytes > (1 << 24) || max_tokens < 1 ||+ extension_bytes < 0 || extension_bytes > (1 << 24)) {+ printf("ERROR %s bad submit header\n", id);+ fflush(stdout);+ return 0;+ }+ size_t total = (size_t)prompt_bytes + (size_t)extension_bytes;+ char *payload = malloc(total + 1);+ if (!payload) {+ printf("ERROR %s out of memory\n", id);+ fflush(stdout);+ return 0;+ }+ if (fread(payload, 1, total, stdin) != total) {+ free(payload);+ return -1;+ }+ (void)fgetc(stdin);+ payload[prompt_bytes] = 0;+ memset(request, 0, sizeof(*request));+ snprintf(request->id, sizeof(request->id), "%s", id);+ request->prompt = payload;+ request->prompt_bytes = prompt_bytes;+ request->max_tokens = max_tokens;+ request->temperature = temperature;+ request->top_p = top_p;+ request->extension_bytes = extension_bytes;+ return 2;+}++static void v4_serve_data(const char *id, const char *data, int bytes) {+ if (bytes <= 0) return;+ printf("DATA %s %d\n", id, bytes);+ fwrite(data, 1, (size_t)bytes, stdout);+ fputc('\n', stdout);+ fflush(stdout);+}++static int v4_serve_token(void *user_data, int token, float logit,+ int position, int ordinal) {+ (void)logit;+ (void)position;+ (void)ordinal;+ V4ServeStream *stream = user_data;+ if (token != 1) {+ char piece[1024];+ int bytes = tok_decode(&stream->session->tokenizer, &token, 1,+ piece, (int)sizeof(piece) - 1);+ v4_serve_data(stream->request_id, piece, bytes);+ }+ while (coli_stdin_readable()) {+ V4ServeRequest queued = {0};+ int result = v4_serve_read_request(&queued, stream->request_id);+ if (result < 0 || result == 1) {+ stream->cancelled = 1;+ free(queued.prompt);+ return 1;+ }+ if (result == 2) {+ printf("ERROR %s engine busy\n", queued.id);+ fflush(stdout);+ free(queued.prompt);+ }+ }+ return 0;+}++static void v4_serve_error(const char *id, const char *message) {+ char clean[512];+ snprintf(clean, sizeof(clean), "%s", message && *message ? message : "engine request failed");+ for (char *p = clean; *p; p++)+ if (*p == '\r' || *p == '\n') *p = ' ';+ printf("ERROR %s %s\n", id, clean);+ fflush(stdout);+}++static void v4_serve_one(ColiV4Engine *engine, ColiV4Session *session,+ V4ServeRequest *request) {+ if (request->extension_bytes) {+ v4_serve_error(request->id, "unsupported request extension");+ return;+ }+ if (request->temperature != 0.0f)+ fprintf(stderr, "[V4] temperature %.3g ignored; target engine is greedy\n",+ request->temperature);+ if (request->top_p != 1.0f)+ fprintf(stderr, "[V4] top_p %.3g ignored; target engine is greedy\n",+ request->top_p);++ int prompt_count = tok_encode(&session->tokenizer, request->prompt,+ request->prompt_bytes, session->prompt_ids,+ session->max_prompt_tokens + 16);+ int context = engine->runtime.context_tokens;+ if (prompt_count < 1 || prompt_count > session->max_prompt_tokens ||+ prompt_count + request->max_tokens > context) {+ char message[256];+ snprintf(message, sizeof(message),+ "CONTEXT_EXCEEDED prompt_tokens=%d requested=%d capacity=%d",+ prompt_count, request->max_tokens, context);+ v4_serve_error(request->id, message);+ return;+ }+ printf("ACCEPT %s %d\n", request->id, prompt_count);+ fflush(stdout);++ ColiExpertStoreStats before = {0}, after = {0};+ if (engine->experts && engine->experts->ops && engine->experts->ops->stats)+ engine->experts->ops->stats(engine->experts, &before);+ V4ServeStream stream = {session, request->id, 0};+ ColiV4SessionGenerateStats stats = {0};+ char error[512] = {0};+ double started = spec_now();+ int result = coli_v4_session_generate(+ session, request->prompt, (size_t)request->prompt_bytes,+ &(ColiV4SessionGenerateOptions){+ .max_new_tokens = request->max_tokens,+ .stop_at_sentence = 0,+ .no_dspark = 1,+ },+ v4_serve_token, &stream, &stats, error, sizeof(error));+ double elapsed = spec_now() - started;+ if (result) {+ v4_serve_error(request->id, error);+ return;+ }+ if (engine->experts && engine->experts->ops && engine->experts->ops->stats)+ engine->experts->ops->stats(engine->experts, &after);+ uint64_t hits = after.hits - before.hits;+ uint64_t misses = after.misses - before.misses;+ double hit_rate = hits + misses ? 100.0 * hits / (hits + misses) : 0.0;+ int completion = stats.generated_tokens - (stats.eos_stopped ? 1 : 0);+ if (completion < 0) completion = 0;+ int length_limited = !stream.cancelled && !stats.eos_stopped &&+ stats.generated_tokens >= request->max_tokens;+ double decode = stats.decode_sec > 0.0 ? stats.decode_sec : elapsed;+ printf("DONE %s STAT %d %.3f %.1f %.2f %d %d\n",+ request->id, completion,+ decode > 0.0 ? completion / decode : 0.0,+ hit_rate, v4_serve_rss_gb(), stats.prompt_tokens, length_limited);+ fflush(stdout);+}++static int v4_serve_main(void) {+ const char *model_dir = getenv("SNAP");+ if (!model_dir || !*model_dir) {+ fprintf(stderr, "set SNAP=<DeepSeek V4 model directory>\n");+ return 1;+ }+ int context = getenv("CTX") ? atoi(getenv("CTX")) : 4096;+ int max_tokens = getenv("NGEN") ? atoi(getenv("NGEN")) : 1024;+ if (context < 2) context = 4096;+ if (max_tokens < 1) max_tokens = 1024;+ char error[512] = {0};+ ColiV4Engine *engine = NULL;+ ColiV4Session *session = NULL;+ ColiV4EngineOpenOptions open_options = {+ .target_model_dir = model_dir,+ .context_tokens = context,+ .pin_slots_per_layer = -1,+ .no_dspark = 1,+ };+ const char *ram = getenv("RAM_GB");+ if (ram && atof(ram) > 0.0)+ open_options.memory_limit_bytes =+ (uint64_t)(atof(ram) * 1073741824.0);+ if (coli_v4_engine_open(&engine, &open_options, error, sizeof(error))) {+ fprintf(stderr, "%s\n", error);+ return 1;+ }+ context = engine->runtime.context_tokens;+ if (coli_v4_session_create(+ &session, engine,+ &(ColiV4SessionCreateOptions){+ .max_prompt_tokens = context,+ .max_new_tokens_cap = max_tokens,+ },+ error, sizeof(error))) {+ fprintf(stderr, "%s\n", error);+ coli_v4_engine_destroy(engine);+ return 1;+ }++ coli_serve_binary_mode();+ setvbuf(stdin, NULL, _IONBF, 0);+ fputs("\x01\x01READY\x01\x01\n", stdout);+ printf("STAT 0 0.0 0.0 %.2f 0 0\n", v4_serve_rss_gb());+ fflush(stdout);+ for (;;) {+ V4ServeRequest request = {0};+ int result;+ do result = v4_serve_read_request(&request, NULL); while (result == 0);+ if (result < 0) break;+ if (result == 2) {+ v4_serve_one(engine, session, &request);+ free(request.prompt);+ }+ }+ coli_v4_session_destroy(session);+ coli_v4_engine_destroy(engine);+ return 0;+}++#ifndef COLI_V4_SKIP_GENERATE_MAINint main(int argc, char **argv) {+ if (getenv("SERVE") && getenv("SERVE")[0] == '1')+ return v4_serve_main();double process_started = spec_now();int result = 1;V4CliOptions cli;@@ -7413,11 +7345,10 @@ int main(int argc, char **argv) {memset(&config, 0, sizeof(config));ColiSafetensorsIndex *index = NULL;ColiExpertStore *experts = NULL;- ColiV4DSparkRunner *runner = NULL;ColiDeepSeekV4WindowAttentionState **attention = NULL;int *prompt_ids = NULL;int *generated = NULL;- float *state = NULL, *next = NULL, *hidden = NULL, *main_x_batch = NULL;+ float *state = NULL, *next = NULL, *hidden = NULL;char *text = NULL;int *full_ids = NULL, *tf_pred = NULL;float *tf_state = NULL, *tf_next = NULL, *tf_hidden = NULL;@@ -7433,7 +7364,6 @@ int main(int argc, char **argv) {{ColiV4EngineOpenOptions open_opts = {.target_model_dir = cli.model_dir,- .dspark_model_dir = cli.draft_model_dir,.no_dspark = cli.no_dspark,.pin_slots_per_layer = -1,};@@ -7552,11 +7482,13 @@ int main(int argc, char **argv) {fprintf(stderr, "cannot build DeepSeek V4 prompt\n");goto cleanup;}- fprintf(stderr, "v4_cli mode=%s memory=%s draft_model=%s no_dspark=%d\n",+ if (cli.no_dspark)+ fprintf(stderr, "note: --no-dspark is a compatibility no-op; "+ "this build is target-only\n");+ fprintf(stderr, "v4_cli mode=%s memory=%s target_only=1\n",cli.prompt_mode == COLI_V4_PROMPT_RAW ? "raw" :cli.prompt_mode == COLI_V4_PROMPT_THINKING ? "thinking" : "chat",- cli.memory_gib > 0.0 ? "limited" : "auto",- cli.draft_model_dir, cli.no_dspark);+ cli.memory_gib > 0.0 ? "limited" : "auto");ColiV4SessionCreateOptions session_opts = {.max_prompt_tokens = 512,@@ -7593,19 +7525,13 @@ int main(int argc, char **argv) {experts->ops->stats(experts, &stats_end);fprintf(stderr, "v4_tokens prompt=%d generated=%d total=%d ""expert_requests=%llu hits=%llu misses=%llu hit_rate=%.3f "- "bytes=%llu speculative_rounds=%llu proposed=%llu accepted=%llu "- "acceptance=%.3f enabled=%d\n",+ "bytes=%llu target_only=1\n",gen_stats.prompt_tokens, gen_stats.generated_tokens,gen_stats.prompt_tokens + gen_stats.generated_tokens,(unsigned long long)stats_end.requests,(unsigned long long)stats_end.hits,(unsigned long long)stats_end.misses, stats_hit_rate(stats_end),- (unsigned long long)stats_end.bytes_read,- (unsigned long long)gen_stats.dspark_rounds,- (unsigned long long)gen_stats.dspark_proposed,- (unsigned long long)gen_stats.dspark_accepted,- gen_stats.dspark_acceptance,- !cli.no_dspark);+ (unsigned long long)stats_end.bytes_read);fprintf(stderr, "generated_text=");if (out_len) fwrite(out_text, 1, out_len, stderr);fprintf(stderr, "\ntiming time_to_first_token=%.3fs after_first=%.3fs\n",@@ -7679,9 +7605,9 @@ int main(int argc, char **argv) {}result = 0;cleanup:- v4_generate_cleanup(session, prompt_storage, engine, runner, attention,+ v4_generate_cleanup(session, prompt_storage, engine, attention,layers, prompt_ids, generated, state, next, hidden,- main_x_batch, text, full_ids, tf_pred, tf_state,+ text, full_ids, tf_pred, tf_state,tf_next, tf_hidden);return result;}@@ -7973,7 +7899,6 @@ int coli_v4_shared_expert_forward_ref(float *output,#include <stdlib.h>#include <string.h>-#include "safetensors_index.h"#ifdef COLI_V4_EXPERIMENTAL_PREFETCH_BATCHint coli_st_prefetch_many(@@ -8742,8 +8667,7 @@ int coli_v4_config_parse(ColiDeepSeekV4Config *config, const char *json,config->num_experts_per_tok < 1 ||config->num_experts_per_tok > config->n_routed_experts ||config->n_shared_experts != 1 || config->hc_mult < 1 ||- config->compress_ratio_count != config->num_hidden_layers +- config->num_nextn_predict_layers) {+ config->compress_ratio_count < config->num_hidden_layers) {json_free(root);free(arena);return set_error(error, error_size, "inconsistent DeepSeek-V4 config dimensions");diff --git a/c/deepseek_v4.h b/c/deepseek_v4.hindex a4271cff..107a0653 100644--- a/c/deepseek_v4.h+++ b/c/deepseek_v4.h@@ -77,13 +77,11 @@ typedef struct ColiV4Engine ColiV4Engine;typedef struct {/* Copied by coli_v4_engine_open; caller strings need not outlive the engine. */const char *target_model_dir; /* required */- const char *dspark_model_dir; /* NULL => same as target */uint64_t memory_limit_bytes; /* 0 => use OS available memory */int context_tokens; /* 0 => 4096 */- int verify_drafts; /* 0 => runner default */int pin_slots_per_layer; /* -1 => auto */uint64_t repin_interval; /* 0 => auto */- int no_dspark; /* skip all DSpark loading and capture */+ int no_dspark; /* compatibility no-op in target-only engine */} ColiV4EngineOpenOptions;typedef struct {@@ -91,7 +89,6 @@ typedef struct {uint64_t expert_cache_bytes;int slots_per_layer;int dense_resident;- int dspark_resident;int head_resident;} ColiV4EngineMemorySummary;@@ -107,7 +104,6 @@ void coli_v4_engine_memory_summary(const ColiV4Engine *engine,ColiV4EngineMemorySummary *summary);const char *coli_v4_engine_target_model_dir(const ColiV4Engine *engine);-const char *coli_v4_engine_dspark_model_dir(const ColiV4Engine *engine);/* ---- experimental public session API ----* Session borrows the engine; destroy all sessions before coli_v4_engine_destroy.@@ -123,17 +119,13 @@ typedef struct {typedef struct {int max_new_tokens; /* required; clamped by session cap */int stop_at_sentence;- int no_dspark;+ int no_dspark; /* compatibility no-op in target-only engine */} ColiV4SessionGenerateOptions;typedef struct {int prompt_tokens;int generated_tokens;int eos_stopped;- uint64_t dspark_rounds;- uint64_t dspark_proposed;- uint64_t dspark_accepted;- float dspark_acceptance;double time_to_first_token_sec;double decode_sec;} ColiV4SessionGenerateStats;diff --git a/c/deepseek_v4_dspark.c b/c/deepseek_v4_dspark.cdeleted file mode 100644index 09b88b32..00000000--- a/c/deepseek_v4_dspark.c+++ /dev/null@@ -1,4057 +0,0 @@-/* Amalgamated deepseek_v4_dspark.c — GLM-style source; compile with -DCOLI_V4_UNIT_* per object */-/* Umbrella API: deepseek_v4_dspark.h (included by units) */--#ifdef COLI_V4_UNIT_CONFIG_DSPARK_COMPAT-/* ######## deepseek_v4_config_dspark_compat.c ######## */-#include "deepseek_v4_dspark.h"-/* ---- begin inlined deepseek_v4_config_dspark_compat.c ---- */-#define coli_v4_config_parse coli_v4_config_parse_strict-#define coli_v4_config_load coli_v4_config_load_strict-/* ---- begin include deepseek_v4_config.c ---- */-#include "deepseek_v4_internal.h"--#include <float.h>-#include <limits.h>-#include <math.h>-#include <stdarg.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "json.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;-}--static int json_int_value(const jval *value, int *output) {- if (!value || value->t != J_NUM || !isfinite(value->num) ||- floor(value->num) != value->num ||- value->num < (double)INT_MIN || value->num > (double)INT_MAX)- return -1;- *output = (int)value->num;- return 0;-}--static int required_int(jval *root, const char *name, int *output,- char *error, size_t error_size) {- if (json_int_value(json_get(root, name), output) != 0)- return set_error(error, error_size, "invalid integer config field: %s", name);- return 0;-}--static int required_float(jval *root, const char *name, float *output,- char *error, size_t error_size) {- jval *value = json_get(root, name);- if (!value || value->t != J_NUM || !isfinite(value->num) ||- fabs(value->num) > (double)FLT_MAX)- return set_error(error, error_size, "invalid numeric config field: %s", name);- *output = (float)value->num;- return 0;-}--static int require_string(jval *root, const char *name, const char *expected,- char *error, size_t error_size) {- jval *value = json_get(root, name);- if (!value || value->t != J_STR || strcmp(value->str, expected))- return set_error(error, error_size, "unsupported %s (expected %s)",- name, expected);- return 0;-}--int coli_v4_config_parse(ColiDeepSeekV4Config *config, const char *json,- char *error, size_t error_size) {- if (!config || !json)- return set_error(error, error_size, "invalid DeepSeek-V4 config arguments");- memset(config, 0, sizeof(*config));- char *arena = NULL;- jval *root = json_parse(json, &arena);- if (!root || root->t != J_OBJ) {- json_free(root);- free(arena);- return set_error(error, error_size, "DeepSeek-V4 config is not an object");- }- int failed =- require_string(root, "model_type", "deepseek_v4", error, error_size) ||- require_string(root, "expert_dtype", "fp4", error, error_size) ||- require_string(root, "scoring_func", "sqrtsoftplus", error, error_size) ||- require_string(root, "topk_method", "noaux_tc", error, error_size) ||- required_int(root, "hidden_size", &config->hidden_size, error, error_size) ||- required_int(root, "num_hidden_layers", &config->num_hidden_layers, error, error_size) ||- required_int(root, "num_attention_heads", &config->num_attention_heads, error, error_size) ||- required_int(root, "head_dim", &config->head_dim, error, error_size) ||- required_int(root, "q_lora_rank", &config->q_lora_rank, error, error_size) ||- required_int(root, "qk_rope_head_dim", &config->qk_rope_head_dim, error, error_size) ||- required_int(root, "o_groups", &config->o_groups, error, error_size) ||- required_int(root, "o_lora_rank", &config->o_lora_rank, error, error_size) ||- required_int(root, "sliding_window", &config->sliding_window, error, error_size) ||- required_int(root, "index_n_heads", &config->index_n_heads, error, error_size) ||- required_int(root, "index_head_dim", &config->index_head_dim, error, error_size) ||- required_int(root, "index_topk", &config->index_topk, error, error_size) ||- required_int(root, "n_routed_experts", &config->n_routed_experts, error, error_size) ||- required_int(root, "num_experts_per_tok", &config->num_experts_per_tok, error, error_size) ||- required_int(root, "n_shared_experts", &config->n_shared_experts, error, error_size) ||- required_int(root, "moe_intermediate_size", &config->moe_intermediate_size, error, error_size) ||- required_int(root, "num_hash_layers", &config->num_hash_layers, error, error_size) ||- required_int(root, "num_nextn_predict_layers", &config->num_nextn_predict_layers, error, error_size) ||- required_int(root, "hc_mult", &config->hc_mult, error, error_size) ||- required_int(root, "hc_sinkhorn_iters", &config->hc_sinkhorn_iters, error, error_size) ||- required_int(root, "vocab_size", &config->vocab_size, error, error_size) ||- required_int(root, "max_position_embeddings", &config->max_position_embeddings, error, error_size) ||- required_float(root, "rms_norm_eps", &config->rms_norm_eps, error, error_size) ||- required_float(root, "hc_eps", &config->hc_eps, error, error_size) ||- required_float(root, "routed_scaling_factor", &config->routed_scaling_factor, error, error_size) ||- required_float(root, "swiglu_limit", &config->swiglu_limit, error, error_size) ||- required_float(root, "rope_theta", &config->rope_theta, error, error_size) ||- required_float(root, "compress_rope_theta", &config->compress_rope_theta, error, error_size);- if (failed) {- json_free(root);- free(arena);- return -1;- }- jval *rope = json_get(root, "rope_scaling");- if (!rope || rope->t != J_OBJ ||- required_int(rope, "original_max_position_embeddings",- &config->original_max_position_embeddings, error, error_size) ||- required_int(rope, "beta_fast", &config->rope_beta_fast, error, error_size) ||- required_int(rope, "beta_slow", &config->rope_beta_slow, error, error_size) ||- required_float(rope, "factor", &config->rope_factor, error, error_size)) {- json_free(root);- free(arena);- return -1;- }- jval *ratios = json_get(root, "compress_ratios");- if (!ratios || ratios->t != J_ARR || ratios->len < 1 ||- ratios->len > COLI_V4_MAX_LAYERS) {- json_free(root);- free(arena);- return set_error(error, error_size, "invalid compress_ratios");- }- config->compress_ratio_count = ratios->len;- for (int index = 0; index < ratios->len; index++) {- if (json_int_value(ratios->kids[index],- &config->compress_ratios[index]) != 0) {- json_free(root);- free(arena);- return set_error(error, error_size, "invalid compress ratio");- }- }- jval *quantization = json_get(root, "quantization_config");- if (!quantization || quantization->t != J_OBJ ||- require_string(quantization, "fmt", "e4m3", error, error_size) ||- require_string(quantization, "scale_fmt", "ue8m0", error, error_size)) {- json_free(root);- free(arena);- return -1;- }- if (config->hidden_size < 1 || config->num_hidden_layers < 1 ||- config->num_attention_heads < 1 || config->n_routed_experts < 1 ||- config->num_experts_per_tok < 1 ||- config->num_experts_per_tok > config->n_routed_experts ||- config->n_shared_experts != 1 || config->hc_mult < 1 ||- config->compress_ratio_count != config->num_hidden_layers +- config->num_nextn_predict_layers) {- json_free(root);- free(arena);- return set_error(error, error_size, "inconsistent DeepSeek-V4 config dimensions");- }- json_free(root);- free(arena);- return 0;-}--int coli_v4_config_load(ColiDeepSeekV4Config *config, const char *model_dir,- char *error, size_t error_size) {- if (!config || !model_dir)- return set_error(error, error_size, "invalid DeepSeek-V4 config path");- size_t path_length = strlen(model_dir) + sizeof("/config.json");- char *path = malloc(path_length);- if (!path) return set_error(error, error_size, "out of memory building config path");- snprintf(path, path_length, "%s/config.json", model_dir);- FILE *stream = fopen(path, "rb");- if (!stream) {- int result = set_error(error, error_size, "cannot open %s", path);- free(path);- return result;- }- fseek(stream, 0, SEEK_END);- long length = ftell(stream);- rewind(stream);- if (length < 1) {- fclose(stream);- free(path);- return set_error(error, error_size, "empty config: %s", model_dir);- }- char *text = malloc((size_t)length + 1);- if (!text || fread(text, 1, (size_t)length, stream) != (size_t)length) {- free(text);- fclose(stream);- free(path);- return set_error(error, error_size, "cannot read config: %s", model_dir);- }- text[length] = 0;- fclose(stream);- int result = coli_v4_config_parse(config, text, error, error_size);- free(text);- free(path);- return result;-}-/* ---- end include deepseek_v4_config.c ---- */--#undef coli_v4_config_load-#undef coli_v4_config_parse--int coli_v4_config_parse(ColiDeepSeekV4Config *config, const char *json,- char *error, size_t error_size) {- char strict_error[256] = {0};- int result = coli_v4_config_parse_strict(- config, json, strict_error, sizeof(strict_error));- if (!result) {- if (error && error_size) error[0] = 0;- return 0;- }- if (strcmp(strict_error, "inconsistent DeepSeek-V4 config dimensions") ||- !config || !json || !strstr(json, "\"dspark_block_size\"") ||- config->num_hidden_layers < 1 ||- config->compress_ratio_count <= config->num_hidden_layers)- return set_error(error, error_size, "%s", strict_error);- int inferred = config->compress_ratio_count - config->num_hidden_layers;- if (inferred < 1 || inferred > COLI_V4_DSPARK_MAX_STAGES)- return set_error(error, error_size, "%s", strict_error);- config->num_nextn_predict_layers = inferred;- if (config->hidden_size < 1 || config->num_hidden_layers < 1 ||- config->num_attention_heads < 1 || config->n_routed_experts < 1 ||- config->num_experts_per_tok < 1 ||- config->num_experts_per_tok > config->n_routed_experts ||- config->n_shared_experts != 1 || config->hc_mult < 1 ||- config->compress_ratio_count != config->num_hidden_layers +- config->num_nextn_predict_layers)- return set_error(error, error_size, "%s", strict_error);- if (error && error_size) error[0] = 0;- return 0;-}--int coli_v4_config_load(ColiDeepSeekV4Config *config, const char *model_dir,- char *error, size_t error_size) {- if (!config || !model_dir)- return set_error(error, error_size, "invalid DeepSeek-V4 config path");- size_t path_length = strlen(model_dir) + sizeof("/config.json");- char *path = malloc(path_length);- if (!path) return set_error(error, error_size, "out of memory building config path");- snprintf(path, path_length, "%s/config.json", model_dir);- FILE *stream = fopen(path, "rb");- if (!stream) { free(path); return set_error(error, error_size,- "cannot open config"); }- fseek(stream, 0, SEEK_END); long length = ftell(stream); rewind(stream);- char *text = length > 0 ? malloc((size_t)length + 1) : NULL;- if (!text || fread(text, 1, (size_t)length, stream) != (size_t)length) {- free(text); fclose(stream); free(path);- return set_error(error, error_size, "cannot read config");- }- text[length] = 0; fclose(stream);- int result = coli_v4_config_parse(config, text, error, error_size);- free(text); free(path); return result;-}-/* ---- end inlined deepseek_v4_config_dspark_compat.c ---- */-#endif /* COLI_V4_UNIT_CONFIG_DSPARK_COMPAT */--#ifdef COLI_V4_UNIT_DSPARK-/* ######## deepseek_v4_dspark.c ######## */-#include <string.h>--static char *dspark_second_dot(const char *text, int character) {- char *first = strchr(text, character);- return first ? strchr(first + 1, character) : NULL;-}--#define strchr dspark_second_dot-/* ---- begin inlined deepseek_v4_dspark.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdarg.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "json.h"-#include "safetensors_index.h"--static int dspark_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;-}--static char *read_config(const char *model_dir) {- size_t length = strlen(model_dir) + sizeof("/config.json");- char *path = malloc(length);- if (!path) return NULL;- snprintf(path, length, "%s/config.json", model_dir);- FILE *stream = fopen(path, "rb"); free(path);- if (!stream) return NULL;- fseek(stream, 0, SEEK_END); long bytes = ftell(stream); rewind(stream);- char *text = bytes > 0 ? malloc((size_t)bytes + 1) : NULL;- if (!text || fread(text, 1, (size_t)bytes, stream) != (size_t)bytes) {- free(text); fclose(stream); return NULL;- }- text[bytes] = 0; fclose(stream); return text;-}--static int json_integer(jval *root, const char *name, int *output) {- jval *value = json_get(root, name);- if (!value || value->t != J_NUM) return -1;- *output = (int)value->num; return 0;-}--int coli_v4_dspark_layer_plan(ColiDeepSeekV4LayerPlan *plan,- const ColiDeepSeekV4Config *config, int stage,- char *error, size_t error_size) {- if (!plan || !config || stage < 0 || stage >= COLI_V4_DSPARK_MAX_STAGES)- return dspark_error(error, error_size, "invalid DSpark layer plan");- ColiDeepSeekV4Config common = *config;- common.num_hash_layers = 0;- common.compress_ratios[0] = 0;- if (coli_v4_layer_plan(plan, &common, 0, error, error_size)) return -1;- plan->layer = stage;- plan->compression_ratio = 0;- plan->uses_hash_router = 0;- plan->has_compressor = 0;- plan->has_indexer = 0;- for (size_t i = 0; i < plan->tensor_count; i++) {- const char *suffix = strchr(plan->tensors[i].name, '.');- if (!suffix) return dspark_error(error, error_size,- "invalid common layer tensor name");- char rewritten[COLI_V4_MAX_TENSOR_NAME];- int written = snprintf(rewritten, sizeof(rewritten), "mtp.%d%s",- stage, suffix);- if (written < 0 || (size_t)written >= sizeof(rewritten))- return dspark_error(error, error_size, "DSpark tensor name too long");- strcpy(plan->tensors[i].name, rewritten);- }- return 0;-}--static int require_tensor(const ColiSafetensorsIndex *index, const char *name,- ColiSafetensorsDType dtype, int rank,- const int64_t *shape, uint64_t *bytes,- char *error, size_t error_size) {- const ColiSafetensorsTensor *tensor = coli_st_find(index, name);- if (!tensor) return dspark_error(error, error_size,- "missing DSpark tensor: %s", name);- if (tensor->dtype != dtype || tensor->rank != rank)- return dspark_error(error, error_size,- "DSpark dtype/rank mismatch: %s", name);- for (int i = 0; i < rank; i++)- if (tensor->shape[i] != shape[i])- return dspark_error(error, error_size,- "DSpark shape mismatch: %s", name);- *bytes += tensor->nbytes; return 0;-}--int coli_v4_dspark_inspect(const char *model_dir,- const ColiDeepSeekV4Config *config,- ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size) {- if (!model_dir || !config || !manifest)- return dspark_error(error, error_size, "invalid DSpark inspect arguments");- memset(manifest, 0, sizeof(*manifest));- char *text = read_config(model_dir), *arena = NULL;- jval *root = text ? json_parse(text, &arena) : NULL;- if (!root || root->t != J_OBJ ||- json_integer(root, "dspark_block_size", &manifest->block_size) ||- json_integer(root, "dspark_noise_token_id", &manifest->noise_token_id) ||- json_integer(root, "dspark_markov_rank", &manifest->markov_rank)) {- free(arena); free(text);- return dspark_error(error, error_size, "missing DSpark config fields");- }- jval *targets = json_get(root, "dspark_target_layer_ids");- if (!targets || targets->t != J_ARR || targets->len < 1 ||- targets->len > COLI_V4_DSPARK_MAX_TARGETS) {- free(arena); free(text);- return dspark_error(error, error_size, "invalid DSpark target layers");- }- manifest->target_count = targets->len;- for (int i = 0; i < targets->len; i++) {- if (targets->kids[i]->t != J_NUM) {- free(arena); free(text);- return dspark_error(error, error_size, "invalid DSpark target layer");- }- manifest->target_layer_ids[i] = (int)targets->kids[i]->num;- }- free(arena); free(text);-- ColiSafetensorsIndex *index = NULL;- if (coli_st_index_open(&index, model_dir, error, error_size)) return -1;- char name[160];- for (int stage = 0; stage < COLI_V4_DSPARK_MAX_STAGES; stage++) {- snprintf(name, sizeof(name), "mtp.%d.attn_norm.weight", stage);- if (!coli_st_find(index, name)) break;- manifest->stage_count++;- ColiDeepSeekV4LayerPlan plan;- ColiDeepSeekV4LayerStats stats;- if (coli_v4_dspark_layer_plan(&plan, config, stage, error, error_size) ||- coli_v4_layer_validate(&plan, index, &stats, error, error_size)) {- coli_st_index_close(index); return -1;- }- manifest->common_stage_bytes[stage] = stats.total_bytes;- }- if (manifest->stage_count < 1) {- coli_st_index_close(index);- return dspark_error(error, error_size, "checkpoint has no DSpark stages");- }- int64_t main_weight[] = {config->hidden_size,- (int64_t)config->hidden_size * manifest->target_count};- int64_t main_scale[] = {(config->hidden_size + 127) / 128,- (main_weight[1] + 127) / 128};- int64_t hidden[] = {config->hidden_size};- int last = manifest->stage_count - 1;- int64_t markov[] = {config->vocab_size, manifest->markov_rank};- int64_t confidence[] = {1, config->hidden_size + manifest->markov_rank};- snprintf(name, sizeof(name), "mtp.0.main_proj.weight");- int failed = require_tensor(index, name, COLI_ST_F8_E4M3, 2, main_weight,- &manifest->special_bytes, error, error_size);- snprintf(name, sizeof(name), "mtp.0.main_proj.scale");- failed |= require_tensor(index, name, COLI_ST_F8_E8M0, 2, main_scale,- &manifest->special_bytes, error, error_size);- failed |= require_tensor(index, "mtp.0.main_norm.weight", COLI_ST_BF16, 1,- hidden, &manifest->special_bytes, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.norm.weight", last);- failed |= require_tensor(index, name, COLI_ST_BF16, 1, hidden,- &manifest->special_bytes, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.markov_head.markov_w1.weight", last);- failed |= require_tensor(index, name, COLI_ST_BF16, 2, markov,- &manifest->special_bytes, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.markov_head.markov_w2.weight", last);- failed |= require_tensor(index, name, COLI_ST_BF16, 2, markov,- &manifest->special_bytes, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.confidence_head.proj.weight", last);- failed |= require_tensor(index, name, COLI_ST_BF16, 2, confidence,- &manifest->special_bytes, error, error_size);- coli_st_index_close(index);- return failed ? -1 : 0;-}-/* ---- end inlined deepseek_v4_dspark.c ---- */--#undef strchr-#endif /* COLI_V4_UNIT_DSPARK */--#ifdef COLI_V4_UNIT_DSPARK_MEMORY-/* ######## deepseek_v4_dspark_memory.c ######## */-#define coli_v4_dspark_memory_plan coli_v4_dspark_memory_plan_unmargined-/* ---- begin inlined deepseek_v4_dspark_memory.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdio.h>-#include <string.h>--#include "deepseek_v4_dspark.h"-#include "safetensors_index.h"--#define DSPARK_MIB UINT64_C(1048576)--int coli_v4_dspark_memory_plan(const char *model_dir,- const ColiDeepSeekV4Config *config,- ColiV4DSparkMemoryPlan *plan,- char *error, size_t error_size) {- if (!model_dir || !config || !plan) return -1;- memset(plan, 0, sizeof(*plan));- ColiDeepSeekV4DSparkManifest manifest;- if (coli_v4_dspark_inspect(model_dir, config, &manifest,- error, error_size)) return -1;- plan->stages = manifest.stage_count;- plan->expert_slots_per_stage = config->num_experts_per_tok;- plan->resident_heads_bytes = manifest.special_bytes;- for (int i = 0; i < manifest.stage_count; i++)- if (manifest.common_stage_bytes[i] > plan->streamed_stage_bytes)- plan->streamed_stage_bytes = manifest.common_stage_bytes[i];- ColiSafetensorsIndex *index = NULL;- if (coli_st_index_open(&index, model_dir, error, error_size)) return -1;- static const char *parts[] = {- "mtp.0.ffn.experts.0.w1.weight", "mtp.0.ffn.experts.0.w1.scale",- "mtp.0.ffn.experts.0.w2.weight", "mtp.0.ffn.experts.0.w2.scale",- "mtp.0.ffn.experts.0.w3.weight", "mtp.0.ffn.experts.0.w3.scale",- };- for (size_t i = 0; i < sizeof(parts) / sizeof(parts[0]); i++) {- const ColiSafetensorsTensor *tensor = coli_st_find(index, parts[i]);- if (!tensor) { coli_st_index_close(index); return -1; }- plan->expert_record_bytes += tensor->nbytes;- }- coli_st_index_close(index);- plan->minimum_expert_cache_bytes = plan->expert_record_bytes *- (uint64_t)plan->stages * config->num_experts_per_tok;- uint64_t capture = (uint64_t)64 * manifest.target_count * config->hc_mult *- config->hidden_size * sizeof(float);- uint64_t query = (uint64_t)64 * config->hc_mult * config->hidden_size *- sizeof(float) * 2;- uint64_t kv = (uint64_t)manifest.stage_count *- (config->sliding_window + 64) * config->head_dim * sizeof(float);- plan->working_bytes = 64 * DSPARK_MIB + capture + query + kv;- plan->incremental_reserve_bytes = plan->resident_heads_bytes +- plan->streamed_stage_bytes + plan->minimum_expert_cache_bytes +- plan->working_bytes;- return 0;-}-/* ---- end inlined deepseek_v4_dspark_memory.c ---- */--#undef coli_v4_dspark_memory_plan--int coli_v4_dspark_memory_plan(const char *model_dir,- const ColiDeepSeekV4Config *config,- ColiV4DSparkMemoryPlan *plan,- char *error, size_t error_size) {- int result = coli_v4_dspark_memory_plan_unmargined(- model_dir, config, plan, error, error_size);- if (result) return result;- /* Native FP8/FP4 batch kernels and OpenMP allocate short-lived per-thread- buffers outside the explicit query/KV arrays. Keep this model-size-- independent margin in the RAM tier plan so low-memory hosts do not lend- the same bytes to the target expert cache. */- uint64_t allocator_margin = 256 * DSPARK_MIB;- if (UINT64_MAX - plan->working_bytes < allocator_margin ||- UINT64_MAX - plan->incremental_reserve_bytes < allocator_margin)- return -1;- plan->working_bytes += allocator_margin;- plan->incremental_reserve_bytes += allocator_margin;- return 0;-}-#endif /* COLI_V4_UNIT_DSPARK_MEMORY */--#ifdef COLI_V4_UNIT_DSPARK_RUNTIME_RESIDENT-/* ######## deepseek_v4_dspark_runtime_resident.c ######## */-#define coli_v4_dspark_layer_load coli_v4_dspark_layer_reference_load-/* ---- begin include deepseek_v4_dspark_runtime.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdarg.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--static int runtime_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;-}--static void add_stats(ColiDeepSeekV4LayerStats *stats,- const ColiSafetensorsTensor *tensor) {- stats->tensor_count++; stats->total_bytes += tensor->nbytes;- switch (tensor->dtype) {- case COLI_ST_BF16: stats->bf16_bytes += tensor->nbytes; break;- case COLI_ST_F32: stats->f32_bytes += tensor->nbytes; break;- case COLI_ST_F8_E4M3: stats->fp8_weight_bytes += tensor->nbytes; break;- case COLI_ST_F8_E8M0: stats->fp8_scale_bytes += tensor->nbytes; break;- case COLI_ST_I64: stats->i64_bytes += tensor->nbytes; break;- default: break;- }-}--int coli_v4_dspark_layer_load(ColiV4Engine *engine,- ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const ColiSafetensorsIndex *index, int stage,- char *error, size_t error_size) {- (void)engine;- if (!weights || !config || !index)- return runtime_error(error, error_size, "invalid DSpark layer load");- memset(weights, 0, sizeof(*weights));- if (coli_v4_dspark_layer_plan(&weights->plan, config, stage,- error, error_size)) return -1;- for (size_t i = 0; i < weights->plan.tensor_count; i++) {- ColiDeepSeekV4TensorSpec *spec = &weights->plan.tensors[i];- char actual[COLI_V4_MAX_TENSOR_NAME];- strcpy(actual, spec->name);- const ColiSafetensorsTensor *tensor = coli_st_find(index, actual);- if (!tensor || tensor->dtype != spec->dtype ||- tensor->rank != spec->rank) {- coli_v4_layer_free(NULL, weights);- return runtime_error(error, error_size,- "invalid DSpark tensor: %s", actual);- }- for (int dimension = 0; dimension < spec->rank; dimension++)- if (tensor->shape[dimension] != spec->shape[dimension]) {- coli_v4_layer_free(NULL, weights);- return runtime_error(error, error_size,- "DSpark shape mismatch: %s", actual);- }- weights->data[i] = malloc((size_t)tensor->nbytes);- if (!weights->data[i] ||- coli_st_read_tensor(index, tensor, weights->data[i])) {- coli_v4_layer_free(NULL, weights);- return runtime_error(error, error_size,- "cannot load DSpark tensor: %s", actual);- }- add_stats(&weights->stats, tensor);- const char *suffix = actual + strlen("mtp.0");- int prefix = snprintf(spec->name, sizeof(spec->name),- "layers.%d", stage);- size_t suffix_length = strlen(suffix);- if (prefix < 0 || (size_t)prefix + suffix_length >= sizeof(spec->name)) {- coli_v4_layer_free(NULL, weights);- return runtime_error(error, error_size,- "DSpark runtime tensor name is too long");- }- memcpy(spec->name + prefix, suffix, suffix_length + 1);- }- return 0;-}-/* ---- end include deepseek_v4_dspark_runtime.c ---- */--#undef coli_v4_dspark_layer_load--#include "deepseek_v4_dspark.h"-#include "deepseek_v4_internal.h"--static int dspark_stages_resident(ColiV4Engine *engine) {- return engine && engine->runtime.dspark_resident;-}--int coli_v4_dspark_layer_load(ColiV4Engine *engine,- ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const ColiSafetensorsIndex *index, int stage,- char *error, size_t error_size) {- if (!dspark_stages_resident(engine))- return coli_v4_dspark_layer_reference_load(- engine, weights, config, index, stage, error, error_size);- if (!engine || !weights || !config || !index || stage < 0 ||- stage >= COLI_V4_DSPARK_MAX_STAGES) return -1;- if (engine->dspark_resident.index &&- engine->dspark_resident.index != index) {- if (error && error_size)- snprintf(error, error_size,- "resident DSpark stages cannot switch model instances");- return -1;- }- engine->dspark_resident.index = index;- if (!engine->dspark_resident.ready[stage]) {- if (coli_v4_dspark_layer_reference_load(- engine, &engine->dspark_resident.layers[stage], config, index,- stage, error, error_size)) return -1;- engine->dspark_resident.ready[stage] = 1;- engine->dspark_resident.total_bytes +=- engine->dspark_resident.layers[stage].stats.total_bytes;- fprintf(stderr, "dspark_stage_resident stage=%d total=%.3fGiB\n",- stage, engine->dspark_resident.total_bytes / 1073741824.0);- }- *weights = engine->dspark_resident.layers[stage]; return 0;-}--void coli_v4_dspark_layer_release(ColiV4Engine *engine,- ColiDeepSeekV4LayerWeights *weights) {- if (!weights) return;- int stage = weights->plan.layer;- if (dspark_stages_resident(engine) && engine && stage >= 0 &&- stage < COLI_V4_DSPARK_MAX_STAGES &&- engine->dspark_resident.ready[stage] &&- weights->data[0] == engine->dspark_resident.layers[stage].data[0]) {- memset(weights, 0, sizeof(*weights)); return;- }- coli_v4_layer_free(engine, weights);-}-#endif /* COLI_V4_UNIT_DSPARK_RUNTIME_RESIDENT */--#ifdef COLI_V4_UNIT_DSPARK_EXPERT_STORE-/* ######## deepseek_v4_dspark_expert_store.c ######## */-#include <stdarg.h>-#include <stdio.h>-#include <string.h>--#include "deepseek_v4_dspark.h"--static int dspark_store_snprintf_v2(char *output, size_t size,- const char *format, ...) {- char rewritten[256];- /* strlen("layers.%d.ffn.experts.") is 22. Comparing 23 bytes also- * compares the literal NUL with the following '%' in the real format,- * preventing the mtp namespace rewrite and loading target experts. */- if (!strncmp(format, "layers.%d.ffn.experts.", 22))- snprintf(rewritten, sizeof(rewritten), "mtp.%s", format + 7);- else- snprintf(rewritten, sizeof(rewritten), "%s", format);- va_list arguments; va_start(arguments, format);- int result = vsnprintf(output, size, rewritten, arguments);- va_end(arguments); return result;-}--#define snprintf dspark_store_snprintf_v2-#define coli_deepseek_v4_expert_store_open \- coli_deepseek_v4_dspark_expert_store_open-/* ---- begin include deepseek_v4_expert_store.c ---- */-#define _GNU_SOURCE-#include "deepseek_v4_internal.h"--#include <assert.h>-#include <pthread.h>-#include <stdarg.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "safetensors_index.h"--#ifdef COLI_V4_EXPERIMENTAL_PREFETCH_BATCH-int coli_st_prefetch_many(- const ColiSafetensorsIndex *index, const int *shards,- const uint64_t *offsets, const size_t *lengths, size_t count);-#endif--enum { V4_W1 = 0, V4_W2 = 1, V4_W3 = 2, V4_MATRIX_COUNT = 3 };--typedef struct {- const ColiSafetensorsTensor *weight[V4_MATRIX_COUNT];- const ColiSafetensorsTensor *scale[V4_MATRIX_COUNT];- int shard;- uint64_t scale_offset;- uint64_t scale_bytes;- uint64_t weight_offset;- uint64_t weight_bytes;- uint64_t record_bytes;-} V4ExpertRecord;--typedef struct {- int expert;- unsigned references;- uint64_t used;- unsigned char *slab;-} V4ExpertSlot;--typedef struct {- ColiSafetensorsIndex *index;- int layers;- int experts_per_layer;- int slots_per_layer;- uint64_t record_bytes;- V4ExpertRecord *records;- V4ExpertSlot *slots;- uint64_t clock;- unsigned active_leases;- ColiExpertStoreStats stats;- pthread_mutex_t mutex;-} V4ExpertStoreState;--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 int compare_tensors(const void *left, const void *right) {- const ColiSafetensorsTensor *const *a = left;- const ColiSafetensorsTensor *const *b = right;- return ((*a)->offset > (*b)->offset) - ((*a)->offset < (*b)->offset);-}--static int contiguous_group(const ColiSafetensorsTensor *const input[3],- int *shard, uint64_t *offset, uint64_t *bytes) {- const ColiSafetensorsTensor *parts[3] = {input[0], input[1], input[2]};- qsort(parts, 3, sizeof(parts[0]), compare_tensors);- if (parts[0]->shard != parts[1]->shard || parts[1]->shard != parts[2]->shard ||- parts[0]->offset + parts[0]->nbytes != parts[1]->offset ||- parts[1]->offset + parts[1]->nbytes != parts[2]->offset)- return -1;- *shard = parts[0]->shard;- *offset = parts[0]->offset;- *bytes = parts[2]->offset + parts[2]->nbytes - parts[0]->offset;- return 0;-}--static int validate_matrix(const ColiSafetensorsTensor *weight,- const ColiSafetensorsTensor *scale) {- if (!weight || !scale || weight->dtype != COLI_ST_I8 ||- scale->dtype != COLI_ST_F8_E8M0 || weight->rank != 2 || scale->rank != 2 ||- weight->shape[0] != scale->shape[0] || weight->shape[1] <= 0 ||- scale->shape[1] <= 0)- return -1;- int64_t logical_columns = weight->shape[1] * 2;- return scale->shape[1] * 32 == logical_columns ? 0 : -1;-}--static int build_record(V4ExpertStoreState *state, int layer, int expert,- V4ExpertRecord *record, char *error, size_t error_size) {- static const char *matrix_names[V4_MATRIX_COUNT] = {"w1", "w2", "w3"};- char name[160];- memset(record, 0, sizeof(*record));- for (int matrix = 0; matrix < V4_MATRIX_COUNT; matrix++) {- snprintf(name, sizeof(name), "layers.%d.ffn.experts.%d.%s.weight",- layer, expert, matrix_names[matrix]);- record->weight[matrix] = coli_st_find(state->index, name);- snprintf(name, sizeof(name), "layers.%d.ffn.experts.%d.%s.scale",- layer, expert, matrix_names[matrix]);- record->scale[matrix] = coli_st_find(state->index, name);- if (validate_matrix(record->weight[matrix], record->scale[matrix]) != 0)- return set_error(error, error_size,- "invalid native FP4 expert matrix: layer=%d expert=%d %s",- layer, expert, matrix_names[matrix]);- }- int scale_shard = -1, weight_shard = -1;- if (contiguous_group(record->scale, &scale_shard, &record->scale_offset,- &record->scale_bytes) != 0 ||- contiguous_group(record->weight, &weight_shard, &record->weight_offset,- &record->weight_bytes) != 0 || scale_shard != weight_shard)- return set_error(error, error_size,- "expert is not two contiguous ranges: layer=%d expert=%d",- layer, expert);- record->shard = scale_shard;- record->record_bytes = record->scale_bytes + record->weight_bytes;- return 0;-}--static V4ExpertRecord *get_record(V4ExpertStoreState *state, ColiExpertKey key) {- if (key.layer < 0 || key.layer >= state->layers || key.expert < 0 ||- key.expert >= state->experts_per_layer)- return NULL;- return &state->records[(size_t)key.layer * state->experts_per_layer + key.expert];-}--static V4ExpertSlot *layer_slots(V4ExpertStoreState *state, int layer) {- return state->slots + (size_t)layer * state->slots_per_layer;-}--static void fill_tensor_view(ColiTensorView *view,- const V4ExpertRecord *record,- const V4ExpertSlot *slot, int matrix) {- const ColiSafetensorsTensor *weight = record->weight[matrix];- const ColiSafetensorsTensor *scale = record->scale[matrix];- memset(view, 0, sizeof(*view));- view->format = COLI_TENSOR_FP4_NATIVE_BLOCK;- view->scale_format = COLI_SCALE_UE8M0;- view->data = slot->slab + record->scale_bytes +- (weight->offset - record->weight_offset);- view->scales = slot->slab + (scale->offset - record->scale_offset);- view->data_bytes = (size_t)weight->nbytes;- view->scale_bytes = (size_t)scale->nbytes;- view->rows = weight->shape[0];- view->columns = weight->shape[1] * 2;- view->block_rows = 1;- view->block_columns = 32;-}--static int lookup(ColiExpertStore *store, ColiExpertKey key,- ColiExpertView *view) {- if (!store || !store->state || !view) {- if (view) memset(view, 0, sizeof(*view));- return -1;- }- V4ExpertStoreState *state = store->state;- V4ExpertRecord *record = get_record(state, key);- if (!record) {- memset(view, 0, sizeof(*view));- return -1;- }- pthread_mutex_lock(&state->mutex);- state->stats.requests++;- V4ExpertSlot *slots = layer_slots(state, key.layer);- V4ExpertSlot *slot = NULL;- for (int i = 0; i < state->slots_per_layer; i++) {- if (slots[i].slab && slots[i].expert == key.expert) {- slot = &slots[i];- state->stats.hits++;- break;- }- }- if (!slot) {- for (int i = 0; i < state->slots_per_layer; i++) {- if (!slots[i].references && (!slot || !slots[i].slab ||- (slot->slab && slots[i].used < slot->used)))- slot = &slots[i];- }- if (!slot) {- pthread_mutex_unlock(&state->mutex);- memset(view, 0, sizeof(*view));- return -1;- }- if (!slot->slab) {- slot->slab = malloc((size_t)state->record_bytes);- if (!slot->slab) {- pthread_mutex_unlock(&state->mutex);- memset(view, 0, sizeof(*view));- return -1;- }- state->stats.resident_bytes += state->record_bytes;- }- /* A short read must never expose a partially overwritten old slot. */- slot->expert = -1;- if (coli_st_read_at(state->index, record->shard, record->scale_offset,- (size_t)record->scale_bytes, slot->slab) != 0 ||- coli_st_read_at(state->index, record->shard, record->weight_offset,- (size_t)record->weight_bytes,- slot->slab + record->scale_bytes) != 0) {- pthread_mutex_unlock(&state->mutex);- memset(view, 0, sizeof(*view));- return -1;- }- slot->expert = key.expert;- state->stats.misses++;- state->stats.bytes_read += record->record_bytes;- }- slot->references++;- state->active_leases++;- slot->used = ++state->clock;- memset(view, 0, sizeof(*view));- view->key = key;- fill_tensor_view(&view->gate, record, slot, V4_W1);- fill_tensor_view(&view->down, record, slot, V4_W2);- fill_tensor_view(&view->up, record, slot, V4_W3);- view->lease = slot;- pthread_mutex_unlock(&state->mutex);- return 0;-}--static void release(ColiExpertStore *store, ColiExpertView *view) {- if (!store || !store->state || !view || !view->lease) {- if (view) memset(view, 0, sizeof(*view));- return;- }- V4ExpertStoreState *state = store->state;- V4ExpertSlot *slot = view->lease;- pthread_mutex_lock(&state->mutex);- if (slot->references) slot->references--;- if (state->active_leases) state->active_leases--;- pthread_mutex_unlock(&state->mutex);- memset(view, 0, sizeof(*view));-}--static int prefetch(ColiExpertStore *store, const ColiExpertKey *keys,- size_t count) {- if (!store || !store->state || (!keys && count)) return 0;- V4ExpertStoreState *state = store->state;- int accepted = 0;-#ifdef COLI_V4_EXPERIMENTAL_PREFETCH_BATCH- size_t capacity = count * 2, ranges = 0;- int *shards = malloc(capacity * sizeof(*shards));- uint64_t *offsets = malloc(capacity * sizeof(*offsets));- size_t *lengths = malloc(capacity * sizeof(*lengths));- int candidates = 0;- if ((!shards || !offsets || !lengths) && capacity) {- free(lengths); free(offsets); free(shards); return 0;- }- pthread_mutex_lock(&state->mutex);- for (size_t i = 0; i < count; i++) {- V4ExpertRecord *record = get_record(state, keys[i]);- if (!record) continue;- int resident = 0;- V4ExpertSlot *slots = layer_slots(state, keys[i].layer);- for (int slot = 0; slot < state->slots_per_layer; slot++)- if (slots[slot].slab && slots[slot].expert == keys[i].expert) {- resident = 1; break;- }- if (resident) continue;- shards[ranges] = record->shard;- offsets[ranges] = record->scale_offset;- lengths[ranges++] = (size_t)record->scale_bytes;- shards[ranges] = record->shard;- offsets[ranges] = record->weight_offset;- lengths[ranges++] = (size_t)record->weight_bytes;- candidates++;- }- pthread_mutex_unlock(&state->mutex);- if (candidates && !coli_st_prefetch_many(- state->index, shards, offsets, lengths, ranges))- accepted = candidates;- free(lengths); free(offsets); free(shards);-#else- for (size_t i = 0; i < count; i++) {- V4ExpertRecord *record = get_record(state, keys[i]);- if (!record) continue;- if (coli_st_prefetch_at(state->index, record->shard, record->scale_offset,- (size_t)record->scale_bytes) == 0 &&- coli_st_prefetch_at(state->index, record->shard, record->weight_offset,- (size_t)record->weight_bytes) == 0)- accepted++;- }-#endif- pthread_mutex_lock(&state->mutex);- state->stats.prefetched += (uint64_t)accepted;- pthread_mutex_unlock(&state->mutex);- return accepted;-}--static void stats(const ColiExpertStore *store, ColiExpertStoreStats *output) {- if (!store || !store->state || !output) return;- V4ExpertStoreState *state = store->state;- pthread_mutex_lock(&state->mutex);- *output = state->stats;- pthread_mutex_unlock(&state->mutex);-}--static void destroy(ColiExpertStore *store) {- if (!store) return;- V4ExpertStoreState *state = store->state;- if (state) {- assert(state->active_leases == 0 && "destroy with active expert leases");- for (int i = 0; i < state->layers * state->slots_per_layer; i++)- free(state->slots[i].slab);- pthread_mutex_destroy(&state->mutex);- coli_st_index_close(state->index);- free(state->records);- free(state->slots);- free(state);- }- free(store);-}--int coli_deepseek_v4_expert_store_open(- const ColiDeepSeekV4ExpertStoreOptions *options, ColiExpertStore **output,- char *error, size_t error_size) {- static const ColiExpertStoreOps operations = {- lookup, release, prefetch, stats, destroy- };- if (!options || !output || !options->model_dir || options->layers < 1 ||- options->experts_per_layer < 1 || !options->cache_bytes)- return set_error(error, error_size, "invalid DeepSeek-V4 ExpertStore options");- *output = NULL;- ColiExpertStore *store = calloc(1, sizeof(*store));- V4ExpertStoreState *state = calloc(1, sizeof(*state));- if (!store || !state) {- free(store);- free(state);- return set_error(error, error_size, "out of memory creating ExpertStore");- }- pthread_mutex_init(&state->mutex, NULL);- state->layers = options->layers;- state->experts_per_layer = options->experts_per_layer;- if (coli_st_index_open(&state->index, options->model_dir, error, error_size) != 0)- goto fail;- size_t record_count = (size_t)state->layers * state->experts_per_layer;- state->records = calloc(record_count, sizeof(*state->records));- if (!state->records) {- set_error(error, error_size, "out of memory creating expert manifest");- goto fail;- }- for (int layer = 0; layer < state->layers; layer++) {- for (int expert = 0; expert < state->experts_per_layer; expert++) {- V4ExpertRecord *record = &state->records[- (size_t)layer * state->experts_per_layer + expert];- if (build_record(state, layer, expert, record, error, error_size) != 0)- goto fail;- if (!state->record_bytes) state->record_bytes = record->record_bytes;- if (record->record_bytes != state->record_bytes) {- set_error(error, error_size, "non-uniform expert size at layer=%d expert=%d",- layer, expert);- goto fail;- }- }- }- state->slots_per_layer = (int)(options->cache_bytes /- ((uint64_t)state->layers * state->record_bytes));- int minimum_slots = state->experts_per_layer < 6- ? state->experts_per_layer : 6;- if (state->slots_per_layer < minimum_slots) {- set_error(error, error_size,- "cache budget cannot hold %d active experts per layer "- "(need %llu bytes)", minimum_slots,- (unsigned long long)((uint64_t)state->layers * minimum_slots *- state->record_bytes));- goto fail;- }- if (state->slots_per_layer > state->experts_per_layer)- state->slots_per_layer = state->experts_per_layer;- state->slots = calloc((size_t)state->layers * state->slots_per_layer,- sizeof(*state->slots));- if (!state->slots) {- set_error(error, error_size, "out of memory creating expert cache slots");- goto fail;- }- for (int i = 0; i < state->layers * state->slots_per_layer; i++)- state->slots[i].expert = -1;- state->stats.capacity_bytes = (uint64_t)state->layers *- state->slots_per_layer * state->record_bytes;- store->ops = &operations;- store->state = state;- *output = store;- return 0;--fail:- if (state->slots) free(state->slots);- free(state->records);- coli_st_index_close(state->index);- pthread_mutex_destroy(&state->mutex);- free(state);- free(store);- return -1;-}-/* ---- end include deepseek_v4_expert_store.c ---- */--#undef coli_deepseek_v4_expert_store_open-#undef snprintf-#endif /* COLI_V4_UNIT_DSPARK_EXPERT_STORE */--#ifdef COLI_V4_UNIT_DSPARK_ATTENTION-/* ######## deepseek_v4_dspark_attention.c ######## */-/* ---- begin inlined deepseek_v4_dspark_attention.c ---- */-#include "deepseek_v4_dspark.h"--#include <math.h>-#include <stdarg.h>-#include <stdint.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "native_quant.h"-#include "native_quant_batch.h"--struct ColiV4DSparkAttentionState {- int window_size;- int head_dim;- int valid;- float *kv;- int *positions;-};--static int ds_attn_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;-}--static const void *ds_layer_data(const ColiDeepSeekV4LayerWeights *weights,- const char *suffix,- const ColiDeepSeekV4TensorSpec **spec) {- char name[COLI_V4_MAX_TENSOR_NAME];- snprintf(name, sizeof(name), "layers.%d.%s", weights->plan.layer, suffix);- return coli_v4_layer_data(weights, name, spec);-}--static int ds_fp8_view(ColiTensorView *view,- const ColiDeepSeekV4LayerWeights *weights,- const char *prefix) {- char name[128]; const ColiDeepSeekV4TensorSpec *ws = NULL, *ss = NULL;- snprintf(name, sizeof(name), "%s.weight", prefix);- const void *data = ds_layer_data(weights, name, &ws);- snprintf(name, sizeof(name), "%s.scale", prefix);- const void *scales = ds_layer_data(weights, name, &ss);- if (!data || !scales || !ws || !ss || ws->rank != 2 || ss->rank != 2)- return -1;- memset(view, 0, sizeof(*view));- view->format = COLI_TENSOR_FP8_E4M3_BLOCK;- view->scale_format = COLI_SCALE_UE8M0;- view->data = data; view->scales = scales;- view->rows = ws->shape[0]; view->columns = ws->shape[1];- view->data_bytes = (size_t)view->rows * view->columns;- view->scale_bytes = (size_t)ss->shape[0] * ss->shape[1];- view->block_rows = 128; view->block_columns = 128;- return 0;-}--int coli_v4_dspark_attention_create(ColiV4DSparkAttentionState **output,- const ColiDeepSeekV4Config *config) {- if (!output || !config || config->sliding_window < 1 || config->head_dim < 1)- return -1;- *output = NULL;- ColiV4DSparkAttentionState *state = calloc(1, sizeof(*state));- if (!state) return -1;- state->window_size = config->sliding_window;- state->head_dim = config->head_dim;- state->kv = calloc((size_t)state->window_size * state->head_dim,- sizeof(*state->kv));- state->positions = malloc((size_t)state->window_size *- sizeof(*state->positions));- if (!state->kv || !state->positions) {- coli_v4_dspark_attention_destroy(state); return -1;- }- coli_v4_dspark_attention_reset(state); *output = state; return 0;-}--void coli_v4_dspark_attention_reset(ColiV4DSparkAttentionState *state) {- if (!state) return;- state->valid = 0;- memset(state->kv, 0, (size_t)state->window_size * state->head_dim *- sizeof(*state->kv));- for (int i = 0; i < state->window_size; i++) state->positions[i] = -1;-}--void coli_v4_dspark_attention_destroy(ColiV4DSparkAttentionState *state) {- if (!state) return;- free(state->positions); free(state->kv); free(state);-}--int coli_v4_dspark_attention_context_count(- const ColiV4DSparkAttentionState *state) { return state ? state->valid : 0; }--int coli_v4_dspark_attention_precompute_context(- ColiV4DSparkAttentionState *state,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const float *main_x, int start_position, int batch,- char *error, size_t error_size) {- if (!state || !weights || !config || !main_x || start_position < 0 ||- batch < 1 || batch > 64 || state->head_dim != config->head_dim)- return ds_attn_error(error, error_size, "invalid DSpark context KV input");- ColiTensorView wkv;- if (ds_fp8_view(&wkv, weights, "attn.wkv"))- return ds_attn_error(error, error_size, "missing DSpark wkv");- int d = config->head_dim, rope = config->qk_rope_head_dim;- float *kv = malloc((size_t)batch * d * sizeof(*kv));- float *norm = malloc((size_t)d * sizeof(*norm));- int end = start_position + batch;- size_t pairs = (size_t)rope / 2;- float *cosines = malloc((size_t)end * pairs * sizeof(*cosines));- float *sines = malloc((size_t)end * pairs * sizeof(*sines));- const uint16_t *raw_norm = ds_layer_data(weights, "attn.kv_norm.weight", NULL);- if (!kv || !norm || !cosines || !sines || !raw_norm) {- free(sines); free(cosines); free(norm); free(kv);- return ds_attn_error(error, error_size, "out of memory in DSpark context KV");- }- for (int i = 0; i < d; i++) norm[i] = coli_bf16_decode(raw_norm[i]);- int result = coli_fp8_matmul_batch_ref(kv, &wkv, main_x, batch);- if (!result) coli_bf16_round_array(kv, (size_t)batch * d);- if (!result) result = coli_v4_rope_precompute(- cosines, sines, rope, end, 0, config->rope_theta,- config->rope_factor, config->rope_beta_fast, config->rope_beta_slow);- for (int item = 0; !result && item < batch; item++) {- float *item_kv = kv + (size_t)item * d;- result = coli_v4_rmsnorm(item_kv, item_kv, norm, d, config->rms_norm_eps);- if (result) break;- coli_bf16_round_array(item_kv, (size_t)d);- int position = start_position + item;- coli_v4_rope_apply(item_kv + d - rope, 1, rope,- cosines + (size_t)position * pairs,- sines + (size_t)position * pairs, 0);- coli_bf16_round_array(item_kv + d - rope, (size_t)rope);- size_t nope = (size_t)(d - rope);- float *qdq = malloc(nope * sizeof(*qdq));- uint8_t *scales = malloc((nope + 63) / 64);- if (!qdq || !scales || coli_fp8_activation_qdq_ref(- qdq, scales, item_kv, nope, 64)) result = -1;- if (!result) {- memcpy(item_kv, qdq, nope * sizeof(*item_kv));- coli_bf16_round_array(item_kv, nope);- int slot = coli_v4_dspark_position_window_put(- state->positions, state->window_size, &state->valid, position);- if (slot < 0)- result = ds_attn_error(- error, error_size,- "invalid DSpark context window update position=%d", position);- else- memcpy(state->kv + (size_t)slot * d, item_kv,- (size_t)d * sizeof(*item_kv));- }- free(scales); free(qdq);- }- free(sines); free(cosines); free(norm); free(kv);- return result ? ds_attn_error(error, error_size,- "DSpark context KV precompute failed") : 0;-}-/* ---- end inlined deepseek_v4_dspark_attention.c ---- */---#include "deepseek_v4_dspark.h"-#include "deepseek_v4_internal.h"--int coli_v4_dspark_attention_block(- float *outputs, ColiV4DSparkAttentionState *state,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, const float *inputs,- int query_start_position, int batch, char *error, size_t error_size) {- if (!outputs || !state || !weights || !config || !inputs ||- query_start_position < 0 || batch < 1 || batch > 64)- return ds_attn_error(error, error_size, "invalid DSpark query block");- int hidden = config->hidden_size, heads = config->num_attention_heads;- int d = config->head_dim, rope = config->qk_rope_head_dim;- int qr = config->q_lora_rank, groups = config->o_groups;- int orank = config->o_lora_rank;- size_t qwidth = (size_t)heads * d;- size_t oawidth = (size_t)groups * orank;- ColiTensorView wqa, wqb, wkv, woa, wob;- if (ds_fp8_view(&wqa, weights, "attn.wq_a") ||- ds_fp8_view(&wqb, weights, "attn.wq_b") ||- ds_fp8_view(&wkv, weights, "attn.wkv") ||- ds_fp8_view(&woa, weights, "attn.wo_a") ||- ds_fp8_view(&wob, weights, "attn.wo_b"))- return ds_attn_error(error, error_size, "missing DSpark attention matrix");- float *qa = calloc((size_t)batch * qr, sizeof(float));- float *q = calloc((size_t)batch * qwidth, sizeof(float));- float *kv = calloc((size_t)batch * d, sizeof(float));- float *attended = calloc((size_t)batch * qwidth, sizeof(float));- float *oa = calloc((size_t)batch * oawidth, sizeof(float));- float *norm = malloc((size_t)(qr > d ? qr : d) * sizeof(float));- int end = query_start_position + batch; size_t pairs = (size_t)rope / 2;- float *cosines = malloc((size_t)end * pairs * sizeof(float));- float *sines = malloc((size_t)end * pairs * sizeof(float));- int context = state->valid, kv_count = context + batch;- float *all_kv = malloc((size_t)kv_count * d * sizeof(float));- int *indices = malloc((size_t)kv_count * sizeof(int));- if (!qa || !q || !kv || !attended || !oa || !norm || !cosines ||- !sines || !all_kv || !indices) {- free(indices); free(all_kv); free(sines); free(cosines); free(norm);- free(oa); free(attended); free(kv); free(q); free(qa);- return ds_attn_error(error, error_size, "out of memory in DSpark block");- }- int result = coli_fp8_matmul_batch_ref(qa, &wqa, inputs, batch);- if (result) ds_attn_error(error, error_size,- "DSpark attention q_a matmul failed");- if (!result) coli_bf16_round_array(qa, (size_t)batch * qr);- const uint16_t *qnorm = ds_layer_data(weights, "attn.q_norm.weight", NULL);- if (!qnorm) result = ds_attn_error(- error, error_size, "missing DSpark attention q_norm");- for (int i = 0; !result && i < qr; i++) norm[i] = coli_bf16_decode(qnorm[i]);- for (int item = 0; !result && item < batch; item++) {- float *row = qa + (size_t)item * qr;- result = coli_v4_rmsnorm(row, row, norm, qr, config->rms_norm_eps);- if (!result) coli_bf16_round_array(row, (size_t)qr);- }- if (!result) {- result = coli_fp8_matmul_batch_ref(q, &wqb, qa, batch);- if (result) ds_attn_error(error, error_size,- "DSpark attention q_b matmul failed");- }- if (!result) coli_bf16_round_array(q, (size_t)batch * qwidth);- for (int item = 0; !result && item < batch; item++)- for (int head = 0; head < heads; head++) {- float *row = q + (size_t)item * qwidth + (size_t)head * d;- float squares = 0.0f;- for (int i = 0; i < d; i++) squares += row[i] * row[i];- float scale = 1.0f / sqrtf(squares / d + config->rms_norm_eps);- for (int i = 0; i < d; i++) row[i] = coli_bf16_round(row[i] * scale);- }- if (!result) {- result = coli_fp8_matmul_batch_ref(kv, &wkv, inputs, batch);- if (result) ds_attn_error(error, error_size,- "DSpark attention query KV matmul failed");- }- if (!result) coli_bf16_round_array(kv, (size_t)batch * d);- const uint16_t *knorm = ds_layer_data(weights, "attn.kv_norm.weight", NULL);- if (!knorm) result = ds_attn_error(- error, error_size, "missing DSpark attention kv_norm");- for (int i = 0; !result && i < d; i++) norm[i] = coli_bf16_decode(knorm[i]);- if (!result) {- result = coli_v4_rope_precompute(- cosines, sines, rope, end, 0, config->rope_theta,- config->rope_factor, config->rope_beta_fast, config->rope_beta_slow);- if (result) ds_attn_error(error, error_size,- "DSpark attention RoPE precompute failed");- }- for (int item = 0; !result && item < batch; item++) {- int position = query_start_position + item;- float *item_kv = kv + (size_t)item * d;- result = coli_v4_rmsnorm(item_kv, item_kv, norm, d, config->rms_norm_eps);- if (result) break;- coli_bf16_round_array(item_kv, (size_t)d);- for (int head = 0; head < heads; head++) {- float *r = q + (size_t)item * qwidth + (size_t)head * d + d - rope;- coli_v4_rope_apply(r, 1, rope,- cosines + (size_t)position * pairs,- sines + (size_t)position * pairs, 0);- coli_bf16_round_array(r, (size_t)rope);- }- coli_v4_rope_apply(item_kv + d - rope, 1, rope,- cosines + (size_t)position * pairs,- sines + (size_t)position * pairs, 0);- coli_bf16_round_array(item_kv + d - rope, (size_t)rope);- size_t nope = (size_t)(d - rope);- float *qdq = malloc(nope * sizeof(float));- uint8_t *scales = malloc((nope + 63) / 64);- if (!qdq || !scales || coli_fp8_activation_qdq_ref(- qdq, scales, item_kv, nope, 64))- result = ds_attn_error(- error, error_size,- "DSpark attention query KV quantization failed item=%d", item);- if (!result) {- memcpy(item_kv, qdq, nope * sizeof(float));- coli_bf16_round_array(item_kv, nope);- }- free(scales); free(qdq);- }- int copied = 0;- for (int slot = 0; !result && slot < state->window_size; slot++)- if (state->positions[slot] >= 0) {- memcpy(all_kv + (size_t)copied * d,- state->kv + (size_t)slot * d, (size_t)d * sizeof(float));- copied++;- }- if (copied != context) result = ds_attn_error(- error, error_size,- "DSpark attention context state mismatch valid=%d copied=%d",- context, copied);- if (!result) memcpy(all_kv + (size_t)context * d, kv,- (size_t)batch * d * sizeof(float));- for (int i = 0; i < kv_count; i++) indices[i] = i;- const float *sinks = ds_layer_data(weights, "attn.attn_sink", NULL);- for (int item = 0; !result && item < batch; item++) {- result = coli_v4_sparse_attention_ref(- attended + (size_t)item * qwidth,- q + (size_t)item * qwidth, all_kv, sinks, indices,- heads, d, kv_count, kv_count, 1.0f / sqrtf((float)d));- if (result) ds_attn_error(- error, error_size,- "DSpark sparse attention failed item=%d position=%d context=%d",- item, query_start_position + item, context);- int position = query_start_position + item;- for (int head = 0; !result && head < heads; head++) {- float *r = attended + (size_t)item * qwidth +- (size_t)head * d + d - rope;- coli_v4_rope_apply(r, 1, rope,- cosines + (size_t)position * pairs,- sines + (size_t)position * pairs, 1);- coli_bf16_round_array(r, (size_t)rope);- }- }- int heads_per_group = heads / groups;- int group_width = heads_per_group * d;- int scale_columns = (group_width + 127) / 128;- int scale_rows = (orank + 127) / 128;- float *group_inputs = malloc((size_t)batch * group_width * sizeof(float));- float *group_outputs = malloc((size_t)batch * orank * sizeof(float));- if (!group_inputs || !group_outputs) result = ds_attn_error(- error, error_size, "out of memory in DSpark grouped output");- for (int group = 0; !result && group < groups; group++) {- for (int item = 0; item < batch; item++)- memcpy(group_inputs + (size_t)item * group_width,- attended + (size_t)item * qwidth +- (size_t)group * group_width,- (size_t)group_width * sizeof(float));- ColiTensorView view = woa;- view.rows = orank; view.columns = group_width;- view.data = (const uint8_t *)woa.data +- (size_t)group * orank * group_width;- view.scales = (const uint8_t *)woa.scales +- (size_t)group * scale_rows * scale_columns;- view.data_bytes = (size_t)orank * group_width;- view.scale_bytes = (size_t)scale_rows * scale_columns;- result = coli_fp8_matmul_batch_ref(group_outputs, &view,- group_inputs, batch);- if (result) ds_attn_error(- error, error_size,- "DSpark attention o_a matmul failed group=%d rows=%lld columns=%lld "- "data_bytes=%zu scale_bytes=%zu",- group, (long long)view.rows, (long long)view.columns,- view.data_bytes, view.scale_bytes);- for (int item = 0; !result && item < batch; item++)- memcpy(oa + (size_t)item * oawidth + (size_t)group * orank,- group_outputs + (size_t)item * orank,- (size_t)orank * sizeof(float));- }- if (!result) coli_bf16_round_array(oa, (size_t)batch * oawidth);- if (!result) {- result = coli_fp8_matmul_batch_ref(outputs, &wob, oa, batch);- if (result) ds_attn_error(error, error_size,- "DSpark attention o_b matmul failed");- }- if (!result) coli_bf16_round_array(outputs, (size_t)batch * hidden);- free(group_outputs); free(group_inputs); free(indices); free(all_kv);- free(sines); free(cosines); free(norm); free(oa); free(attended);- free(kv); free(q); free(qa);- if (!result) return 0;- if (error && error_size && error[0]) return -1;- return ds_attn_error(error, error_size,- "DSpark non-causal attention failed");-}-#endif /* COLI_V4_UNIT_DSPARK_ATTENTION */--#ifdef COLI_V4_UNIT_DSPARK_BLOCK-/* ######## deepseek_v4_dspark_block.c ######## */-#define coli_v4_block_window_batch_ref coli_v4_dspark_causal_block_unused-/* ---- begin include deepseek_v4_block_batch.c ---- */-#define coli_v4_block_token_ref coli_v4_block_token_batch_serial_ref-#define coli_v4_block_window_token_ref coli_v4_block_window_token_batch_serial_ref-/* ---- begin include deepseek_v4_block.c ---- */-#include "deepseek_v4_internal.h"--#include <stdarg.h>-#include <stdint.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.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;-}--static const void *value(const ColiDeepSeekV4LayerWeights *weights,- const char *suffix,- const ColiDeepSeekV4TensorSpec **spec) {- char name[COLI_V4_MAX_TENSOR_NAME];- snprintf(name, sizeof(name), "layers.%d.%s", weights->plan.layer, suffix);- return coli_v4_layer_data(weights, name, spec);-}--static int fp8_view(ColiTensorView *view,- const ColiDeepSeekV4LayerWeights *weights,- const char *prefix) {- char name[128];- const ColiDeepSeekV4TensorSpec *ws = NULL, *ss = NULL;- snprintf(name, sizeof(name), "%s.weight", prefix);- const void *data = value(weights, name, &ws);- snprintf(name, sizeof(name), "%s.scale", prefix);- const void *scales = value(weights, name, &ss);- if (!data || !scales || !ws || !ss || ws->rank != 2) return -1;- *view = (ColiTensorView){- COLI_TENSOR_FP8_E4M3_BLOCK, COLI_SCALE_UE8M0, data, scales,- (size_t)(ws->shape[0] * ws->shape[1]),- (size_t)(ss->shape[0] * ss->shape[1]),- ws->shape[0], ws->shape[1], 128, 128- };- return 0;-}--static void decode_bf16(float *output, const uint16_t *input, size_t count) {- for (size_t i = 0; i < count; i++) output[i] = coli_bf16_decode(input[i]);-}--static int normalized_hc_pre(float *reduced, float *post, float *comb,- float *normalized, const float *input_hc,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const char *branch, const char *norm_name) {- char name[64];- snprintf(name, sizeof(name), "hc_%s_fn", branch);- const float *function = value(weights, name, NULL);- snprintf(name, sizeof(name), "hc_%s_scale", branch);- const float *scale = value(weights, name, NULL);- snprintf(name, sizeof(name), "hc_%s_base", branch);- const float *base = value(weights, name, NULL);- const uint16_t *raw_norm = value(weights, norm_name, NULL);- int d = config->hidden_size;- float *norm = malloc((size_t)d * sizeof(*norm));- if (!function || !scale || !base || !raw_norm || !norm) {- free(norm);- return -1;- }- decode_bf16(norm, raw_norm, (size_t)d);- int result = coli_v4_hc_pre(reduced, post, comb, input_hc, function,- scale, base, config->hc_mult, d,- config->hc_sinkhorn_iters,- config->rms_norm_eps, config->hc_eps);- if (!result) {- coli_bf16_round_array(reduced, (size_t)d);- result = coli_v4_rmsnorm(normalized, reduced, norm, d,- config->rms_norm_eps);- coli_bf16_round_array(normalized, (size_t)d);- }- free(norm);- return result;-}--static int moe_token(float *output,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *store, const float *input, int token) {- int d = config->hidden_size;- int n = config->n_routed_experts;- int topk = config->num_experts_per_tok;- size_t gate_count = (size_t)n * d;- float *gate = malloc(gate_count * sizeof(*gate));- float *route_weights = malloc((size_t)topk * sizeof(*route_weights));- int *indices = malloc((size_t)topk * sizeof(*indices));- float *expert_output = malloc((size_t)d * sizeof(*expert_output));- float *shared_output = malloc((size_t)d * sizeof(*shared_output));- if (!gate || !route_weights || !indices || !expert_output || !shared_output) {- free(shared_output); free(expert_output); free(indices);- free(route_weights); free(gate);- return -1;- }- decode_bf16(gate, value(weights, "ffn.gate.weight", NULL), gate_count);- const int64_t *table = value(weights, "ffn.gate.tid2eid", NULL);- const float *bias = value(weights, "ffn.gate.bias", NULL);- int result = token < 0 || token >= config->vocab_size;- if (!result && weights->plan.uses_hash_router) {- if (!table) result = -1;- }- if (!result && weights->plan.uses_hash_router) {- for (int i = 0; i < topk; i++)- indices[i] = (int)table[(size_t)token * topk + i];- }- if (!result) result = coli_v4_route(- route_weights, indices, input, gate, bias,- weights->plan.uses_hash_router ? indices : NULL,- n, d, topk, config->routed_scaling_factor);-- ColiTensorView w1, w2, w3;- if (!result && (fp8_view(&w1, weights, "ffn.shared_experts.w1") ||- fp8_view(&w2, weights, "ffn.shared_experts.w2") ||- fp8_view(&w3, weights, "ffn.shared_experts.w3"))) result = -1;- if (!result) result = coli_v4_shared_expert_forward_ref(- shared_output, &w1, &w2, &w3, input, config->swiglu_limit);- if (!result) memset(output, 0, (size_t)d * sizeof(*output));- for (int expert_id = 0; !result && expert_id < n; expert_id++) {- int rank = -1;- for (int candidate = 0; candidate < topk; candidate++)- if (indices[candidate] == expert_id) rank = candidate;- if (rank < 0) continue;- ColiExpertView expert;- if (coli_expert_lookup(store,- (ColiExpertKey){weights->plan.layer, expert_id},- &expert)) {- result = -1;- break;- }- result = coli_v4_expert_forward_ref(expert_output, &expert, input,- route_weights[rank],- config->swiglu_limit);- coli_expert_release(store, &expert);- if (!result)- for (int i = 0; i < d; i++) output[i] += expert_output[i];- }- if (!result)- for (int i = 0; i < d; i++)- output[i] = coli_bf16_round(output[i] + shared_output[i]);- free(shared_output); free(expert_output); free(indices);- free(route_weights); free(gate);- return result;-}--static int block_token_impl(float *output_hc,- ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- if (!output_hc || !weights || !config || !experts || !input_hc)- return set_error(error, error_size, "invalid block arguments");- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *residual = malloc(hd * sizeof(*residual));- float *state = malloc(hd * sizeof(*state));- float *reduced = malloc((size_t)d * sizeof(*reduced));- float *normalized = malloc((size_t)d * sizeof(*normalized));- float *branch = malloc((size_t)d * sizeof(*branch));- float *post = malloc((size_t)hc * sizeof(*post));- float *comb = malloc((size_t)hc * hc * sizeof(*comb));- if (!residual || !state || !reduced || !normalized || !branch || !post || !comb) {- free(comb); free(post); free(branch); free(normalized);- free(reduced); free(state); free(residual);- return set_error(error, error_size, "out of memory in block");- }- memcpy(residual, input_hc, hd * sizeof(*residual));- int result = normalized_hc_pre(reduced, post, comb, normalized, input_hc,- weights, config, "attn", "attn_norm.weight");- if (!result) result = attention- ? coli_v4_attention_window_token_ref(branch, attention, weights, config,- normalized, position, error, error_size)- : coli_v4_attention_token_ref(branch, weights, config, normalized,- position, error, error_size);- if (!result) result = coli_v4_hc_post(state, branch, residual, post, comb, hc, d);- if (!result) coli_bf16_round_array(state, hd);-- if (!result) memcpy(residual, state, hd * sizeof(*residual));- if (!result) result = normalized_hc_pre(reduced, post, comb, normalized, state,- weights, config, "ffn", "ffn_norm.weight");- if (!result) result = moe_token(branch, weights, config, experts, normalized, token);- if (!result) result = coli_v4_hc_post(output_hc, branch, residual, post, comb, hc, d);- if (!result) coli_bf16_round_array(output_hc, hd);-- free(comb); free(post); free(branch); free(normalized);- free(reduced); free(state); free(residual);- return result ? set_error(error, error_size, "block computation failed") : 0;-}--int coli_v4_block_token_ref(float *output_hc,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- return block_token_impl(output_hc, NULL, weights, config, experts, input_hc,- token, position, error, error_size);-}--int coli_v4_block_window_token_ref(- float *output_hc, ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- return block_token_impl(output_hc, attention, weights, config, experts,- input_hc, token, position, error, error_size);-}-/* ---- end include deepseek_v4_block.c ---- */--#undef coli_v4_block_token_ref-#undef coli_v4_block_window_token_ref--#include "deepseek_v4_internal.h"-#include "native_quant_batch.h"--static int shared_expert_batch(float *outputs, const ColiTensorView *w1,- const ColiTensorView *w2,- const ColiTensorView *w3,- const float *inputs, int batch,- float swiglu_limit) {- int intermediate = (int)w1->rows, d = (int)w2->rows;- float *gate = malloc((size_t)batch * intermediate * sizeof(*gate));- float *up = malloc((size_t)batch * intermediate * sizeof(*up));- float *activated = malloc((size_t)batch * intermediate * sizeof(*activated));- if (!gate || !up || !activated) {- free(activated); free(up); free(gate); return -1;- }- int result = coli_fp8_matmul_batch_ref(gate, w1, inputs, batch) ||- coli_fp8_matmul_batch_ref(up, w3, inputs, batch);- for (int item = 0; !result && item < batch; item++) {- float *item_gate = gate + (size_t)item * intermediate;- float *item_up = up + (size_t)item * intermediate;- float *item_activated = activated + (size_t)item * intermediate;- coli_bf16_round_array(item_gate, (size_t)intermediate);- coli_bf16_round_array(item_up, (size_t)intermediate);- result = coli_v4_swiglu(item_activated, item_gate, item_up,- intermediate, swiglu_limit);- if (!result) coli_bf16_round_array(item_activated,- (size_t)intermediate);- }- if (!result) result = coli_fp8_matmul_batch_ref(- outputs, w2, activated, batch);- if (!result) coli_bf16_round_array(outputs, (size_t)batch * d);- free(activated); free(up); free(gate);- return result;-}--static int routed_expert_batch(float *outputs, const ColiExpertView *expert,- const float *inputs, const float *route_weights,- int batch, float swiglu_limit) {- int intermediate = (int)expert->gate.rows;- int d = (int)expert->down.rows;- float *gate = malloc((size_t)batch * intermediate * sizeof(*gate));- float *up = malloc((size_t)batch * intermediate * sizeof(*up));- float *activated = malloc((size_t)batch * intermediate * sizeof(*activated));- if (!gate || !up || !activated) {- free(activated); free(up); free(gate); return -1;- }- int result = coli_fp4_matmul_batch_ref(gate, &expert->gate, inputs, batch) ||- coli_fp4_matmul_batch_ref(up, &expert->up, inputs, batch);- for (int item = 0; !result && item < batch; item++) {- float *item_gate = gate + (size_t)item * intermediate;- float *item_up = up + (size_t)item * intermediate;- float *item_activated = activated + (size_t)item * intermediate;- coli_bf16_round_array(item_gate, (size_t)intermediate);- coli_bf16_round_array(item_up, (size_t)intermediate);- result = coli_v4_swiglu(item_activated, item_gate, item_up,- intermediate, swiglu_limit);- for (int i = 0; !result && i < intermediate; i++)- item_activated[i] = coli_bf16_round(- item_activated[i] * route_weights[item]);- }- if (!result) result = coli_fp4_matmul_batch_ref(- outputs, &expert->down, activated, batch);- if (!result) coli_bf16_round_array(outputs, (size_t)batch * d);- free(activated); free(up); free(gate);- return result;-}--static int moe_batch(float *outputs,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *store, const float *inputs,- const int *tokens, int batch,- char *error, size_t error_size) {- int d = config->hidden_size, n = config->n_routed_experts;- int topk = config->num_experts_per_tok;- float *gate = malloc((size_t)n * d * sizeof(*gate));- float *route_weights = malloc((size_t)batch * topk * sizeof(*route_weights));- int *indices = malloc((size_t)batch * topk * sizeof(*indices));- float *shared = malloc((size_t)batch * d * sizeof(*shared));- float *compact_inputs = malloc((size_t)batch * d * sizeof(*compact_inputs));- float *compact_outputs = malloc((size_t)batch * d * sizeof(*compact_outputs));- float *compact_weights = malloc((size_t)batch * sizeof(*compact_weights));- int *compact_items = malloc((size_t)batch * sizeof(*compact_items));- if (!gate || !route_weights || !indices || !shared || !compact_inputs ||- !compact_outputs || !compact_weights || !compact_items) {- free(compact_items); free(compact_weights); free(compact_outputs);- free(compact_inputs); free(shared); free(indices); free(route_weights);- free(gate);- return set_error(error, error_size,- "out of memory in DSpark MoE scratch");- }- const uint16_t *raw_gate = value(weights, "ffn.gate.weight", NULL);- if (!raw_gate) {- free(compact_items); free(compact_weights); free(compact_outputs);- free(compact_inputs); free(shared); free(indices); free(route_weights);- free(gate);- return set_error(error, error_size, "missing DSpark MoE gate weight");- }- decode_bf16(gate, raw_gate, (size_t)n * d);- const int64_t *table = value(weights, "ffn.gate.tid2eid", NULL);- const float *bias = value(weights, "ffn.gate.bias", NULL);- int result = 0;- for (int item = 0; !result && item < batch; item++) {- int *item_indices = indices + (size_t)item * topk;- float *item_weights = route_weights + (size_t)item * topk;- if (tokens[item] < 0 || tokens[item] >= config->vocab_size)- result = set_error(- error, error_size,- "DSpark MoE invalid token item=%d token=%d vocab=%d",- item, tokens[item], config->vocab_size);- if (!result && weights->plan.uses_hash_router) {- if (!table) result = set_error(- error, error_size, "missing DSpark MoE hash routing table");- else for (int i = 0; i < topk; i++)- item_indices[i] = (int)table[(size_t)tokens[item] * topk + i];- }- if (!result && coli_v4_route(- item_weights, item_indices, inputs + (size_t)item * d,- gate, bias, weights->plan.uses_hash_router ? item_indices : NULL,- n, d, topk, config->routed_scaling_factor))- result = set_error(error, error_size,- "DSpark MoE routing failed item=%d token=%d",- item, tokens[item]);- }- ColiTensorView w1, w2, w3;- if (!result && fp8_view(&w1, weights, "ffn.shared_experts.w1"))- result = set_error(error, error_size,- "invalid DSpark shared expert w1");- if (!result && fp8_view(&w2, weights, "ffn.shared_experts.w2"))- result = set_error(error, error_size,- "invalid DSpark shared expert w2");- if (!result && fp8_view(&w3, weights, "ffn.shared_experts.w3"))- result = set_error(error, error_size,- "invalid DSpark shared expert w3");- if (!result && shared_expert_batch(- shared, &w1, &w2, &w3, inputs, batch, config->swiglu_limit))- result = set_error(error, error_size,- "DSpark shared expert batch failed");- if (!result) memset(outputs, 0, (size_t)batch * d * sizeof(*outputs));-- for (int expert_id = 0; !result && expert_id < n; expert_id++) {- int count = 0;- for (int item = 0; item < batch; item++) {- for (int rank = 0; rank < topk; rank++) {- if (indices[(size_t)item * topk + rank] == expert_id) {- compact_items[count] = item;- compact_weights[count] =- route_weights[(size_t)item * topk + rank];- memcpy(compact_inputs + (size_t)count * d,- inputs + (size_t)item * d, (size_t)d * sizeof(float));- count++;- }- }- }- if (!count) continue;- ColiExpertView expert;- if (coli_expert_lookup(store,- (ColiExpertKey){weights->plan.layer, expert_id},- &expert)) {- result = set_error(- error, error_size,- "DSpark expert lookup failed layer=%d expert=%d count=%d",- weights->plan.layer, expert_id, count);- break;- }- if (routed_expert_batch(compact_outputs, &expert, compact_inputs,- compact_weights, count,- config->swiglu_limit))- result = set_error(- error, error_size,- "DSpark routed expert batch failed layer=%d expert=%d count=%d",- weights->plan.layer, expert_id, count);- coli_expert_release(store, &expert);- for (int compact = 0; !result && compact < count; compact++) {- float *destination = outputs + (size_t)compact_items[compact] * d;- const float *source = compact_outputs + (size_t)compact * d;- for (int i = 0; i < d; i++) destination[i] += source[i];- }- }- for (int item = 0; !result && item < batch; item++)- for (int i = 0; i < d; i++)- outputs[(size_t)item * d + i] = coli_bf16_round(- outputs[(size_t)item * d + i] + shared[(size_t)item * d + i]);- free(compact_items); free(compact_weights); free(compact_outputs);- free(compact_inputs); free(shared); free(indices); free(route_weights);- free(gate); return result;-}--int coli_v4_block_window_batch_ref(- float *outputs_hc, ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *inputs_hc, const int *tokens, int start_position, int batch,- char *error, size_t error_size) {- if (!outputs_hc || !attention || !weights || !config || !experts ||- !inputs_hc || !tokens || batch < 1 || batch > 64) return -1;- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *states = malloc((size_t)batch * hd * sizeof(*states));- float *normalized_ffn = malloc((size_t)batch * d * sizeof(*normalized_ffn));- float *branches = malloc((size_t)batch * d * sizeof(*branches));- float *posts = malloc((size_t)batch * hc * sizeof(*posts));- float *combs = malloc((size_t)batch * hc * hc * sizeof(*combs));- float *residual = malloc(hd * sizeof(*residual));- float *reduced = malloc((size_t)d * sizeof(*reduced));- float *normalized = malloc((size_t)d * sizeof(*normalized));- float *branch = malloc((size_t)d * sizeof(*branch));- float *post = malloc((size_t)hc * sizeof(*post));- float *comb = malloc((size_t)hc * hc * sizeof(*comb));- if (!states || !normalized_ffn || !branches || !posts || !combs ||- !residual || !reduced || !normalized || !branch || !post || !comb) {- free(comb); free(post); free(branch); free(normalized); free(reduced);- free(residual); free(combs); free(posts); free(branches);- free(normalized_ffn); free(states); return -1;- }- int result = 0;- for (int item = 0; !result && item < batch; item++) {- const float *input = inputs_hc + (size_t)item * hd;- float *state = states + (size_t)item * hd;- memcpy(residual, input, hd * sizeof(float));- result = normalized_hc_pre(reduced, post, comb, normalized, input,- weights, config, "attn", "attn_norm.weight");- if (!result) result = coli_v4_attention_window_token_ref(- branch, attention, weights, config, normalized,- start_position + item, error, error_size);- if (!result) result = coli_v4_hc_post(state, branch, residual,- post, comb, hc, d);- if (!result) coli_bf16_round_array(state, hd);- if (!result) result = normalized_hc_pre(- reduced, posts + (size_t)item * hc,- combs + (size_t)item * hc * hc,- normalized_ffn + (size_t)item * d, state,- weights, config, "ffn", "ffn_norm.weight");- }- if (!result) result = moe_batch(branches, weights, config, experts,- normalized_ffn, tokens, batch,- error, error_size);- for (int item = 0; !result && item < batch; item++) {- result = coli_v4_hc_post(- outputs_hc + (size_t)item * hd,- branches + (size_t)item * d,- states + (size_t)item * hd,- posts + (size_t)item * hc,- combs + (size_t)item * hc * hc, hc, d);- if (!result) coli_bf16_round_array(- outputs_hc + (size_t)item * hd, hd);- }- free(comb); free(post); free(branch); free(normalized); free(reduced);- free(residual); free(combs); free(posts); free(branches);- free(normalized_ffn); free(states);- return result ? set_error(error, error_size, "batched block failed") : 0;-}-/* ---- end include deepseek_v4_block_batch.c ---- */--#undef coli_v4_block_window_batch_ref--#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"--int coli_v4_dspark_block(- float *outputs_hc, ColiV4DSparkAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *inputs_hc, const int *tokens,- int query_start_position, int batch,- char *error, size_t error_size) {- if (error && error_size) error[0] = '\0';- if (!outputs_hc || !attention || !weights || !config || !experts ||- !inputs_hc || !tokens || batch < 1 || batch > 64)- return set_error(error, error_size, "invalid DSpark block arguments");- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *states = malloc((size_t)batch * hd * sizeof(float));- float *attn_norm = malloc((size_t)batch * d * sizeof(float));- float *attn_branch = malloc((size_t)batch * d * sizeof(float));- float *attn_post = malloc((size_t)batch * hc * sizeof(float));- float *attn_comb = malloc((size_t)batch * hc * hc * sizeof(float));- float *ffn_norm = malloc((size_t)batch * d * sizeof(float));- float *ffn_branch = malloc((size_t)batch * d * sizeof(float));- float *ffn_post = malloc((size_t)batch * hc * sizeof(float));- float *ffn_comb = malloc((size_t)batch * hc * hc * sizeof(float));- float *reduced = malloc((size_t)d * sizeof(float));- if (!states || !attn_norm || !attn_branch || !attn_post || !attn_comb ||- !ffn_norm || !ffn_branch || !ffn_post || !ffn_comb || !reduced) {- free(reduced); free(ffn_comb); free(ffn_post); free(ffn_branch);- free(ffn_norm); free(attn_comb); free(attn_post); free(attn_branch);- free(attn_norm); free(states);- return set_error(error, error_size,- "out of memory in DSpark block scratch");- }- int result = 0;- const char *failed_step = NULL;- for (int item = 0; !result && item < batch; item++) {- result = normalized_hc_pre(- reduced, attn_post + (size_t)item * hc,- attn_comb + (size_t)item * hc * hc,- attn_norm + (size_t)item * d,- inputs_hc + (size_t)item * hd,- weights, config, "attn", "attn_norm.weight");- if (result) failed_step = "attention HC pre";- }- if (!result) {- result = coli_v4_dspark_attention_block(- attn_branch, attention, weights, config, attn_norm,- query_start_position, batch, error, error_size);- if (result) failed_step = "attention";- }- for (int item = 0; !result && item < batch; item++) {- result = coli_v4_hc_post(- states + (size_t)item * hd,- attn_branch + (size_t)item * d,- inputs_hc + (size_t)item * hd,- attn_post + (size_t)item * hc,- attn_comb + (size_t)item * hc * hc, hc, d);- if (result) failed_step = "attention HC post";- if (!result) coli_bf16_round_array(states + (size_t)item * hd, hd);- }- for (int item = 0; !result && item < batch; item++) {- result = normalized_hc_pre(- reduced, ffn_post + (size_t)item * hc,- ffn_comb + (size_t)item * hc * hc,- ffn_norm + (size_t)item * d,- states + (size_t)item * hd,- weights, config, "ffn", "ffn_norm.weight");- if (result) failed_step = "FFN HC pre";- }- if (!result) {- result = moe_batch(ffn_branch, weights, config, experts, ffn_norm,- tokens, batch, error, error_size);- if (result) failed_step = "MoE";- }- for (int item = 0; !result && item < batch; item++) {- result = coli_v4_hc_post(- outputs_hc + (size_t)item * hd,- ffn_branch + (size_t)item * d,- states + (size_t)item * hd,- ffn_post + (size_t)item * hc,- ffn_comb + (size_t)item * hc * hc, hc, d);- if (result) failed_step = "FFN HC post";- if (!result) coli_bf16_round_array(outputs_hc + (size_t)item * hd, hd);- }- free(reduced); free(ffn_comb); free(ffn_post); free(ffn_branch);- free(ffn_norm); free(attn_comb); free(attn_post); free(attn_branch);- free(attn_norm); free(states);- if (!result) return 0;- char detail[256] = {0};- if (error && error_size && error[0])- snprintf(detail, sizeof(detail), "%s", error);- return set_error(error, error_size,- "DSpark block failed layer=%d step=%s%s%s",- weights->plan.layer, failed_step ? failed_step : "unknown",- detail[0] ? ": " : "", detail);-}-#endif /* COLI_V4_UNIT_DSPARK_BLOCK */--#ifdef COLI_V4_UNIT_DSPARK_FINAL-/* ######## deepseek_v4_dspark_final.c ######## */-#include "native_quant.h"-/* ---- begin inlined deepseek_v4_dspark_final.c ---- */-#include "deepseek_v4_dspark.h"--#include <math.h>-#include <stdio.h>-#include <stdlib.h>--#include "deepseek_v4_internal.h"-#include "safetensors_index.h"-#include "tensor_io.h"--struct ColiV4DSparkFinal {- int hidden, hc;- float eps, hc_eps;- ColiFloatTensor function, base, scale, norm;-};--void coli_v4_dspark_final_close(ColiV4DSparkFinal *final) {- if (!final) return;- coli_float_tensor_free(&final->norm);- coli_float_tensor_free(&final->scale);- coli_float_tensor_free(&final->base);- coli_float_tensor_free(&final->function);- free(final);-}--int coli_v4_dspark_final_open(ColiV4DSparkFinal **output,- const char *model_dir,- const ColiDeepSeekV4Config *config,- const ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size) {- if (!output || !model_dir || !config || !manifest ||- manifest->stage_count < 1) return -1;- *output = NULL; ColiSafetensorsIndex *index = NULL;- if (coli_st_index_open(&index, model_dir, error, error_size)) return -1;- ColiV4DSparkFinal *final = calloc(1, sizeof(*final));- if (!final) { coli_st_index_close(index); return -1; }- final->hidden = config->hidden_size; final->hc = config->hc_mult;- final->eps = config->rms_norm_eps; final->hc_eps = config->hc_eps;- char name[160]; int last = manifest->stage_count - 1, failed = 0;- snprintf(name, sizeof(name), "mtp.%d.hc_head_fn", last);- failed |= coli_tensor_load_f32(&final->function, index, name,- error, error_size);- snprintf(name, sizeof(name), "mtp.%d.hc_head_base", last);- failed |= coli_tensor_load_f32(&final->base, index, name, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.hc_head_scale", last);- failed |= coli_tensor_load_f32(&final->scale, index, name, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.norm.weight", last);- failed |= coli_tensor_load_f32(&final->norm, index, name, error, error_size);- coli_st_index_close(index);- if (failed) { coli_v4_dspark_final_close(final); return -1; }- *output = final; return 0;-}--int coli_v4_dspark_final_hidden(ColiV4DSparkFinal *final,- float *outputs, const float *states_hc,- int batch) {- if (!final || !outputs || !states_hc || batch < 1 || batch > 64) return -1;- int d = final->hidden, hc = final->hc, flattened = d * hc;- if (hc > 16) return -1;- for (int item = 0; item < batch; item++) {- const float *state = states_hc + (size_t)item * flattened;- float *output = outputs + (size_t)item * d;- float square = 0.0f, pre[16];- for (int i = 0; i < flattened; i++) square += state[i] * state[i];- float inverse = 1.0f / sqrtf(square / flattened + final->eps);- for (int copy = 0; copy < hc; copy++) {- float mix = 0.0f;- for (int i = 0; i < flattened; i++)- mix += final->function.data[(size_t)copy * flattened + i] *- state[i];- float z = mix * inverse * final->scale.data[0] +- final->base.data[copy];- float sigmoid = z >= 0.0f ? 1.0f / (1.0f + expf(-z))- : expf(z) / (1.0f + expf(z));- pre[copy] = sigmoid + final->hc_eps;- }- for (int i = 0; i < d; i++) {- float value = 0.0f;- for (int copy = 0; copy < hc; copy++)- value += pre[copy] * state[(size_t)copy * d + i];- output[i] = coli_bf16_round(value);- }- if (coli_v4_rmsnorm(output, output, final->norm.data, d, final->eps))- return -1;- coli_bf16_round_array(output, (size_t)d);- }- return 0;-}-/* ---- end inlined deepseek_v4_dspark_final.c ---- */-#endif /* COLI_V4_UNIT_DSPARK_FINAL */--#ifdef COLI_V4_UNIT_DSPARK_RUNNER-/* ######## deepseek_v4_dspark_runner.c ######## */-#include "native_quant.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"--#define coli_v4_dspark_runner_open coli_v4_dspark_runner_owned_open-#define coli_v4_dspark_runner_close coli_v4_dspark_runner_owned_close-/* ---- begin inlined deepseek_v4_dspark_runner.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_internal.h"-#include "safetensors_index.h"--struct ColiV4DSparkRunner {- ColiDeepSeekV4Config config;- ColiDeepSeekV4DSparkManifest manifest;- char *model_dir;- ColiSafetensorsIndex *dspark_index;- ColiSafetensorsIndex *target_index;- ColiV4DSparkHeads *heads;- ColiV4DSparkFinal *final;- ColiExpertStore *experts;- ColiV4DSparkAttentionState *attention[COLI_V4_DSPARK_MAX_STAGES];- uint64_t loaded_stage_peak;- ColiV4Engine *engine;-};--static int runner_error(char *error, size_t size, const char *message) {- if (error && size) snprintf(error, size, "%s", message);- return -1;-}--static int runner_embedding(ColiV4DSparkRunner *runner, float *state,- int token) {- const ColiSafetensorsTensor *embed =- coli_st_find(runner->dspark_index, "embed.weight");- int d = runner->config.hidden_size, hc = runner->config.hc_mult;- uint16_t *raw = malloc((size_t)d * sizeof(*raw));- if (!embed || embed->dtype != COLI_ST_BF16 || !raw || token < 0 ||- token >= runner->config.vocab_size ||- coli_st_read_at(runner->dspark_index, embed->shard,- embed->offset + (uint64_t)token * d * sizeof(*raw),- (size_t)d * sizeof(*raw), raw)) {- free(raw); return -1;- }- for (int copy = 0; copy < hc; copy++)- for (int i = 0; i < d; i++)- state[(size_t)copy * d + i] = coli_bf16_decode(raw[i]);- free(raw); return 0;-}--void coli_v4_dspark_runner_close(ColiV4DSparkRunner *runner) {- if (!runner) return;- for (int stage = 0; stage < runner->manifest.stage_count; stage++)- coli_v4_dspark_attention_destroy(runner->attention[stage]);- if (runner->experts) runner->experts->ops->destroy(runner->experts);- coli_v4_dspark_final_close(runner->final);- coli_v4_dspark_heads_close(runner->heads);- coli_st_index_close(runner->target_index);- coli_st_index_close(runner->dspark_index);- free(runner->model_dir); free(runner);-}--int coli_v4_dspark_runner_open(ColiV4DSparkRunner **output,- const char *dspark_model_dir,- const char *target_model_dir,- const ColiDeepSeekV4Config *config,- uint64_t expert_cache_bytes,- char *error, size_t error_size) {- if (!output || !dspark_model_dir || !target_model_dir || !config) return -1;- *output = NULL; ColiV4DSparkRunner *runner = calloc(1, sizeof(*runner));- if (!runner) return -1;- runner->config = *config;- runner->model_dir = malloc(strlen(dspark_model_dir) + 1);- if (!runner->model_dir) { coli_v4_dspark_runner_close(runner); return -1; }- strcpy(runner->model_dir, dspark_model_dir);- if (coli_v4_dspark_inspect(dspark_model_dir, config, &runner->manifest,- error, error_size) ||- coli_st_index_open(&runner->dspark_index, dspark_model_dir,- error, error_size) ||- coli_st_index_open(&runner->target_index, target_model_dir,- error, error_size) ||- coli_v4_dspark_heads_open(&runner->heads, dspark_model_dir, config,- &runner->manifest, error, error_size) ||- coli_v4_dspark_final_open(&runner->final, dspark_model_dir, config,- &runner->manifest, error, error_size)) {- coli_v4_dspark_runner_close(runner); return -1;- }- for (int stage = 0; stage < runner->manifest.stage_count; stage++) {- if (runner->manifest.common_stage_bytes[stage] > runner->loaded_stage_peak)- runner->loaded_stage_peak = runner->manifest.common_stage_bytes[stage];- if (coli_v4_dspark_attention_create(&runner->attention[stage], config)) {- coli_v4_dspark_runner_close(runner); return -1;- }- }- ColiDeepSeekV4ExpertStoreOptions options = {- dspark_model_dir, runner->manifest.stage_count,- config->n_routed_experts, expert_cache_bytes, -1, 0};- if (coli_deepseek_v4_dspark_expert_store_open(- &options, &runner->experts, error, error_size)) {- coli_v4_dspark_runner_close(runner); return -1;- }- *output = runner; return 0;-}--int coli_v4_dspark_runner_prefill(ColiV4DSparkRunner *runner,- const float *main_x,- int start_position, int batch,- char *error, size_t error_size) {- if (!runner || !main_x || start_position < 0 || batch < 1 || batch > 64)- return runner_error(error, error_size, "invalid DSpark prefill");- for (int stage = 0; stage < runner->manifest.stage_count; stage++) {- ColiDeepSeekV4LayerWeights weights;- if (coli_v4_dspark_layer_load(runner->engine, &weights, &runner->config,- runner->dspark_index, stage,- error, error_size)) return -1;- int result = coli_v4_dspark_attention_precompute_context(- runner->attention[stage], &weights, &runner->config,- main_x, start_position, batch, error, error_size);- coli_v4_dspark_layer_release(runner->engine, &weights);- if (result) return -1;- }- return 0;-}--int coli_v4_dspark_runner_draft(ColiV4DSparkRunner *runner,- const float *main_x, int anchor_token,- int position, int *draft_tokens,- float *draft_logits,- char *error, size_t error_size) {- if (!runner || !main_x || !draft_tokens || position < 0 ||- anchor_token < 0 || anchor_token >= runner->config.vocab_size)- return runner_error(error, error_size, "invalid DSpark draft");- int batch = runner->manifest.block_size;- int d = runner->config.hidden_size, hc = runner->config.hc_mult;- size_t hd = (size_t)hc * d;- float *state = calloc((size_t)batch * hd, sizeof(*state));- float *next = calloc((size_t)batch * hd, sizeof(*next));- float *hidden = malloc((size_t)batch * d * sizeof(*hidden));- int *input_tokens = malloc((size_t)batch * sizeof(*input_tokens));- if (!state || !next || !hidden || !input_tokens) {- free(input_tokens); free(hidden); free(next); free(state);- return runner_error(error, error_size, "out of memory in DSpark draft");- }- for (int item = 0; item < batch; item++) {- input_tokens[item] = item ? runner->manifest.noise_token_id : anchor_token;- if (runner_embedding(runner, state + (size_t)item * hd,- input_tokens[item])) {- free(input_tokens); free(hidden); free(next); free(state);- return runner_error(error, error_size, "DSpark embedding read failed");- }- }- for (int stage = 0; stage < runner->manifest.stage_count; stage++) {- ColiDeepSeekV4LayerWeights weights;- if (coli_v4_dspark_layer_load(runner->engine, &weights, &runner->config,- runner->dspark_index, stage,- error, error_size)) {- free(input_tokens); free(hidden); free(next); free(state); return -1;- }- int result = coli_v4_dspark_attention_precompute_context(- runner->attention[stage], &weights, &runner->config,- main_x, position, 1, error, error_size);- if (!result) result = coli_v4_dspark_block(- next, runner->attention[stage], &weights, &runner->config,- runner->experts, state, input_tokens, position + 1, batch,- error, error_size);- coli_v4_dspark_layer_release(runner->engine, &weights);- if (result) {- free(input_tokens); free(hidden); free(next); free(state); return -1;- }- float *swap = state; state = next; next = swap;- }- int result = coli_v4_dspark_final_hidden(runner->final, hidden, state, batch);- ColiV4Engine *engine = runner->engine;- int limit = batch;- if (engine) {- int requested = engine->runtime.verify_drafts;- if (requested >= 1 && requested < limit) limit = requested;- engine->dspark_verify.available = batch;- engine->dspark_verify.limit = limit;- engine->dspark_verify.head_slot = 0;- }- if (!result && limit > 0) {- int *tokens_out = engine ? engine->dspark_verify.tokens : draft_tokens;- float *logits_out = engine ? engine->dspark_verify.logits : draft_logits;- float local_logits[64];- if (!logits_out) logits_out = local_logits;- result = coli_v4_dspark_biased_argmax_batch(- engine, runner->heads, runner->target_index, hidden, anchor_token,- tokens_out, logits_out, limit);- for (int item = 0; !result && item < limit; item++) {- draft_tokens[item] = tokens_out[item];- if (draft_logits) draft_logits[item] = logits_out[item];- }- }- int previous = limit > 0 ? draft_tokens[limit - 1] : anchor_token;- for (int item = limit; !result && item < batch; item++) {- draft_tokens[item] = previous;- if (draft_logits) draft_logits[item] = 0.0f;- }- free(input_tokens); free(hidden); free(next); free(state);- return result ? runner_error(error, error_size, "DSpark draft head failed") : 0;-}--int coli_v4_dspark_runner_block_size(const ColiV4DSparkRunner *runner) {- return runner ? runner->manifest.block_size : 0;-}--int coli_v4_dspark_runner_verify_block_size(const ColiV4DSparkRunner *runner) {- if (!runner) return 0;- int available = runner->manifest.block_size;- ColiV4Engine *engine = runner->engine;- int requested = engine ? engine->runtime.verify_drafts : 0;- if (requested < 1) return available;- return requested < available ? requested : available;-}--uint64_t coli_v4_dspark_runner_loaded_stage_peak(- const ColiV4DSparkRunner *runner) {- return runner ? runner->loaded_stage_peak : 0;-}-/* ---- end inlined deepseek_v4_dspark_runner.c ---- */--#undef coli_v4_dspark_runner_close-#undef coli_v4_dspark_runner_open--#include "deepseek_v4_dspark.h"--int coli_v4_dspark_runner_open(ColiV4DSparkRunner **output,- ColiV4Engine *engine,- const char *dspark_model_dir,- const char *target_model_dir,- const ColiDeepSeekV4Config *config,- uint64_t expert_cache_bytes,- char *error, size_t error_size) {- uint64_t cache = (engine && engine->runtime.dspark_expert_cache_bytes)- ? engine->runtime.dspark_expert_cache_bytes : expert_cache_bytes;- int rc = coli_v4_dspark_runner_owned_open(- output, dspark_model_dir, target_model_dir, config,- cache, error, error_size);- if (!rc && output && *output) (*output)->engine = engine;- return rc;-}--int coli_v4_dspark_runner_use_shared_heads(ColiV4DSparkRunner *runner,- ColiV4DSparkHeads *heads) {- if (!runner || !heads) return -1;- coli_v4_dspark_heads_close(runner->heads);- runner->heads = heads;- return 0;-}--void coli_v4_dspark_runner_close(ColiV4DSparkRunner *runner) {- if (runner && runner->engine &&- runner->heads == runner->engine->dspark_capture.heads)- runner->heads = NULL;- coli_v4_dspark_runner_owned_close(runner);-}-#endif /* COLI_V4_UNIT_DSPARK_RUNNER */--#ifdef COLI_V4_UNIT_TARGET_HEAD_BATCH-/* ######## deepseek_v4_target_head_batch.c ######## */-#include "deepseek_v4_dspark.h"--#include <float.h>-#include <math.h>-#include <stdint.h>-#include <stdlib.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "native_quant.h"-#include "tensor_io.h"--int coli_v4_target_load_embeddings(float *states_hc,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config,- const int *tokens, int batch) {- const ColiSafetensorsTensor *embed = coli_st_find(index, "embed.weight");- if (!states_hc || !index || !config || !tokens || batch < 1 || batch > 64 ||- !embed || embed->dtype != COLI_ST_BF16) return -1;- int d = config->hidden_size, hc = config->hc_mult;- uint16_t *raw = malloc((size_t)d * sizeof(*raw));- if (!raw) return -1;- for (int item = 0; item < batch; item++) {- if (tokens[item] < 0 || tokens[item] >= config->vocab_size ||- coli_st_read_at(index, embed->shard,- embed->offset + (uint64_t)tokens[item] * d * 2,- (size_t)d * sizeof(*raw), raw)) {- free(raw); return -1;- }- float *state = states_hc + (size_t)item * hc * d;- for (int copy = 0; copy < hc; copy++)- for (int i = 0; i < d; i++)- state[(size_t)copy * d + i] = coli_bf16_decode(raw[i]);- }- free(raw); return 0;-}--int coli_v4_target_head_argmax_batch(- const float *states_hc, const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, int batch,- int *tokens, float *logits, char *error, size_t error_size) {- if (!states_hc || !index || !config || batch < 1 || batch > 64 || !tokens)- return -1;- ColiFloatTensor function = {0}, base = {0}, scale = {0}, norm = {0};- if (coli_tensor_load_f32(&function, index, "hc_head_fn", error, error_size) ||- coli_tensor_load_f32(&base, index, "hc_head_base", error, error_size) ||- coli_tensor_load_f32(&scale, index, "hc_head_scale", error, error_size) ||- coli_tensor_load_f32(&norm, index, "norm.weight", error, error_size))- return -1;- int d = config->hidden_size, hc = config->hc_mult, flat = hc * d;- float *hidden = malloc((size_t)batch * d * sizeof(*hidden));- if (!hidden || hc > 16) { free(hidden); return -1; }- for (int item = 0; item < batch; item++) {- const float *state = states_hc + (size_t)item * flat;- float *out = hidden + (size_t)item * d;- float square = 0.0f, pre[16];- for (int i = 0; i < flat; i++) square += state[i] * state[i];- float inverse = 1.0f / sqrtf(square / flat + config->rms_norm_eps);- for (int copy = 0; copy < hc; copy++) {- float mix = 0.0f;- for (int i = 0; i < flat; i++)- mix += function.data[(size_t)copy * flat + i] * state[i];- float z = mix * inverse * scale.data[0] + base.data[copy];- float sigmoid = z >= 0.0f ? 1.0f / (1.0f + expf(-z))- : expf(z) / (1.0f + expf(z));- pre[copy] = sigmoid + config->hc_eps;- }- for (int i = 0; i < d; i++) {- float value = 0.0f;- for (int copy = 0; copy < hc; copy++)- value += pre[copy] * state[(size_t)copy * d + i];- out[i] = coli_bf16_round(value);- }- if (coli_v4_rmsnorm(out, out, norm.data, d, config->rms_norm_eps))- return -1;- coli_bf16_round_array(out, (size_t)d);- tokens[item] = -1; if (logits) logits[item] = -FLT_MAX;- }- const ColiSafetensorsTensor *head = coli_st_find(index, "head.weight");-#ifndef COLI_V4_DISABLE_ZERO_COPY_HEAD- const uint16_t *resident = head ? coli_v4_head_cache_data(- NULL, head->shard, head->offset, (size_t)head->nbytes) : NULL;- if (resident) {- float *resident_scores = malloc(- (size_t)batch * config->vocab_size * sizeof(*resident_scores));- if (!resident_scores) return -1;- #pragma omp parallel for schedule(static)- for (int row = 0; row < config->vocab_size; row++) {- float sums[64] = {0};- const uint16_t *weight = resident + (size_t)row * d;- for (int i = 0; i < d; i++) {- float decoded = coli_bf16_decode(weight[i]);- for (int item = 0; item < batch; item++)- sums[item] += decoded * hidden[(size_t)item * d + i];- }- for (int item = 0; item < batch; item++)- resident_scores[(size_t)item * config->vocab_size + row] =- sums[item];- }- for (int item = 0; item < batch; item++)- for (int row = 0; row < config->vocab_size; row++) {- float score = resident_scores[- (size_t)item * config->vocab_size + row];- float current = logits ? logits[item] :- (tokens[item] < 0 ? -FLT_MAX : 0.0f);- if (tokens[item] < 0 || score > current) {- tokens[item] = row;- if (logits) logits[item] = score;- }- }- free(resident_scores);- goto head_complete;- }-#endif- enum { ROWS = 32 };- uint16_t *raw = malloc((size_t)ROWS * d * sizeof(*raw));- float *scores = malloc((size_t)batch * ROWS * sizeof(*scores));- if (!head || head->dtype != COLI_ST_BF16 || !raw || !scores) return -1;- for (int start = 0; start < config->vocab_size; start += ROWS) {- int rows = config->vocab_size - start < ROWS- ? config->vocab_size - start : ROWS;- if (coli_st_read_at(index, head->shard,- head->offset + (uint64_t)start * d * 2,- (size_t)rows * d * sizeof(*raw), raw)) return -1;- #pragma omp parallel for collapse(2) schedule(static)- for (int item = 0; item < batch; item++) for (int row = 0; row < rows; row++) {- float sum = 0.0f; const uint16_t *weight = raw + (size_t)row * d;- const float *input = hidden + (size_t)item * d;- for (int i = 0; i < d; i++) sum += coli_bf16_decode(weight[i]) * input[i];- scores[(size_t)item * ROWS + row] = sum;- }- for (int item = 0; item < batch; item++) for (int row = 0; row < rows; row++) {- float score = scores[(size_t)item * ROWS + row];- float current = logits ? logits[item] :- (tokens[item] < 0 ? -FLT_MAX : 0.0f);- if (tokens[item] < 0 || score > current) {- tokens[item] = start + row;- if (logits) logits[item] = score;- }- }- }- free(scores); free(raw);-#ifndef COLI_V4_DISABLE_ZERO_COPY_HEAD-head_complete:-#endif- free(hidden);- coli_float_tensor_free(&norm); coli_float_tensor_free(&scale);- coli_float_tensor_free(&base); coli_float_tensor_free(&function);- return 0;-}-#endif /* COLI_V4_UNIT_TARGET_HEAD_BATCH */--#ifdef COLI_V4_UNIT_SPECULATIVE-/* ######## deepseek_v4_speculative.c ######## */-#include "deepseek_v4_dspark.h"--#include <string.h>--void coli_v4_speculative_controller_init(ColiV4SpeculativeController *state,- uint64_t minimum_proposals,- float disable_threshold) {- if (!state) return;- memset(state, 0, sizeof(*state));- state->minimum_proposals = minimum_proposals ? minimum_proposals : 32;- state->disable_threshold = disable_threshold > 0.0f &&- disable_threshold <= 1.0f- ? disable_threshold : 0.35f;- state->enabled = 1;-}--float coli_v4_speculative_acceptance(const ColiV4SpeculativeController *state) {- return state && state->proposed- ? (float)state->accepted / (float)state->proposed : 0.0f;-}--void coli_v4_speculative_record(ColiV4SpeculativeController *state,- int proposed, int accepted) {- if (!state || !state->enabled || proposed < 1 || accepted < 0 ||- accepted > proposed) return;- state->rounds++;- state->proposed += (uint64_t)proposed;- state->accepted += (uint64_t)accepted;- if (state->proposed >= state->minimum_proposals &&- coli_v4_speculative_acceptance(state) < state->disable_threshold)- state->enabled = 0;-}--int coli_v4_verify_greedy(ColiV4VerificationResult *result,- int *output_tokens, int output_capacity,- const int *draft_tokens, int draft_count,- const int *target_tokens, int target_count) {- if (!result || !output_tokens || !draft_tokens || !target_tokens ||- draft_count < 1 || target_count != draft_count + 1 ||- output_capacity < draft_count + 1) return -1;- int accepted = 0;- while (accepted < draft_count &&- draft_tokens[accepted] == target_tokens[accepted]) {- output_tokens[accepted] = draft_tokens[accepted];- accepted++;- }- output_tokens[accepted] = target_tokens[accepted];- result->accepted_draft_tokens = accepted;- result->output_count = accepted + 1;- result->mismatch_index = accepted < draft_count ? accepted : -1;- return 0;-}-#endif /* COLI_V4_UNIT_SPECULATIVE */--#ifdef COLI_V4_UNIT_DSPARK_HEADS-/* ######## deepseek_v4_dspark_heads.c ######## */-/* ---- begin inlined deepseek_v4_dspark_heads_v2.c ---- */-/* ---- begin inlined deepseek_v4_dspark_heads.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdarg.h>-#include <stdint.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "native_quant.h"-#include "safetensors_index.h"--struct ColiV4DSparkHeads {- int hidden, hc, targets, vocab, rank;- float rms_eps;- ColiTensorView main_proj;- unsigned char *main_weight;- unsigned char *main_scale;- float *main_norm;- uint16_t *markov_w1;- uint16_t *markov_w2;-};--static int heads_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;-}--static void *read_named(ColiSafetensorsIndex *index, const char *name,- ColiSafetensorsDType dtype, char *error, size_t size) {- const ColiSafetensorsTensor *tensor = coli_st_find(index, name);- if (!tensor || tensor->dtype != dtype) {- heads_error(error, size, "invalid DSpark head tensor: %s", name);- return NULL;- }- void *data = malloc((size_t)tensor->nbytes);- if (!data || coli_st_read_tensor(index, tensor, data)) {- free(data); heads_error(error, size, "cannot read DSpark head: %s", name);- return NULL;- }- return data;-}--void coli_v4_dspark_heads_close(ColiV4DSparkHeads *heads) {- if (!heads) return;- free(heads->markov_w2); free(heads->markov_w1); free(heads->main_norm);- free(heads->main_scale); free(heads->main_weight); free(heads);-}--int coli_v4_dspark_heads_open(ColiV4DSparkHeads **output,- const char *model_dir,- const ColiDeepSeekV4Config *config,- const ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size) {- if (!output || !model_dir || !config || !manifest ||- manifest->stage_count < 1) return -1;- *output = NULL; ColiSafetensorsIndex *index = NULL;- if (coli_st_index_open(&index, model_dir, error, error_size)) return -1;- ColiV4DSparkHeads *heads = calloc(1, sizeof(*heads));- if (!heads) { coli_st_index_close(index); return -1; }- heads->hidden = config->hidden_size; heads->hc = config->hc_mult;- heads->targets = manifest->target_count; heads->vocab = config->vocab_size;- heads->rank = manifest->markov_rank; heads->rms_eps = config->rms_norm_eps;- heads->main_weight = read_named(index, "mtp.0.main_proj.weight",- COLI_ST_F8_E4M3, error, error_size);- heads->main_scale = read_named(index, "mtp.0.main_proj.scale",- COLI_ST_F8_E8M0, error, error_size);- uint16_t *norm_bf16 = read_named(index, "mtp.0.main_norm.weight",- COLI_ST_BF16, error, error_size);- char name[160]; int last = manifest->stage_count - 1;- snprintf(name, sizeof(name), "mtp.%d.markov_head.markov_w1.weight", last);- heads->markov_w1 = read_named(index, name, COLI_ST_BF16, error, error_size);- snprintf(name, sizeof(name), "mtp.%d.markov_head.markov_w2.weight", last);- heads->markov_w2 = read_named(index, name, COLI_ST_BF16, error, error_size);- coli_st_index_close(index);- heads->main_norm = malloc((size_t)heads->hidden * sizeof(float));- if (!heads->main_weight || !heads->main_scale || !norm_bf16 ||- !heads->markov_w1 || !heads->markov_w2 || !heads->main_norm) {- free(norm_bf16); coli_v4_dspark_heads_close(heads); return -1;- }- for (int i = 0; i < heads->hidden; i++)- heads->main_norm[i] = coli_bf16_decode(norm_bf16[i]);- free(norm_bf16);- size_t columns = (size_t)heads->hidden * heads->targets;- heads->main_proj = (ColiTensorView){- COLI_TENSOR_FP8_E4M3_BLOCK, COLI_SCALE_UE8M0,- heads->main_weight, heads->main_scale,- (size_t)heads->hidden * columns,- (size_t)((heads->hidden + 127) / 128) * ((columns + 127) / 128),- heads->hidden, (int64_t)columns, 128, 128- };- *output = heads; return 0;-}--int coli_v4_dspark_combine_hidden(ColiV4DSparkHeads *heads, float *output,- const float *target_hidden_hc) {- if (!heads || !output || !target_hidden_hc) return -1;- size_t columns = (size_t)heads->hidden * heads->targets;- float *combined = malloc(columns * sizeof(*combined));- float *projected = malloc((size_t)heads->hidden * sizeof(*projected));- if (!combined || !projected) { free(projected); free(combined); return -1; }- size_t hc_width = (size_t)heads->hc * heads->hidden;- for (int target = 0; target < heads->targets; target++)- for (int column = 0; column < heads->hidden; column++) {- float sum = 0.0f;- for (int copy = 0; copy < heads->hc; copy++)- sum += target_hidden_hc[(size_t)target * hc_width +- (size_t)copy * heads->hidden + column];- combined[(size_t)target * heads->hidden + column] =- sum / (float)heads->hc;- }- int result = coli_fp8_matvec_ref(projected, &heads->main_proj, combined);- if (!result) {- coli_bf16_round_array(projected, (size_t)heads->hidden);- result = coli_v4_rmsnorm(output, projected, heads->main_norm,- heads->hidden, heads->rms_eps);- if (!result) coli_bf16_round_array(output, (size_t)heads->hidden);- }- free(projected); free(combined); return result;-}--int coli_v4_dspark_markov_bias(ColiV4DSparkHeads *heads, float *bias,- int previous_token) {- if (!heads || !bias || previous_token < 0 || previous_token >= heads->vocab)- return -1;- float *embedding = malloc((size_t)heads->rank * sizeof(*embedding));- if (!embedding) return -1;- const uint16_t *row = heads->markov_w1 + (size_t)previous_token * heads->rank;- for (int i = 0; i < heads->rank; i++) embedding[i] = coli_bf16_decode(row[i]);- #pragma omp parallel for schedule(static)- for (int64_t token = 0; token < heads->vocab; token++) {- const uint16_t *weight = heads->markov_w2 + (size_t)token * heads->rank;- float sum = 0.0f;- for (int i = 0; i < heads->rank; i++)- sum += embedding[i] * coli_bf16_decode(weight[i]);- bias[token] = sum;- }- free(embedding); return 0;-}-/* ---- end inlined deepseek_v4_dspark_heads.c ---- */---#include <float.h>----int coli_v4_dspark_biased_argmax(- ColiV4Engine *engine, ColiV4DSparkHeads *heads,- const ColiSafetensorsIndex *target_index, const float *hidden,- int previous_token, int *best_token, float *best_logit) {- if (!heads || !target_index || !hidden || !best_token || !best_logit ||- previous_token < 0 || previous_token >= heads->vocab) return -1;- const ColiSafetensorsTensor *head = coli_st_find(target_index, "head.weight");- if (!head || head->dtype != COLI_ST_BF16 || head->rank != 2 ||- head->shape[0] != heads->vocab || head->shape[1] != heads->hidden)- return -1;- enum { ROWS = 32 };- uint16_t *raw = malloc((size_t)ROWS * heads->hidden * sizeof(*raw));- float *scores = malloc((size_t)ROWS * sizeof(*scores));- float *markov = malloc((size_t)heads->rank * sizeof(*markov));- if (!raw || !scores || !markov) {- free(markov); free(scores); free(raw); return -1;- }- const uint16_t *m1 = heads->markov_w1 +- (size_t)previous_token * heads->rank;- for (int i = 0; i < heads->rank; i++) markov[i] = coli_bf16_decode(m1[i]);- int winner = -1; float maximum = -FLT_MAX;- for (int start = 0; start < heads->vocab; start += ROWS) {- int rows = heads->vocab - start < ROWS ? heads->vocab - start : ROWS;- size_t bytes = (size_t)rows * heads->hidden * sizeof(*raw);- if (coli_st_read_at_engine(- engine, target_index, head->shard,- head->offset + (uint64_t)start * heads->hidden * 2,- bytes, raw)) {- free(markov); free(scores); free(raw); return -1;- }- #pragma omp parallel for schedule(static)- for (int row = 0; row < rows; row++) {- float sum = 0.0f;- const uint16_t *weight = raw + (size_t)row * heads->hidden;- const uint16_t *m2 = heads->markov_w2 +- (size_t)(start + row) * heads->rank;- for (int i = 0; i < heads->hidden; i++)- sum += coli_bf16_decode(weight[i]) * hidden[i];- for (int i = 0; i < heads->rank; i++)- sum += coli_bf16_decode(m2[i]) * markov[i];- scores[row] = sum;- }- for (int row = 0; row < rows; row++)- if (scores[row] > maximum) {- maximum = scores[row]; winner = start + row;- }- }- free(markov); free(scores); free(raw);- *best_token = winner; *best_logit = maximum;- return winner < 0 ? -1 : 0;-}-/* ---- end inlined deepseek_v4_dspark_heads_v2.c ---- */-----int coli_v4_dspark_biased_argmax_batch(- ColiV4Engine *engine, ColiV4DSparkHeads *heads,- const ColiSafetensorsIndex *target_index, const float *hidden_batch,- int previous_token, int *best_tokens, float *best_logits, int batch) {- if (!heads || !target_index || !hidden_batch || !best_tokens ||- !best_logits || batch < 1 || batch > 64 || previous_token < 0 ||- previous_token >= heads->vocab) return -1;- const ColiSafetensorsTensor *head = coli_st_find(target_index, "head.weight");- if (!head || head->dtype != COLI_ST_BF16 || head->rank != 2 ||- head->shape[0] != heads->vocab || head->shape[1] != heads->hidden)- return -1;-- enum { ROWS = 32 };- uint16_t *raw = malloc((size_t)ROWS * heads->hidden * sizeof(*raw));- float *base = malloc((size_t)batch * heads->vocab * sizeof(*base));- float *markov = malloc((size_t)heads->rank * sizeof(*markov));- if (!raw || !base || !markov) {- free(markov); free(base); free(raw); return -1;- }-- /* Each sum still visits columns in scalar order; BF16 decode is shared. */- for (int start = 0; start < heads->vocab; start += ROWS) {- int rows = heads->vocab - start < ROWS ? heads->vocab - start : ROWS;- size_t bytes = (size_t)rows * heads->hidden * sizeof(*raw);- if (coli_st_read_at_engine(- engine, target_index, head->shard,- head->offset + (uint64_t)start * heads->hidden * 2,- bytes, raw)) {- free(markov); free(base); free(raw); return -1;- }- #pragma omp parallel for schedule(static)- for (int row = 0; row < rows; row++) {- const uint16_t *weight = raw + (size_t)row * heads->hidden;- float sums[64] = {0};- for (int i = 0; i < heads->hidden; i++) {- float decoded = coli_bf16_decode(weight[i]);- for (int item = 0; item < batch; item++)- sums[item] += decoded *- hidden_batch[(size_t)item * heads->hidden + i];- }- for (int item = 0; item < batch; item++)- base[(size_t)item * heads->vocab + start + row] = sums[item];- }- }-- for (int item = 0; item < batch; item++) {- const uint16_t *m1 = heads->markov_w1 +- (size_t)previous_token * heads->rank;- for (int i = 0; i < heads->rank; i++)- markov[i] = coli_bf16_decode(m1[i]);- float *scores = base + (size_t)item * heads->vocab;- #pragma omp parallel for schedule(static)- for (int token = 0; token < heads->vocab; token++) {- const uint16_t *m2 = heads->markov_w2 +- (size_t)token * heads->rank;- float sum = scores[token];- for (int i = 0; i < heads->rank; i++)- sum += coli_bf16_decode(m2[i]) * markov[i];- scores[token] = sum;- }- int winner = 0;- for (int token = 1; token < heads->vocab; token++)- if (scores[token] > scores[winner]) winner = token;- best_tokens[item] = winner;- best_logits[item] = scores[winner];- previous_token = winner;- }- free(markov); free(base); free(raw);- return 0;-}-#endif /* COLI_V4_UNIT_DSPARK_HEADS */--#ifdef COLI_V4_UNIT_DSPARK_CAPTURE-/* ######## deepseek_v4_dspark_capture.c ######## */-#include <math.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"--static int capture_init(ColiV4Engine *engine, const ColiDeepSeekV4Config *config) {- if (!engine) return -1;- if (engine->dspark_capture.heads) return 0;- ColiDeepSeekV4RuntimeOptions *runtime = &engine->runtime;- const char *model = runtime->dspark_model_dir;- char error[512];- if (!model ||- coli_v4_dspark_inspect(model, config, &engine->dspark_capture.manifest,- error, sizeof(error)) ||- coli_v4_dspark_heads_open(&engine->dspark_capture.heads, model, config,- &engine->dspark_capture.manifest, error,- sizeof(error))) {- fprintf(stderr, "dspark capture disabled: %s\n", model ? error :- "DSpark model path is unset");- return -1;- }- return 0;-}--static int target_ordinal(const ColiV4Engine *engine, int layer) {- for (int i = 0; i < engine->dspark_capture.manifest.target_count; i++)- if (engine->dspark_capture.manifest.target_layer_ids[i] == layer)- return i;- return -1;-}--static void capture_publish(ColiV4Engine *engine,- const ColiDeepSeekV4Config *config, int batch) {- size_t token_size = (size_t)config->hc_mult * config->hidden_size;- int targets = engine->dspark_capture.manifest.target_count;- float *joined = malloc((size_t)targets * token_size * sizeof(float));- float *main_x = malloc((size_t)config->hidden_size * sizeof(float));- if (!joined || !main_x) { free(main_x); free(joined); return; }- for (int item = 0; item < batch; item++) {- for (int target = 0; target < targets; target++)- memcpy(joined + (size_t)target * token_size,- engine->dspark_capture.states[target] +- (size_t)item * token_size,- token_size * sizeof(float));- if (coli_v4_dspark_combine_hidden(engine->dspark_capture.heads, main_x,- joined))- break;- double checksum = 0.0;- for (int i = 0; i < config->hidden_size; i++)- checksum += fabs((double)main_x[i]);- if (item == batch - 1)- fprintf(stderr, "dspark_main_x batch=%d first=%.9g l1=%.9g\n",- batch, main_x[0], checksum);- }- free(main_x); free(joined);-}--void coli_v4_dspark_capture_after_block(- ColiV4Engine *engine, const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, const float *outputs, int batch) {- if (!engine || !weights || !config || !outputs || batch < 1) return;- if (!engine->runtime.dspark_model_dir) return;- if (capture_init(engine, config)) return;- int ordinal = target_ordinal(engine, weights->plan.layer);- if (ordinal < 0) return;- size_t count = (size_t)batch * config->hc_mult * config->hidden_size;- if (count > engine->dspark_capture.capacity) {- for (int i = 0; i < engine->dspark_capture.manifest.target_count; i++) {- float *allocation = realloc(engine->dspark_capture.states[i],- count * sizeof(float));- if (!allocation) return;- engine->dspark_capture.states[i] = allocation;- }- engine->dspark_capture.capacity = count;- }- memcpy(engine->dspark_capture.states[ordinal], outputs,- count * sizeof(float));- if (ordinal == engine->dspark_capture.manifest.target_count - 1)- capture_publish(engine, config, batch);-}--static int capture_main_x_from_states(ColiV4Engine *engine, float *outputs,- int batch,- const ColiDeepSeekV4Config *config) {- if (!outputs || !config || batch < 1 || !engine ||- capture_init(engine, config) ||- engine->dspark_capture.capacity <- (size_t)batch * config->hc_mult * config->hidden_size)- return -1;- size_t token_size = (size_t)config->hc_mult * config->hidden_size;- int targets = engine->dspark_capture.manifest.target_count;- float *joined = malloc((size_t)targets * token_size * sizeof(*joined));- if (!joined) return -1;- int result = 0;- for (int item = 0; !result && item < batch; item++) {- for (int target = 0; target < targets; target++)- memcpy(joined + (size_t)target * token_size,- engine->dspark_capture.states[target] +- (size_t)item * token_size,- token_size * sizeof(*joined));- result = coli_v4_dspark_combine_hidden(- engine->dspark_capture.heads,- outputs + (size_t)item * config->hidden_size, joined);- }- free(joined); return result;-}--ColiV4DSparkHeads *coli_v4_dspark_capture_heads(ColiV4Engine *engine) {- return engine ? engine->dspark_capture.heads : NULL;-}--int coli_v4_dspark_capture_stage_main_x(ColiV4Engine *engine,- const float *values, int batch,- int hidden_size) {- if (!engine || !values || batch < 1 || batch > 64 || hidden_size < 1)- return -1;- size_t count = (size_t)batch * hidden_size;- float *copy = realloc(engine->dspark_capture.staged_main_x,- count * sizeof(*copy));- if (!copy) return -1;- engine->dspark_capture.staged_main_x = copy;- memcpy(engine->dspark_capture.staged_main_x, values,- count * sizeof(*copy));- engine->dspark_capture.staged_batch = batch;- engine->dspark_capture.staged_hidden = hidden_size;- return 0;-}--int coli_v4_dspark_capture_main_x(ColiV4Engine *engine, float *outputs,- int batch,- const ColiDeepSeekV4Config *config) {- if (engine && engine->dspark_capture.staged_batch) {- if (!outputs || !config || batch < 1 ||- batch > engine->dspark_capture.staged_batch ||- config->hidden_size != engine->dspark_capture.staged_hidden)- return -1;- memcpy(outputs, engine->dspark_capture.staged_main_x,- (size_t)batch * engine->dspark_capture.staged_hidden *- sizeof(*outputs));- engine->dspark_capture.staged_batch = 0;- return 0;- }- return capture_main_x_from_states(engine, outputs, batch, config);-}-#endif /* COLI_V4_UNIT_DSPARK_CAPTURE */---#ifdef COLI_V4_UNIT_TARGET_VERIFY-/* ######## deepseek_v4_target_verify.c ######## */-#define coli_v4_target_verify_greedy_batch \- coli_v4_target_verify_greedy_batch_v2_fallback-/* ---- begin inlined deepseek_v4_target_verify_v2.c ---- */-#include "deepseek_v4_dspark.h"--#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"--static int run_target_block_record(- ColiV4Engine *engine, float **state_ptr, float **next_ptr,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const int *tokens, int start, int batch, float *layer_inputs,- char *error, size_t error_size) {- float *state = *state_ptr, *next = *next_ptr;- size_t hd = (size_t)config->hc_mult * config->hidden_size;- for (int layer_id = 0; layer_id < config->num_hidden_layers; layer_id++) {- if (layer_inputs)- memcpy(layer_inputs + (size_t)layer_id * batch * hd, state,- (size_t)batch * hd * sizeof(float));- ColiDeepSeekV4LayerWeights layer;- if (coli_v4_layer_load(engine, &layer, config, index, layer_id,- error, error_size)) return -1;- int result = coli_v4_block_window_batch_ref(- next, attention[layer_id], &layer, config, experts,- state, tokens, start, batch, error, error_size);- if (!result)- coli_v4_dspark_capture_after_block(engine, &layer, config, next,- batch);- coli_v4_layer_free(engine, &layer);- if (result) return -1;- float *swap = state; state = next; next = swap;- }- *state_ptr = state; *next_ptr = next; return 0;-}--static int commit_target_attention(- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config,- const float *layer_inputs, int recorded_batch,- int start, int commit_batch, char *error, size_t error_size) {- size_t hd = (size_t)config->hc_mult * config->hidden_size;- for (int layer_id = 0; layer_id < config->num_hidden_layers; layer_id++) {- ColiDeepSeekV4LayerWeights layer;- if (coli_v4_layer_load(engine, &layer, config, index, layer_id,- error, error_size)) return -1;- int result = coli_v4_target_attention_commit_batch(- attention[layer_id], &layer, config,- layer_inputs + (size_t)layer_id * recorded_batch * hd,- start, commit_batch, error, error_size);- coli_v4_layer_free(engine, &layer);- if (result) return -1;- }- return 0;-}--int coli_v4_target_verify_greedy_batch(- ColiV4VerificationResult *verification,- int *output_tokens, int output_capacity,- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- int anchor_token, const int *draft_tokens, int draft_count,- int start_position, char *error, size_t error_size) {- if (!verification || !output_tokens || !attention || !index || !config ||- !experts || !draft_tokens || draft_count < 1 || draft_count > 63 ||- output_capacity < draft_count + 1) return -1;- int batch = draft_count + 1;- int *inputs = malloc((size_t)batch * sizeof(*inputs));- int *targets = malloc((size_t)batch * sizeof(*targets));- float *logits = malloc((size_t)batch * sizeof(*logits));- size_t hd = (size_t)config->hc_mult * config->hidden_size;- float *state = malloc((size_t)batch * hd * sizeof(*state));- float *next = malloc((size_t)batch * hd * sizeof(*next));- float *layer_inputs = malloc((size_t)config->num_hidden_layers *- batch * hd * sizeof(*layer_inputs));- ColiV4AttentionSnapshot **snapshots = calloc(- (size_t)config->num_hidden_layers, sizeof(*snapshots));- if (!inputs || !targets || !logits || !state || !next || !layer_inputs ||- !snapshots) return -1;- inputs[0] = anchor_token;- for (int i = 0; i < draft_count; i++) inputs[i + 1] = draft_tokens[i];- for (int layer = 0; layer < config->num_hidden_layers; layer++)- if (coli_v4_attention_snapshot_create(attention[layer],- &snapshots[layer])) return -1;- if (coli_v4_target_load_embeddings(state, index, config, inputs, batch) ||- run_target_block_record(engine, &state, &next, attention, index, config,- experts, inputs, start_position, batch,- layer_inputs, error, error_size) ||- coli_v4_target_head_argmax_batch(state, index, config, batch,- targets, logits, error, error_size) ||- coli_v4_verify_greedy(verification, output_tokens, output_capacity,- draft_tokens, draft_count, targets, batch))- return -1;- if (verification->accepted_draft_tokens < draft_count) {- for (int layer = 0; layer < config->num_hidden_layers; layer++)- if (coli_v4_attention_snapshot_restore(attention[layer],- snapshots[layer])) return -1;- int commit = verification->accepted_draft_tokens + 1;- if (commit_target_attention(engine, attention, index, config,- layer_inputs, batch, start_position, commit,- error, error_size)) return -1;- }- for (int layer = 0; layer < config->num_hidden_layers; layer++)- coli_v4_attention_snapshot_destroy(snapshots[layer]);- free(snapshots); free(layer_inputs); free(next); free(state);- free(logits); free(targets); free(inputs); return 0;-}-/* ---- end inlined deepseek_v4_target_verify_v2.c ---- */--#undef coli_v4_target_verify_greedy_batch--#include "deepseek_v4_dspark.h"---static void destroy_snapshots(ColiV4AttentionSnapshot **snapshots, int layers) {- if (!snapshots) return;- for (int layer = 0; layer < layers; layer++)- coli_v4_attention_snapshot_destroy(snapshots[layer]);- free(snapshots);-}--static int create_snapshots(- ColiV4AttentionSnapshot ***output,- ColiDeepSeekV4WindowAttentionState **attention, int layers) {- ColiV4AttentionSnapshot **snapshots = calloc(- (size_t)layers, sizeof(*snapshots));- if (!snapshots) return -1;- for (int layer = 0; layer < layers; layer++)- if (coli_v4_attention_snapshot_create(attention[layer],- &snapshots[layer])) {- destroy_snapshots(snapshots, layers); return -1;- }- *output = snapshots; return 0;-}--static int restore_snapshots(- ColiDeepSeekV4WindowAttentionState **attention,- ColiV4AttentionSnapshot **snapshots, int layers) {- for (int layer = 0; layer < layers; layer++)- if (coli_v4_attention_snapshot_restore(attention[layer],- snapshots[layer])) return -1;- return 0;-}--int coli_v4_target_verify_greedy_batch(- ColiV4VerificationResult *verification,- int *output_tokens, int output_capacity,- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- int anchor_token, const int *draft_tokens, int draft_count,- int start_position, char *error, size_t error_size) {- if (draft_count != 4)- return coli_v4_target_verify_greedy_batch_v2_fallback(- verification, output_tokens, output_capacity, engine, attention,- index, config, experts, anchor_token, draft_tokens, draft_count,- start_position, error, error_size);- if (!verification || !output_tokens || output_capacity < 5 || !attention ||- !index || !config || !experts || !draft_tokens) return -1;-- enum { FIRST_BATCH = 3, TAIL_BATCH = 2 };- int first_inputs[FIRST_BATCH] = {- anchor_token, draft_tokens[0], draft_tokens[1]- };- int first_targets[FIRST_BATCH]; float first_logits[FIRST_BATCH];- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)d * hc;- size_t layer_stride_first = (size_t)FIRST_BATCH * hd;- float *state = malloc((size_t)FIRST_BATCH * hd * sizeof(*state));- float *next = malloc((size_t)FIRST_BATCH * hd * sizeof(*next));- float *layer_inputs = malloc((size_t)config->num_hidden_layers *- layer_stride_first * sizeof(*layer_inputs));- float *combined_main_x = malloc((FIRST_BATCH + TAIL_BATCH) *- (size_t)d * sizeof(*combined_main_x));- ColiV4AttentionSnapshot **snapshots = NULL;- if (!state || !next || !layer_inputs || !combined_main_x ||- create_snapshots(&snapshots, attention, config->num_hidden_layers))- return -1;- int result = coli_v4_target_load_embeddings(- state, index, config, first_inputs, FIRST_BATCH) ||- run_target_block_record(- engine, &state, &next, attention, index, config, experts,- first_inputs, start_position, FIRST_BATCH, layer_inputs,- error, error_size) ||- coli_v4_target_head_argmax_batch(- state, index, config, FIRST_BATCH,- first_targets, first_logits, error, error_size) ||- coli_v4_dspark_capture_main_x(engine, combined_main_x, FIRST_BATCH, config);- if (result) goto cleanup;- int accepted = 0;- while (accepted < FIRST_BATCH &&- draft_tokens[accepted] == first_targets[accepted]) accepted++;- if (accepted < FIRST_BATCH) {- for (int i = 0; i < accepted; i++) output_tokens[i] = draft_tokens[i];- output_tokens[accepted] = first_targets[accepted];- verification->accepted_draft_tokens = accepted;- verification->output_count = accepted + 1;- verification->mismatch_index = accepted;- int commit = accepted + 1;- if (commit < FIRST_BATCH &&- (restore_snapshots(attention, snapshots,- config->num_hidden_layers) ||- commit_target_attention(- engine, attention, index, config, layer_inputs, FIRST_BATCH,- start_position, commit, error, error_size))) result = -1;- goto cleanup;- }- destroy_snapshots(snapshots, config->num_hidden_layers); snapshots = NULL;- free(layer_inputs); layer_inputs = NULL;- free(next); free(state); next = NULL; state = NULL;-- int tail_inputs[TAIL_BATCH] = {draft_tokens[2], draft_tokens[3]};- int tail_targets[TAIL_BATCH]; float tail_logits[TAIL_BATCH];- state = malloc((size_t)TAIL_BATCH * hd * sizeof(*state));- next = malloc((size_t)TAIL_BATCH * hd * sizeof(*next));- layer_inputs = malloc((size_t)config->num_hidden_layers * TAIL_BATCH *- hd * sizeof(*layer_inputs));- if (!state || !next || !layer_inputs ||- create_snapshots(&snapshots, attention, config->num_hidden_layers)) {- result = -1; goto cleanup;- }- result = coli_v4_target_load_embeddings(- state, index, config, tail_inputs, TAIL_BATCH) ||- run_target_block_record(- engine, &state, &next, attention, index, config, experts,- tail_inputs, start_position + FIRST_BATCH, TAIL_BATCH,- layer_inputs, error, error_size) ||- coli_v4_target_head_argmax_batch(- state, index, config, TAIL_BATCH,- tail_targets, tail_logits, error, error_size) ||- coli_v4_dspark_capture_main_x(engine, combined_main_x + (size_t)FIRST_BATCH * d,- TAIL_BATCH, config);- if (result) goto cleanup;- for (int i = 0; i < FIRST_BATCH; i++) output_tokens[i] = draft_tokens[i];- if (draft_tokens[3] == tail_targets[0]) {- output_tokens[3] = draft_tokens[3];- output_tokens[4] = tail_targets[1];- verification->accepted_draft_tokens = 4;- verification->output_count = 5;- verification->mismatch_index = -1;- result = coli_v4_dspark_capture_stage_main_x(engine, combined_main_x, 5, d);- } else {- output_tokens[3] = tail_targets[0];- verification->accepted_draft_tokens = 3;- verification->output_count = 4;- verification->mismatch_index = 3;- if (restore_snapshots(attention, snapshots,- config->num_hidden_layers) ||- commit_target_attention(- engine, attention, index, config, layer_inputs, TAIL_BATCH,- start_position + FIRST_BATCH, 1, error, error_size) ||- coli_v4_dspark_capture_stage_main_x(engine, combined_main_x, 4, d))- result = -1;- }--cleanup:- destroy_snapshots(snapshots, config->num_hidden_layers);- free(combined_main_x); free(layer_inputs); free(next); free(state);- return result;-}-#endif /* COLI_V4_UNIT_TARGET_VERIFY */--#ifdef COLI_V4_UNIT_TARGET_ATTENTION_COMMIT-/* ######## deepseek_v4_target_attention_commit.c ######## */-#include "deepseek_v4_internal.h"-#define coli_v4_block_token_batch_serial_ref \- coli_v4_commit_block_token_serial_ref-#define coli_v4_block_window_token_batch_serial_ref \- coli_v4_commit_block_window_token_serial_ref-/* ---- begin inlined deepseek_v4_target_attention_commit.c ---- */-#define coli_v4_block_window_batch_ref coli_v4_commit_unused_full_block-/* ---- begin include deepseek_v4_block_batch.c ---- */-#define coli_v4_block_token_ref coli_v4_block_token_batch_serial_ref-#define coli_v4_block_window_token_ref coli_v4_block_window_token_batch_serial_ref-/* ---- begin include deepseek_v4_block.c ---- */-#include "deepseek_v4_internal.h"--#include <stdarg.h>-#include <stdint.h>-#include <stdio.h>-#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.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;-}--static const void *value(const ColiDeepSeekV4LayerWeights *weights,- const char *suffix,- const ColiDeepSeekV4TensorSpec **spec) {- char name[COLI_V4_MAX_TENSOR_NAME];- snprintf(name, sizeof(name), "layers.%d.%s", weights->plan.layer, suffix);- return coli_v4_layer_data(weights, name, spec);-}--static int fp8_view(ColiTensorView *view,- const ColiDeepSeekV4LayerWeights *weights,- const char *prefix) {- char name[128];- const ColiDeepSeekV4TensorSpec *ws = NULL, *ss = NULL;- snprintf(name, sizeof(name), "%s.weight", prefix);- const void *data = value(weights, name, &ws);- snprintf(name, sizeof(name), "%s.scale", prefix);- const void *scales = value(weights, name, &ss);- if (!data || !scales || !ws || !ss || ws->rank != 2) return -1;- *view = (ColiTensorView){- COLI_TENSOR_FP8_E4M3_BLOCK, COLI_SCALE_UE8M0, data, scales,- (size_t)(ws->shape[0] * ws->shape[1]),- (size_t)(ss->shape[0] * ss->shape[1]),- ws->shape[0], ws->shape[1], 128, 128- };- return 0;-}--static void decode_bf16(float *output, const uint16_t *input, size_t count) {- for (size_t i = 0; i < count; i++) output[i] = coli_bf16_decode(input[i]);-}--static int normalized_hc_pre(float *reduced, float *post, float *comb,- float *normalized, const float *input_hc,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const char *branch, const char *norm_name) {- char name[64];- snprintf(name, sizeof(name), "hc_%s_fn", branch);- const float *function = value(weights, name, NULL);- snprintf(name, sizeof(name), "hc_%s_scale", branch);- const float *scale = value(weights, name, NULL);- snprintf(name, sizeof(name), "hc_%s_base", branch);- const float *base = value(weights, name, NULL);- const uint16_t *raw_norm = value(weights, norm_name, NULL);- int d = config->hidden_size;- float *norm = malloc((size_t)d * sizeof(*norm));- if (!function || !scale || !base || !raw_norm || !norm) {- free(norm);- return -1;- }- decode_bf16(norm, raw_norm, (size_t)d);- int result = coli_v4_hc_pre(reduced, post, comb, input_hc, function,- scale, base, config->hc_mult, d,- config->hc_sinkhorn_iters,- config->rms_norm_eps, config->hc_eps);- if (!result) {- coli_bf16_round_array(reduced, (size_t)d);- result = coli_v4_rmsnorm(normalized, reduced, norm, d,- config->rms_norm_eps);- coli_bf16_round_array(normalized, (size_t)d);- }- free(norm);- return result;-}--static int moe_token(float *output,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *store, const float *input, int token) {- int d = config->hidden_size;- int n = config->n_routed_experts;- int topk = config->num_experts_per_tok;- size_t gate_count = (size_t)n * d;- float *gate = malloc(gate_count * sizeof(*gate));- float *route_weights = malloc((size_t)topk * sizeof(*route_weights));- int *indices = malloc((size_t)topk * sizeof(*indices));- float *expert_output = malloc((size_t)d * sizeof(*expert_output));- float *shared_output = malloc((size_t)d * sizeof(*shared_output));- if (!gate || !route_weights || !indices || !expert_output || !shared_output) {- free(shared_output); free(expert_output); free(indices);- free(route_weights); free(gate);- return -1;- }- decode_bf16(gate, value(weights, "ffn.gate.weight", NULL), gate_count);- const int64_t *table = value(weights, "ffn.gate.tid2eid", NULL);- const float *bias = value(weights, "ffn.gate.bias", NULL);- int result = token < 0 || token >= config->vocab_size;- if (!result && weights->plan.uses_hash_router) {- if (!table) result = -1;- }- if (!result && weights->plan.uses_hash_router) {- for (int i = 0; i < topk; i++)- indices[i] = (int)table[(size_t)token * topk + i];- }- if (!result) result = coli_v4_route(- route_weights, indices, input, gate, bias,- weights->plan.uses_hash_router ? indices : NULL,- n, d, topk, config->routed_scaling_factor);-- ColiTensorView w1, w2, w3;- if (!result && (fp8_view(&w1, weights, "ffn.shared_experts.w1") ||- fp8_view(&w2, weights, "ffn.shared_experts.w2") ||- fp8_view(&w3, weights, "ffn.shared_experts.w3"))) result = -1;- if (!result) result = coli_v4_shared_expert_forward_ref(- shared_output, &w1, &w2, &w3, input, config->swiglu_limit);- if (!result) memset(output, 0, (size_t)d * sizeof(*output));- for (int expert_id = 0; !result && expert_id < n; expert_id++) {- int rank = -1;- for (int candidate = 0; candidate < topk; candidate++)- if (indices[candidate] == expert_id) rank = candidate;- if (rank < 0) continue;- ColiExpertView expert;- if (coli_expert_lookup(store,- (ColiExpertKey){weights->plan.layer, expert_id},- &expert)) {- result = -1;- break;- }- result = coli_v4_expert_forward_ref(expert_output, &expert, input,- route_weights[rank],- config->swiglu_limit);- coli_expert_release(store, &expert);- if (!result)- for (int i = 0; i < d; i++) output[i] += expert_output[i];- }- if (!result)- for (int i = 0; i < d; i++)- output[i] = coli_bf16_round(output[i] + shared_output[i]);- free(shared_output); free(expert_output); free(indices);- free(route_weights); free(gate);- return result;-}--static int block_token_impl(float *output_hc,- ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- if (!output_hc || !weights || !config || !experts || !input_hc)- return set_error(error, error_size, "invalid block arguments");- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *residual = malloc(hd * sizeof(*residual));- float *state = malloc(hd * sizeof(*state));- float *reduced = malloc((size_t)d * sizeof(*reduced));- float *normalized = malloc((size_t)d * sizeof(*normalized));- float *branch = malloc((size_t)d * sizeof(*branch));- float *post = malloc((size_t)hc * sizeof(*post));- float *comb = malloc((size_t)hc * hc * sizeof(*comb));- if (!residual || !state || !reduced || !normalized || !branch || !post || !comb) {- free(comb); free(post); free(branch); free(normalized);- free(reduced); free(state); free(residual);- return set_error(error, error_size, "out of memory in block");- }- memcpy(residual, input_hc, hd * sizeof(*residual));- int result = normalized_hc_pre(reduced, post, comb, normalized, input_hc,- weights, config, "attn", "attn_norm.weight");- if (!result) result = attention- ? coli_v4_attention_window_token_ref(branch, attention, weights, config,- normalized, position, error, error_size)- : coli_v4_attention_token_ref(branch, weights, config, normalized,- position, error, error_size);- if (!result) result = coli_v4_hc_post(state, branch, residual, post, comb, hc, d);- if (!result) coli_bf16_round_array(state, hd);-- if (!result) memcpy(residual, state, hd * sizeof(*residual));- if (!result) result = normalized_hc_pre(reduced, post, comb, normalized, state,- weights, config, "ffn", "ffn_norm.weight");- if (!result) result = moe_token(branch, weights, config, experts, normalized, token);- if (!result) result = coli_v4_hc_post(output_hc, branch, residual, post, comb, hc, d);- if (!result) coli_bf16_round_array(output_hc, hd);-- free(comb); free(post); free(branch); free(normalized);- free(reduced); free(state); free(residual);- return result ? set_error(error, error_size, "block computation failed") : 0;-}--int coli_v4_block_token_ref(float *output_hc,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- return block_token_impl(output_hc, NULL, weights, config, experts, input_hc,- token, position, error, error_size);-}--int coli_v4_block_window_token_ref(- float *output_hc, ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *input_hc, int token, int position,- char *error, size_t error_size) {- return block_token_impl(output_hc, attention, weights, config, experts,- input_hc, token, position, error, error_size);-}-/* ---- end include deepseek_v4_block.c ---- */--#undef coli_v4_block_token_ref-#undef coli_v4_block_window_token_ref--#include "deepseek_v4_internal.h"-#include "native_quant_batch.h"--static int shared_expert_batch(float *outputs, const ColiTensorView *w1,- const ColiTensorView *w2,- const ColiTensorView *w3,- const float *inputs, int batch,- float swiglu_limit) {- int intermediate = (int)w1->rows, d = (int)w2->rows;- float *gate = malloc((size_t)batch * intermediate * sizeof(*gate));- float *up = malloc((size_t)batch * intermediate * sizeof(*up));- float *activated = malloc((size_t)batch * intermediate * sizeof(*activated));- if (!gate || !up || !activated) {- free(activated); free(up); free(gate); return -1;- }- int result = coli_fp8_matmul_batch_ref(gate, w1, inputs, batch) ||- coli_fp8_matmul_batch_ref(up, w3, inputs, batch);- for (int item = 0; !result && item < batch; item++) {- float *item_gate = gate + (size_t)item * intermediate;- float *item_up = up + (size_t)item * intermediate;- float *item_activated = activated + (size_t)item * intermediate;- coli_bf16_round_array(item_gate, (size_t)intermediate);- coli_bf16_round_array(item_up, (size_t)intermediate);- result = coli_v4_swiglu(item_activated, item_gate, item_up,- intermediate, swiglu_limit);- if (!result) coli_bf16_round_array(item_activated,- (size_t)intermediate);- }- if (!result) result = coli_fp8_matmul_batch_ref(- outputs, w2, activated, batch);- if (!result) coli_bf16_round_array(outputs, (size_t)batch * d);- free(activated); free(up); free(gate);- return result;-}--static int routed_expert_batch(float *outputs, const ColiExpertView *expert,- const float *inputs, const float *route_weights,- int batch, float swiglu_limit) {- int intermediate = (int)expert->gate.rows;- int d = (int)expert->down.rows;- float *gate = malloc((size_t)batch * intermediate * sizeof(*gate));- float *up = malloc((size_t)batch * intermediate * sizeof(*up));- float *activated = malloc((size_t)batch * intermediate * sizeof(*activated));- if (!gate || !up || !activated) {- free(activated); free(up); free(gate); return -1;- }- int result = coli_fp4_matmul_batch_ref(gate, &expert->gate, inputs, batch) ||- coli_fp4_matmul_batch_ref(up, &expert->up, inputs, batch);- for (int item = 0; !result && item < batch; item++) {- float *item_gate = gate + (size_t)item * intermediate;- float *item_up = up + (size_t)item * intermediate;- float *item_activated = activated + (size_t)item * intermediate;- coli_bf16_round_array(item_gate, (size_t)intermediate);- coli_bf16_round_array(item_up, (size_t)intermediate);- result = coli_v4_swiglu(item_activated, item_gate, item_up,- intermediate, swiglu_limit);- for (int i = 0; !result && i < intermediate; i++)- item_activated[i] = coli_bf16_round(- item_activated[i] * route_weights[item]);- }- if (!result) result = coli_fp4_matmul_batch_ref(- outputs, &expert->down, activated, batch);- if (!result) coli_bf16_round_array(outputs, (size_t)batch * d);- free(activated); free(up); free(gate);- return result;-}--static int moe_batch(float *outputs,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- ColiExpertStore *store, const float *inputs,- const int *tokens, int batch) {- int d = config->hidden_size, n = config->n_routed_experts;- int topk = config->num_experts_per_tok;- float *gate = malloc((size_t)n * d * sizeof(*gate));- float *route_weights = malloc((size_t)batch * topk * sizeof(*route_weights));- int *indices = malloc((size_t)batch * topk * sizeof(*indices));- float *shared = malloc((size_t)batch * d * sizeof(*shared));- float *compact_inputs = malloc((size_t)batch * d * sizeof(*compact_inputs));- float *compact_outputs = malloc((size_t)batch * d * sizeof(*compact_outputs));- float *compact_weights = malloc((size_t)batch * sizeof(*compact_weights));- int *compact_items = malloc((size_t)batch * sizeof(*compact_items));- if (!gate || !route_weights || !indices || !shared || !compact_inputs ||- !compact_outputs || !compact_weights || !compact_items) {- free(compact_items); free(compact_weights); free(compact_outputs);- free(compact_inputs); free(shared); free(indices); free(route_weights);- free(gate); return -1;- }- decode_bf16(gate, value(weights, "ffn.gate.weight", NULL), (size_t)n * d);- const int64_t *table = value(weights, "ffn.gate.tid2eid", NULL);- const float *bias = value(weights, "ffn.gate.bias", NULL);- int result = 0;- for (int item = 0; !result && item < batch; item++) {- int *item_indices = indices + (size_t)item * topk;- float *item_weights = route_weights + (size_t)item * topk;- if (tokens[item] < 0 || tokens[item] >= config->vocab_size) result = -1;- if (!result && weights->plan.uses_hash_router) {- if (!table) result = -1;- else for (int i = 0; i < topk; i++)- item_indices[i] = (int)table[(size_t)tokens[item] * topk + i];- }- if (!result) result = coli_v4_route(- item_weights, item_indices, inputs + (size_t)item * d,- gate, bias, weights->plan.uses_hash_router ? item_indices : NULL,- n, d, topk, config->routed_scaling_factor);- }- ColiTensorView w1, w2, w3;- if (!result && (fp8_view(&w1, weights, "ffn.shared_experts.w1") ||- fp8_view(&w2, weights, "ffn.shared_experts.w2") ||- fp8_view(&w3, weights, "ffn.shared_experts.w3"))) result = -1;- if (!result) result = shared_expert_batch(- shared, &w1, &w2, &w3, inputs, batch, config->swiglu_limit);- if (!result) memset(outputs, 0, (size_t)batch * d * sizeof(*outputs));-- for (int expert_id = 0; !result && expert_id < n; expert_id++) {- int count = 0;- for (int item = 0; item < batch; item++) {- for (int rank = 0; rank < topk; rank++) {- if (indices[(size_t)item * topk + rank] == expert_id) {- compact_items[count] = item;- compact_weights[count] =- route_weights[(size_t)item * topk + rank];- memcpy(compact_inputs + (size_t)count * d,- inputs + (size_t)item * d, (size_t)d * sizeof(float));- count++;- }- }- }- if (!count) continue;- ColiExpertView expert;- if (coli_expert_lookup(store,- (ColiExpertKey){weights->plan.layer, expert_id},- &expert)) { result = -1; break; }- result = routed_expert_batch(compact_outputs, &expert, compact_inputs,- compact_weights, count,- config->swiglu_limit);- coli_expert_release(store, &expert);- for (int compact = 0; !result && compact < count; compact++) {- float *destination = outputs + (size_t)compact_items[compact] * d;- const float *source = compact_outputs + (size_t)compact * d;- for (int i = 0; i < d; i++) destination[i] += source[i];- }- }- for (int item = 0; !result && item < batch; item++)- for (int i = 0; i < d; i++)- outputs[(size_t)item * d + i] = coli_bf16_round(- outputs[(size_t)item * d + i] + shared[(size_t)item * d + i]);- free(compact_items); free(compact_weights); free(compact_outputs);- free(compact_inputs); free(shared); free(indices); free(route_weights);- free(gate); return result;-}--int coli_v4_block_window_batch_ref(- float *outputs_hc, ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *inputs_hc, const int *tokens, int start_position, int batch,- char *error, size_t error_size) {- if (!outputs_hc || !attention || !weights || !config || !experts ||- !inputs_hc || !tokens || batch < 1 || batch > 64) return -1;- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *states = malloc((size_t)batch * hd * sizeof(*states));- float *normalized_ffn = malloc((size_t)batch * d * sizeof(*normalized_ffn));- float *branches = malloc((size_t)batch * d * sizeof(*branches));- float *posts = malloc((size_t)batch * hc * sizeof(*posts));- float *combs = malloc((size_t)batch * hc * hc * sizeof(*combs));- float *residual = malloc(hd * sizeof(*residual));- float *reduced = malloc((size_t)d * sizeof(*reduced));- float *normalized = malloc((size_t)d * sizeof(*normalized));- float *branch = malloc((size_t)d * sizeof(*branch));- float *post = malloc((size_t)hc * sizeof(*post));- float *comb = malloc((size_t)hc * hc * sizeof(*comb));- if (!states || !normalized_ffn || !branches || !posts || !combs ||- !residual || !reduced || !normalized || !branch || !post || !comb) {- free(comb); free(post); free(branch); free(normalized); free(reduced);- free(residual); free(combs); free(posts); free(branches);- free(normalized_ffn); free(states); return -1;- }- int result = 0;- for (int item = 0; !result && item < batch; item++) {- const float *input = inputs_hc + (size_t)item * hd;- float *state = states + (size_t)item * hd;- memcpy(residual, input, hd * sizeof(float));- result = normalized_hc_pre(reduced, post, comb, normalized, input,- weights, config, "attn", "attn_norm.weight");- if (!result) result = coli_v4_attention_window_token_ref(- branch, attention, weights, config, normalized,- start_position + item, error, error_size);- if (!result) result = coli_v4_hc_post(state, branch, residual,- post, comb, hc, d);- if (!result) coli_bf16_round_array(state, hd);- if (!result) result = normalized_hc_pre(- reduced, posts + (size_t)item * hc,- combs + (size_t)item * hc * hc,- normalized_ffn + (size_t)item * d, state,- weights, config, "ffn", "ffn_norm.weight");- }- if (!result) result = moe_batch(branches, weights, config, experts,- normalized_ffn, tokens, batch);- for (int item = 0; !result && item < batch; item++) {- result = coli_v4_hc_post(- outputs_hc + (size_t)item * hd,- branches + (size_t)item * d,- states + (size_t)item * hd,- posts + (size_t)item * hc,- combs + (size_t)item * hc * hc, hc, d);- if (!result) coli_bf16_round_array(- outputs_hc + (size_t)item * hd, hd);- }- free(comb); free(post); free(branch); free(normalized); free(reduced);- free(residual); free(combs); free(posts); free(branches);- free(normalized_ffn); free(states);- return result ? set_error(error, error_size, "batched block failed") : 0;-}-/* ---- end include deepseek_v4_block_batch.c ---- */--#undef coli_v4_block_window_batch_ref--#include "deepseek_v4_dspark.h"--int coli_v4_target_attention_commit_batch(- ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const float *inputs_hc, int start_position, int batch,- char *error, size_t error_size) {- if (!attention || !weights || !config || !inputs_hc ||- start_position < 0 || batch < 1 || batch > 64) return -1;- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)hc * d;- float *normalized = malloc((size_t)batch * d * sizeof(*normalized));- float *discarded = malloc((size_t)batch * d * sizeof(*discarded));- float *reduced = malloc((size_t)d * sizeof(*reduced));- float *post = malloc((size_t)hc * sizeof(*post));- float *comb = malloc((size_t)hc * hc * sizeof(*comb));- if (!normalized || !discarded || !reduced || !post || !comb) {- free(comb); free(post); free(reduced); free(discarded); free(normalized);- return -1;- }- int result = 0;- for (int item = 0; !result && item < batch; item++)- result = normalized_hc_pre(- reduced, post, comb, normalized + (size_t)item * d,- inputs_hc + (size_t)item * hd, weights, config,- "attn", "attn_norm.weight");- if (!result) result = coli_v4_attention_window_batch_ref(- discarded, attention, weights, config, normalized,- start_position, batch, error, error_size);- free(comb); free(post); free(reduced); free(discarded); free(normalized);- return result;-}-/* ---- end inlined deepseek_v4_target_attention_commit.c ---- */--#undef coli_v4_block_window_token_batch_serial_ref-#undef coli_v4_block_token_batch_serial_ref-#endif /* COLI_V4_UNIT_TARGET_ATTENTION_COMMIT */--#ifdef COLI_V4_UNIT_TARGET_VERIFY_PREFIX-/* ######## deepseek_v4_target_verify_prefix.c ######## */-#include "deepseek_v4_dspark.h"--#include <stdlib.h>-#include <string.h>--#include "deepseek_v4_internal.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_internal.h"-#include "deepseek_v4_dspark.h"-#include "deepseek_v4_dspark.h"--static void prefix_destroy_snapshots(ColiV4AttentionSnapshot **snapshots,- int layers) {- if (!snapshots) return;- for (int layer = 0; layer < layers; layer++)- coli_v4_attention_snapshot_destroy(snapshots[layer]);- free(snapshots);-}--static int prefix_create_snapshots(- ColiV4AttentionSnapshot ***output,- ColiDeepSeekV4WindowAttentionState **attention, int layers) {- ColiV4AttentionSnapshot **snapshots = calloc(- (size_t)layers, sizeof(*snapshots));- if (!snapshots) return -1;- for (int layer = 0; layer < layers; layer++)- if (coli_v4_attention_snapshot_create(attention[layer],- &snapshots[layer])) {- prefix_destroy_snapshots(snapshots, layers); return -1;- }- *output = snapshots;- return 0;-}--static int prefix_restore_snapshots(- ColiDeepSeekV4WindowAttentionState **attention,- ColiV4AttentionSnapshot **snapshots, int layers) {- for (int layer = 0; layer < layers; layer++)- if (coli_v4_attention_snapshot_restore(attention[layer],- snapshots[layer])) return -1;- return 0;-}--static int prefix_run_target_batch(- ColiV4Engine *engine, float **state_ptr, float **next_ptr,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const int *tokens, int start, int batch, float *layer_inputs,- char *error, size_t error_size) {- float *state = *state_ptr, *next = *next_ptr;- size_t hd = (size_t)config->hc_mult * config->hidden_size;- for (int layer_id = 0; layer_id < config->num_hidden_layers; layer_id++) {- memcpy(layer_inputs + (size_t)layer_id * batch * hd, state,- (size_t)batch * hd * sizeof(*state));- ColiDeepSeekV4LayerWeights layer;- if (coli_v4_layer_load(engine, &layer, config, index, layer_id,- error, error_size)) return -1;- int result = coli_v4_block_window_batch_ref(- next, attention[layer_id], &layer, config, experts,- state, tokens, start, batch, error, error_size);- if (!result)- coli_v4_dspark_capture_after_block(engine, &layer, config, next,- batch);- coli_v4_layer_free(engine, &layer);- if (result) return -1;- float *swap = state; state = next; next = swap;- }- *state_ptr = state;- *next_ptr = next;- return 0;-}--static int prefix_commit_attention(- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config,- const float *layer_inputs, int recorded_batch,- int start, int commit_batch, char *error, size_t error_size) {- size_t hd = (size_t)config->hc_mult * config->hidden_size;- for (int layer_id = 0; layer_id < config->num_hidden_layers; layer_id++) {- ColiDeepSeekV4LayerWeights layer;- if (coli_v4_layer_load(engine, &layer, config, index, layer_id,- error, error_size)) return -1;- int result = coli_v4_target_attention_commit_batch(- attention[layer_id], &layer, config,- layer_inputs + (size_t)layer_id * recorded_batch * hd,- start, commit_batch, error, error_size);- coli_v4_layer_free(engine, &layer);- if (result) return -1;- }- return 0;-}--int coli_v4_target_verify_after_prefix_v69(- ColiV4VerificationResult *verification,- int *output_tokens, int output_capacity,- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const int *draft_tokens, int draft_count, int prefix_position,- const float *prefix_main_x, char *error, size_t error_size) {- enum { FIRST_BATCH = 2, TAIL_BATCH = 2, TOTAL_ROWS = 5 };- if (!verification || !output_tokens || output_capacity < TOTAL_ROWS ||- !attention || !index || !config || !experts || !draft_tokens ||- draft_count != 4 || prefix_position < 0 || !prefix_main_x) return -1;-- int result = 0;- int d = config->hidden_size, hc = config->hc_mult;- size_t hd = (size_t)d * hc;- float *combined_main_x = malloc((size_t)TOTAL_ROWS * d * sizeof(float));- float *state = malloc((size_t)FIRST_BATCH * hd * sizeof(float));- float *next = malloc((size_t)FIRST_BATCH * hd * sizeof(float));- float *layer_inputs = malloc((size_t)config->num_hidden_layers *- FIRST_BATCH * hd * sizeof(float));- ColiV4AttentionSnapshot **snapshots = NULL;- if (!combined_main_x || !state || !next || !layer_inputs ||- prefix_create_snapshots(&snapshots, attention,- config->num_hidden_layers)) {- result = -1; goto cleanup;- }- memcpy(combined_main_x, prefix_main_x, (size_t)d * sizeof(float));-- int first_inputs[FIRST_BATCH] = {draft_tokens[0], draft_tokens[1]};- int first_targets[FIRST_BATCH];- float first_logits[FIRST_BATCH];- result = coli_v4_target_load_embeddings(- state, index, config, first_inputs, FIRST_BATCH) ||- prefix_run_target_batch(- engine, &state, &next, attention, index, config, experts,- first_inputs, prefix_position + 1, FIRST_BATCH,- layer_inputs, error, error_size) ||- coli_v4_target_head_argmax_batch(- state, index, config, FIRST_BATCH,- first_targets, first_logits, error, error_size) ||- coli_v4_dspark_capture_main_x(engine, combined_main_x + d, FIRST_BATCH, config);- if (result) goto cleanup;-- output_tokens[0] = draft_tokens[0];- int accepted = 0;- while (accepted < FIRST_BATCH &&- draft_tokens[accepted + 1] == first_targets[accepted]) {- output_tokens[accepted + 1] = draft_tokens[accepted + 1];- accepted++;- }- if (accepted < FIRST_BATCH) {- int commit = accepted + 1;- output_tokens[accepted + 1] = first_targets[accepted];- verification->accepted_draft_tokens = accepted + 1;- verification->output_count = accepted + 2;- verification->mismatch_index = accepted + 1;- if (prefix_restore_snapshots(attention, snapshots,- config->num_hidden_layers) ||- prefix_commit_attention(- engine, attention, index, config, layer_inputs, FIRST_BATCH,- prefix_position + 1, commit, error, error_size) ||- coli_v4_dspark_capture_stage_main_x(engine, combined_main_x, commit + 1, d)) result = -1;- goto cleanup;- }-- prefix_destroy_snapshots(snapshots, config->num_hidden_layers);- snapshots = NULL;- free(layer_inputs); free(next); free(state);- layer_inputs = NULL; next = NULL; state = NULL;-- state = malloc((size_t)TAIL_BATCH * hd * sizeof(float));- next = malloc((size_t)TAIL_BATCH * hd * sizeof(float));- layer_inputs = malloc((size_t)config->num_hidden_layers *- TAIL_BATCH * hd * sizeof(float));- if (!state || !next || !layer_inputs ||- prefix_create_snapshots(&snapshots, attention,- config->num_hidden_layers)) {- result = -1; goto cleanup;- }- int tail_inputs[TAIL_BATCH] = {draft_tokens[2], draft_tokens[3]};- int tail_targets[TAIL_BATCH];- float tail_logits[TAIL_BATCH];- result = coli_v4_target_load_embeddings(- state, index, config, tail_inputs, TAIL_BATCH) ||- prefix_run_target_batch(- engine, &state, &next, attention, index, config, experts,- tail_inputs, prefix_position + 3, TAIL_BATCH,- layer_inputs, error, error_size) ||- coli_v4_target_head_argmax_batch(- state, index, config, TAIL_BATCH,- tail_targets, tail_logits, error, error_size) ||- coli_v4_dspark_capture_main_x(engine, combined_main_x + (size_t)3 * d, TAIL_BATCH, config);- if (result) goto cleanup;-- output_tokens[1] = draft_tokens[1];- output_tokens[2] = draft_tokens[2];- if (draft_tokens[3] == tail_targets[0]) {- output_tokens[3] = draft_tokens[3];- output_tokens[4] = tail_targets[1];- verification->accepted_draft_tokens = 4;- verification->output_count = 5;- verification->mismatch_index = -1;- result = coli_v4_dspark_capture_stage_main_x(engine, combined_main_x, TOTAL_ROWS, d);- } else {- output_tokens[3] = tail_targets[0];- verification->accepted_draft_tokens = 3;- verification->output_count = 4;- verification->mismatch_index = 3;- if (prefix_restore_snapshots(attention, snapshots,- config->num_hidden_layers) ||- prefix_commit_attention(- engine, attention, index, config, layer_inputs, TAIL_BATCH,- prefix_position + 3, 1, error, error_size) ||- coli_v4_dspark_capture_stage_main_x(engine, combined_main_x, 4, d)) result = -1;- }--cleanup:- prefix_destroy_snapshots(snapshots, config->num_hidden_layers);- free(layer_inputs); free(next); free(state); free(combined_main_x);- return result ? -1 : 0;-}-#endif /* COLI_V4_UNIT_TARGET_VERIFY_PREFIX */--#ifdef COLI_V4_UNIT_DSPARK_VERIFY_WINDOW-/* ######## deepseek_v4_dspark_verify_window.c ######## */-/* Verify-window batching now lives in coli_v4_dspark_runner_draft /- * coli_v4_dspark_runner_verify_block_size (no ld --wrap). */-#endif /* COLI_V4_UNIT_DSPARK_VERIFY_WINDOW */diff --git a/c/deepseek_v4_dspark.h b/c/deepseek_v4_dspark.hdeleted file mode 100644index 452aed84..00000000--- a/c/deepseek_v4_dspark.h+++ /dev/null@@ -1,358 +0,0 @@-#ifndef COLIBRI_DEEPSEEK_V4_DSPARK_H-#define COLIBRI_DEEPSEEK_V4_DSPARK_H--#include "deepseek_v4_internal.h"--#include "tensor.h"-#include "expert_store.h"-#include "native_quant.h"-#include "native_quant_batch.h"-#include "native_quant_dual.h"-#include "native_quant_fp4_rows16.h"-#include "safetensors_index.h"-#include "tensor_io.h"--/* ==== begin deepseek_v4_dspark.h ==== */--#include <stddef.h>-#include <stdint.h>--/* via deepseek_v4.h: deepseek_v4_config.h */-/* via deepseek_v4.h: deepseek_v4_layer.h */--/* COLI_V4_DSPARK_MAX_* and ColiDeepSeekV4DSparkManifest: deepseek_v4_internal.h */--int coli_v4_dspark_inspect(const char *model_dir,- const ColiDeepSeekV4Config *config,- ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size);-int coli_v4_dspark_layer_plan(ColiDeepSeekV4LayerPlan *plan,- const ColiDeepSeekV4Config *config, int stage,- char *error, size_t error_size);-/* ==== end deepseek_v4_dspark.h ==== */--/* ==== begin deepseek_v4_dspark_memory.h ==== */--#include <stddef.h>-#include <stdint.h>--/* via deepseek_v4.h: deepseek_v4_config.h */--typedef struct {- uint64_t resident_heads_bytes;- uint64_t streamed_stage_bytes;- uint64_t minimum_expert_cache_bytes;- uint64_t working_bytes;- uint64_t incremental_reserve_bytes;- uint64_t expert_record_bytes;- int stages;- int expert_slots_per_stage;-} ColiV4DSparkMemoryPlan;--int coli_v4_dspark_memory_plan(const char *model_dir,- const ColiDeepSeekV4Config *config,- ColiV4DSparkMemoryPlan *plan,- char *error, size_t error_size);-/* ==== end deepseek_v4_dspark_memory.h ==== */--/* ==== begin deepseek_v4_dspark_runtime.h ==== */--/* amalgamated: deepseek_v4_dspark.h */-/* via deepseek_v4.h: deepseek_v4_expert_store.h */--int coli_v4_dspark_layer_load(ColiV4Engine *engine,- ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const ColiSafetensorsIndex *index, int stage,- char *error, size_t error_size);-void coli_v4_dspark_layer_release(ColiV4Engine *engine,- ColiDeepSeekV4LayerWeights *weights);-int coli_deepseek_v4_dspark_expert_store_open(- const ColiDeepSeekV4ExpertStoreOptions *options,- ColiExpertStore **store, char *error, size_t error_size);-/* ==== end deepseek_v4_dspark_runtime.h ==== */--/* ==== begin deepseek_v4_dspark_runtime_resident.h ==== */--/* via deepseek_v4.h: deepseek_v4_layer.h */-/* coli_v4_dspark_layer_release declared above with engine parameter */--/* ==== end deepseek_v4_dspark_runtime_resident.h ==== */--/* ==== begin deepseek_v4_dspark_attention.h ==== */--#include <stddef.h>--/* via deepseek_v4.h: deepseek_v4_config.h */-/* via deepseek_v4.h: deepseek_v4_layer.h */--typedef struct ColiV4DSparkAttentionState ColiV4DSparkAttentionState;--/*- * Record an absolute token position in a sparse fixed-size sliding window.- * Positions may jump when one speculative verification commits several- * tokens, so occupancy cannot be inferred from the number of writes.- */-static inline int coli_v4_dspark_position_window_put(- int *positions, int window_size, int *valid, int position) {- if (!positions || !valid || window_size < 1 || position < 0) return -1;- int64_t minimum = (int64_t)position - window_size + 1;- for (int slot = 0; slot < window_size; slot++)- if (positions[slot] >= 0 && (int64_t)positions[slot] < minimum)- positions[slot] = -1;- int slot = position % window_size;- positions[slot] = position;- int occupied = 0;- for (int index = 0; index < window_size; index++)- if (positions[index] >= 0) occupied++;- *valid = occupied;- return slot;-}--int coli_v4_dspark_attention_create(ColiV4DSparkAttentionState **state,- const ColiDeepSeekV4Config *config);-void coli_v4_dspark_attention_reset(ColiV4DSparkAttentionState *state);-void coli_v4_dspark_attention_destroy(ColiV4DSparkAttentionState *state);-int coli_v4_dspark_attention_context_count(- const ColiV4DSparkAttentionState *state);-int coli_v4_dspark_attention_precompute_context(- ColiV4DSparkAttentionState *state,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const float *main_x, int start_position, int batch,- char *error, size_t error_size);-/* ==== end deepseek_v4_dspark_attention.h ==== */--/* ==== begin deepseek_v4_dspark_attention_block.h ==== */--/* amalgamated: deepseek_v4_dspark_attention.h */--int coli_v4_dspark_attention_block(- float *outputs, ColiV4DSparkAttentionState *state,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, const float *inputs,- int query_start_position, int batch, char *error, size_t error_size);-/* ==== end deepseek_v4_dspark_attention_block.h ==== */--/* ==== begin deepseek_v4_dspark_block.h ==== */--/* amalgamated: deepseek_v4_dspark_attention.h */-/* via deepseek_v4.h: deepseek_v4_expert_store.h */--int coli_v4_dspark_block(- float *outputs_hc, ColiV4DSparkAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const float *inputs_hc, const int *tokens,- int query_start_position, int batch,- char *error, size_t error_size);-/* ==== end deepseek_v4_dspark_block.h ==== */--/* ==== begin deepseek_v4_dspark_final.h ==== */--/* via deepseek_v4.h: deepseek_v4_config.h */-/* amalgamated: deepseek_v4_dspark.h */--typedef struct ColiV4DSparkFinal ColiV4DSparkFinal;--int coli_v4_dspark_final_open(ColiV4DSparkFinal **output,- const char *model_dir,- const ColiDeepSeekV4Config *config,- const ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size);-void coli_v4_dspark_final_close(ColiV4DSparkFinal *final);-int coli_v4_dspark_final_hidden(ColiV4DSparkFinal *final,- float *outputs, const float *states_hc,- int batch);-/* ==== end deepseek_v4_dspark_final.h ==== */--/* ==== begin deepseek_v4_dspark_heads.h ==== */--#include <stddef.h>--/* via deepseek_v4.h: deepseek_v4_config.h */-/* amalgamated: deepseek_v4_dspark.h */-#include "safetensors_index.h"--typedef struct ColiV4DSparkHeads ColiV4DSparkHeads;--int coli_v4_dspark_heads_open(ColiV4DSparkHeads **output,- const char *model_dir,- const ColiDeepSeekV4Config *config,- const ColiDeepSeekV4DSparkManifest *manifest,- char *error, size_t error_size);-void coli_v4_dspark_heads_close(ColiV4DSparkHeads *heads);-int coli_v4_dspark_combine_hidden(ColiV4DSparkHeads *heads, float *output,- const float *target_hidden_hc);-int coli_v4_dspark_markov_bias(ColiV4DSparkHeads *heads, float *bias,- int previous_token);-int coli_v4_dspark_biased_argmax(- ColiV4Engine *engine, ColiV4DSparkHeads *heads,- const ColiSafetensorsIndex *target_index, const float *hidden,- int previous_token, int *best_token, float *best_logit);-int coli_v4_dspark_biased_argmax_batch(- ColiV4Engine *engine, ColiV4DSparkHeads *heads,- const ColiSafetensorsIndex *target_index, const float *hidden_batch,- int previous_token, int *best_tokens, float *best_logits, int batch);-/* ==== end deepseek_v4_dspark_heads.h ==== */--/* ==== begin deepseek_v4_dspark_runner.h ==== */--#include <stddef.h>-#include <stdint.h>--/* via deepseek_v4.h: deepseek_v4_config.h */--typedef struct ColiV4DSparkRunner ColiV4DSparkRunner;--int coli_v4_dspark_runner_open(ColiV4DSparkRunner **output,- ColiV4Engine *engine,- const char *dspark_model_dir,- const char *target_model_dir,- const ColiDeepSeekV4Config *config,- uint64_t expert_cache_bytes,- char *error, size_t error_size);-void coli_v4_dspark_runner_close(ColiV4DSparkRunner *runner);-int coli_v4_dspark_runner_prefill(ColiV4DSparkRunner *runner,- const float *main_x,- int start_position, int batch,- char *error, size_t error_size);-int coli_v4_dspark_runner_draft(ColiV4DSparkRunner *runner,- const float *main_x, int anchor_token,- int position, int *draft_tokens,- float *draft_logits,- char *error, size_t error_size);-int coli_v4_dspark_runner_block_size(const ColiV4DSparkRunner *runner);-/* Verify-window draft count (min of manifest.block_size and runtime.verify_drafts). */-int coli_v4_dspark_runner_verify_block_size(const ColiV4DSparkRunner *runner);-uint64_t coli_v4_dspark_runner_loaded_stage_peak(- const ColiV4DSparkRunner *runner);-/* ==== end deepseek_v4_dspark_runner.h ==== */--/* ==== begin deepseek_v4_dspark_runner_shared.h ==== */--/* amalgamated: deepseek_v4_dspark_heads.h */-/* amalgamated: deepseek_v4_dspark_runner.h */--int coli_v4_dspark_runner_use_shared_heads(ColiV4DSparkRunner *runner,- ColiV4DSparkHeads *heads);-/* ==== end deepseek_v4_dspark_runner_shared.h ==== */--/* ==== begin deepseek_v4_dspark_capture.h ==== */--/* via deepseek_v4.h: deepseek_v4_config.h */-/* amalgamated: deepseek_v4_dspark_heads.h */--int coli_v4_dspark_capture_main_x(ColiV4Engine *engine, float *outputs,- int batch,- const ColiDeepSeekV4Config *config);-ColiV4DSparkHeads *coli_v4_dspark_capture_heads(ColiV4Engine *engine);-int coli_v4_dspark_capture_stage_main_x(ColiV4Engine *engine,- const float *values, int batch,- int hidden_size);-void coli_v4_dspark_capture_after_block(- ColiV4Engine *engine, const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config, const float *outputs, int batch);-/* ==== end deepseek_v4_dspark_capture.h ==== */--/* ==== begin deepseek_v4_speculative.h ==== */--#include <stdint.h>--typedef struct {- uint64_t rounds;- uint64_t proposed;- uint64_t accepted;- uint64_t minimum_proposals;- float disable_threshold;- int enabled;-} ColiV4SpeculativeController;--typedef struct {- int accepted_draft_tokens;- int output_count;- int mismatch_index;-} ColiV4VerificationResult;--void coli_v4_speculative_controller_init(ColiV4SpeculativeController *state,- uint64_t minimum_proposals,- float disable_threshold);-void coli_v4_speculative_record(ColiV4SpeculativeController *state,- int proposed, int accepted);-float coli_v4_speculative_acceptance(const ColiV4SpeculativeController *state);--int coli_v4_verify_greedy(ColiV4VerificationResult *result,- int *output_tokens, int output_capacity,- const int *draft_tokens, int draft_count,- const int *target_tokens, int target_count);-/* ==== end deepseek_v4_speculative.h ==== */--/* ==== begin deepseek_v4_target_verify.h ==== */--/* via deepseek_v4.h: deepseek_v4_attention.h */-/* via deepseek_v4.h: deepseek_v4_config.h */-/* via deepseek_v4.h: deepseek_v4_expert_store.h */-/* amalgamated: deepseek_v4_speculative.h */--int coli_v4_target_verify_greedy_batch(- ColiV4VerificationResult *verification,- int *output_tokens, int output_capacity,- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- int anchor_token, const int *draft_tokens, int draft_count,- int start_position, char *error, size_t error_size);-/* ==== end deepseek_v4_target_verify.h ==== */--/* ==== begin deepseek_v4_target_verify_prefix.h ==== */--/* amalgamated: deepseek_v4_target_verify.h */--/* The target has already processed the anchor and draft_tokens[0] matched its- * prediction. Verify drafts 1..3 with the same 2+2 schedule as the prior- * verifier, while preserving the prefix main_x row for the next DSpark round. */-int coli_v4_target_verify_after_prefix_v69(- ColiV4VerificationResult *verification,- int *output_tokens, int output_capacity,- ColiV4Engine *engine,- ColiDeepSeekV4WindowAttentionState **attention,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, ColiExpertStore *experts,- const int *draft_tokens, int draft_count, int prefix_position,- const float *prefix_main_x, char *error, size_t error_size);-/* ==== end deepseek_v4_target_verify_prefix.h ==== */--/* ==== begin deepseek_v4_target_attention_commit.h ==== */--/* via deepseek_v4.h: deepseek_v4_attention.h */-/* via deepseek_v4.h: deepseek_v4_config.h */-/* via deepseek_v4.h: deepseek_v4_layer.h */--/* Advance only a target layer's causal attention/cache for already-computed- * layer inputs. Used after speculative rollback to avoid replaying HC post and- * the complete MoE branch. */-int coli_v4_target_attention_commit_batch(- ColiDeepSeekV4WindowAttentionState *attention,- const ColiDeepSeekV4LayerWeights *weights,- const ColiDeepSeekV4Config *config,- const float *inputs_hc, int start_position, int batch,- char *error, size_t error_size);-/* ==== end deepseek_v4_target_attention_commit.h ==== */--/* ==== begin deepseek_v4_target_head_batch.h ==== */--/* via deepseek_v4.h: deepseek_v4_config.h */-#include "safetensors_index.h"--int coli_v4_target_load_embeddings(float *states_hc,- const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config,- const int *tokens, int batch);-int coli_v4_target_head_argmax_batch(- const float *states_hc, const ColiSafetensorsIndex *index,- const ColiDeepSeekV4Config *config, int batch,- int *tokens, float *logits, char *error, size_t error_size);-/* ==== end deepseek_v4_target_head_batch.h ==== */--#endif /* COLIBRI_DEEPSEEK_V4_DSPARK_H */diff --git a/c/deepseek_v4_internal.h b/c/deepseek_v4_internal.hindex a9fa3434..12190323 100644--- a/c/deepseek_v4_internal.h+++ b/c/deepseek_v4_internal.h@@ -13,8 +13,59 @@#include "native_quant_batch.h"#include "native_quant_dual.h"#include "native_quant_fp4_rows16.h"-#include "safetensors_index.h"-#include "tensor_io.h"+#include "st.h"++#define COLI_ST_MAX_RANK ST_MAX_RANK+#define COLI_ST_BF16 ST_DTYPE_BF16+#define COLI_ST_F16 ST_DTYPE_F16+#define COLI_ST_F32 ST_DTYPE_F32+#define COLI_ST_U8 ST_DTYPE_U8+#define COLI_ST_I8 ST_DTYPE_I8+#define COLI_ST_I64 ST_DTYPE_I64+#define COLI_ST_F8_E4M3 ST_DTYPE_F8_E4M3+#define COLI_ST_F8_E8M0 ST_DTYPE_F8_E8M0++typedef int ColiSafetensorsDType;+typedef st_tensor ColiSafetensorsTensor;+typedef shards ColiSafetensorsIndex;++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_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);++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);typedef struct ColiV4Engine ColiV4Engine;@@ -69,7 +120,6 @@ int coli_v4_swiglu(float *output, const float *gate, const float *up,#include <stdint.h>/* amalgamated: deepseek_v4_config.h */-#include "safetensors_index.h"#ifdef __cplusplusextern "C" {@@ -511,17 +561,12 @@ typedef struct {uint64_t available_bytes;uint64_t fixed_bytes;uint64_t dense_bytes;- uint64_t dspark_streamed_bytes;- uint64_t dspark_full_bytes;uint64_t minimum_expert_bytes;- int has_dspark;} ColiDeepSeekV4ResidentTierInputs;typedef struct {uint64_t dense_bytes;- uint64_t dspark_bytes;int dense_resident;- int dspark_resident;} ColiDeepSeekV4ResidentTierPlan;uint64_t coli_v4_os_available_memory(void);@@ -553,41 +598,14 @@ const void *coli_v4_head_cache_data(const ColiV4Engine *engine,/* Runtime options live on ColiV4Engine. */typedef struct {const char *target_model_dir;- const char *dspark_model_dir;uint64_t memory_limit_bytes;int context_tokens;int dense_resident;- int dspark_resident;- uint64_t dspark_expert_cache_bytes;- int verify_drafts;+ uint64_t target_expert_cache_bytes;int pin_slots_per_layer;uint64_t repin_interval;} ColiDeepSeekV4RuntimeOptions;-/* Shared with deepseek_v4_dspark.h (guarded there to avoid double typedef). */-#ifndef COLI_V4_DSPARK_MAX_STAGES-#define COLI_V4_DSPARK_MAX_STAGES 8-#endif-#ifndef COLI_V4_DSPARK_MAX_TARGETS-#define COLI_V4_DSPARK_MAX_TARGETS 8-#endif--#ifndef COLIBRI_DEEPSEEK_V4_DSPARK_MANIFEST_DEFINED-#define COLIBRI_DEEPSEEK_V4_DSPARK_MANIFEST_DEFINED-typedef struct {- int stage_count;- int block_size;- int noise_token_id;- int markov_rank;- int target_count;- int target_layer_ids[COLI_V4_DSPARK_MAX_TARGETS];- uint64_t common_stage_bytes[COLI_V4_DSPARK_MAX_STAGES];- uint64_t special_bytes;-} ColiDeepSeekV4DSparkManifest;-#endif--typedef struct ColiV4DSparkHeads ColiV4DSparkHeads;-enum { COLI_V4_RESIDENT_MAX_LAYERS = 128 };struct ColiV4Engine {@@ -602,49 +620,21 @@ struct ColiV4Engine {uint64_t offset;int shard;} head_cache;- struct {- ColiV4DSparkHeads *heads;- ColiDeepSeekV4DSparkManifest manifest;- float *states[COLI_V4_DSPARK_MAX_TARGETS];- size_t capacity;- float *staged_main_x;- int staged_batch;- int staged_hidden;- } dspark_capture;- struct {- int available;- int limit;- int head_slot;- int tokens[64];- float logits[64];- } dspark_verify;struct {ColiDeepSeekV4LayerWeights layers[COLI_V4_RESIDENT_MAX_LAYERS];unsigned char ready[COLI_V4_RESIDENT_MAX_LAYERS];const ColiSafetensorsIndex *index;uint64_t total_bytes;} dense_resident;- struct {- ColiDeepSeekV4LayerWeights layers[COLI_V4_DSPARK_MAX_STAGES];- unsigned char ready[COLI_V4_DSPARK_MAX_STAGES];- const ColiSafetensorsIndex *index;- uint64_t total_bytes;- } dspark_resident;char *owned_target_model_dir;- char *owned_dspark_model_dir;int owns_experts;int owns_index;int active_sessions; /* sessions created against this engine */};-typedef struct ColiV4DSparkRunner ColiV4DSparkRunner;-/* Session ownership helpers shared by production session code and tests. */void coli_v4_engine_attach_session(ColiV4Engine *engine);void coli_v4_engine_detach_session(ColiV4Engine *engine);-void coli_v4_session_take_runner(ColiV4Session *session,- ColiV4DSparkRunner *runner);-void coli_v4_session_clear_runner(ColiV4Session *session);#include "tok.h"@@ -655,14 +645,12 @@ struct ColiV4Session {float *state;float *next;float *hidden;- float *main_x_batch;int *prompt_ids;int *generated;int max_prompt_tokens;int max_new_tokens_cap;int prompt_count;int generated_count;- ColiV4DSparkRunner *runner;Tok tokenizer;int tokenizer_ready;char *text;@@ -697,7 +685,6 @@ extern int coli_v4_test_closed_owned_index;ColiV4Session *coli_v4_test_session_bare_create(ColiV4Engine *engine);void coli_v4_test_session_bare_destroy(ColiV4Session *session);-ColiV4DSparkRunner *coli_v4_session_peek_runner(const ColiV4Session *session);#endif /* COLI_V4_TEST_HOOKS */#endif /* COLIBRI_DEEPSEEK_V4_INTERNAL_H */diff --git a/c/native_quant.c b/c/native_quant.cindex 9771c9fc..823cb08f 100644--- a/c/native_quant.c+++ b/c/native_quant.c@@ -1,4 +1,12 @@#include "native_quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wunused-variable"+#endif+#include "quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic pop+#endif#include <float.h>#include <math.h>@@ -215,24 +223,17 @@ int coli_fp4_matvec_ref(float *output, const ColiTensorView *weight,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;- }+ matmul_mxfp4(output, activation, weight->data, weight->scales,+ 1, (int)columns, (int)rows);free(activation_scales);free(activation);return 0;}+/* TODO(upstream-fmt8-ue8m0): This is a temporary DeepSeek-V4-private+ * compatibility path. Replace it with quant.h's shared fmt=8 E4M3 + UE8M0+ * 128x128 block-scale implementation once upstream provides that decoder.+ * Do not extend this private path with new backends or container behavior. */int coli_fp8_matvec_ref(float *output, const ColiTensorView *weight,const float *input) {if (!output || !weight || !input ||diff --git a/c/native_quant_batch.c b/c/native_quant_batch.cindex e1b3cbf9..bef0492a 100644--- a/c/native_quant_batch.c+++ b/c/native_quant_batch.c@@ -4,6 +4,14 @@#include <stdlib.h>#include "native_quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wunused-variable"+#endif+#include "quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic pop+#endifstatic 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);@@ -86,27 +94,7 @@ int coli_fp4_matmul_batch_ref(float *outputs, const ColiTensorView *weight,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];- }+ matmul_mxfp4(outputs, activations, weight->data, weight->scales,+ batch, (int)columns, (int)rows);free(activation_scales); free(activations); return 0;}diff --git a/c/native_quant_batch_avx512.c b/c/native_quant_batch_avx512.cindex e83de669..09250fa3 100644--- a/c/native_quant_batch_avx512.c+++ b/c/native_quant_batch_avx512.c@@ -11,82 +11,7 @@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;+ return coli_fp4_matmul_batch_baseline_v4(outputs, weight, inputs, batch);}/* ---- end inlined native_quant_batch_interleaved_v4.c ---- */diff --git a/c/native_quant_dual.c b/c/native_quant_dual.cindex 1190618c..269d64b3 100644--- a/c/native_quant_dual.c+++ b/c/native_quant_dual.c@@ -4,6 +4,14 @@#include <stdlib.h>#include "native_quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic push+#pragma GCC diagnostic ignored "-Wunused-variable"+#endif+#include "quant.h"+#if defined(__GNUC__)+#pragma GCC diagnostic pop+#endifstatic int dual_same_shape(const ColiTensorView *a, const ColiTensorView *b) {return a && b && a->rows == b->rows && a->columns == b->columns &&@@ -38,32 +46,10 @@ int coli_fp4_dual_matvec_ref(float *output_a, float *output_b,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;- }+ matmul_mxfp4(output_a, activation, a->data, a->scales,+ 1, (int)columns, (int)rows);+ matmul_mxfp4(output_b, activation, b->data, b->scales,+ 1, (int)columns, (int)rows);free(activation_scales); free(activation); return 0;}diff --git a/c/native_quant_fp4_rows16.c b/c/native_quant_fp4_rows16.cindex f19a926f..93cf7c68 100644--- a/c/native_quant_fp4_rows16.c+++ b/c/native_quant_fp4_rows16.c@@ -1,5 +1,10 @@#include "native_quant_fp4_rows16.h"+/* TODO(upstream-fmt7-rows16): quant.h now owns the canonical fmt=7 MXFP4+ * decoder. This private rows16 repack/fused kernel remains only because the+ * shared layer has no resident-cache rows16 layout yet. Migrate and delete it+ * when that performance API lands upstream. */+#ifdef __AVX512F__#include <immintrin.h>#elif defined(__aarch64__)diff --git a/c/native_quant_parallel.c b/c/native_quant_parallel.cindex c6dfb3ba..2a497c63 100644--- a/c/native_quant_parallel.c+++ b/c/native_quant_parallel.c@@ -19,58 +19,7 @@ static void build_decode_tables_v4(float fp4[16], float fp8[256],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;+ return coli_fp4_matvec_serial_ref(output, weight, input);}int coli_fp8_matvec_ref(float *output, const ColiTensorView *weight,diff --git a/c/safetensors_index.c b/c/safetensors_index.cdeleted file mode 100644index b1c9f11a..00000000--- a/c/safetensors_index.c+++ /dev/null@@ -1,451 +0,0 @@-#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.hdeleted file mode 100644index 519c7492..00000000--- a/c/safetensors_index.h+++ /dev/null@@ -1,57 +0,0 @@-#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_io.c b/c/tensor_io.cdeleted file mode 100644index 93485637..00000000--- a/c/tensor_io.c+++ /dev/null@@ -1,105 +0,0 @@-#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.hdeleted file mode 100644index a0a86747..00000000--- a/c/tensor_io.h+++ /dev/null@@ -1,41 +0,0 @@-#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_deepseek_v4.c b/c/tests/test_deepseek_v4.cindex 3b7efcdf..b29690e5 100644--- a/c/tests/test_deepseek_v4.c+++ b/c/tests/test_deepseek_v4.c@@ -1,6 +1,5 @@/* Merged DeepSeek V4 unit tests (GLM-style single harness). */#include "../deepseek_v4_internal.h"-#include "../deepseek_v4_dspark.h"#include "../compat.h"#include "../native_quant.h"@@ -44,38 +43,6 @@ static int test_attention_cache(void) {}/* ==== end test_deepseek_v4_attention_cache.c ==== */-static int test_dspark_position_window(void) {- enum { WINDOW = 8 };- int positions[WINDOW];- int valid = 0;- for (int slot = 0; slot < WINDOW; slot++) positions[slot] = -1;- const int sequence[] = {0, 1, 2, 3, 8, 11, 17, 17};- for (size_t item = 0; item < sizeof(sequence) / sizeof(sequence[0]); item++) {- int position = sequence[item];- int slot = coli_v4_dspark_position_window_put(- positions, WINDOW, &valid, position);- if (slot != position % WINDOW) return 1;- int occupied = 0;- int64_t minimum = (int64_t)position - WINDOW + 1;- for (int index = 0; index < WINDOW; index++) {- if (positions[index] < 0) continue;- if ((int64_t)positions[index] < minimum ||- positions[index] > position)- return 1;- occupied++;- }- if (valid != occupied) return 1;- }- if (valid != 2 || positions[1] != 17 || positions[3] != 11)- return 1;- if (coli_v4_dspark_position_window_put(NULL, WINDOW, &valid, 18) >= 0 ||- coli_v4_dspark_position_window_put(positions, 0, &valid, 18) >= 0 ||- coli_v4_dspark_position_window_put(positions, WINDOW, &valid, -1) >= 0)- return 1;- puts("DeepSeek-V4 DSpark position window tests: ok");- return 0;-}-/* ==== begin test_deepseek_v4_config.c ==== *//* umbrella headers *//* <stdio.h> */@@ -136,6 +103,19 @@ static int test_config(int argc, char **argv) {config.compress_ratio_count != 4 || config.compress_ratios[1] != 4 ||config.compress_ratios[2] != 128 || config.rope_factor != 4.0f)return 1;+ {+ static const char needle[] = "\"compress_ratios\":[0,4,128,0]";+ static const char replacement[] =+ "\"compress_ratios\":[0,4,128,0,0,0]";+ const char *at = strstr(config_json, needle);+ char extended[sizeof(config_json) + 8];+ if (!at || snprintf(extended, sizeof(extended), "%.*s%s%s",+ (int)(at - config_json), config_json, replacement,+ at + strlen(needle)) < 0 ||+ coli_v4_config_parse(&config, extended, error, sizeof(error)) != 0 ||+ config.compress_ratio_count != 6)+ return 1;+ }static const struct {const char *label;const char *needle;@@ -171,12 +151,12 @@ static int test_config(int argc, char **argv) {int flash = config.hidden_size == 4096 &&config.num_hidden_layers == 43 &&config.n_routed_experts == 256 &&- config.compress_ratio_count == 44 &&+ config.compress_ratio_count >= config.num_hidden_layers &&config.compress_ratios[0] == 0;int pro = config.hidden_size == 7168 &&config.num_hidden_layers == 61 &&config.n_routed_experts == 384 &&- config.compress_ratio_count == 62 &&+ config.compress_ratio_count >= config.num_hidden_layers &&config.compress_ratios[0] == 128;if ((!flash && !pro) || config.num_experts_per_tok != 6 ||config.compress_ratios[2] != 4 ||@@ -670,45 +650,16 @@ static int test_resource_plan(void) {ColiDeepSeekV4ResidentTierPlan tiers;ColiDeepSeekV4ResidentTierInputs target_only = {- 40 * GIB, 4 * GIB, 24 * GIB, 0, 0, 12 * GIB, 0,+ 40 * GIB, 4 * GIB, 24 * GIB, 12 * GIB,};if (coli_v4_resident_tier_plan(&tiers, &target_only, error, sizeof(error)) ||- !tiers.dense_resident || tiers.dspark_resident ||- tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes)+ !tiers.dense_resident || tiers.dense_bytes != 24 * GIB)return 1;target_only.available_bytes = 39 * GIB;if (coli_v4_resident_tier_plan(&tiers, &target_only, error, sizeof(error)) ||- tiers.dense_resident || tiers.dspark_resident || tiers.dense_bytes ||- tiers.dspark_bytes)- return 1;-- ColiDeepSeekV4ResidentTierInputs with_dspark = {- 60 * GIB, 4 * GIB, 24 * GIB, 2 * GIB, 20 * GIB, 12 * GIB, 1,- };- if (coli_v4_resident_tier_plan(- &tiers, &with_dspark, error, sizeof(error)) ||- !tiers.dense_resident || !tiers.dspark_resident ||- tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes != 20 * GIB)- return 1;- with_dspark.available_bytes = 48 * GIB;- if (coli_v4_resident_tier_plan(- &tiers, &with_dspark, error, sizeof(error)) ||- !tiers.dense_resident || tiers.dspark_resident ||- tiers.dense_bytes != 24 * GIB || tiers.dspark_bytes != 2 * GIB)- return 1;- with_dspark.available_bytes = 40 * GIB;- if (coli_v4_resident_tier_plan(- &tiers, &with_dspark, error, sizeof(error)) ||- tiers.dense_resident || !tiers.dspark_resident || tiers.dense_bytes ||- tiers.dspark_bytes != 20 * GIB)- return 1;- with_dspark.available_bytes = 32 * GIB;- if (coli_v4_resident_tier_plan(- &tiers, &with_dspark, error, sizeof(error)) ||- tiers.dense_resident || tiers.dspark_resident || tiers.dense_bytes ||- tiers.dspark_bytes != 2 * GIB)+ tiers.dense_resident || tiers.dense_bytes)return 1;puts("DeepSeek V4 resource plan tests: ok");return 0;@@ -751,10 +702,6 @@ int main(int argc, char **argv) {fprintf(stderr, "FAIL: test_attention_cache\n");return 1;}- if (test_dspark_position_window() != 0) {- fprintf(stderr, "FAIL: test_dspark_position_window\n");- return 1;- }if (test_config(argc, argv) != 0) {fprintf(stderr, "FAIL: test_config\n");return 1;diff --git a/c/tests/test_safetensors_index.c b/c/tests/test_safetensors_index.cdeleted file mode 100644index 40909f20..00000000--- a/c/tests/test_safetensors_index.c+++ /dev/null@@ -1,202 +0,0 @@-#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.cdeleted file mode 100644index bf042c8b..00000000--- a/c/tests/test_tensor_io.c+++ /dev/null@@ -1,82 +0,0 @@-#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;-}diff --git a/c/tests/test_v4_config_dspark_compat.c b/c/tests/test_v4_config_dspark_compat.cdeleted file mode 100644index b772913f..00000000--- a/c/tests/test_v4_config_dspark_compat.c+++ /dev/null@@ -1,135 +0,0 @@-/* Focused regression test for the config parser linked by the production V4- * binary. This intentionally links COLI_V4_UNIT_CONFIG_DSPARK_COMPAT, not the- * standalone COLI_V4_UNIT_CONFIG test object. */-#include "../deepseek_v4.h"--#include <stdio.h>-#include <stdlib.h>-#include <string.h>--static const char target_config[] =- "{\"model_type\":\"deepseek_v4\",\"expert_dtype\":\"fp4\","- "\"scoring_func\":\"sqrtsoftplus\",\"topk_method\":\"noaux_tc\","- "\"hidden_size\":128,\"num_hidden_layers\":3,"- "\"num_attention_heads\":4,\"head_dim\":32,\"q_lora_rank\":64,"- "\"qk_rope_head_dim\":8,\"o_groups\":2,\"o_lora_rank\":64,"- "\"sliding_window\":16,\"index_n_heads\":4,\"index_head_dim\":16,"- "\"index_topk\":8,\"n_routed_experts\":8,\"num_experts_per_tok\":2,"- "\"n_shared_experts\":1,\"moe_intermediate_size\":32,"- "\"num_hash_layers\":1,\"num_nextn_predict_layers\":1,"- "\"hc_mult\":4,\"hc_sinkhorn_iters\":5,\"vocab_size\":256,"- "\"max_position_embeddings\":4096,\"rms_norm_eps\":1e-6,"- "\"hc_eps\":1e-6,\"routed_scaling_factor\":1.5,\"swiglu_limit\":10,"- "\"rope_theta\":10000,\"compress_rope_theta\":40000,"- "\"compress_ratios\":[0,4,128,0],"- "\"rope_scaling\":{\"original_max_position_embeddings\":1024,"- "\"beta_fast\":32,\"beta_slow\":1,\"factor\":4},"- "\"quantization_config\":{\"fmt\":\"e4m3\",\"scale_fmt\":\"ue8m0\"}}";--static const char dspark_config[] =- "{\"model_type\":\"deepseek_v4\",\"expert_dtype\":\"fp4\","- "\"scoring_func\":\"sqrtsoftplus\",\"topk_method\":\"noaux_tc\","- "\"hidden_size\":128,\"num_hidden_layers\":3,"- "\"num_attention_heads\":4,\"head_dim\":32,\"q_lora_rank\":64,"- "\"qk_rope_head_dim\":8,\"o_groups\":2,\"o_lora_rank\":64,"- "\"sliding_window\":16,\"index_n_heads\":4,\"index_head_dim\":16,"- "\"index_topk\":8,\"n_routed_experts\":8,\"num_experts_per_tok\":2,"- "\"n_shared_experts\":1,\"moe_intermediate_size\":32,"- "\"num_hash_layers\":1,\"num_nextn_predict_layers\":0,"- "\"hc_mult\":4,\"hc_sinkhorn_iters\":5,\"vocab_size\":256,"- "\"max_position_embeddings\":4096,\"rms_norm_eps\":1e-6,"- "\"hc_eps\":1e-6,\"routed_scaling_factor\":1.5,\"swiglu_limit\":10,"- "\"rope_theta\":10000,\"compress_rope_theta\":40000,"- "\"compress_ratios\":[0,4,128,0],\"dspark_block_size\":5,"- "\"rope_scaling\":{\"original_max_position_embeddings\":1024,"- "\"beta_fast\":32,\"beta_slow\":1,\"factor\":4},"- "\"quantization_config\":{\"fmt\":\"e4m3\",\"scale_fmt\":\"ue8m0\"}}";--static char *replace_once(const char *source, const char *needle,- const char *replacement) {- const char *match = strstr(source, needle);- if (!match) return NULL;- size_t prefix = (size_t)(match - source);- size_t length = prefix + strlen(replacement) +- strlen(match + strlen(needle)) + 1;- char *result = malloc(length);- if (!result) return NULL;- memcpy(result, source, prefix);- strcpy(result + prefix, replacement);- strcpy(result + prefix + strlen(replacement), match + strlen(needle));- return result;-}--static int parse_ok(const char *json, int expected_nextn, const char *label) {- ColiDeepSeekV4Config config;- char error[256] = {0};- if (coli_v4_config_parse(&config, json, error, sizeof(error))) {- fprintf(stderr, "%s rejected: %s\n", label, error);- return 1;- }- if (config.hidden_size != 128 || config.num_hidden_layers != 3 ||- config.num_nextn_predict_layers != expected_nextn ||- config.compress_ratio_count != 4 ||- config.compress_ratios[1] != 4 || config.compress_ratios[2] != 128) {- fprintf(stderr, "%s produced incorrect config values\n", label);- return 1;- }- return 0;-}--static int parse_rejected(const char *json, const char *label) {- ColiDeepSeekV4Config config;- char error[256] = {0};- if (!coli_v4_config_parse(&config, json, error, sizeof(error))) {- fprintf(stderr, "%s was accepted\n", label);- return 1;- }- return 0;-}--int main(void) {- static const struct {- const char *label;- const char *needle;- const char *replacement;- } invalid[] = {- {"fractional integer", "\"hidden_size\":128", "\"hidden_size\":1.5"},- {"integer NaN", "\"hidden_size\":128", "\"hidden_size\":NaN"},- {"integer Infinity", "\"hidden_size\":128", "\"hidden_size\":1e309"},- {"floating NaN", "\"rms_norm_eps\":1e-6", "\"rms_norm_eps\":NaN"},- {"floating Infinity", "\"rms_norm_eps\":1e-6",- "\"rms_norm_eps\":1e309"},- {"integer overflow", "\"hidden_size\":128",- "\"hidden_size\":2147483648"},- {"invalid compress ratio", "\"compress_ratios\":[0,4,128,0]",- "\"compress_ratios\":[0,1.5,128,0]"},- {"non-finite compress ratio", "\"compress_ratios\":[0,4,128,0]",- "\"compress_ratios\":[0,NaN,128,0]"},- {"overflowing compress ratio", "\"compress_ratios\":[0,4,128,0]",- "\"compress_ratios\":[0,2147483648,128,0]"},- };- enum { REPEAT_COUNT = 1000 };- char *invalid_json[sizeof(invalid) / sizeof(invalid[0])] = {0};- for (size_t item = 0; item < sizeof(invalid) / sizeof(invalid[0]); item++) {- invalid_json[item] = replace_once(- dspark_config, invalid[item].needle, invalid[item].replacement);- if (!invalid_json[item]) {- fprintf(stderr, "cannot build %s fixture\n", invalid[item].label);- return 1;- }- }-- int failed = 0;- for (int iteration = 0; iteration < REPEAT_COUNT && !failed; iteration++) {- failed = parse_ok(target_config, 1, "target config") ||- parse_ok(dspark_config, 1, "DSpark compatibility config");- for (size_t item = 0;- item < sizeof(invalid) / sizeof(invalid[0]) && !failed; item++)- failed = parse_rejected(invalid_json[item], invalid[item].label);- }- for (size_t item = 0; item < sizeof(invalid) / sizeof(invalid[0]); item++)- free(invalid_json[item]);- if (failed) return 1;- puts("DeepSeek-V4 production DSpark config parser tests: ok");- return 0;-}diff --git a/c/tests/test_v4_ownership.c b/c/tests/test_v4_ownership.cindex 3695ad2c..984f4a80 100644--- a/c/tests/test_v4_ownership.c+++ b/c/tests/test_v4_ownership.c@@ -9,8 +9,6 @@#include <string.h>#include <unistd.h>-int coli_v4_test_runner_close_count = 0;-/* Stubs for symbols referenced by RUNTIME but unused in these tests. */int coli_v4_expert_store_open_planned(ColiV4Engine *engine,@@ -32,17 +30,6 @@ void coli_v4_layer_resident_reference_free((void)weights;}-void coli_v4_dspark_heads_close(ColiV4DSparkHeads *heads) {- (void)heads;-}--/* Ownership tests use blank runners; count closes through the real helper path. */-void coli_v4_dspark_runner_close(ColiV4DSparkRunner *runner) {- if (!runner) return;- coli_v4_test_runner_close_count++;- free(runner);-}-static int write_all(int fd, const void *data, size_t length) {const unsigned char *bytes = (const unsigned char *)data;while (length) {@@ -255,59 +242,6 @@ static int test_session_lifetime_accounting(void) {return 0;}-static int test_runner_closed_after_shared_heads_fail(void) {- char directory[128], error[256];- if (make_fixture(directory, sizeof(directory))) return 1;-- coli_v4_test_skip_expert_store_open = 1;- ColiV4Engine *engine = NULL;- ColiV4EngineOpenOptions options = {.target_model_dir = directory};- if (coli_v4_engine_open(&engine, &options, error, sizeof(error))) {- fprintf(stderr, "engine open failed: %s\n", error);- cleanup_fixture(directory);- return 1;- }-- ColiV4Session *session = coli_v4_test_session_bare_create(engine);- if (!session) {- coli_v4_engine_destroy(engine);- cleanup_fixture(directory);- return 1;- }-- coli_v4_test_runner_close_count = 0;- ColiV4DSparkRunner *runner = calloc(1, sizeof(void *) * 8);- if (!runner) {- coli_v4_test_session_bare_destroy(session);- coli_v4_engine_destroy(engine);- cleanup_fixture(directory);- return 1;- }- /* Mirror session_generate: take runner before shared-head bind fails. */- coli_v4_session_take_runner(session, runner);- if (!coli_v4_session_peek_runner(session)) {- fprintf(stderr, "session should own runner after take\n");- coli_v4_test_session_bare_destroy(session);- coli_v4_engine_destroy(engine);- cleanup_fixture(directory);- return 1;- }- /* Simulated shared-head bind failure: leave runner on session, then destroy. */- coli_v4_test_session_bare_destroy(session);- if (coli_v4_test_runner_close_count != 1) {- fprintf(stderr, "expected runner close once via clear_runner, got %d\n",- coli_v4_test_runner_close_count);- coli_v4_engine_destroy(engine);- cleanup_fixture(directory);- return 1;- }- coli_v4_engine_destroy(engine);- coli_v4_test_skip_expert_store_open = 0;- cleanup_fixture(directory);- puts("ownership: runner closed after shared-heads fail: ok");- return 0;-}-static int test_session_tokenizer_freed(void) {char directory[128];if (make_fixture(directory, sizeof(directory))) return 1;@@ -354,7 +288,6 @@ int main(void) {if (test_index_closed_on_expert_fail()) return 1;if (test_engine_owns_model_path()) return 1;if (test_session_lifetime_accounting()) return 1;- if (test_runner_closed_after_shared_heads_fail()) return 1;if (test_session_tokenizer_freed()) return 1;puts("DeepSeek-V4 ownership tests: ok");return 0;diff --git a/c/tools/clean.py b/c/tools/clean.pyindex 178b364a..a935f363 100644--- a/c/tools/clean.py+++ b/c/tools/clean.py@@ -20,7 +20,6 @@ FILES = ["backend_metal.o", "backend_metal_test","coli_cuda.dll", "coli_cuda.lib", "coli_cuda.exp","deepseek_v4", "deepseek_v4.exe",- "safetensors_index.o", "tensor_io.o","native_quant.o", "native_quant_parallel.o", "native_quant_dual.o","native_quant_batch_avx512.o", "native_quant_fp4_rows16.o",]diff --git a/c/v4 b/c/v4deleted file mode 100644index 205aa979..00000000--- a/c/v4+++ /dev/null@@ -1,326 +0,0 @@-#!/usr/bin/env python3-"""DeepSeek V4 command-line launcher for colibri."""--import argparse-import json-import os-import re-import subprocess-import sys-import tempfile---HERE = os.path.dirname(os.path.abspath(__file__))-EXE = ".exe" if sys.platform == "win32" else ""-ENGINE = os.path.join(HERE, "deepseek_v4" + EXE)--BOS = "<\uff5cbegin\u2581of\u2581sentence\uff5c>"-USER = "<\uff5cUser\uff5c>"-ASSISTANT = "<\uff5cAssistant\uff5c>"-EOS = "<\uff5cend\u2581of\u2581sentence\uff5c>"-DSPARK_CONFIG_FIELDS = (- "dspark_block_size",- "dspark_noise_token_id",- "dspark_markov_rank",- "dspark_target_layer_ids",-)---def configure_stdio_utf8():- """Make PowerShell / Windows consoles accept Chinese input and output."""- os.environ.setdefault("PYTHONIOENCODING", "utf-8")- os.environ.setdefault("PYTHONUTF8", "1")- if sys.platform == "win32":- try:- import ctypes-- ctypes.windll.kernel32.SetConsoleCP(65001)- ctypes.windll.kernel32.SetConsoleOutputCP(65001)- except (AttributeError, OSError):- pass- for stream in (sys.stdin, sys.stdout, sys.stderr):- if stream is None:- continue- reconfigure = getattr(stream, "reconfigure", None)- if not callable(reconfigure):- continue- try:- reconfigure(encoding="utf-8", errors="replace")- except (AttributeError, OSError, ValueError):- pass---def positive_int(text):- value = int(text)- if value < 1:- raise argparse.ArgumentTypeError("must be greater than zero")- return value---def positive_float(text):- value = float(text)- if value <= 0:- raise argparse.ArgumentTypeError("must be greater than zero")- return value---def validate_model(model):- if not os.path.isdir(model):- raise SystemExit(f"model not found: {model}")- config_path = os.path.join(model, "config.json")- tokenizer_path = os.path.join(model, "tokenizer.json")- if not os.path.isfile(config_path):- raise SystemExit(f"config.json is missing from {model}")- if not os.path.isfile(tokenizer_path):- raise SystemExit(f"tokenizer.json is missing from {model}")- try:- with open(config_path, "r", encoding="utf-8") as stream:- config = json.load(stream)- except (OSError, ValueError) as error:- raise SystemExit(f"cannot read {config_path}: {error}") from error- architectures = config.get("architectures") or []- is_v4 = config.get("model_type") == "deepseek_v4" or any(- str(name).startswith("DeepseekV4") for name in architectures- )- if not is_v4:- raise SystemExit(f"model is not a DeepSeek V4 checkpoint: {model}")- return config---def has_dspark_manifest(config):- return all(field in config for field in DSPARK_CONFIG_FIELDS)---def validate_engine():- if not os.path.isfile(ENGINE):- raise SystemExit(- "DeepSeek V4 engine is not built. Run: make deepseek-v4"- )---def new_history(system_prompt):- return BOS + (system_prompt or "")---def turn_prompt(history, message, thinking):- prefix = "<think>" if thinking else "</think>"- return history + USER + message + ASSISTANT + prefix---def completed_history(prompt, answer):- return prompt + answer + EOS---def engine_command(args, prompt=None, raw=True, prompt_file=None):- command = [ENGINE, os.path.abspath(args.model)]- if prompt_file:- command.extend(("--prompt-file", prompt_file))- elif prompt is not None:- command.append(prompt)- else:- raise ValueError("prompt or prompt_file is required")- command.extend(("--max-tokens", str(args.ngen)))- if raw:- command.append("--raw-prompt")- if args.ram:- command.extend(("--memory-gb", f"{args.ram:g}"))- draft_model = getattr(args, "draft_model", None)- if draft_model:- command.extend(("--draft-model", os.path.abspath(draft_model)))- elif not getattr(args, "model_has_dspark", False):- # Target-only checkpoints (including V4 Pro) do not carry the- # dspark_* manifest required by the native speculative runner.- command.append("--no-dspark")- if getattr(args, "stop_sentence", False):- command.append("--stop-sentence")- return command---def write_prompt_file(prompt):- handle = tempfile.NamedTemporaryFile(- mode="w",- encoding="utf-8",- suffix=".txt",- delete=False,- newline="\n",- )- try:- handle.write(prompt)- handle.flush()- return handle.name- finally:- handle.close()---def compact_stats(log):- fields = []- memory = re.search(- r"ram_tiers available=([0-9.]+)GiB .* projected=([0-9.]+)GiB", log- )- prefill = re.search(- r"prefill_timing .* wall_to_first=([0-9.]+)s "- r"target_tok_s=[0-9.]+ combined_tok_s=([0-9.]+)", log- )- decode = re.search(r"decode_timing tokens=(\d+) seconds=[0-9.]+ tok_s=([0-9.]+)", log)- summary = re.search(- r"dspark_rounds=\d+ proposed=(\d+) accepted=(\d+) rate=([0-9.]+)", log- )- if memory:- fields.append(f"RAM {float(memory.group(2)):.2f}/{float(memory.group(1)):.2f} GiB")- if prefill:- fields.append(f"TTFT {float(prefill.group(1)):.2f}s")- fields.append(f"prefill {float(prefill.group(2)):.3f} tok/s")- if decode:- fields.append(f"decode {float(decode.group(2)):.3f} tok/s")- if summary and int(summary.group(1)):- fields.append(f"DSpark acceptance {100.0 * float(summary.group(3)):.1f}%")- return " | ".join(fields)---def emit_text(text):- """Write Unicode text through the UTF-8 text stream when possible."""- try:- sys.stdout.write(text)- sys.stdout.flush()- return- except UnicodeEncodeError:- pass- sys.stdout.buffer.write(text.encode("utf-8", errors="replace"))- sys.stdout.buffer.flush()---def emit_bytes(chunk):- """Stream engine UTF-8 bytes; decode via text stdout after UTF-8 setup."""- try:- sys.stdout.buffer.write(chunk)- sys.stdout.buffer.flush()- except (AttributeError, OSError, ValueError):- emit_text(chunk.decode("utf-8", errors="replace"))---def generate(args, prompt, raw=True, stream=True):- target_config = validate_model(args.model)- args.model_has_dspark = has_dspark_manifest(target_config)- if getattr(args, "draft_model", None):- draft_config = validate_model(args.draft_model)- if not has_dspark_manifest(draft_config):- raise SystemExit(- f"DSpark config fields are missing from {args.draft_model}"- )- validate_engine()- # Always pass the prompt through a UTF-8 file. Windows argv uses the ANSI- # code page for MinGW main(), which corrupts Chinese from PowerShell.- prompt_path = write_prompt_file(prompt)- try:- with tempfile.TemporaryFile(mode="w+b") as error_log:- process = subprocess.Popen(- engine_command(args, raw=raw, prompt_file=prompt_path),- stdout=subprocess.PIPE,- stderr=error_log,- bufsize=0,- )- chunks = []- while True:- chunk = process.stdout.read(256)- if not chunk:- break- chunks.append(chunk)- if stream:- emit_bytes(chunk)- return_code = process.wait()- error_log.seek(0)- diagnostics = error_log.read().decode("utf-8", errors="replace")- finally:- try:- os.unlink(prompt_path)- except OSError:- pass- answer = b"".join(chunks).decode("utf-8", errors="replace").rstrip("\r\n")- if return_code:- tail = "\n".join(diagnostics.rstrip().splitlines()[-12:])- raise SystemExit(tail or f"DeepSeek V4 engine exited with status {return_code}")- return answer, diagnostics---def cmd_run(args):- prompt = " ".join(args.prompt).strip()- if not prompt:- raise SystemExit('usage: v4 run --model PATH "your prompt"')- _, diagnostics = generate(args, prompt, raw=False)- stats = compact_stats(diagnostics)- if stats:- print(f"[stats] {stats}", file=sys.stderr)- return 0---def cmd_chat(args):- validate_model(args.model)- validate_engine()- history = new_history(args.system)- ram_label = f"{args.ram:g} GiB" if args.ram else "auto"- print(f"DeepSeek V4 chat | {os.path.basename(os.path.normpath(args.model))} | RAM {ram_label}")- print("Commands: :reset clears history, :q exits.")- print("Note: conversation history is re-prefilled on each turn.\n")- while True:- try:- message = input("You> ").strip()- except (EOFError, KeyboardInterrupt):- print()- break- if not message:- continue- if message in (":q", ":quit", ":exit"):- break- if message == ":reset":- history = new_history(args.system)- print("History cleared.\n")- continue- prompt = turn_prompt(history, message, args.thinking)- print("Assistant> ", end="", flush=True)- answer, diagnostics = generate(args, prompt, raw=True)- history = completed_history(prompt, answer)- stats = compact_stats(diagnostics)- if stats:- print(f"[stats] {stats}", file=sys.stderr)- print()- return 0---def add_runtime_arguments(parser):- parser.add_argument("--model", required=True, help="DeepSeek V4 model directory")- parser.add_argument("--draft-model", metavar="PATH",- help="separate DSpark checkpoint; disabled when no manifest is present")- parser.add_argument("--ram", type=positive_float, default=0, metavar="GIB",- help="process RAM limit in GiB (default: auto)")- parser.add_argument("--ngen", type=positive_int, default=128, metavar="N",- help="maximum response tokens (default: 128)")---def make_parser():- parser = argparse.ArgumentParser(- prog="v4", description="run DeepSeek V4 Flash locally with colibri"- )- subparsers = parser.add_subparsers(dest="command", required=True)- chat = subparsers.add_parser("chat", help="interactive multi-turn chat")- add_runtime_arguments(chat)- chat.add_argument("--system", default="", help="system message")- chat.add_argument("--thinking", action="store_true", help="enable thinking mode")- chat.set_defaults(handler=cmd_chat)-- run = subparsers.add_parser("run", help="one-shot generation")- add_runtime_arguments(run)- run.add_argument("--stop-sentence", action="store_true",- help="stop at the first sentence terminator")- run.add_argument("prompt", nargs="*")- run.set_defaults(handler=cmd_run)- return parser---def main():- configure_stdio_utf8()- args = make_parser().parse_args()- return args.handler(args)---if __name__ == "__main__":- raise SystemExit(main())