Run frontier MoE models on hardware you already own — pure C, zero deps, experts streamed from disk. Tiny engine, immense model. 🐦
C
test(deepseek-v41): an image through the server, and the CI to run all of it
JustVugg78912b5caaf6
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 44c9a8b7..e84ea8d3 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -572,10 +572,10 @@ jobs:python-version: '3.12'cache: pipcache-dependency-path: c/tools/oracle-requirements.txt- - name: Install torch (CPU) + sympy+ - name: Install torch (CPU) + sympy + Pillowrun: |pip install -r c/tools/oracle-requirements.txt- pip install sympy+ pip install sympy pillow- name: Tiny V4.1-shaped container and its referencerun: |cd c@@ -611,12 +611,39 @@ jobs:exit 1fiecho "the two index-key policies differ, as documented"+ - name: "DSpark: a verified draft is the token sequential decode would have given"+ run: |+ cd c+ # The fixture's draft head is random, so nothing it proposes would ever be+ # accepted and the verification path would never run. V41_SPEC_FORCE drafts+ # the reference's own tokens instead: 1 accepts the whole block, 2 corrupts+ # the last draft so a round is rejected part way and the rollback runs, 3+ # keeps the head's drafts, which is what serving does. All three have to+ # reproduce the reference token for token, at any cache capacity.+ for force in 1 2 3; do+ for cap in 1 8; do+ echo "::group::V41_SPEC_FORCE=$force cap=$cap"+ SNAP=dsv41_tiny V41_SPEC_FORCE=$force ./deepseek_v41 "$cap" dsv41_tiny/ref.json+ echo "::endgroup::"+ done+ done+ # and with only part of the block verified, which is a different rollback+ SNAP=dsv41_tiny V41_SPEC_FORCE=2 V41_DSPARK_MAX=1 ./deepseek_v41 8 dsv41_tiny/ref.json- name: "Brain tab: EMAP after READY and STAT, HITS after every turn"run: |cd c- # the oracle fixture ships no tokenizer; serve mode needs one to encode- python3 tools/make_edge_tiny_tokenizer.py --vocab-size 256 dsv41_tinyCOLI_DSV41_FIXTURE=dsv41_tiny python3 -m unittest -v tests.test_dsv41_dashboard+ - name: "Serving: an image changes the answer, a draft does not"+ run: |+ cd c+ COLI_DSV41_FIXTURE=dsv41_tiny python3 -m unittest -v \+ tests.test_dsv41_image_serve tests.test_dsv41_dspark_serve+ - name: "Tool calling: the checkpoint's own encoding cases, byte for byte"+ run: |+ cd c+ # no engine and no fixture here: the mock speaks the SERVE protocol, and the+ # vendor's encoding cases are checked into tests/fixtures+ python3 -m unittest -v tests.test_openai_tools_v41_e2eqwen38-tiny-check:name: Qwen3.8 tiny oracle (GDN + QSA + PLE + MoE)diff --git a/README.it.md b/README.it.mdindex 57fe4541..c201e6cc 100644--- a/README.it.md+++ b/README.it.md@@ -13,7 +13,7 @@ in C puro e senza dipendenze del motore, trattando storage, RAM e VRAM comeun'unica gerarchia di inferenza.Oggi girano otto famiglie: **GLM-5.2/5.3** (744B), **GLM-5.3-Flash** (321B, con-vision), **Inkling** (975B), **Kimi K3** (2,8T), **DeepSeek V4 Flash** (284B), **DeepSeek V4.1 Flash** (552B),+vision), **Inkling** (975B), **Kimi K3** (2,8T), **DeepSeek V4 Flash** (284B), **DeepSeek V4.1 Flash** (552B, con visione),**Qwen3.8-Flash-Next** (125B + 51B n-gram), **Qwen3.6** (35B-A3B) e**OLMoE** (7B) — unfile C ciascuna, la stessa interfaccia `coli chat` / `coli serve` / `coli web`. [Elenco completo](README.md#other-supported-models)diff --git a/README.md b/README.mdindex 896e70e4..4028cecd 100644--- a/README.md+++ b/README.md@@ -19,7 +19,7 @@ engine dependencies, by treating storage, RAM, and VRAM as a single inferencehierarchy (AI memory multitiering).Eight families run today: **GLM-5.2/5.3** (744B), **GLM-5.3-Flash** (321B, with-vision), **Inkling** (975B), **Kimi K3** (2.8T), **DeepSeek V4 Flash** (284B), **DeepSeek V4.1 Flash** (552B),+vision), **Inkling** (975B), **Kimi K3** (2.8T), **DeepSeek V4 Flash** (284B), **DeepSeek V4.1 Flash** (552B, with vision),**Qwen3.8-Flash-Next** (125B + 51B n-gram), **Qwen3.6** (35B-A3B) and**OLMoE** (7B) —one C file each, the same `coli chat` / `coli serve` / `coli web` front end.@@ -424,7 +424,7 @@ the model's `config.json`):| **GLM-5.3-Flash** (Z.ai) | 321B / 40B | [`zai-org/GLM-5.3-Flash`](https://huggingface.co/zai-org/GLM-5.3-Flash) — converted to **int4-gs64** routed experts, dense stays BF16 and the precision is a load-time choice; vision included | `make -C c glm53` | [glm53-flash.md](docs/glm53-flash.md) || **Kimi K3** (Moonshot) | 2.8T / 104B | [`moonshotai/Kimi-K3`](https://huggingface.co/moonshotai/Kimi-K3) — original checkpoint, routed experts stay **native MXFP4** | `make -C c kimi_k3` | [kimi_k3.md](docs/kimi_k3.md) || **DeepSeek V4 Flash** | 284B / 13B | official sharded checkpoint — routed experts stay **native fp4**, dense stays fp8-e4m3; the **REAP-pruned 150B** ([`puwaer/DeepSeek-V4-Flash-0731-reap-150b`](https://huggingface.co/puwaer/DeepSeek-V4-Flash-0731-reap-150b), 85 GB, 132 of 256 experts) loads with the same engine and no conversion | `make -C c deepseek-v4` | [deepseek-v4.md](docs/deepseek-v4.md) |-| **DeepSeek V4.1 Flash** | 552B / 16B | official checkpoint, **no conversion**: experts are already fp4, dense is fp8-e4m3. 203 GB of it is an n-gram memory read from disk a few hundred bytes at a time, and the routed experts cost **4.5 GB per token** against GLM-5.2's 12.7 | `make -C c deepseek_v41` | [deepseek-v41.md](docs/deepseek-v41.md) |+| **DeepSeek V4.1 Flash** | 552B / 16B | official checkpoint, **no conversion**: experts are already fp4, dense is fp8-e4m3. 203 GB of it is an n-gram memory read from disk a few hundred bytes at a time, and the routed experts cost **4.5 GB per token** against GLM-5.2's 12.7. Vision, tool calling and the DSpark draft head are all on | `make -C c deepseek_v41` | [deepseek-v41.md](docs/deepseek-v41.md) || **Qwen3.8-Flash-Next** (Alibaba) | 125B + 51B n-gram / 6B | [`Qwen/Qwen3.8-Flash-Next-FP8`](https://huggingface.co/Qwen/Qwen3.8-Flash-Next-FP8) — original checkpoint; PLE stays pageable and experts stay **native block-FP8** | `make -C c qwen38` (CPU only) | [qwen38.md](docs/qwen38.md) || **Qwen3.6** (Alibaba) | 35B / 3B | [`Kreuzzelg/qwen36-35b-a3b-colibri-i4-gs64`](https://huggingface.co/Kreuzzelg/qwen36-35b-a3b-colibri-i4-gs64) (~20 GB, **recommended**) — hybrid Gated Attention + Gated DeltaNet | `make -C c qwen36` (`CUDA=1` for the VRAM expert tier) | [qwen36.md](docs/qwen36.md) || **OLMoE** (AI2) | 7B / 1B | converted with `c/tools/convert_olmoe_merged.py` — **int8** container, ~7 GB | `make -C c olmoe` | — |diff --git a/README.zh-CN.md b/README.zh-CN.mdindex 77a981ba..542c17e5 100644--- a/README.zh-CN.md+++ b/README.zh-CN.md@@ -11,7 +11,7 @@2.8T 参数**——以引擎零依赖的纯 C 实现,将存储、RAM 与 VRAM 视为统一的推理层级。目前可运行八个模型家族:**GLM-5.2/5.3**(744B)、**GLM-5.3-Flash**(321B,含视觉)、-**Inkling**(975B)、**Kimi K3**(2.8T)、**DeepSeek V4 Flash**(284B)、, **DeepSeek V4.1 Flash** (552B)+**Inkling**(975B)、**Kimi K3**(2.8T)、**DeepSeek V4 Flash**(284B)、**DeepSeek V4.1 Flash**(552B,含视觉)、**Qwen3.8-Flash-Next**(125B + 51B n-gram)、**Qwen3.6**(35B-A3B)与 **OLMoE**(7B)——各自一个 C 文件,共用同一套 `coli chat` / `coli serve` / `coli web` 前端。[完整列表](README.md#other-supported-models)diff --git a/README.zh-TW.md b/README.zh-TW.mdindex f2a5272b..f397e739 100644--- a/README.zh-TW.md+++ b/README.zh-TW.md@@ -11,7 +11,7 @@2.8T 參數**——以引擎零相依套件的純 C 實作,將儲存、RAM 與 VRAM 視為統一的推論階層。目前可執行八個模型家族:**GLM-5.2/5.3**(744B)、**GLM-5.3-Flash**(321B,含視覺)、-**Inkling**(975B)、**Kimi K3**(2.8T)、**DeepSeek V4 Flash**(284B)、, **DeepSeek V4.1 Flash** (552B)+**Inkling**(975B)、**Kimi K3**(2.8T)、**DeepSeek V4 Flash**(284B)、**DeepSeek V4.1 Flash**(552B,含視覺)、**Qwen3.8-Flash-Next**(125B + 51B n-gram)、**Qwen3.6**(35B-A3B)與 **OLMoE**(7B)——各自一個 C 檔案,共用同一套 `coli chat` / `coli serve` / `coli web` 前端。[完整清單](README.md#other-supported-models)diff --git a/c/tests/test_dsv41_image_serve.py b/c/tests/test_dsv41_image_serve.pynew file mode 100644index 00000000..e19f0917--- /dev/null+++ b/c/tests/test_dsv41_image_serve.py@@ -0,0 +1,160 @@+"""An image reaches DeepSeek V4.1 through the gateway, and changes the answer.++The chain this covers is the one a user actually drives: an OpenAI chat request with+an `image_url` part, the gateway's preprocessing and placeholder span, the IMAGE frame+on the wire, the ViT and the aligner in the engine, and the rows landing on the+placeholder positions of the prompt.++Answering is not the assertion. A model that threw the pixels away would still answer,+and the answer would still look plausible: the check is that **two different images+give two different answers**, with the same request run twice as the control that the+difference is the image and not the sampler. If the frame were dropped, or the rows+landed on the wrong positions, or the span were miscounted (the engine says so on+stderr and answers without the image), both answers would be the same text.++Needs a V4.1 container with a vision tower and a tokenizer, plus Pillow and numpy.+Set COLI_DSV41_FIXTURE to the container; CI builds it with tools/make_dsv41_tiny.py.+"""+import base64+import io+import json+import os+import socket+import subprocess+import sys+import time+import unittest+import urllib.error+import urllib.request+from pathlib import Path++HERE = Path(__file__).resolve().parent.parent+FIXTURE = Path(os.environ.get("COLI_DSV41_FIXTURE", ""))+# The fixture's context is 64 positions, so the image has to be told to be small: at+# the container's own ceiling of 64 image tokens one photo would fill the whole window.+IMAGE_TOKENS = "16"+++def have_imaging():+ try:+ import numpy # noqa: F401+ from PIL import Image # noqa: F401+ except ImportError:+ return False+ return True+++def free_port():+ with socket.socket() as s:+ s.bind(("127.0.0.1", 0))+ return s.getsockname()[1]+++def png_data_url(seed):+ """A deterministic 24x24 image, as a data URL. No file touches the disk."""+ import numpy+ from PIL import Image++ pixels = numpy.random.default_rng(seed).integers(0, 256, (24, 24, 3), dtype=numpy.uint8)+ buffer = io.BytesIO()+ Image.fromarray(pixels).save(buffer, format="PNG")+ return "data:image/png;base64," + base64.b64encode(buffer.getvalue()).decode()++[email protected](FIXTURE.name and (FIXTURE / "config.json").is_file()+ and (FIXTURE / "tokenizer.json").is_file(),+ "COLI_DSV41_FIXTURE not set to a V4.1 container with a tokenizer")[email protected]((HERE / "deepseek_v41").exists() or (HERE / "deepseek_v41.exe").exists(),+ "deepseek_v41 engine is not built")[email protected](have_imaging(), "Pillow and numpy are needed to build the test image")+class Dsv41ImageServeTest(unittest.TestCase):+ @classmethod+ def setUpClass(cls):+ cls.port = free_port()+ cls.proc = subprocess.Popen(+ [sys.executable, str(HERE / "coli"), "serve", "--model", str(FIXTURE),+ "--port", str(cls.port), "--cap", "4"],+ stdout=subprocess.PIPE, stderr=subprocess.STDOUT, text=True,+ env={**os.environ, "V41_MAX_IMAGE_TOKENS": IMAGE_TOKENS})+ deadline = time.time() + 180+ while time.time() < deadline:+ try:+ cls.model = cls.get(f"http://127.0.0.1:{cls.port}/v1/models")["data"][0]["id"]+ break+ except Exception:+ if cls.proc.poll() is not None:+ raise RuntimeError("coli serve exited: " + cls.proc.stdout.read()[-2000:])+ time.sleep(1)+ else:+ raise RuntimeError("coli serve did not come up in 180 s")++ @classmethod+ def tearDownClass(cls):+ cls.proc.terminate()+ try:+ cls.proc.wait(10)+ except subprocess.TimeoutExpired:+ cls.proc.kill()++ @staticmethod+ def get(url, timeout=10):+ with urllib.request.urlopen(url, timeout=timeout) as response:+ return json.load(response)++ def post(self, body, timeout=300):+ request = urllib.request.Request(+ f"http://127.0.0.1:{self.port}/v1/chat/completions",+ data=json.dumps(body).encode(), headers={"Content-Type": "application/json"})+ try:+ with urllib.request.urlopen(request, timeout=timeout) as response:+ return json.load(response)+ except urllib.error.HTTPError as failure:+ self.fail(f"HTTP {failure.code}: {failure.read().decode('utf-8', 'replace')[:800]}")++ def ask(self, seed):+ return self.post({+ "model": self.model, "max_tokens": 3, "temperature": 0.0,+ "messages": [{"role": "user", "content": [+ {"type": "image_url", "image_url": {"url": png_data_url(seed)}},+ {"type": "text", "text": "q"}]}],+ })++ def test_two_images_give_two_answers(self):+ first, second = self.ask(1), self.ask(2)+ for answer in (first, second):+ self.assertEqual(answer["choices"][0]["message"]["role"], "assistant")+ again = self.ask(1)+ self.assertEqual(first["choices"][0]["message"]["content"],+ again["choices"][0]["message"]["content"],+ "the same image gave two different answers: the run is not "+ "deterministic, so the comparison below proves nothing")+ self.assertNotEqual(first["choices"][0]["message"]["content"],+ second["choices"][0]["message"]["content"],+ "two different images gave the same answer: the pixels are "+ "not reaching the model")++ def test_the_span_is_in_the_prompt(self):+ """The placeholders are real prompt positions, not a marker the gateway eats."""+ sys.path.insert(0, str(HERE / "tools"))+ from dsv41_image import load_config, plan_grid, span_tokens++ settings = load_config(FIXTURE)+ _, _, height, width = plan_grid(24, 24, settings, int(IMAGE_TOKENS))+ patch, ratio = settings["patch_size"], settings["downsample_ratio"]+ llm_h = -(-(height // patch) // ratio)+ llm_w = -(-(width // patch) // ratio)+ span = span_tokens(llm_h, llm_w)+ self.assertGreater(span, 1)+ usage = self.ask(3)["usage"]+ self.assertGreaterEqual(usage["prompt_tokens"], span,+ "the prompt is shorter than the image span alone")++ def test_a_text_turn_still_works_on_the_same_session(self):+ """An image turn must not leave the engine holding state for the next one."""+ answer = self.post({"model": self.model, "max_tokens": 3, "temperature": 0.0,+ "messages": [{"role": "user", "content": "hello"}]})+ self.assertIsInstance(answer["choices"][0]["message"]["content"], str)+++if __name__ == "__main__":+ unittest.main()diff --git a/docs/ENVIRONMENT.md b/docs/ENVIRONMENT.mdindex 3ce40f71..f86544b4 100644--- a/docs/ENVIRONMENT.md+++ b/docs/ENVIRONMENT.md@@ -496,4 +496,8 @@ COLI_TEMP=0 COLI_METAL=1 DIRECT=1 COLI_NO_OMP_TUNE=1 PIPE=1 PIPE_WORKERS=6 MTP=0| `V41_ENGRAM_ROWS` | 65536 | DeepSeek V4.1: rows of engram cache per table. The n-gram traffic is Zipfian, so a small cache absorbs most of it; 65536 rows is 64 MB per table on the released head_dim. || `V41_INDEX_OWNER` | unset | DeepSeek V4.1: score each layer against its OWN index keys instead of the last published cache. The default reproduces the released inference code; this changes the model's behaviour, see docs/deepseek-v41.md. || `V41_MAX_IMAGE_TOKENS` | the checkpoint's `max_image_tokens` | DeepSeek V4.1: ceiling on what one image costs in prompt tokens. |-| `V41_TRACE` | unset | DeepSeek V4.1: print per-sublayer checksums, matching tools/dsv41_ref.py's, to locate a divergence by diffing two columns. |+| `V41_TRACE` | unset | DeepSeek V4.1: print per-sublayer checksums, matching tools/dsv41_ref.py's, to locate a divergence by diffing two columns. `2` follows the first row of a speculative step rather than the last. |+| `V41_DSPARK` | on when the checkpoint carries the head | DeepSeek V4.1: `0` disables the DSpark draft head, which is then not loaded at all. Drafts never change what a turn produces, only how many forwards it takes. |+| `V41_DSPARK_MAX` | the checkpoint's `dspark_block_size` | DeepSeek V4.1: how many drafted tokens go in front of the main model per round. Fewer costs less when a round is rejected and caps the win when it is not. |+| `V41_DSPARK_MINACC` | 30 | DeepSeek V4.1: percent of drafts that must be accepted over a window of 24 before drafting pauses for 64 tokens. |+| `V41_SPEC_FORCE` | unset | DeepSeek V4.1, oracle mode only: draft the reference's own tokens (`1`), corrupt the last one (`2`), or keep the head's (`3`), so the verification path runs on a fixture whose draft head is random noise. |diff --git a/docs/deepseek-v41.md b/docs/deepseek-v41.mdindex 43217f17..54bd90cd 100644--- a/docs/deepseek-v41.md+++ b/docs/deepseek-v41.md@@ -60,6 +60,47 @@ Each mechanism mirrors a named piece of the vendor's `inference/model.py`:not scale them, plus one shared expert every token pays for.- **vision**: a 32-layer ViT with 2D split-half RoPE and a 3x3 aligner, resident.+## DSpark: drafting, and why accepting a draft is safe++The checkpoint carries an MTP draft head under `mtp.*`: three stages of the same block+the backbone uses, reading the attention input of layers 37, 38 and 39, and proposing+five tokens at a time. Their attention never compresses -- it is window-only, and the+window holds the **main** stream's keys, not the drafts' -- and they route over 128+experts of their own instead of 384, three per token, so a round of drafting costs+about a fifth of what one main token costs and produces up to five candidates.++Nothing is emitted on the draft head's word. The five drafts and the token that+produced them go back through the main model as **one forward**, which prices five+positions for one pass over the dense trunk and one pass over the union of their+experts. Each draft is kept while it agrees with what that forward says (greedy), or+with probability `p(draft)` under the sampler's own distribution when the temperature+is above zero, which for a deterministic drafter is exactly the speculative-sampling+rule; a rejected draft is banned from the resample, so the residual distribution is+the right one. What survives is what sequential decoding would have produced, position+by position.++Being exactly equal to sequential decoding is the whole load-bearing claim, and it is+not free. Three pieces of per-position state are addressed modulo something and so can+be clobbered by a draft several positions ahead:++- the **window ring**, where a draft at `p + 2` overwrites the key of `p - 6`, which a+ committed position still needs;+- the **compressor's group slots**, where a draft can overwrite the earlier half of a+ group that has not closed yet;+- the **published index-key slot**, which is per-step state in the vendor and has to+ read, for each row, what was published as of that row's own position.++Each row saves what it displaced, and a rejected row puts it back. `V41_SPEC_FORCE` in+the oracle drafts the reference's own next tokens (`1`), or corrupts the last of them+so a round is rejected part way (`2`), or keeps the head's own (`3`); all three have to+reproduce the reference token for token, and CI runs them.++Drafting is on whenever the checkpoint carries the head. It is not always worth it: a+round that is rejected has still read its stages' experts, so acceptance is measured+over a window and the drafts pause for 64 tokens when it falls under+`V41_DSPARK_MINACC`. `V41_DSPARK=0` turns the head off entirely, and it is then not+even loaded.+## The index-key slot, and why the default is the odd one`model.py` keeps the published index-key cache in one module-level slot and@@ -89,7 +130,11 @@ default cannot be "tidied" by accident.| `V41_ENGRAM_ROWS` | 65536 | rows of engram cache per table. The traffic is Zipfian: common 2-grams repeat constantly, so a small cache absorbs most of it. 65536 rows is 64 MB per table on the released head_dim. || `V41_INDEX_OWNER` | unset | each layer scores against its own owner's index keys (see above). Changes the model's behaviour. || `V41_MAX_IMAGE_TOKENS` | the checkpoint's `max_image_tokens` | a ceiling on what one image costs in prompt tokens. |-| `V41_TRACE` | unset | print a checksum of the tensors the reference prints too, for locating a divergence by diffing two columns. |+| `V41_TRACE` | unset | print a checksum of the tensors the reference prints too, for locating a divergence by diffing two columns. `2` follows the first row of a speculative step instead of the last, which is the row a sequential decode is comparable to. |+| `V41_DSPARK` | on when the checkpoint carries the head | `0` disables the draft head and does not load it. |+| `V41_DSPARK_MAX` | the checkpoint's `dspark_block_size` | how many of the drafted tokens are put in front of the main model. Fewer means a cheaper rejected round and a lower ceiling on the win. |+| `V41_DSPARK_MINACC` | 30 | percent of drafts that must be accepted over a window of 24 for drafting to continue; below it, drafts pause for 64 tokens. |+| `V41_SPEC_FORCE` | unset | oracle mode only: draft the reference's tokens (`1`), corrupt the last one (`2`), or use the head's own (`3`), to exercise the verification path on a fixture whose draft head is random. |## How it is tested@@ -102,4 +147,21 @@ capacities and holds the vision tower to its own reference rows.Writing both sides found three defects that a single implementation would have kept:a hyper-connection mix summed over the wrong axis, hash multipliers rounded by a JSONreader that stores numbers as doubles, and an index list that a non-source layer-inherited from uninitialized memory instead of from its source.+inherited from uninitialized memory instead of from its source. Holding a speculative+step to the same reference found two more, both in what a rejected draft leaves+behind: a window slot and a compressor group slot that a committed position still+needed.++The gateway is tested against the checkpoint's own encoding fixtures+(`tests/test_openai_tools_v41_e2e.py`), and an image is followed all the way from an+OpenAI request to a different answer in `tests/test_dsv41_image_serve.py`.++## Where this engine is not the vendor++The vendor quantizes some activations on the fly, in kernels that only exist for the+GPU: the KV cache is rounded to fp8 before it is stored (`act_quant(..., inplace=True)`+in `Attention.forward`), and the indexer's queries and keys, and the compressor's+latents, are rounded to fp4. This engine keeps all of them in fp32 -- more precise, and+therefore not bit-identical to a GPU run of the same weights. Nothing downstream is an+argmax over a near-tie by construction, but it is a difference, and it is the reason a+divergence against a GPU reference would not necessarily be a bug here.