DwarfStar 4

ds4.c A Native Inference Engine for DeepSeek V4 Flash

A deliberately narrow, self-contained C inference engine — not a generic GGUF runner, not a wrapper around another runtime. Built for one model, tested against official logits, and ready for coding agents.

284B
Total Parameters
13B
Active per Token
1M
Token Context
137
Commits (11 days)
3
Backends

Project Timeline

137 commits over 11 days — from a bare initial release to a polished multi-backend inference engine with tool streaming, disk KV cache, eval harness, and agent APIs.

Phase 1: Foundation & Initial Release
May 7 – May 8
May 7, 2026

Initial Release d997b56

Salvatore Sanfilippo (antirez) releases the first version of ds4 — a standalone C inference engine for DeepSeek V4 Flash. The project begins with a CPU reference backend, Metal GPU support, and a basic interactive CLI.

releasemetalcli
May 7

MTP Validator Fix & README Polish efce64b · c39962f

Community contributions land: ffn_gate_inp tensor accepted as F32 in the MTP speculative decoder, plus spelling fixes across README and source comments.

communitymtpfix
May 7

Terminal Diagnostics & Q4 Benchmarks d57c6cd · ab64b9c

Improved terminal diagnostics for debug output, and the first Q4 quantization benchmark results documented in the README.

diagnosticsbenchmark
May 7–8

OpenAI Tool Argument Streaming a1e6945 · 404f0a1

Major feature: the server now streams OpenAI tool arguments token-by-token as they are generated. Rejects incomplete streamed tool calls that would break parsing. A critical capability for agentic coding workflows.

tool-streamingserver
May 8

Thinking Stream Routing Fix b43a0bc

Fixes routing of OpenAI thinking/reasoning content through the streaming path so agent clients receive structured reasoning_content events instead of raw text.

thinkingstream
May 8

Curl Download Progress d615ab0

Adds visible curl progress bars while downloading model GGUFs, making the 80+ GB download experience less opaque.

uxdownload
Phase 2: KV Cache & Tool Replay Engineering
May 9 – May 10
May 9

Token Dump Debugging 9c0e6ac

Adds backend-independent token dump debugging — a crucial tool for aligning local inference output with official DeepSeek logits during regression testing.

debugtesting
May 9

Exact DSML Tool Replay Memory 52f8b95 · d967f63 · c184499

Critical innovation. DeepSeek models emit tool calls as DSML text, but agent clients send back JSON tool-call objects. If the server re-rendered those objects differently, the KV cache prefix would mismatch and force a full rebuild. This series adds exact replay memory backed by radix trees: every tool call's original DSML bytes are stored and reused verbatim on the next turn. The map survives in KV cache files across server restarts.

tool-replaykv-cacheexact-replay
May 9

KV Cache Reporting & Anthropic Cache 0ca2e28 · 38800bf

Server now reports KV cache usage stats and Anthropic-style cache metrics — essential for debugging long-context performance and disk cache policy.

kv-cacheanthropic
May 9

Metal Debug Validation & JSON Parser Fix f9e8715 · 8e7575b

Metal backend passes debug-layer buffer validation, and a JSON parser nesting DoS vulnerability is patched — safety for agent-originated tool call payloads.

metalsecurity
May 9

Tool Replay & Streaming Documentation d3fd981 · cb7feea

Documents the KV tool replay map format and the tool streaming behavior — making the architecture accessible to contributors and agent integrators.

docstool-replay
May 9–10

Toolless Thinking Fix 091e502

Fixes a session cache miss on every turn when operating in toolless thinking mode — a subtle KV checkpoint boundary bug that cost performance in agent sessions.

kv-cachethinking
May 10

Metal Hardware Info & DSML Fixes 7120b85 · 22ca6ab

Prints Metal GPU hardware info at startup, fixes DSML payload sampling repetition, and aligns continued KV checkpoints to aligned frontiers for cache reuse.

metaldsml
May 10

Rendered Text Prefixes for KV Cache Reuse 28cbb95

