Skip to content

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

C

docs(v4): describe target-only engine split

DrewZaa1ec1627703
diff --git a/README.md b/README.md
index f5f2ec3c..138c7b43 100644
--- a/README.md
+++ b/README.md
@@ -459,20 +459,22 @@ Two things that differ per model, both documented in the per-model page:
## DeepSeek V4
-The experimental CPU path for **DeepSeek V4 Flash + DSpark** uses native FP4
-experts, automatic RAM planning, and lossless speculative verification. It is
-supported on x86-64 Linux and Windows/MSYS2; other platforms keep validating
-the main colibri engine through `make check`.
+The experimental CPU path for **DeepSeek V4 Flash** uses native FP4 experts,
+automatic RAM planning, shared `st.h` / `quant.h` infrastructure, and a
+persistent target engine. DSpark is intentionally kept for a separate stacked
+follow-up. The target engine is supported on x86-64/aarch64 Linux and
+Windows/MSYS2.
```bash
cd c
make deepseek-v4
-python ./v4 run --model /path/to/DeepSeek-V4-Flash-DSpark --ram 32 \
- --stop-sentence "What is the capital of France?"
+python ./coli run --model /path/to/DeepSeek-V4-Flash --ram 32 \
+ "What is the capital of France?"
+# The same model also works with: coli chat / coli serve / coli web
```
-See [docs/deepseek-v4.md](docs/deepseek-v4.md) for status, benchmarks,
-checkpoint validation, and the committed tiny independent oracle.
+See [docs/deepseek-v4.md](docs/deepseek-v4.md) for status, checkpoint
+validation, unified CLI/server usage, and the generated tiny independent oracle.
## What's next
diff --git a/docs/deepseek-v4.md b/docs/deepseek-v4.md
index 5092fc41..ade4636b 100644
--- a/docs/deepseek-v4.md
+++ b/docs/deepseek-v4.md
@@ -1,274 +1,96 @@
-# DeepSeek V4 (colibri CPU)
+# DeepSeek V4 target engine (colibri CPU)
-English · [简体中文](deepseek-v4.zh-CN.md)
+[简体中文](deepseek-v4.zh-CN.md)
-Local CPU inference for DeepSeek V4 Flash + DSpark on colibri: weight loading,
-expert caching, sparse attention, speculative decode, and automatic RAM
-tiering—end-to-end generation that passes smoke tests.
+This is the target-only DeepSeek V4 Flash engine for the first PR of the V4
+split. DSpark speculative decoding is intentionally excluded and belongs in a
+separate stacked follow-up.
-## Done
+## Scope
-- **Target engine**: config / layer / attention / block / expert store / math /
- runtime / prompt; FP8 dense + native FP4 expert kernels; AVX-512 batch
- verify and rows16 hot-expert layout when available.
-- **DSpark speculative**: draft runner, heads, verify window, prefix/commit;
- acceptance reaches 100% on the smoke prompt.
-- **Automatic RAM policy**: plans resident tensors, DSpark stages, expert
- cache, and the output head from OS-available memory or `--ram`.
-- **SSD expert streaming**: two coalesced reads per expert (scales + weights);
- no reordered 160 GB container required.
-- **Source layout**: GLM-style amalgams `deepseek_v4.c` /
- `deepseek_v4_dspark.c`; public API in `deepseek_v4.h`
- (`ColiV4Engine` / `ColiV4Session` / config / prompt); implementation details in
- `deepseek_v4_internal.h` (not a stability commitment).
- `make deepseek-v4` builds `c/deepseek_v4.exe`.
-- **CLI**: `c/v4` (Python launcher, stdlib only) wraps `run` / `chat`; inference
- itself is engine + session (`coli_v4_engine_open` → `coli_v4_session_create` /
- `generate` → destroy sessions, then engine). The engine/session surface in
- `deepseek_v4.h` is an **experimental** public API and may change. Engine copies
- model directory strings; destroy every session before `coli_v4_engine_destroy`.
- Index and ExpertStore accessors stay internal (`deepseek_v4_internal.h`).
+- Production code is in `c/deepseek_v4.c`; the experimental public engine and
+ session API is in `c/deepseek_v4.h`.
+- Official sharded safetensors checkpoints load through shared `st.h`.
+- Standard MXFP4 matrix multiplication uses shared `quant.h`.
+- Unified `c/coli` routes `run`, `chat`, `serve`, and `web` to V4. Serving keeps
+ the engine and caches warm across requests.
+- `--no-dspark` is a compatibility no-op. This PR has no DSpark model, memory
+ tier, or speculative loop.
+- Build targets are x86-64/aarch64 Linux and Windows/MSYS2.
-## Model snapshot
+Destroy every session before destroying its engine.
-Typical DeepSeek-V4-Flash-DSpark shape (from checkpoint metadata):
+## Shared migration status
-| Item | Value |
-|------|------:|
-| Transformer layers | 43 |
-| Hidden size | 4096 |
-| Routed experts / layer | 256 (top-k 6) |
-| Bytes per expert record | ~12.75 MiB (FP4 E2M1 + UE8M0 scales) |
-| Sliding window | 128 |
-| Dense resident (layers) | ~6.27 GiB |
-| Routed expert payload | ~137 GiB (streamed; not all resident) |
+| Checkpoint path | Current implementation | Follow-up |
+|---|---|---|
+| Safetensors index/range reads | shared `st.h` | done |
+| fmt7 standard MXFP4 matmul | shared `quant.h` | done |
+| fmt7 resident rows16 expert cache | temporary V4-private layout | **TODO:** migrate after upstream exposes a resident rows16 API |
+| fmt8 E4M3 + UE8M0 128x128 scales | temporary V4-private decoder | **TODO:** replace after upstream shared fmt8 UE8M0 decode exists |
-Experts are packed FP4 (`float4_e2m1fn_x2` in I8 safetensors), not INT8.
-Dense weights use E4M3 with UE8M0 block scales. Activations are FP8×FP4 with
-FP32 accumulate on the reference path.
+The last two paths remain so the engine is usable. Source markers
+`TODO(upstream-fmt7-rows16)` and `TODO(upstream-fmt8-ue8m0)` make the required
+migration explicit.
-## Automatic RAM
+## Memory policy
-Budget order: system reserve → runtime working set → minimum expert slots
-(top-k × sparse layers) → optional resident BF16 lm_head (~1.06 GiB) → grow
-per-layer expert-cache slots with leftover budget.
+A typical checkpoint has 43 transformer layers, hidden size 4096, and 256
+routed experts per sparse layer with top-k 6. Dense weights occupy about
+6.27 GiB and a resident BF16 output head about 1.06 GiB. Routed-expert weights
+are streamed and cached according to the RAM budget.
-- Without `--ram`, the planner uses **OS-available** memory (not total RAM) and
- keeps an adaptive system reserve.
-- With `--ram GiB`, that value is a **planner budget**, not an OS-enforced hard
- limit. It governs projected resident weights, caches, and runtime workspace.
-- If the minimum expert working set does not fit, startup fails with a clear
- shortfall (no silent swap overcommit).
-- Head residency is optional: low-memory modes stream the BF16 head; surplus
- keeps it resident for speed.
-- Hot experts may be pinned and rearranged in place to a 16-row AVX-512 layout;
- cold experts stay official row-major FP4. Capacity does not grow from the
- rearrange.
+The planner reserves workspace and a minimum expert working set, then enables
+dense/head residency and grows the expert cache when memory permits. Dense
+residency is independent of DSpark and works in this target-only build,
+including with the legacy `--no-dspark` option.
-Example residency under an explicit 32 GiB planner budget:
+`--ram GiB` is a planner budget, not an OS-enforced limit. Without it, the
+budget is derived from currently available OS memory.
-```text
-dense ≈ 6.27 GiB
-dspark ≈ 10.45 GiB
-target expert cache ≈ 9.1 GiB (more slots when RAM allows)
-head = resident BF16
-```
-
-At 8 GiB the planner can still produce a process plan when the **host** has
-enough free memory for the minimum working set; decode is slower because the
-expert cache is tighter. That is not the same as shipping on a physical 8 GiB
-PC—see Bench.
-
-## Bench
-
-Hardware used for the numbers below:
-
-| Item | Value |
-|------|-------|
-| CPU | AMD Ryzen AI MAX+ 395 (16 cores / 32 threads, Radeon 8060S) |
-| System RAM | 128 GiB |
-| OS | Windows 11 |
-| Build | `make deepseek-v4` (MSYS2 UCRT64, `-march=x86-64-v3`) |
-
-Model: `DeepSeek-V4-Flash-DSpark`
-
-Prompt: `--stop-sentence "What is the capital of France?"`
-(output: *The capital of France is Paris.*)
-
-`--ram` here is a **planner budget** on this high-RAM machine, not a hard RSS
-limit or a physical 8 GiB/32 GiB PC. The **8 GiB row is a planning setting**
-(`--ram 8`): the host still has ample OS RAM/page cache for SSD expert I/O.
-A real ~8 GiB system may fail to start or run much slower once OS reserve,
-runtime scratch, and disk cache compete for the same budget—do not treat that
-row as a guarantee for 8 GiB hardware.
-
-| `--ram` | TTFT | prefill | decode | DSpark acceptance |
-|---------|------|---------|--------|-------------------|
-| 32 GiB | 9.57s | 1.403 tok/s | 1.236 tok/s | 100% |
-| 8 GiB (planner budget) | 10.02s | 1.338 tok/s | 0.712 tok/s | 100% |
-
-```text
-# --ram 32
-[stats] RAM 31.98/32.00 GiB | TTFT 9.57s | prefill 1.403 tok/s | decode 1.236 tok/s | DSpark acceptance 100.0%
-
-# --ram 8 (planner budget on ~127 GiB host — not a physical 8 GiB machine)
-[stats] RAM 7.55/8.00 GiB | TTFT 10.02s | prefill 1.338 tok/s | decode 0.712 tok/s | DSpark acceptance 100.0%
-```
-
-## Build
-
-Supported platforms for the V4 engine and its amalgam unit tests:
-
-- x86-64 Linux (gcc; AVX-512 paths when available)
-- Windows / MSYS2 UCRT64 (same)
-
-macOS, PowerPC, and other hosts keep validating the main colibri engine via
-`make check` and do
-**not** build or link DeepSeek V4. On unsupported platforms `make deepseek-v4`
-exits with a clear error.
+## Build and use
```bash
-# MSYS2 UCRT64
-export PATH=/ucrt64/bin:/usr/bin
-cd /d/ai/colibri/c
+cd c
make deepseek-v4
+python ./coli run --model /path/to/DeepSeek-V4-Flash --ram 32 \
+ "What is the capital of France?"
+python ./coli chat --model /path/to/DeepSeek-V4-Flash --ram 32
+python ./coli serve --model /path/to/DeepSeek-V4-Flash --ram 32
+python ./coli web --model /path/to/DeepSeek-V4-Flash --ram 32
```
-Or from the repo root: `make deepseek-v4` → `c/deepseek_v4.exe`.
-
-Amalgamated sources are compiled per former top-level unit via
-`-DCOLI_V4_UNIT_*` so onion `#include` + macro wraps stay correct. Shared
-kernels (`native_quant*`, `safetensors_index`, `tensor_io`) remain separate
-translation units.
+V4 chat uses native model markers. Native serving currently supports greedy
+generation and one active KV slot; tools and grammar are rejected. Requests
+re-prefill their context, while the process, weights, dense tensors, head, and
+expert cache stay warm.
-## Committed tiny independent oracle
+## Validation
-`make check` on x86-64 Linux and Windows/MSYS2 builds the V4 engine and runs
-`make deepseek-v4-tiny-check`. The committed `c/deepseek_v4_tiny` fixture is a
-valid reduced checkpoint, including one DSpark stage, and is about 1.2 MiB.
-It requires no network, PyTorch, Transformers, or model download at test time.
-Unsupported platforms skip the V4 execution while retaining the ordinary GLM
-build and platform-gating checks.
-
-The reference in `deepseek_v4_tiny/ref.json` is generated by the official
-Transformers `DeepseekV4ForCausalLM`, after the dense FP8, routed-expert FP4,
-and BF16 weight round trips used by the C checkpoint. The dependency-free
-test compares integer token IDs, never decoded text, and covers:
-
-- target teacher forcing and target-only greedy decoding;
-- target session generation with drafting disabled;
-- DSpark proposal plus target verification, with exact target identity;
-- sliding, compressed sparse, and heavily compressed attention;
-- a 72-token prompt crossing the internal 64-token prefill boundary; and
-- repeated engine/session open, generate, and destroy lifecycles.
-
-Regeneration is intentionally separate from CI. The checked-in fixture was
-created with Python 3.12, PyTorch 2.13.0, Transformers 5.14.1, and
-safetensors 0.8.0 (installed as a Transformers dependency):
+The tiny safetensors fixture is generated locally, ignored, and not committed:
```bash
-python -m pip install torch==2.13.0 transformers==5.14.1 safetensors==0.8.0
-python c/tools/make_deepseek_v4_tiny.py --force
-make -C c deepseek-v4-tiny-check
+python -m pip install -r tools/requirements-deepseek-v4-tiny.txt
+make deepseek-v4-tiny-check
```
-The generator has no C-engine fallback: it fails if official DeepSeek V4
-support is unavailable, prints every tensor name and shape, and records its
-schema/generator, PyTorch, and Transformers versions in `ref.json`.
+This covers loading, teacher forcing, greedy decode, long/repeated sessions,
+`--no-dspark` compatibility, and two requests through the persistent
+`SUBMIT`/`DATA`/`DONE` protocol.
-These checks prove top-1 token identity for this reduced, quantized model and
-exercise the real target/DSpark/session paths. They do not prove logit-level
-identity, production-checkpoint performance, every expert/cache residency
-policy, or full-model quality.
-
-To exercise the normal runtime without drafting:
-
-```text
-./deepseek_v4 deepseek_v4_tiny '<t005><t007><t009>' \
- --raw-prompt --draft-model deepseek_v4_tiny/dspark --no-dspark
-```
-
-Source distinction:
-
-- tiny committed fixture: independent `source=transformers` oracle;
-- full checkpoint smoke test below: `source=coli-self` consistency oracle.
-
-## Full-checkpoint oracle validation (not in light CI)
-
-Upstream expects targeted, token-level checks. V4 unit tests cover config /
-stores / math; full-model correctness is a separate heavy path:
+For a real checkpoint:
```bash
-cd c
-make deepseek-v4-oracle MODEL=/path/to/DeepSeek-V4-Flash-DSpark MEMORY_GB=32
-# or:
-python tools/make_deepseek_v4_oracle.py \
- --model /path/to/DeepSeek-V4-Flash-DSpark \
- --binary ./deepseek_v4.exe \
- --output tests/deepseek_v4_oracle.json \
- --validate --teacher-forcing 32 --greedy 20 --check-dspark
-```
-
-```text
-./deepseek_v4 MODEL --oracle tests/deepseek_v4_oracle.json \
- --teacher-forcing 32 --greedy 20 --memory-gb 32
-```
-
-### Comparison contract
-
-| Check | Criterion |
-|-------|-----------|
-| Teacher-forcing | top-1 token exact: N/N positions vs `tf_pred` |
-| Greedy | top-1 token exact: N/N continuation tokens vs `full_ids` |
-| DSpark on/off | greedy token sequences identical (`--check-dspark`) |
-| Logits / top-k | reserved for `source=transformers` fixtures |
-
-Fixture `source` field:
-
-- `coli-self` — recorded by the C engine with `--no-dspark` (default when
- Hugging Face DeepSeek V4 is unavailable). Proves reproducibility and that
- speculative decode matches the target greedy path; **not** HF bit-exact.
-- `transformers` — official implementation when
- `DeepseekV4ForCausalLM` loads (`--prefer-transformers`).
-
-The full-checkpoint oracle JSON is local/generated and is not required for
-`make check`; the committed tiny independent oracle is required there.
-
-## Run
-
-```powershell
-cd D:\ai\colibri
-python ./c/v4 run --model D:/ai/DeepSeek-V4-Flash-DSpark --ram 32 `
- --stop-sentence "What is the capital of France?"
-
+make deepseek-v4-oracle MODEL=/path/to/DeepSeek-V4-Flash \
+ MEMORY_GB=32 ORACLE_TEACHER_FORCING=32 ORACLE_GREEDY=20
```
-Or call the engine directly:
-`.\c\deepseek_v4.exe <model> <prompt> --max-tokens N --memory-gb G …`.
-
-### Options
-
-- `--model PATH` (required) DeepSeek V4 checkpoint directory
-- `--ram GiB` planner budget; omit for adaptive OS-available planning
-- `--ngen N` max generation tokens (default 128)
-- `--stop-sentence` (`run`) stop at the first sentence terminator
-- `--system` / `--thinking` (`chat` only)
-
-Chat re-prefills history each turn; cross-turn KV reuse is not implemented yet.
-Default non-thinking encoding:
-
-```text
-<|begin▁of▁sentence|>[system]<|User|>[user]<|Assistant|></think>
-```
+The oracle is target-only. DSpark on/off speed, acceptance, and token identity
+evidence belong to the stacked DSpark PR.
-## Todo
+## Follow-ups
-- [ ] **session parallel-prefix**: wire `COLI_V4_EXPERIMENTAL_PARALLEL_PREFIX_VERIFY`
- into `coli_v4_session_generate` (match legacy CLI verify throughput)
-- [ ] **16 GiB performance**: close the decode gap vs 32 GiB (cache, pinning, I/O overlap)
-- [ ] **Model quantization**: more aggressive weight/activation paths for footprint and bandwidth
-- [ ] **Server**: HTTP / OpenAI-compatible API for multi-client use
-- [ ] **CUDA**: optional GPU backend alongside the CPU path
-- [ ] **Dynamic DSpark for long outputs**: adapt the verify window between K=2–4
- from recent prefix survival / confidence instead of keeping a fixed K
-- [ ] Chat cross-turn KV cache reuse (avoid full re-prefill every turn)
+- Add non-greedy sampling and more serving slots.
+- Add shared replacements for the two temporary private quant paths above.
+- In the stacked PR, restore DSpark without changing target tokens and report
+ DSpark on/off performance and acceptance data.
diff --git a/docs/deepseek-v4.zh-CN.md b/docs/deepseek-v4.zh-CN.md
index 5d01cc13..9bb41be6 100644
--- a/docs/deepseek-v4.zh-CN.md
+++ b/docs/deepseek-v4.zh-CN.md
@@ -1,267 +1,87 @@
-# DeepSeek V4(colibri CPU)
+# DeepSeek V4 目标引擎(colibri CPU)
-[English](deepseek-v4.md) · 简体中文
+[English](deepseek-v4.md)
-colibri 上的 DeepSeek V4 Flash + DSpark 本地 CPU 推理:涵盖权重加载、
-专家缓存、稀疏注意力、推测解码和自动 RAM 分层,端到端生成已通过冒烟测试。
+这是 V4 拆分后第一个 PR 中的 DeepSeek V4 Flash 目标引擎。DSpark 推测解码
+不属于本 PR,将放在后续连续(stacked)PR 中。
-## 已完成
+## 当前范围
-- **目标模型引擎**:配置/层/注意力/块/专家存储/数学运算/运行时/
- prompt;FP8 稠密权重与原生 FP4 专家内核;在硬件支持时启用 AVX-512
- 批量验证和 rows16 热门专家布局。
-- **DSpark 推测解码**:草稿运行器、heads、验证窗口、prefix/commit;
- 在冒烟测试 prompt 上接受率达到 100%。
-- **自动 RAM 策略**:根据操作系统可用内存或 `--ram`,规划常驻张量、
- DSpark stages、专家缓存和输出 head。
-- **SSD 专家流式加载**:每个专家使用两次合并读取(scales + weights);
- 无需重新排列成 160 GB 容器。
-- **源码布局**:采用与 GLM 类似的聚合源文件 `deepseek_v4.c`/
- `deepseek_v4_dspark.c`;公共 API 位于 `deepseek_v4.h`
- (`ColiV4Engine`/`ColiV4Session`/配置/prompt);实现细节位于
- `deepseek_v4_internal.h`,不承诺接口稳定性。
- `make deepseek-v4` 会构建 `c/deepseek_v4.exe`。
-- **CLI**:`c/v4` 是仅使用标准库的 Python 启动器,封装 `run`/`chat`;
- 推理本身由 engine + session 完成(`coli_v4_engine_open` →
- `coli_v4_session_create`/`generate` → 销毁所有 session,再销毁 engine)。
- `deepseek_v4.h` 中的 engine/session 接口是**实验性**公共 API,未来可能变化。
- Engine 会复制模型目录字符串;调用 `coli_v4_engine_destroy` 前必须销毁所有
- session。Index 与 ExpertStore 访问器仍是内部接口
- (`deepseek_v4_internal.h`)。
+- 生产代码位于 `c/deepseek_v4.c`,实验性公共 engine/session API 位于
+ `c/deepseek_v4.h`。
+- 官方分片 safetensors checkpoint 通过共享 `st.h` 加载。
+- 标准 MXFP4 矩阵乘法使用共享 `quant.h`。
+- 统一入口 `c/coli` 会把 `run`、`chat`、`serve`、`web` 路由到 V4,
+ 服务模式会跨请求保留引擎和缓存。
+- `--no-dspark` 只是兼容性空操作。本 PR 没有 DSpark 模型、内存层级或推测循环。
+- 支持 x86-64、aarch64 Linux 和 Windows/MSYS2。
-## 模型概况
+销毁 engine 前必须先销毁全部 session。
-典型 `DeepSeek-V4-Flash-DSpark` 结构(来自 checkpoint 元数据):
+## 共享迁移状态
-| 项目 | 数值 |
-|------|-----:|
-| Transformer 层数 | 43 |
-| Hidden size | 4096 |
-| 每层路由专家数 | 256(top-k 6) |
-| 每条专家记录大小 | 约 12.75 MiB(FP4 E2M1 + UE8M0 scales) |
-| 滑动窗口 | 128 |
-| 稠密层常驻大小 | 约 6.27 GiB |
-| 路由专家 payload | 约 137 GiB(流式加载,不会全部常驻) |
+| checkpoint 路径 | 当前实现 | 后续工作 |
+|---|---|---|
+| safetensors 索引与区间读取 | 共享 `st.h` | 已完成 |
+| fmt7 标准 MXFP4 matmul | 共享 `quant.h` | 已完成 |
+| fmt7 常驻 rows16 专家缓存 | 临时 V4 私有布局 | **TODO:**上游提供常驻 rows16 API 后迁移 |
+| fmt8 E4M3 + UE8M0 128x128 scales | 临时 V4 私有解码器 | **TODO:**上游共享 fmt8 UE8M0 解码实现后替换 |
-专家使用 packed FP4(I8 safetensors 中的 `float4_e2m1fn_x2`),并非 INT8。
-稠密权重使用带 UE8M0 block scales 的 E4M3。参考路径以 FP8×FP4 计算激活,
-并使用 FP32 累加。
+为保证引擎当前可用,最后两条私有路径暂时保留。源码中已经分别标注
+`TODO(upstream-fmt7-rows16)` 和 `TODO(upstream-fmt8-ue8m0)`。
-## 自动 RAM 规划
+## 内存策略
-预算分配顺序:系统保留 → 运行时工作集 → 最小专家 slots
-(top-k × 稀疏层数)→ 可选的常驻 BF16 `lm_head`(约 1.06 GiB)→
-用剩余预算增加每层专家缓存 slots。
+典型 checkpoint 有 43 层 transformer、hidden size 4096,每个稀疏层有
+256 个路由专家,top-k 为 6。稠密权重大约占 6.27 GiB,常驻 BF16 输出
+head 大约占 1.06 GiB;路由专家权重按 RAM 预算流式读取和缓存。
-- 未指定 `--ram` 时,规划器使用**操作系统可用内存**而非总内存,并保留
- 自适应系统余量。
-- 指定 `--ram GiB` 时,该数值是**规划预算**,不是操作系统强制执行的硬上限;
- 它控制预计常驻权重、缓存和运行时工作区。
-- 如果最小专家工作集无法容纳,启动会明确报告差额并失败,不会静默依赖
- swap 超额分配。
-- 输出 head 是否常驻是可选的:低内存模式会流式读取 BF16 head;预算充足时
- 则常驻以提高速度。
-- 热门专家可固定并原地重排为 16-row AVX-512 布局;冷门专家仍使用官方的
- row-major FP4。重排不会增加容量占用。
+规划器先预留工作区与最小专家工作集,再在预算允许时启用 dense/head 常驻
+并扩大专家缓存。Dense 常驻与 DSpark 相互独立,在当前 target-only 版本和
+旧调用方传入 `--no-dspark` 时都能正常工作。
-显式指定 32 GiB 规划预算时的常驻示例:
+`--ram GiB` 是规划预算,不是操作系统硬上限;不传入时按当前可用内存估算。
-```text
-dense ≈ 6.27 GiB
-dspark ≈ 10.45 GiB
-target expert cache ≈ 9.1 GiB(RAM 允许时增加 slots)
-head = resident BF16
-```
-
-在**宿主机**有足够空闲内存容纳最小工作集时,规划器也能根据 8 GiB 预算
-生成进程方案;由于专家缓存更紧,解码会更慢。这不等同于可以在实体 8 GiB
-电脑上交付运行,详见下面的基准测试说明。
-
-## 基准测试
-
-以下数据使用的硬件:
-
-| 项目 | 数值 |
-|------|------|
-| CPU | AMD Ryzen AI MAX+ 395(16 核/32 线程,Radeon 8060S) |
-| 系统内存 | 128 GiB |
-| 操作系统 | Windows 11 |
-| 构建 | `make deepseek-v4`(MSYS2 UCRT64,`-march=x86-64-v3`) |
-
-模型:`DeepSeek-V4-Flash-DSpark`
-
-Prompt:`--stop-sentence "What is the capital of France?"`
-(输出:*The capital of France is Paris.*)
-
-这里的 `--ram` 是高内存机器上的**规划预算**,不是 RSS 硬上限,也不代表
-实体 8 GiB/32 GiB 电脑。**8 GiB 一行只是规划设置**(`--ram 8`):
-宿主机仍有充足的操作系统内存/页面缓存供 SSD 专家 I/O 使用。实体约 8 GiB
-系统可能无法启动,或在系统保留、运行时临时空间和磁盘缓存争夺同一预算时
-运行得慢得多;请勿把该行当作 8 GiB 硬件保证。
-
-| `--ram` | TTFT | prefill | decode | DSpark 接受率 |
-|---------|------|---------|--------|---------------|
-| 32 GiB | 9.57s | 1.403 tok/s | 1.236 tok/s | 100% |
-| 8 GiB(规划预算) | 10.02s | 1.338 tok/s | 0.712 tok/s | 100% |
-
-```text
-# --ram 32
-[stats] RAM 31.98/32.00 GiB | TTFT 9.57s | prefill 1.403 tok/s | decode 1.236 tok/s | DSpark acceptance 100.0%
-
-# --ram 8(约 127 GiB 宿主机上的规划预算,并非实体 8 GiB 机器)
-[stats] RAM 7.55/8.00 GiB | TTFT 10.02s | prefill 1.338 tok/s | decode 0.712 tok/s | DSpark acceptance 100.0%
-```
-
-## 构建
-
-V4 引擎及其聚合源文件单元测试支持以下平台:
-
-- x86-64 Linux(gcc;硬件支持时使用 AVX-512 路径)
-- Windows/MSYS2 UCRT64(同上)
-
-macOS、PowerPC 和其他主机仍通过 `make check` 验证 colibri 主引擎,
-但**不会**构建或链接 DeepSeek V4。在不支持的平台上,
-`make deepseek-v4` 会给出明确错误并退出。
+## 构建与使用
```bash
-# MSYS2 UCRT64
-export PATH=/ucrt64/bin:/usr/bin
-cd /d/ai/colibri/c
+cd c
make deepseek-v4
+python ./coli run --model /path/to/DeepSeek-V4-Flash --ram 32 \
+ "What is the capital of France?"
+python ./coli chat --model /path/to/DeepSeek-V4-Flash --ram 32
+python ./coli serve --model /path/to/DeepSeek-V4-Flash --ram 32
+python ./coli web --model /path/to/DeepSeek-V4-Flash --ram 32
```
-也可以在仓库根目录运行:`make deepseek-v4` → `c/deepseek_v4.exe`。
+V4 chat 使用模型原生标记。原生服务当前只支持 greedy 和一个活动 KV slot,
+tools 与 grammar 会被拒绝。请求会重新 prefill,但进程、权重、dense、
+head 与专家缓存会保持热状态。
-聚合源文件按照原先的顶层单元,使用 `-DCOLI_V4_UNIT_*` 分别编译,确保多层
-`#include` 与宏封装保持正确。共享内核(`native_quant*`、
-`safetensors_index`、`tensor_io`)仍是独立的编译单元。
+## 验证
-## 已提交的 tiny 独立 oracle
-
-x86-64 Linux 和 Windows/MSYS2 上的 `make check` 会构建 V4 引擎并运行
-`make deepseek-v4-tiny-check`。仓库中的 `c/deepseek_v4_tiny` fixture 是有效的
-缩小版 checkpoint,包含一个 DSpark stage,大小约 1.2 MiB。测试时无需网络、
-PyTorch、Transformers 或下载模型。不支持的平台会跳过 V4 执行,同时保留
-普通 GLM 构建和平台门控检查。
-
-`deepseek_v4_tiny/ref.json` 中的参考结果由官方 Transformers
-`DeepseekV4ForCausalLM` 生成,并经过 C checkpoint 使用的稠密 FP8、路由专家
-FP4 和 BF16 权重 round trip。这个零依赖测试比较整数 token ID,而不是解码后的
-文本,覆盖:
-
-- 目标模型 teacher forcing 与仅目标模型的 greedy decoding;
-- 禁用 drafting 时的目标模型 session 生成;
-- DSpark proposal 加目标模型验证,并保证与目标路径精确一致;
-- 滑动、压缩稀疏和高度压缩注意力;
-- 一个 72-token prompt,跨越内部 64-token prefill 边界;
-- 重复执行 engine/session 的打开、生成和销毁生命周期。
-
-Fixture 再生成刻意与 CI 分离。仓库中的 fixture 使用 Python 3.12、
-PyTorch 2.13.0、Transformers 5.14.1 和 safetensors 0.8.0 创建
-(safetensors 作为 Transformers 依赖安装):
+Tiny safetensors fixture 在本地生成、已忽略且不提交:
```bash
-python -m pip install torch==2.13.0 transformers==5.14.1 safetensors==0.8.0
-python c/tools/make_deepseek_v4_tiny.py --force
-make -C c deepseek-v4-tiny-check
-```
-
-生成器没有 C 引擎 fallback:如果官方 DeepSeek V4 支持不可用,它会直接失败;
-同时会打印每个张量的名称与 shape,并在 `ref.json` 中记录 schema/generator、
-PyTorch 和 Transformers 版本。
-
-这些检查证明缩小量化模型的 top-1 token 一致性,并执行真实的
-target/DSpark/session 路径;但不能证明 logit 级一致性、生产 checkpoint 性能、
-所有专家/缓存常驻策略或完整模型质量。
-
-要在禁用 drafting 的情况下执行普通运行时:
-
-```text
-./deepseek_v4 deepseek_v4_tiny '<t005><t007><t009>' \
- --raw-prompt --draft-model deepseek_v4_tiny/dspark --no-dspark
+python -m pip install -r tools/requirements-deepseek-v4-tiny.txt
+make deepseek-v4-tiny-check
```
-参考来源的区别:
-
-- 已提交的 tiny fixture:独立的 `source=transformers` oracle;
-- 下方完整 checkpoint 冒烟测试:`source=coli-self` 一致性 oracle。
-
-## 完整 checkpoint oracle 验证(不属于轻量 CI)
+测试覆盖加载、teacher forcing、greedy decode、长/重复 session、
+`--no-dspark` 兼容,以及持久化 `SUBMIT`/`DATA`/`DONE` 协议中的两次请求。
-Upstream 要求有针对性的 token 级检查。V4 单元测试覆盖配置/存储/数学运算;
-完整模型正确性使用单独的重型路径验证:
+真实 checkpoint 可运行:
```bash
-cd c
-make deepseek-v4-oracle MODEL=/path/to/DeepSeek-V4-Flash-DSpark MEMORY_GB=32
-# 或者:
-python tools/make_deepseek_v4_oracle.py \
- --model /path/to/DeepSeek-V4-Flash-DSpark \
- --binary ./deepseek_v4.exe \
- --output tests/deepseek_v4_oracle.json \
- --validate --teacher-forcing 32 --greedy 20 --check-dspark
-```
-
-```text
-./deepseek_v4 MODEL --oracle tests/deepseek_v4_oracle.json \
- --teacher-forcing 32 --greedy 20 --memory-gb 32
-```
-
-### 比较约定
-
-| 检查 | 判定标准 |
-|------|----------|
-| Teacher-forcing | top-1 token 精确一致:N/N 个位置与 `tf_pred` 比较 |
-| Greedy | top-1 token 精确一致:N/N 个续写 token 与 `full_ids` 比较 |
-| DSpark 开/关 | greedy token 序列相同(`--check-dspark`) |
-| Logits/top-k | 仅用于 `source=transformers` fixture |
-
-Fixture 的 `source` 字段:
-
-- `coli-self`——由 C 引擎使用 `--no-dspark` 记录(Hugging Face DeepSeek V4
- 不可用时的默认方式)。它证明结果可复现,并证明推测解码与目标模型 greedy
- 路径一致;**不代表**与 HF bit-exact。
-- `transformers`——成功加载 `DeepseekV4ForCausalLM` 时使用的官方实现
- (`--prefer-transformers`)。
-
-完整 checkpoint oracle JSON 是本地生成文件,不是 `make check` 的必需项;
-已提交的 tiny 独立 oracle 则是必需项。
-
-## 运行
-
-```powershell
-cd D:\ai\colibri
-python ./c/v4 run --model D:/ai/DeepSeek-V4-Flash-DSpark --ram 32 `
- --stop-sentence "What is the capital of France?"
+make deepseek-v4-oracle MODEL=/path/to/DeepSeek-V4-Flash \
+ MEMORY_GB=32 ORACLE_TEACHER_FORCING=32 ORACLE_GREEDY=20
```
-也可以直接调用引擎:
-`.\c\deepseek_v4.exe <model> <prompt> --max-tokens N --memory-gb G …`。
-
-### 选项
-
-- `--model PATH`(必需):DeepSeek V4 checkpoint 目录
-- `--ram GiB`:规划预算;省略时根据操作系统可用内存自适应规划
-- `--ngen N`:最大生成 token 数,默认 128
-- `--stop-sentence`(`run`):在第一个句子终止符处停止
-- `--system`/`--thinking`:仅适用于 `chat`
-
-Chat 每轮都会重新 prefill 历史记录;尚未实现跨轮 KV 复用。
-默认的非 thinking 编码为:
-
-```text
-<|begin▁of▁sentence|>[system]<|User|>[user]<|Assistant|></think>
-```
+这个 oracle 只验证目标引擎。DSpark 开关速度、接受率和 token 一致性证据
+属于后续 stacked DSpark PR。
-## 待办事项
+## 后续工作
-- [ ] **session parallel-prefix**:将
- `COLI_V4_EXPERIMENTAL_PARALLEL_PREFIX_VERIFY` 接入
- `coli_v4_session_generate`,达到旧版 CLI 的验证吞吐
-- [ ] **16 GiB 性能**:缩小与 32 GiB 的解码差距(缓存、固定、I/O 重叠)
-- [ ] **模型量化**:采用更激进的权重/激活路径,降低占用和带宽需求
-- [ ] **服务器**:面向多客户端的 HTTP/OpenAI 兼容 API
-- [ ] **CUDA**:在 CPU 路径之外增加可选 GPU 后端
-- [ ] **长输出动态 DSpark 调节**:根据近期 prefix survival/confidence,
- 在 K=2–4 之间动态选择验证窗口,不再始终使用固定 K
-- [ ] Chat 跨轮 KV cache 复用,避免每轮重新 prefill 全部历史
+- 增加非 greedy 采样与更多服务 slot。
+- 为上述两条临时私有 quant 路径增加共享替代实现。
+- stacked PR 恢复 DSpark 时必须保持目标 token 不变,并提供开关性能与接受率数据。