{"id":49774440,"url":"https://github.com/antirez/ds4","last_synced_at":"2026-05-13T16:00:57.198Z","repository":{"id":356369256,"uuid":"1231148626","full_name":"antirez/ds4","owner":"antirez","description":"DeepSeek 4 Flash local inference engine for Metal","archived":false,"fork":false,"pushed_at":"2026-05-11T11:12:55.000Z","size":1613,"stargazers_count":7106,"open_issues_count":33,"forks_count":514,"subscribers_count":58,"default_branch":"main","last_synced_at":"2026-05-11T14:41:08.416Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"C","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/antirez.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2026-05-06T17:17:05.000Z","updated_at":"2026-05-11T14:39:54.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/antirez/ds4","commit_stats":null,"previous_names":["antirez/ds4"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/antirez/ds4","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antirez%2Fds4","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antirez%2Fds4/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antirez%2Fds4/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antirez%2Fds4/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/antirez","download_url":"https://codeload.github.com/antirez/ds4/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/antirez%2Fds4/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32914533,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-05-11T17:09:15.040Z","status":"ssl_error","status_checked_at":"2026-05-11T17:08:45.420Z","response_time":120,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-05-11T14:26:33.255Z","updated_at":"2026-05-13T16:00:57.173Z","avatar_url":"https://github.com/antirez.png","language":"C","funding_links":[],"categories":["C","AI开源项目"],"sub_categories":["AI Agent"],"readme":"# DwarfStar 4\n\nDrawfStar 4 is a small native inference engine for DeepSeek V4 Flash. It is\nintentionally narrow: not a generic GGUF runner, not a wrapper around another\nruntime, and not a framework. The main path is a DeepSeek V4 Flash-specific\nMetal and CUDA graph executor with DS4-specific loading, prompt rendering,\nKV state, and server API glue.\n\nThis project would not exist without **llama.cpp and GGML**, make sure to read\nthe acknowledgements section, a big thank you to Georgi Gerganov and all the\nother contributors.\n\nNow, back at this project. Why we believe DeepSeek v4 Flash to be a pretty special\nmodel deserving a stand alone engine? Because after comparing it with powerful smaller\ndense models, we can report that:\n\n1. DeepSeek v4 Flash is faster because of less active parameters.\n2. In thinking mode, if you avoid *max thinking*, it produces a thinking section that is a lot shorter than other models, even 1/5 of other models in many cases, and crucially, the thinking section length is **proportional to the problem complexity**. This makes DeepSeek v4 Flash usable with thinking enabled when other models are practically impossible to use in the same conditions.\n3. The model features a context window of **1 million tokens**.\n4. Being so large, it knows more things if you go sampling at the edge of knowledge. For instance asking about Italian show or political questions soon uncovers that 284B parameters are a lot more than 27B or 35B parameters.\n5. It writes much better English and Italian. It *feels* a quasi-frontier model.\n6. The KV cache is incredibly compressed, allowing long context inference on local computers and **on disk KV cache persistence**.\n7. It works well with 2-bit quantization, if quantized in a special way (read later). This allows to run it in MacBooks with 128GB of RAM.\n8. We expect DeepSeek to release **updated versions of v4 Flash** in the future, even better than the current one.\n\nThat said, a few important things about this project:\n\n* The local inference landscape contains many excellent projects, but new models are released continuously, and the attention immediately gets captured by the next model to implement. This project takes a deliberately narrow bet: one model at a time, official-vector validation (logits obtained with the official implementation), long-context tests, and enough agent integration to know if it really works. The exact model may change as the landscape evolves, but the constraint remains: local inference credible on high end personal machines or Mac Studios, starting from 128GB of memory.\n* This software is developed with **strong assistance from GPT 5.5** and with humans leading the ideas, testing, and debugging. We say this openly because it shaped how the project was built. If you are not happy with AI-developed code, this software is not for you. The acknowledgement below is equally important: this would not exist without `llama.cpp` and GGML, largely written by hand.\n* This implementation is based on the idea that compressed KV caches like the one of DeepSeek v4 and the fast SSD disks of modern MacBooks should change our idea that KV cache belongs to RAM. **The KV cache is actually a first-class disk citizen**.\n* Our vision is that local inference should be a set of three things working well together, out of the box: A) inference engine with HTTP API + B) GGUF specially crafted to run well under a given engine and given assumptions + C) testing and validation with coding agents implementations. This inference engine only runs with the GGUF files provided. It gets tested against officially obtained logits at different context sizes. This project exists because we wanted to make one local model feel finished end to end, not just runnable. However this is just alpha quality code, so probably we are not still there.\n* The optimized graph path targets **Metal on macOS** and **CUDA on Linux**. The CPU path is only for correctness checks and model/tokenizer diagnostics. For CPU-only Linux builds, use `make cpu`; it builds the normal `./ds4` and `./ds4-server` binaries without CUDA or Metal. On macOS, **warning: current macOS versions have a bug in the virtual memory implementation that will crash the kernel** if you try to run the CPU code. Remember? Software sucks. It was not possible to fix the CPU inference to avoid crashing, since each time you have to restart the computer, which is not funny. Help us, if you have the guts.\n\n## Acknowledgements to llama.cpp and GGML\n\n`ds4.c` does not link against GGML, but it **exists thanks to the path opened by the\nllama.cpp project and the kernels, quantization formats, GGUF ecosystem, and hard-won\nengineering knowledge developed there**.\nWe are thankful and indebted to [`llama.cpp`](https://github.com/ggml-org/llama.cpp)\nand its contributors. Their implementation, kernels, tests, and design choices were\nan essential reference while building this DeepSeek V4 Flash-specific inference path.\nSome source-level pieces are retained or adapted here under the MIT license: GGUF\nquant layouts and tables, CPU quant/dot logic, and certain kernels. For this\nreason, and because we are genuinely grateful, we keep the GGML authors copyright\nnotice in our `LICENSE` file.\n\n## Status\n\nThe code and GGUF files are to be considered of **alpha quality** because\ninference and model serving is a complicated matter and all this exists\nonly for a few days. It will take months to reach a more stable form.\nHowever, we try to keep the project in a usable state, and we are making\nprogresses. If you have issues, make sure to use `--trace` to log the\nsessions, and open issues including the full trace.\n\n## Model Weights\n\nThis implementation only works with the DeepSeek V4 Flash GGUFs published for\nthis project. It is not a general GGUF loader, and arbitrary DeepSeek/GGUF files\nwill not have the tensor layout, quantization mix, metadata, or optional MTP\nstate expected by the engine. The 2 bit quantizations provided here are not\na joke: they behave well, work under coding agents, call tools in a reliable way.\nThe 2 bit quants use a very asymmetrical quantization: only the routed MoE\nexperts are quantized, up/gate at `IQ2_XXS`, down at `Q2_K`. They are the\nmajority of all the model space: the other components (shared experts,\nprojections, routing) are left untouched to guarantee quality.\n\nDownload one main model:\n\n```sh\n./download_model.sh q2   # 128 GB RAM machines\n./download_model.sh q4   # \u003e= 256 GB RAM machines\n```\n\nThe script downloads from `https://huggingface.co/antirez/deepseek-v4-gguf`,\nstores files under `./gguf/`, resumes partial downloads with `curl -C -`, and\nupdates `./ds4flash.gguf` to point at the selected q2/q4 model. Authentication\nis optional for public downloads, but `--token TOKEN`, `HF_TOKEN`, or the local\nHugging Face token cache are used when present.\n\n`./download_model.sh mtp` fetches the optional speculative decoding support\nGGUF. It can be used with both q2 and q4, but must be enabled explicitly with\n`--mtp`. The current MTP/speculative decoding path is still experimental: it is\ncorrectness-gated and currently provides at most a slight speedup, not a\nmeaningful generation-speed win.\n\nThen build:\n\n```sh\nmake\n```\n\n`./ds4flash.gguf` is the default model path used by both binaries. Pass `-m` to\nselect another supported GGUF from `./gguf/`. Run `./ds4 --help` and\n`./ds4-server --help` for the full flag list.\n\n## Speed\n\nThese are single-run Metal CLI numbers with `--ctx 32768`, `--nothink`, greedy\ndecoding, and `-n 256`. The short prompt is a normal small Italian story\nprompt. The long prompts exercise chunked prefill plus long-context decode.\nQ4 requires the larger-memory machine class, so M3 Max Q4 numbers are `N/A`.\n\n| Machine | Quant | Prompt | Prefill | Generation |\n| --- | ---: | ---: | ---: | ---: |\n| MacBook Pro M3 Max, 128 GB | q2 | short | 58.52 t/s | 26.68 t/s |\n| MacBook Pro M3 Max, 128 GB | q2 | 11709 tokens | 250.11 t/s | 21.47 t/s |\n| MacBook Pro M3 Max, 128 GB | q4 | short | N/A | N/A |\n| MacBook Pro M3 Max, 128 GB | q4 | long | N/A | N/A |\n| Mac Studio M3 Ultra, 512 GB | q2 | short | 84.43 t/s | 36.86 t/s |\n| Mac Studio M3 Ultra, 512 GB | q2 | 11709 tokens | 468.03 t/s | 27.39 t/s |\n| Mac Studio M3 Ultra, 512 GB | q4 | short | 78.95 t/s | 35.50 t/s |\n| Mac Studio M3 Ultra, 512 GB | q4 | 12018 tokens | 448.82 t/s | 26.62 t/s |\n| DGX Spark GB10, 128 GB | q2 | 7047 tokens | 343.81 t/s | 13.75 t/s |\n\n![M3 Max t/s](bench/m3_max_ts.svg)\n\n## Benchmarking\n\n`ds4-bench` measures instantaneous prefill and generation throughput at context\nfrontiers instead of reporting one whole-run average. It loads the model once,\nwalks a fixed token sequence to frontiers such as 2048, 4096, 6144, and uses\nincremental prefill so each row measures only the newly-added token interval.\nAfter each frontier it saves the live KV state to memory, generates a fixed\ngreedy non-EOS probe, restores the memory snapshot, and continues prefill.\n\n```sh\n./ds4-bench \\\n  -m ds4flash.gguf \\\n  --prompt-file bench/promessi_sposi.txt \\\n  --ctx-start 2048 \\\n  --ctx-max 65536 \\\n  --step-incr 2048 \\\n  --gen-tokens 128\n```\n\nThe example file is a cleaned public-domain Project Gutenberg text of\nAlessandro Manzoni's *I Promessi Sposi* (ebook #45334), with the Gutenberg\nheader and footer removed: \u003chttps://www.gutenberg.org/ebooks/45334\u003e.\n\nUse `--step-incr N` for different linear spacing, or `--step-mul F` for\nexponential sweeps. Output is CSV with one row per frontier: latest prefill\ninterval tokens/sec, generation tokens/sec at that frontier, and\n`kvcache_bytes`.\n\n## CLI\n\nOne-shot prompt:\n\n```sh\n./ds4 -p \"Explain Redis streams in one paragraph.\"\n```\n\nNo `-p` starts the interactive prompt:\n\n```sh\n./ds4\nds4\u003e\n```\n\nThe interactive CLI is a real multi-turn DS4 chat. It keeps the rendered chat\ntranscript and the live graph KV checkpoint, so each turn extends the previous\nconversation. Useful commands are `/help`, `/think`, `/think-max`, `/nothink`,\n`/ctx N`, `/read FILE`, and `/quit`. Ctrl+C interrupts the current generation\nand returns to `ds4\u003e`.\n\nThe CLI defaults to thinking mode. Use `/nothink` or `--nothink` for direct\nanswers. `--mtp MTP.gguf --mtp-draft 2` enables the optional MTP speculative\npath; it is useful only for greedy decoding, currently uses a confidence gate\n(`--mtp-margin`) to avoid slow partial accepts, and should be treated as an\nexperimental slight-speedup path.\n\n## Server\n\nStart a local OpenAI/Anthropic-compatible server:\n\n```sh\n./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192\n```\n\nThe server keeps one mutable backend/KV checkpoint in memory,\nso stateless clients that resend a longer version of the same prompt can reuse\nthe shared prefix instead of pre-filling from token zero.\n\nRequest parsing and sockets run in client threads, but inference itself is\nserialized through one graph worker. The current server does not batch multiple\nindependent requests together; concurrent requests wait their turn on the single\nlive graph/session.\n\nSupported endpoints:\n\n- `GET /v1/models`\n- `GET /v1/models/deepseek-v4-flash`\n- `POST /v1/chat/completions`\n- `POST /v1/completions`\n- `POST /v1/messages`\n\n`/v1/chat/completions` accepts the usual OpenAI-style `messages`,\n`max_tokens`/`max_completion_tokens`, `temperature`, `top_p`, `top_k`, `min_p`,\n`seed`, `stream`, `stream_options.include_usage`, `tools`, and `tool_choice`.\nTool schemas are rendered into DeepSeek's DSML tool format, and generated DSML\ntool calls are mapped back to OpenAI tool calls.\n\n`/v1/messages` is the Anthropic-compatible endpoint used by Claude Code style\nclients. It accepts `system`, `messages`, `tools`, `tool_choice`, `max_tokens`,\n`temperature`, `top_p`, `top_k`, `stream`, `stop_sequences`, and thinking\ncontrols. Tool uses are returned as Anthropic `tool_use` blocks.\n\nBoth APIs support SSE streaming. In thinking mode, reasoning is streamed in the\nnative API shape instead of being mixed into final text. OpenAI chat streaming\nalso streams tool calls as soon as the DSML invocation is recognized: the tool\nheader is sent first, then parameter bytes are forwarded as\n`tool_calls[].function.arguments` deltas while generation continues. The\nAnthropic endpoint streams thinking and text live, then emits structured\n`tool_use` blocks when the generated tool block is complete.\n\n### Tool call handling and canonicalization\n\nDeepSeek V4 Flash emits tool calls as [DSML text](https://huggingface.co/deepseek-ai/DeepSeek-V4-Pro/blob/main/encoding/README.md). Agent clients do not send that\nsame text back on the next request: they send normalized OpenAI/Anthropic JSON\ntool-call objects. **If the server re-rendered those objects slightly\ndifferently, the rendered byte prefix would no longer match the live KV\ncheckpoint** and the next turn would have to be rebuilt.\n\nThe first line of defense is exact replay. Every tool call gets an unguessable\nAPI tool ID, and the server remembers `tool id -\u003e exact sampled DSML block` in\na bounded in-memory map backed by radix trees. When the client later sends that\ntool ID back, the prompt renderer uses the exact DSML bytes the model sampled,\nnot a freshly formatted approximation. This map can also be saved inside KV\ncache files, so exact replay survives server restarts for cached histories.\n\n**Canonicalization is only the backup path**. If the exact DSML block is missing,\nor exact replay is disabled with `--disable-exact-dsml-tool-replay`, the server\nrenders a deterministic DSML form from the JSON tool object. After a tool-call\nturn, it compares the live sampled token stream with the prompt that the next\nclient request will render. If needed, it rewrites the live checkpoint, or\nfalls back to an older disk KV snapshot and replays only the suffix. This keeps\nthe model continuation aligned with the stateless API transcript.\n\nDuring generation, the server also treats DSML syntax differently from payload.\nWhen the model is emitting stable protocol structure such as DSML tags,\nparameter headers, JSON punctuation, or closing markers, sampling is forced to\n`temperature=0` so the tool call stays parseable. This greedy mode does **not**\napply to argument payloads: `string=true` parameter bodies and JSON string\nvalues, including file contents and edit text, use the request's normal sampling\nsettings. That separation is important: deterministic decoding is helpful for\nsyntax, but can create repeated text when applied to long code or file bodies.\n\nMinimal OpenAI example:\n\n```sh\ncurl http://127.0.0.1:8000/v1/chat/completions \\\n  -H 'Content-Type: application/json' \\\n  -d '{\n    \"model\":\"deepseek-v4-flash\",\n    \"messages\":[{\"role\":\"user\",\"content\":\"List three Redis design principles.\"}],\n    \"stream\":true\n  }'\n```\n\n### Agent Client Usage\n\n`ds4-server` can be used by local coding agents that speak OpenAI-compatible\nchat completions. Start the server first, and set the client context limit no\nhigher than the `--ctx` value you started the server with:\n\n```sh\n./ds4-server --ctx 100000 --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192\n```\n\nYou can use larger context and larger cache if you wish. Full context of\n1M tokens is going to use more or less 26GB of memory (compressed indexer\nalone will be like 22GB), so configure a context which makes sense in\nyour system. With 128GB of RAM you would run the 2-bit quants, which are\nalready 81GB, 26GB are going to be likely too much, so a context window\nof 100~300k tokens is wiser.\n\nThe `384000` output limit below avoids token caps since the model is able\nto generate very long replies otherwise (up to 384k tokens). The server\nstill stops when the configured context window is full.\n\nFor **opencode**, add a provider and agent entry to\n`~/.config/opencode/opencode.json`:\n\n```json\n{\n  \"$schema\": \"https://opencode.ai/config.json\",\n  \"provider\": {\n    \"ds4\": {\n      \"name\": \"ds4.c (local)\",\n      \"npm\": \"@ai-sdk/openai-compatible\",\n      \"options\": {\n        \"baseURL\": \"http://127.0.0.1:8000/v1\",\n        \"apiKey\": \"dsv4-local\"\n      },\n      \"models\": {\n        \"deepseek-v4-flash\": {\n          \"name\": \"DeepSeek V4 Flash (ds4.c local)\",\n          \"limit\": {\n            \"context\": 100000,\n            \"output\": 384000\n          }\n        }\n      }\n    }\n  },\n  \"agent\": {\n    \"ds4\": {\n      \"description\": \"DeepSeek V4 Flash served by local ds4-server\",\n      \"model\": \"ds4/deepseek-v4-flash\",\n      \"temperature\": 0\n    }\n  }\n}\n```\n\nFor **Pi**, add a provider to `~/.pi/agent/models.json`:\n\n```json\n{\n  \"providers\": {\n    \"ds4\": {\n      \"name\": \"ds4.c local\",\n      \"baseUrl\": \"http://127.0.0.1:8000/v1\",\n      \"api\": \"openai-completions\",\n      \"apiKey\": \"dsv4-local\",\n      \"compat\": {\n        \"supportsStore\": false,\n        \"supportsDeveloperRole\": false,\n        \"supportsReasoningEffort\": true,\n        \"supportsUsageInStreaming\": true,\n        \"maxTokensField\": \"max_tokens\",\n        \"supportsStrictMode\": false,\n        \"thinkingFormat\": \"deepseek\",\n        \"requiresReasoningContentOnAssistantMessages\": true\n      },\n      \"models\": [\n        {\n          \"id\": \"deepseek-v4-flash\",\n          \"name\": \"DeepSeek V4 Flash (ds4.c local)\",\n          \"reasoning\": true,\n          \"thinkingLevelMap\": {\n            \"off\": null,\n            \"minimal\": \"low\",\n            \"low\": \"low\",\n            \"medium\": \"medium\",\n            \"high\": \"high\",\n            \"xhigh\": \"xhigh\"\n          },\n          \"input\": [\"text\"],\n          \"contextWindow\": 100000,\n          \"maxTokens\": 384000,\n          \"cost\": {\n            \"input\": 0,\n            \"output\": 0,\n            \"cacheRead\": 0,\n            \"cacheWrite\": 0\n          }\n        }\n      ]\n    }\n  }\n}\n```\n\nOptionally make it the default Pi model in `~/.pi/agent/settings.json`:\n\n```json\n{\n  \"defaultProvider\": \"ds4\",\n  \"defaultModel\": \"deepseek-v4-flash\"\n}\n```\n\nFor **Claude Code**, use the Anthropic-compatible endpoint. A wrapper like this\nmatches the local `~/bin/claude-ds4` setup:\n\n```sh\n#!/bin/sh\nunset ANTHROPIC_API_KEY\n\nexport ANTHROPIC_BASE_URL=\"${DS4_ANTHROPIC_BASE_URL:-http://127.0.0.1:8000}\"\nexport ANTHROPIC_AUTH_TOKEN=\"${DS4_API_KEY:-dsv4-local}\"\nexport ANTHROPIC_MODEL=\"deepseek-v4-flash\"\n\nexport ANTHROPIC_CUSTOM_MODEL_OPTION=\"deepseek-v4-flash\"\nexport ANTHROPIC_CUSTOM_MODEL_OPTION_NAME=\"DeepSeek V4 Flash local ds4\"\nexport ANTHROPIC_CUSTOM_MODEL_OPTION_DESCRIPTION=\"ds4.c local GGUF\"\n\nexport ANTHROPIC_DEFAULT_SONNET_MODEL=\"deepseek-v4-flash\"\nexport ANTHROPIC_DEFAULT_HAIKU_MODEL=\"deepseek-v4-flash\"\nexport ANTHROPIC_DEFAULT_OPUS_MODEL=\"deepseek-v4-flash\"\nexport CLAUDE_CODE_SUBAGENT_MODEL=\"deepseek-v4-flash\"\n\nexport CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC=1\nexport CLAUDE_CODE_DISABLE_NONSTREAMING_FALLBACK=1\nexport CLAUDE_STREAM_IDLE_TIMEOUT_MS=600000\n\nexec \"$HOME/.local/bin/claude\" \"$@\"\n```\n\nClaude Code may send a large initial prompt, often around 25k tokens, before it\nstarts doing useful work. Keep `--kv-disk-dir` enabled: after the first expensive\nprefill, the disk KV cache lets later continuations or restarted sessions reuse\nthe saved prefix instead of processing the whole prompt again.\n\n## Thinking Modes\n\nDeepSeek V4 Flash has distinct non-thinking, thinking, and Think Max modes.\nThe server defaults to thinking mode. `reasoning_effort=max` requests Think\nMax, but it is only applied when the context size is large enough for the model\ncard recommendation; smaller contexts fall back to normal thinking. OpenAI\n`reasoning_effort=xhigh` still maps to normal thinking, not Think Max.\n\nFor direct replies, use `thinking: {\"type\":\"disabled\"}`, `think:false`, or a\nnon-thinking model alias such as `deepseek-chat`.\n\n## Disk KV Cache\n\nChat/completion APIs are stateless: agent clients usually resend the whole\nconversation every request. `ds4-server` first tries the cheap exact token-prefix\ncheck, then falls back to comparing rendered prompt bytes with decoded\ncheckpoint bytes. The live in-memory checkpoint covers the current session; the\ndisk KV cache makes useful prefixes survive session switches and server\nrestarts.\n\nFor RAM reasons there is currently only one live KV cache in memory. When a new\nunrelated session replaces it, the old checkpoint can only be resumed without\nre-processing if it was written to the disk KV cache. In other words, memory\ncache handles the active session; disk cache is the resume mechanism for\ndifferent sessions.\n\nEnable it with:\n\n```sh\n./ds4-server --kv-disk-dir /tmp/ds4-kv --kv-disk-space-mb 8192\n```\n\nThe cache key is the SHA1 of the rendered byte prefix, and files are named\n`\u003csha1\u003e.kv`. The DS4 payload still stores the exact token IDs and graph state\nfor that prefix. This matters for continued chats: the model may have generated\none token whose decoded text is later sent back by a client as two canonical\nprompt tokens. A rendered byte-prefix hit can still reuse the checkpoint and\ntokenize only the new suffix.\nThe file is intentionally written with ordinary `read`/`write` I/O, not\n`mmap`, so restoring cache entries does not add more VM mappings to a process\nthat already maps the model.\n\nTool calls also keep a bounded exact-DSML replay map keyed by unguessable tool\nIDs, so client JSON history can be rendered back to the exact sampled text. The\nRAM map keeps up to 100000 IDs by default; tune it with `--tool-memory-max-ids`.\nUse `--disable-exact-dsml-tool-replay` to disable this and fall back to\ncanonical JSON-to-DSML rendering.\n\nOn disk, a cache file is:\n\n```text\nKVC fixed header, 48 bytes\nu32 rendered_text_bytes\nrendered_text_bytes of UTF-8-ish token text\nDS4 session payload, payload_bytes from the KVC header\noptional tool-id map section\n```\n\nThe fixed header is little-endian:\n\n```text\n0   u8[3]  magic = \"KVC\"\n3   u8     version = 1\n4   u8     routed expert quant bits, currently 2 or 4\n5   u8     save reason: 0 unknown, 1 cold, 2 continued, 3 evict, 4 shutdown\n6   u8     extension flags, bit 0 = appended tool-id map\n7   u8     reserved\n8   u32    cached token count\n12  u32    hit count\n16  u32    context size the snapshot was written for\n20  u8[4]  reserved\n24  u64    creation Unix time\n32  u64    last-used Unix time\n40  u64    DS4 session payload byte count\n```\n\nThe rendered text is the tokenizer-decoded text for the cached token prefix.\nIt is both the human-inspectable prefix and the lookup identity: its SHA1 is\nthe filename, and a file is reusable only when those bytes are a prefix of the\nincoming rendered prompt. After load, the exact checkpoint tokens from the DS4\npayload remain authoritative, and only the incoming text suffix after the cached\nbytes is tokenized.\n\nThe optional tool-id map is present only when header extension bit 0 is set.\nAppended sections use fixed bit order, so future extension bits can add fields\nwithout ambiguity. The map stores unguessable API tool call IDs back to the\nexact DSML block the model sampled. Only mappings whose DSML block is present\nin the rendered cached text are stored. This lets restarted servers render\nlater client history byte-for-byte like the original model output, even if the\nclient reorders JSON arguments.\n\nThe current tool-id map section is:\n\n```text\n0   u8[3]  magic = \"KTM\"\n3   u8     version = 1\n4   u32    entry count\n\nFor each entry:\n0   u32    tool id byte length\n4   u32    sampled DSML byte length\n8   bytes  tool id\n... bytes  exact sampled DSML block\n```\n\nThe section is auxiliary replay memory, not model state. A cache hit restores\nthe session payload first, then loads the map if present. Before rendering a\nrequest, the server can also scan cache files for the tool IDs present in the\nclient history and load just those mappings, so an exact DSML replay can survive\nserver restarts even when the matching KV snapshot is not the one ultimately\nused for the rendered-prefix hit.\n\nThe DS4 session payload starts with thirteen little-endian `u32` fields:\n\n```text\n0   magic = \"DSV4\"\n1   payload version = 1\n2   saved context size\n3   prefill chunk size\n4   raw KV ring capacity\n5   raw sliding-window length\n6   compressed KV capacity\n7   checkpoint token count\n8   layer count\n9   raw/head KV dimension\n10  indexer head dimension\n11  vocabulary size\n12  live raw rows serialized below\n```\n\nThen it stores:\n\n- `u32[token_count]` checkpoint token IDs.\n- `float32[vocab_size]` logits for the next token after that checkpoint.\n- `u32[layer_count]` compressed attention row counts.\n- `u32[layer_count]` ratio-4 indexer row counts.\n- For every layer: the live raw sliding-window KV rows, written in logical\n  position order rather than physical ring order.\n- For compressed layers: live compressed KV rows and compressor frontier\n  tensors.\n- For ratio-4 compressed layers: live indexer compressed rows and indexer\n  frontier tensors.\n\nThe logits are raw IEEE-754 `float32` values from the host `ds4_session`\nbuffer. They are saved immediately after the checkpoint tokens so a loaded\nsnapshot can sample or continue from the exact next-token distribution without\nrunning one extra decode step. MTP draft logits/state are not persisted; after\nloading a disk checkpoint the draft state is invalidated and rebuilt by normal\ngeneration.\n\nThe tensor payload is DS4-specific KV/session state, not a generic inference\ngraph dump. It is expected to be portable only across compatible `ds4.c`\nbuilds for this model layout.\n\nThe cache stores checkpoints at four moments:\n\n- `cold`: after a long first prompt reaches a stable prefix, before generation.\n- `continued`: when prefill or generation reaches the next absolute aligned frontier.\n- `evict`: before an unrelated request replaces the live in-memory session.\n- `shutdown`: when the server exits cleanly.\n\nCold saves intentionally trim a small token suffix and align down to a prefill\nchunk boundary. This avoids common BPE boundary retokenization misses when a\nfuture request appends text to the same prompt. The defaults are conservative:\nstore prefixes of at least 512 tokens, cold-save prompts up to 30000 tokens,\ntrim 32 tail tokens, and align to 2048-token chunks. The important knobs are:\n\nContinued saves use the same alignment and are written only when the live graph\nnaturally reaches an absolute frontier. With the defaults this means roughly\nevery 10k tokens, independent of where the first cold checkpoint landed, so long\ngenerations leave restart points behind without persisting the fragile final few\ntokens.\n\n- `--kv-cache-min-tokens`\n- `--kv-cache-cold-max-tokens`\n- `--kv-cache-continued-interval-tokens`\n- `--kv-cache-boundary-trim-tokens`\n- `--kv-cache-boundary-align-tokens`\n- `--tool-memory-max-ids`\n- `--disable-exact-dsml-tool-replay`\n\nBy default, checkpoints may be reused across the 2-bit and 4-bit routed-expert\nvariants if the rendered prefix matches. Use `--kv-cache-reject-different-quant`\nwhen you want strict same-quant reuse only.\n\nThe cache directory is disposable. If behavior looks suspicious, stop the\nserver and remove it. You can investigate what is cached with hexdump as\nthe kv cache files include the verbatim prompt cached.\n\n## Backends\n\nThe default graph backend is Metal on macOS and CUDA on Linux CUDA builds:\n\n```sh\n./ds4 -p \"Hello\" --metal\n./ds4 -p \"Hello\" --cuda\n```\n\nThere is also a CPU reference/debug path:\n\n```sh\n./ds4 -p \"Hello\" --cpu\nmake cpu\n./ds4\n./ds4 -p \"Hello\"\n```\n\nDo not treat the CPU path as the production target. The CLI and `ds4-server`\nsupport the CPU backend for reference/debug use and share the same KV session\nand snapshot format as Metal and CUDA, but normal inference should use Metal or\nCUDA.\n\n## Steering\n\nThis project supports steering with single-vector activation directions; see the\n`dir-steering` directory for more information. This follows the core idea of the\n[Refusal in Language Models Is Mediated by a Single Direction](https://arxiv.org/abs/2406.11717)\npaper. You can use it to make the model more or less verbose, less likely to\nanswer programming questions if it is a chatbot for your car rental web site,\nand so forth, much faster than fine-tuning.\nThis is also useful for cybersecurity researchers who want to reduce a model's\nwillingness to provide dual-use or offensive security guidance.\n\n## Test Vectors\n\n`tests/test-vectors` contains short and long-context continuation vectors\ncaptured from the official DeepSeek V4 Flash API. The requests use\n`deepseek-v4-flash`, greedy decoding, thinking disabled, and the maximum\n`top_logprobs` slice exposed by the API. Local vectors are generated with\n`./ds4 --dump-logprobs` and compared by token bytes, so tokenizer/template or\nattention regressions show up before they become long generation failures.\n\nAll project tests are driven by the C runner:\n\n```sh\nmake test                  # ./ds4_test --all\n./ds4_test --logprob-vectors\n./ds4_test --server\n```\n\n## Debugging Notes\n\nWhen a generation looks wrong, three small tools are usually enough to get a\nfirst answer:\n\n```sh\n./ds4 --dump-tokens -p \"...\"\n./ds4 --dump-logprobs /tmp/out.json --logprobs-top-k 20 --temp 0 -p \"...\"\n./ds4-server --trace /tmp/ds4-trace.txt ...\n```\n\n- `--dump-tokens` tokenizes the `-p` or `--prompt-file` string exactly as\n  written, recognizes DS4 protocol specials, and then exits before inference\n  starts. For example, the DSML tool close marker starts as two tokens: `\u003c/`\n  and `｜DSML｜`.\n- `--dump-logprobs` stores a greedy continuation with the top local\n  alternatives at each step, which helps separate sampling choices from\n  logit/model issues.\n- `ds4-server --trace` writes the rendered prompts, cache decisions, generated\n  text, and tool-parser events for a whole agent session.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fantirez%2Fds4","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fantirez%2Fds4","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fantirez%2Fds4/lists"}