Uses rendered text prefixes (not just token IDs) to decide KV cache reuse — makes the cache hit rate dramatically better when prompt structures change slightly between turns.

kv-cacheoptimization
May 10

Loose DSML Tool Parameters & Checkpoint Canonicalization 3222caf · fe0d26b

Recovers loose nested DSML tool parameters (the model sometimes wraps parameters oddly), canonicalizes toolless thinking checkpoints, and returns recoverable output for malformed tool calls.

tool-callscanonicalization
Phase 3: Multi-Backend, Benchmarks & Rename
May 10 – May 12
May 10

Project Status & Directional Steering e88a51f · 3f7e5c9

README gets a candid project status section. Directional steering pipeline added — the ability to bias model outputs by injecting steering vectors during generation.

docssteering
May 11

CUDA Support Added 48beef8

Major milestone. NVIDIA CUDA backend joins Metal. Includes CUDA-specific kernels, memory management, and graph scheduling. The DGX Spark (NVIDIA's local AI machine) becomes a first-class target.

cudanvidia
May 11

Backend Refactoring 0ac5df3

Refactors the backend abstraction layer — Metal, CUDA, and CPU now share a unified interface. Makes adding new backends (like ROCm) tractable.

refactor
May 11

Verbosity Steering & Incremental Benchmark 9deabad · 0c1c023

Adds verbosity steering (controlling how much the model writes), plus an incremental throughput benchmark that measures prefill and generation at context frontiers.

steeringbenchmark
May 11

Project Renamed: DwarfStar 4 ae302c2

From "ds4" to "DwarfStar 4" — a proper name that reflects the project's identity as a compact but powerful inference engine, like a dwarf star that burns hot and dense.

branding
May 11

imatrix Weights & Thinking Checkpoint Fix 5161bc9 · b1ed832

Q2-imatrix weights added to download script (importance-matrix-tuned quantization for better quality). Thinking checkpoint rebuild on length-stop fixed.

imatrixthinking
May 11

CUDA Architecture Build Knob & Prefill Progress 66afd65 · 412bae1

Adds explicit CUDA architecture targeting for build (e.g., make cuda-spark vs make cuda-generic). Server reports prefill progress by suffix token for long prompts.

cudaserver
May 11

96 GB Memory Documentation 920f987

Documents that ds4 runs well with 96 GB of system memory — enabling MacBook Pro users with the M3 Max 96 GB config to run the 2-bit quant at reasonable context windows.

docscommunity
May 12

ROCm (AMD GPU) Backend & README Rework 7a751eb · c5ef7ac

Community adds ROCm support for AMD GPUs (kept in a separate branch since antirez lacks AMD hardware). README gets a major rework with separate motivations section.

rocmamddocs
May 12

Benchmark Infrastructure ef75c30 · e801b2b · 9e41f36

Benchmarks reorganized: renamed to speed-bench for clarity, CSV files unified into a single directory, and a Python SVG rendering script added for visual benchmark charts.

benchmarkvisualization
May 12

M2 Ultra (192 GB) Benchmark d9e2317

Community benchmark results for the Mac Studio M2 Ultra with 192 GB — showing 84 t/s prefill and 36 t/s generation on the 2-bit quant.

benchmarkm2-ultra
Phase 4: Responses API, CUDA Polish & Eval
May 12 – May 15
May 12

OpenAI Responses API (/v1/responses) bb697b3

Major feature. Adds the OpenAI Responses API endpoint — the preferred interface for Codex CLI. Supports input, instructions, tools, reasoning, and streaming. Continuations bound to live state when possible.

responses-apicodex
May 12

CUDA Memory & Graph Optimizations a97e7a3 · eb3c0b8 · ad8a926

Guards CUDA q8 fp16 cache memory use, allocates graph tensors in device memory, zeroes compressor state with memset. Core CUDA performance and correctness work.

cudamemory
May 12–13

CUDA Long-Context Fixes & Regression 320b779 · 0c41d58 · a464840

Imports CUDA long-context fixes to handle the 1M token context window correctly. Reduces long-context prefill slope for faster chunked processing. Adds a formal long-context regression test.

cudalong-contexttesting
May 12

Backend Names in Errors & README Fixes 03a14e4 · 67e450c

Session errors now include the backend name for clarity. README benchmark paths and image references fixed.

uxdocs
May 12

GGUF Quantization Tools 453a5fa

Adds the gguf-tools suite: offline GGUF generation, importance matrix collection, quantization, and quality checks. Enables the community to build their own GGUFs.

ggufquantization
May 12–13

CUDA MoE Block16 & MTP Fixes e85c051 · 0230891 · a5f4f76

MoE down-projection block16 path made opt-in then cleaned up. Live MTP correctness fixes kept for the speculative decoding path. CUDA q8 fp16 cache restored for large-memory devices.

cudamoemtp
May 12–13

imatrix Calibration Corpus Improved dbfdd94

Broader and better calibration prompts for the importance matrix — directly improves quantization quality for the imatrix-tuned GGUFs.

imatrixcalibration
May 13

Contributing Guide & CUDA Target Selection d57ae3f · 8aaf3d1

Formal contributing guide with correctness and speed regression testing requirements. CUDA target selection made explicit in the build system.

docscuda
May 13

gguf-tools CUDA Quality Scorer d540955

CUDA backend now usable for quality scoring in the gguf-tools pipeline — enables GPU-accelerated validation of custom GGUFs against official DeepSeek continuations.

cudaquality
May 13

Story Recall Regression Test 0cba357

Adds a long-context story fact-recall regression test — the model must retrieve spelled-out person-number assignments from a long prose prompt. Essential for validating the 1M context window.

testinglong-context
Phase 5: Agent API Polish, Eval Harness & Finalization
May 13 – May 16
May 13–14

Responses API Replay & Tool Hardening f7e07f8 · 6396966 · a01bf1d

Harden the Responses API tool replay: tighter tool_search replay, fix tool checkpoint cache reuse, fix live continuation. Makes Codex CLI sessions robust across turns.

responses-apitool-replay
May 13–14

Metal Q4 Expert Tensors & Merge Responses API 2a7a5f3 · b4c5f7c · e88a71e

Metal backend covers q4 expert tensors in model views. Skips tool checkpoint canonicalization for exact DSML replay. The Responses API branch is merged into main.

metalresponses-api
May 14

Visible Live Checkpoints & Logs 5453ad0 · 646798f

Uses visible live checkpoints for toolless thinking (avoids hidden checkpoint state). Server progress logs clarified for debugging agent sessions.

kv-cachelogging
May 14

Anthropic Live Tool Continuation & Streaming 43535e1 · 94c1f38

Adds Anthropic live tool continuation and streams Anthropic tool calls live — Claude Code clients get real-time tool use events instead of waiting for completion.

anthropicstreaming
May 14

Responses API Logs & Hidden Reasoning Recovery 0083475 · 0610591

Tags Responses API server logs for debugging. Recovers Responses replays without hidden reasoning — ensures the model's visible output isn't lost when reasoning is stripped.

responses-apireasoning
May 14

Anthropic Tool Replay Parse Order Fix 2964a93

Fixes the order in which Anthropic tool replay parses DSML blocks — critical for correct multi-tool call handling in Claude Code sessions.

anthropictool-replay
May 14

CUDA Managed KV Cache for Huge Contexts 04b6fda

CUDA backend uses managed memory for the KV cache when contexts are huge (>100k tokens) — enables the 1M context window on GPU without exhausting device memory.

cudakv-cache
May 14

Standardized Context Length Errors c4b8e37 · be43477

Adds context-exceeded errors with token counts (matching OpenAI API behavior), then standardizes the format. Makes agent clients handle context overflow gracefully.

apierrors
May 15

ds4-eval: Benchmark Harness de5ec6d · 899b207 · d4f3133

Major feature. The ds4-eval benchmark harness is added — questions drawn from GPQA Diamond, SuperGPQA, AIME 2025, and COMPSEC. Model card synopsis document added. KV disk cache eviction thrash fixed.

evalbenchmark
May 15

ds4-eval TUI Polish & Controls 336fbd6 · 950e8e6

Split-screen TUI for the eval harness gets polished. Literal tool result text preserved (no stripping). p to pause, q to exit with report, Up/Down to select questions.

evaltui
May 15

Tool Schemas Prepend & KV Hit Decay 7b68234 · b62292c

Server prepends tool schemas to the rendered system prompt for better model adherence. KV cache gets optional hit-count decay for eviction scoring — aging out stale cache entries.

tool-schemaskv-cache
May 15

Cache Report, KV Decay Default & CORS 6f9fecf · d0357ec · 312935e

OpenAI cached token counts kept read-only in API responses. KV cache hit decay made the default eviction strategy. Opt-in CORS support for browser-based clients.

kv-cachecors
May 15–16

ds4-eval Benchmark Items & Audit e258d51 · b166a73 · 2ae607f

Benchmark items cleaned up, prompts audited for quality, and ds4-eval controls improved (auto-sizing context, reporting polished).

evalaudit
May 15–16

imatrix Calibration & Cold KV Checkpoints 1f6a8fe · f074c7b

Imatrix calibration prompts broadened for better quantization. Cold KV checkpoints anchored at chat task boundaries — disk cache now properly scoped to conversation turns.

imatrixkv-cache
May 16

COMPSEC Eval Cases & Auto-Size Context 4441e56 · 48c4d4d · 011aa67

Auto-sizing added to the eval context window. COMPSEC category introduced — 17 single-function C/C++ security reasoning items derived from public CVE writeups. Localization cases refined for clarity.

evalcompsecsecurity
May 16

Final Polish: Min-P Default, Tool Thinking Ignore, Working Dir 037ee39 · 613e9b2 · ef0a490

Default sampling changed to min-p filtering (relative probability, not nucleus mass). Tool calls emitted inside thinking blocks are ignored. Server gets a --chdir working directory option.

samplingtool-callsconfig
Phase 6: Graph & CUDA Correctness
May 17
May 17

Flash Graph Correctness Fixes 5bc1e6d

Applies correctness fixes to the Flash computation graph — addresses numerical accuracy issues in the forward pass that could cause subtle output divergence from the reference implementation.

correctnessflash
May 17

CUDA: Fix Compressed Prefill RoPE Positions c9dd949

Fixes RoPE (Rotary Position Embedding) position indices during compressed prefill on CUDA — a correctness bug where position assignments were incorrect for compressed attention rows, causing degraded output quality on long contexts.

cudaropecorrectness

Architecture

How ds4.c is structured — a single-model inference engine with three backends and a narrow public API.

📦

Model Loading (mmap)

GGUF files are memory-mapped, not eagerly copied. The 80+ GB model sits on disk and is accessed via page faults. This keeps startup fast and memory usage proportional to active working set.

🧬

Compressed Sparse Attention

DeepSeek V4 uses CSA + HCA: a 128-token sliding window (raw), ratio-4 compressed rows with indexer (even layers, top-k=512), and ratio-128 compressed rows (odd layers). DS4 implements this mixed-attention computation natively.

🗄️

KV Cache: First-Class Disk Citizen

The KV cache is designed for disk persistence, not just RAM. --kv-disk-dir stores compressed KV state as files on SSD. The server can cold-start from disk checkpoints, making long agent sessions practical without keeping everything in memory.

🖥️

Three Backends

Metal (macOS, primary target), CUDA (NVIDIA, DGX Spark focus), CPU (reference/diagnostics). Unified backend interface with backend-specific graph scheduling and kernel implementations.

🔗

DSML Tool Replay

Exact replay memory backed by radix trees: every tool call's original DSML bytes are stored and reused verbatim. Falls back to deterministic canonicalization. The map survives in KV cache files across server restarts.

🌐

Three API Protocols

OpenAI Chat Completions (/v1/chat/completions), OpenAI Responses (/v1/responses), and Anthropic Messages (/v1/messages). All support SSE streaming, tool calls, and thinking mode.

// ds4.h — the narrow public API boundary // CLI and server code should not know tensor internals typedef enum { DS4_BACKEND_METAL, DS4_BACKEND_CUDA, DS4_BACKEND_CPU } ds4_backend; typedef enum { DS4_THINK_NONE, DS4_THINK_HIGH, DS4_THINK_MAX } ds4_think_mode; // ... ds4_engine holds the loaded model, ds4_session holds one mutable timeline

Key Features

What makes ds4.c unique — and why it exists as a standalone engine rather than a GGML plugin.

1

Single-Model Focus

Not a generic GGUF runner. Every optimization, kernel, and memory policy is tailored for DeepSeek V4 Flash's specific tensor layout, quantization mix, and compressed attention pattern. This narrowness is the source of its speed and correctness.

2

Disk KV Cache

The KV cache is a first-class disk citizen, not a RAM-only structure. Compressed KV state is stored as files on fast SSDs. This changes the assumption that long-context inference requires enormous RAM — the disk absorbs the history, and only the active window lives in memory.

3

Exact DSML Tool Replay

The model emits tool calls as DSML text, but agents send back JSON. Without exact replay, every turn would force a full KV cache rebuild. DS4 stores the original DSML bytes verbatim and replays them — making multi-turn agent sessions efficient.

4

Smart Thinking Mode

DeepSeek V4 Flash produces a thinking section that is proportional to problem complexity — often 1/5 the length of other models. DS4 exposes --think, --think-max, --nothink controls and streams reasoning content in the native API format.

5

1M Token Context

The model's 1 million token context window is fully supported. Compressed KV cache (indexer + ratio-4/ratio-128 rows) keeps memory manageable: ~26 GB for the full 1M context, making it feasible on 128 GB machines at smaller windows.

6

Official-Vector Validation

Every GGUF is tested against official DeepSeek continuation vectors. The ds4_test suite compares token bytes and logit slices against the reference implementation. No "works on my machine" — correctness is verified by ground truth.

7

Agent-Ready APIs

Three complete API implementations: OpenAI Chat, OpenAI Responses (for Codex CLI), and Anthropic Messages (for Claude Code). All support streaming, tool calls, thinking mode, and KV cache reuse. Tool schemas are prepended to the system prompt automatically.

8

Specialized 2-Bit Quantization

The 2-bit quants are not a joke: they use asymmetrical quantization where only routed MoE experts are quantized (up/gate at IQ2_XXS, down at Q2_K), while shared experts, projections, and routing are left untouched. The result is remarkable quality at 81 GB model size.

# Model architecture summary (from MODEL_CARD.md) # Compressed Sparse Attention + Heavily Compressed Attention Layers 0-1: raw 128-token sliding window only Even layers 2+: ratio-4 compressed KV + indexer KV (top-k=512) Odd layers 3+: ratio-128 compressed KV (no indexer)

Performance

Real-world throughput numbers across hardware configurations. Short prompts, long prompts, and the DGX Spark.

Machine Quant Prompt Type Prefill (t/s) Generation (t/s)
MacBook Pro M3 Max, 128 GB q2 short 58.52 26.68
MacBook Pro M3 Max, 128 GB q2 11,709 tokens 250.11 21.47
Mac Studio M3 Ultra, 512 GB q2 short 84.43 36.86
Mac Studio M3 Ultra, 512 GB q2 11,709 tokens 468.03 27.39
Mac Studio M3 Ultra, 512 GB q4 short 78.95 35.50
Mac Studio M3 Ultra, 512 GB q4 12,018 tokens 448.82 26.62
DGX Spark GB10, 128 GB q2 7,047 tokens 343.81 13.75
Key insight: Prefill throughput is higher for long prompts because DS4 uses chunked prefill with KV cache reuse. The M3 Ultra hits 468 t/s prefill on a 12k prompt — reading a 284B parameter model at nearly 500 tokens per second.
Generation scales with active parameters: At only 13B active parameters per token, generation speed is high even on the 2-bit quant. The M3 Ultra delivers 36 t/s — comparable to running a 13B dense model locally.

Capability Evaluation

ds4-eval — a 92-question regression suite, not a leaderboard runner.

25

GPQA Diamond

Graduate-level science questions (physics, chemistry, biology) with multiple-choice answers. Tests whether the model can still reason correctly after kernel or quantization changes.

25

SuperGPQA

Broad specialist knowledge and domain-transfer questions. Curated from the upstream dataset — rows with wrong keys or underspecified prompts are replaced.

25

AIME 2025

Exact-answer contest math problems. No multiple-choice prior, no partial credit — a single arithmetic slip changes the grade. The most unforgiving items in the set.

17

COMPSEC

Single-function C/C++ security reasoning items reduced from public CVE writeups. Identify the best source line where the defensive code flaw is introduced.

Purpose: After a kernel, quantization, prompt-rendering, KV-cache, or tool-streaming change — does DeepSeek V4 Flash still solve a representative mix of hard science, broad knowledge, exact math, and security-code problems? Not a pass/fail unit test; a capability regression suite.

Recommended Reading

To understand ds4.c and the DeepSeek V4 Flash model, start here.

README.md (full)

The primary documentation — motivations, architecture, CLI, server setup, agent configuration, and tool-call handling. Read this first.

MODEL_CARD.md

Synopsis of the official DeepSeek-V4-Flash Hugging Face model card. Covers model family, architecture (CSA/HCA), quantization strategy, and benchmark interpretation.

CONTRIBUTING.md

Correctness and speed regression testing guide. Describes the ds4_test suite: logprob vectors, long-context story recall, tool-call quality, and server tests.

AGENT.md

Internal developer notes: goals, quality rules, safety constraints, and code layout. Explains why the project is structured the way it is.

gguf-tools/README.md

Offline GGUF generation, imatrix collection, quantization tooling, and quality checks. For building custom GGUFs.

speed-bench/README.md

Benchmark methodology, CSV files, and SVG graph generation. Explains how ds4-bench measures incremental throughput at context frontiers.

dir-steering/README.md

Directional steering data, vector generation, and usage — how to bias model outputs by injecting steering vectors during generation.

tests/test-vectors/README.md

Official continuation vectors used for regression checks. Critical for understanding the correctness validation pipeline.

Hugging Face: DeepSeek-V4-Flash

The official model card: architecture details, training data, benchmarks, and the DSML encoding specification used for tool calls.

huggingface.co/deepseek-ai/DeepSeek-V4-Flash

llama.cpp / GGML

DS4's spiritual parent. Understanding GGML's approach to tensor scheduling, quantization, and Metal/CUDA kernels provides context for DS4's design decisions.

github.com/ggml-org/llama.cpp

How to Make Sense of ds4

1. Understand the "Why"

DS4 exists because DeepSeek V4 Flash is special: 13B active parameters from 284B total, compressed KV cache, 1M context, remarkably short thinking traces, and excellent 2-bit quantization behavior. A generic GGUF runner can't optimize for all these properties — DS4 is deliberately narrow.

2. Trace the Architecture

Start with ds4.h (the public API), then ds4.c (model loading + sessions), then ds4_server.c (API orchestration), then ds4_metal.m (GPU scheduling). The code is organized around this boundary — CLI and server code don't know tensor internals.

3. Follow the Commit Timeline

The commit history in this page tells a story: initial release → tool streaming → KV cache replay → CUDA support → Responses API → eval harness → correctness fixes. Each phase added a critical capability. Understanding the order reveals why features were built.

4. Run the Tests

make test runs the full regression suite. ./ds4_test --logprob-vectors compares against official continuations. ./ds4_test --long-context checks story recall at 100k+ tokens. Tests are the ground truth for correctness.

5. Read the Sub-READMEs

Each subdirectory has its own README: gguf-tools/ for quantization, speed-bench/ for benchmarking, dir-steering/ for steering vectors, tests/test-vectors/ for regression data. The main README links to them all.

6. Understand the Agent Integration

DS4 speaks three API protocols. The key innovation is exact DSML tool replay — the bridge between the model's native DSML tool format and the agent's JSON tool-call objects. This is what makes multi-turn agent sessions efficient.