Instructions to use smalinin/DeepSeek-V4.1-Flash-GGUF with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- llama.cpp
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with llama.cpp:
Install (macOS, Linux)
curl -LsSf https://llama.app/install.sh | sh # Start a local OpenAI-compatible server with a web UI: llama serve -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS # Run inference directly in the terminal: llama cli -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS # Run inference directly in the terminal: llama cli -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Use pre-built binary
# Download pre-built binary from: # https://github.com/ggerganov/llama.cpp/releases # Start a local OpenAI-compatible server with a web UI: ./llama-server -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS # Run inference directly in the terminal: ./llama-cli -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Build from source code
git clone https://github.com/ggerganov/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-server llama-cli # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama-server -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS # Run inference directly in the terminal: ./build/bin/llama-cli -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Use Docker
docker model run hf.co/smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
- LM Studio
- Jan
- vLLM
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "smalinin/DeepSeek-V4.1-Flash-GGUF" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "smalinin/DeepSeek-V4.1-Flash-GGUF", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
- Ollama
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with Ollama:
ollama run hf.co/smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
- Unsloth Desktop
- Pi
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Configure the model in Pi
# Install Pi: npm install -g @earendil-works/pi-coding-agent # Add to ~/.pi/agent/models.json: { "providers": { "llama-cpp": { "baseUrl": "http://localhost:8080/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with Docker Model Runner:
docker model run hf.co/smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
- Lemonade
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Run and chat with the model
lemonade run user.DeepSeek-V4.1-Flash-GGUF-IQ3_XS
List all available models
lemonade list
- Hermes Agent
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Configure Hermes
# Install Hermes: curl -fsSL https://hermes-agent.nousresearch.com/install.sh | bash hermes setup # Point Hermes at the local server: hermes config set model.provider custom hermes config set model.base_url http://127.0.0.1:8080/v1 hermes config set model.default smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use smalinin/DeepSeek-V4.1-Flash-GGUF with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS
Configure OpenClaw
# Install OpenClaw: npm install -g openclaw@latest # Register the local server and set it as the default model: openclaw onboard --non-interactive --mode local \ --auth-choice custom-api-key \ --custom-base-url http://127.0.0.1:8080/v1 \ --custom-model-id "smalinin/DeepSeek-V4.1-Flash-GGUF:IQ3_XS" \ --custom-provider-id llama-cpp \ --custom-compatibility openai \ --custom-text-input \ --accept-risk \ --skip-health
Run OpenClaw
openclaw agent --local --agent main --message "Hello from Hugging Face"
Duplicate from vcruz305/DeepSeek-V4.1-Flash-GGUF
Browse filesCo-authored-by: Victor Cruz <vcruz305@users.noreply.huggingface.co>
- .gitattributes +75 -0
- .probe.md +1 -0
- DeepSeek-V4.1-Flash-Q1_0-00001-of-00003.gguf +3 -0
- DeepSeek-V4.1-Flash-Q1_0-00002-of-00003.gguf +3 -0
- DeepSeek-V4.1-Flash-Q1_0-00003-of-00003.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00001-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00002-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00003-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00004-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00005-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00006-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q2_K-00007-of-00007.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00001-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00002-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00003-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00004-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00005-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00006-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00007-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00008-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q3_K_M-00009-of-00009.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00001-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00002-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00003-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00004-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00005-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00006-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00007-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00008-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00009-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00010-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q4_K_M-00011-of-00011.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00001-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00002-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00003-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00004-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00005-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00006-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00007-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00008-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00009-of-00010.gguf +3 -0
- DeepSeek-V4.1-Flash-Q8_0-00010-of-00010.gguf +3 -0
- README.md +70 -0
- llama.cpp/patches/README.md +79 -0
- llama.cpp/patches/fix_gguf_engram_kv.py +290 -0
- llama.cpp/patches/patch_llamacpp_v41.py +701 -0
.gitattributes
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
*.7z filter=lfs diff=lfs merge=lfs -text
|
| 2 |
+
*.arrow filter=lfs diff=lfs merge=lfs -text
|
| 3 |
+
*.bin filter=lfs diff=lfs merge=lfs -text
|
| 4 |
+
*.bz2 filter=lfs diff=lfs merge=lfs -text
|
| 5 |
+
*.ckpt filter=lfs diff=lfs merge=lfs -text
|
| 6 |
+
*.ftz filter=lfs diff=lfs merge=lfs -text
|
| 7 |
+
*.gz filter=lfs diff=lfs merge=lfs -text
|
| 8 |
+
*.h5 filter=lfs diff=lfs merge=lfs -text
|
| 9 |
+
*.joblib filter=lfs diff=lfs merge=lfs -text
|
| 10 |
+
*.lfs.* filter=lfs diff=lfs merge=lfs -text
|
| 11 |
+
*.mlmodel filter=lfs diff=lfs merge=lfs -text
|
| 12 |
+
*.model filter=lfs diff=lfs merge=lfs -text
|
| 13 |
+
*.msgpack filter=lfs diff=lfs merge=lfs -text
|
| 14 |
+
*.npy filter=lfs diff=lfs merge=lfs -text
|
| 15 |
+
*.npz filter=lfs diff=lfs merge=lfs -text
|
| 16 |
+
*.onnx filter=lfs diff=lfs merge=lfs -text
|
| 17 |
+
*.ot filter=lfs diff=lfs merge=lfs -text
|
| 18 |
+
*.parquet filter=lfs diff=lfs merge=lfs -text
|
| 19 |
+
*.pb filter=lfs diff=lfs merge=lfs -text
|
| 20 |
+
*.pickle filter=lfs diff=lfs merge=lfs -text
|
| 21 |
+
*.pkl filter=lfs diff=lfs merge=lfs -text
|
| 22 |
+
*.pt filter=lfs diff=lfs merge=lfs -text
|
| 23 |
+
*.pth filter=lfs diff=lfs merge=lfs -text
|
| 24 |
+
*.rar filter=lfs diff=lfs merge=lfs -text
|
| 25 |
+
*.safetensors filter=lfs diff=lfs merge=lfs -text
|
| 26 |
+
saved_model/**/* filter=lfs diff=lfs merge=lfs -text
|
| 27 |
+
*.tar.* filter=lfs diff=lfs merge=lfs -text
|
| 28 |
+
*.tar filter=lfs diff=lfs merge=lfs -text
|
| 29 |
+
*.tflite filter=lfs diff=lfs merge=lfs -text
|
| 30 |
+
*.tgz filter=lfs diff=lfs merge=lfs -text
|
| 31 |
+
*.wasm filter=lfs diff=lfs merge=lfs -text
|
| 32 |
+
*.xz filter=lfs diff=lfs merge=lfs -text
|
| 33 |
+
*.zip filter=lfs diff=lfs merge=lfs -text
|
| 34 |
+
*.zst filter=lfs diff=lfs merge=lfs -text
|
| 35 |
+
*tfevents* filter=lfs diff=lfs merge=lfs -text
|
| 36 |
+
DeepSeek-V4.1-Flash-Q2_K-00001-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
DeepSeek-V4.1-Flash-Q2_K-00002-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
DeepSeek-V4.1-Flash-Q2_K-00003-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
DeepSeek-V4.1-Flash-Q2_K-00004-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
DeepSeek-V4.1-Flash-Q2_K-00005-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
DeepSeek-V4.1-Flash-Q2_K-00006-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
DeepSeek-V4.1-Flash-Q8_0-00001-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 43 |
+
DeepSeek-V4.1-Flash-Q8_0-00002-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 44 |
+
DeepSeek-V4.1-Flash-Q8_0-00003-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 45 |
+
DeepSeek-V4.1-Flash-Q8_0-00004-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 46 |
+
DeepSeek-V4.1-Flash-Q8_0-00005-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 47 |
+
DeepSeek-V4.1-Flash-Q8_0-00006-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 48 |
+
DeepSeek-V4.1-Flash-Q8_0-00007-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 49 |
+
DeepSeek-V4.1-Flash-Q8_0-00008-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 50 |
+
DeepSeek-V4.1-Flash-Q8_0-00009-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 51 |
+
DeepSeek-V4.1-Flash-Q8_0-00010-of-00010.gguf filter=lfs diff=lfs merge=lfs -text
|
| 52 |
+
DeepSeek-V4.1-Flash-Q2_K-00007-of-00007.gguf filter=lfs diff=lfs merge=lfs -text
|
| 53 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00001-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 54 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00002-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 55 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00003-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 56 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00004-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 57 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00005-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 58 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00006-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 59 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00007-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 60 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00008-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 61 |
+
DeepSeek-V4.1-Flash-Q3_K_M-00009-of-00009.gguf filter=lfs diff=lfs merge=lfs -text
|
| 62 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00001-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 63 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00002-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 64 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00003-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 65 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00004-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 66 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00005-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 67 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00006-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 68 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00007-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 69 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00008-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 70 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00009-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 71 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00010-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 72 |
+
DeepSeek-V4.1-Flash-Q4_K_M-00011-of-00011.gguf filter=lfs diff=lfs merge=lfs -text
|
| 73 |
+
DeepSeek-V4.1-Flash-Q1_0-00001-of-00003.gguf filter=lfs diff=lfs merge=lfs -text
|
| 74 |
+
DeepSeek-V4.1-Flash-Q1_0-00002-of-00003.gguf filter=lfs diff=lfs merge=lfs -text
|
| 75 |
+
DeepSeek-V4.1-Flash-Q1_0-00003-of-00003.gguf filter=lfs diff=lfs merge=lfs -text
|
.probe.md
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
DeepSeek-V4.1-Flash GGUF quantizations. Work in progress.
|
DeepSeek-V4.1-Flash-Q1_0-00001-of-00003.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1a6185fb832c3f523791c677bf126e2e3d7aea3ea2e261aecab6f5a6fdd172c2
|
| 3 |
+
size 41640881376
|
DeepSeek-V4.1-Flash-Q1_0-00002-of-00003.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bd6679ee04bc0d0378e995f608715c64f410df7ed8e68d23989b1c103d36bcee
|
| 3 |
+
size 44857126912
|
DeepSeek-V4.1-Flash-Q1_0-00003-of-00003.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7d507eb21bfe10d71777134afe6765e923609358166eb6049571a3553a865fbd
|
| 3 |
+
size 19363037984
|
DeepSeek-V4.1-Flash-Q2_K-00001-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0bcee934bd4e8350c54410681d9300b0321a300fcb1df1437a20703394d08ee0
|
| 3 |
+
size 43072989056
|
DeepSeek-V4.1-Flash-Q2_K-00002-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:124ffa15b6b7ec9630715ad18752a4c3f371749647837b8c9d5f7eb52c4f73c0
|
| 3 |
+
size 44805480352
|
DeepSeek-V4.1-Flash-Q2_K-00003-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4dd35b0b086cc0fb19d3a72afd8aed331317950e2257f37b9672702edc3f2453
|
| 3 |
+
size 14935107904
|
DeepSeek-V4.1-Flash-Q2_K-00004-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d24832f4c2f42340d5d4bf4d9b3277c861e0a0a9ccd25e94bda5581c5351f960
|
| 3 |
+
size 44217904672
|
DeepSeek-V4.1-Flash-Q2_K-00005-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:34714c3880bde310207e3d12fa488d8d676f338ff635157fded8ec73e133efad
|
| 3 |
+
size 44804598176
|
DeepSeek-V4.1-Flash-Q2_K-00006-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:08dc941d26687cb51f736a4f1c3a2c4843fb1d79573164c645106711081f5faf
|
| 3 |
+
size 44803713696
|
DeepSeek-V4.1-Flash-Q2_K-00007-of-00007.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:550bbdb94a69142abfa4b2f2db86ffe3dd6d4ca45eafbb6728f4fe40506fa6b9
|
| 3 |
+
size 27875485600
|
DeepSeek-V4.1-Flash-Q3_K_M-00001-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6499c20b172f30bf68dfbf4465e8067482bdc33f701c30e37cf422935e4d4bc3
|
| 3 |
+
size 7971784416
|
DeepSeek-V4.1-Flash-Q3_K_M-00002-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eb1bc512e478184086ffcf58882efdce4c188c1e461a4bb285a9dc2e3f2fa3f5
|
| 3 |
+
size 42308283648
|
DeepSeek-V4.1-Flash-Q3_K_M-00003-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:65e6fed865793f2719e9d47819f4901e88c4499d783b1a3bf10448ae2422ea98
|
| 3 |
+
size 44181213952
|
DeepSeek-V4.1-Flash-Q3_K_M-00004-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3ed43f59a734c97e4dbef6fc77c7047267742bffc76e415d9e5fb6719dda2447
|
| 3 |
+
size 41111992000
|
DeepSeek-V4.1-Flash-Q3_K_M-00005-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:9be50bb502735bebaee0fc6acc7e8dbc4e7e473f428bbb2f4c96210cedf00fbe
|
| 3 |
+
size 44864115552
|
DeepSeek-V4.1-Flash-Q3_K_M-00006-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:433b4362bb2fcb97c796935d01c53c3da0b9a3cbcc36e06d0314c6e69916bdbf
|
| 3 |
+
size 43066406752
|
DeepSeek-V4.1-Flash-Q3_K_M-00007-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:bc5f9a0bde117716b22ee10f5be7d735b438f40040d08fac22474a9d9883d712
|
| 3 |
+
size 43611224640
|
DeepSeek-V4.1-Flash-Q3_K_M-00008-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e6b08013c406e01d186487eaca04da53c24431346400904fae15723b8762ac44
|
| 3 |
+
size 43664455008
|
DeepSeek-V4.1-Flash-Q3_K_M-00009-of-00009.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c069f939d796f14cb89c0b519f27a17de435315802efd110a35971db7593135c
|
| 3 |
+
size 36491996320
|
DeepSeek-V4.1-Flash-Q4_K_M-00001-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:aa0ef0b26baacebda187bc7a675b60a61b9407097b39ff244a8d72273910beff
|
| 3 |
+
size 9903019232
|
DeepSeek-V4.1-Flash-Q4_K_M-00002-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0f7e076a531423b4c52294652ddb1b87859793781fabc6618a0d13d6f8540aaf
|
| 3 |
+
size 55296888384
|
DeepSeek-V4.1-Flash-Q4_K_M-00003-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:eaf7000aa1ee038f4a979708131f036f2f52cac5b1510c29e544ad89e16a8693
|
| 3 |
+
size 43477027712
|
DeepSeek-V4.1-Flash-Q4_K_M-00004-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:14d9641d478a2d7a8a79fd3043dc759a3a052ab0dcda6a17b7bf5e0b052c529c
|
| 3 |
+
size 43601417504
|
DeepSeek-V4.1-Flash-Q4_K_M-00005-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5c0e4d0e120fe5485052d479add7445e2f3d1f65e598accc8c758449458b41bf
|
| 3 |
+
size 21838521504
|
DeepSeek-V4.1-Flash-Q4_K_M-00006-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:56e2de3c9d3da27ee1c48be3d6d2b0293b70e842b34ef5a3b1fc3397a29e0cbc
|
| 3 |
+
size 55298402400
|
DeepSeek-V4.1-Flash-Q4_K_M-00007-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:656e0636bc9b97158889a04d36128373bcee38b83b42fdbf4ac95d3ce5e40cc6
|
| 3 |
+
size 43686966240
|
DeepSeek-V4.1-Flash-Q4_K_M-00008-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e3ec8118206d5ebdc877b68375021150143f31ac5c5c74c5854ed17a6454b8e3
|
| 3 |
+
size 44992770528
|
DeepSeek-V4.1-Flash-Q4_K_M-00009-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4f20e2cf9d3da6158f02f4c933274bd28966a91a531ef42d228f7b70e0ada62a
|
| 3 |
+
size 43668184320
|
DeepSeek-V4.1-Flash-Q4_K_M-00010-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4c3c9101d61dd4e5c8a3a05a30604299f3cffaf28c8d388e8fdedd51d92c3b4b
|
| 3 |
+
size 44773274272
|
DeepSeek-V4.1-Flash-Q4_K_M-00011-of-00011.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:1f7ed637779d529bd56fbcdfe7008bd28d546dc3d0fe3c5ce78bc51edfc0deca
|
| 3 |
+
size 38200982624
|
DeepSeek-V4.1-Flash-Q8_0-00001-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:167304a8d1123d8a9b7d53a82c01aab659eba51be6d58763f769eb294f62617e
|
| 3 |
+
size 43322444352
|
DeepSeek-V4.1-Flash-Q8_0-00002-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d9f95f3ec801d07bddb374b3943a7bdb484e48dd8b24c5eae9218b091e146f52
|
| 3 |
+
size 43316676000
|
DeepSeek-V4.1-Flash-Q8_0-00003-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c53687cc23e2e32ab3ad5dbd8052de07801e12a8b3ce278967dfa6c2eb2983b4
|
| 3 |
+
size 43316676032
|
DeepSeek-V4.1-Flash-Q8_0-00004-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ba84c194c41feb6f7fb65fb4a0a4e188ee2cb85516b86ba2818e16cec2017343
|
| 3 |
+
size 43316676032
|
DeepSeek-V4.1-Flash-Q8_0-00005-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:66fdac198238c64c7310de22e46a1f9a15284fbde65f6a020f6e94395155b8b5
|
| 3 |
+
size 43316676032
|
DeepSeek-V4.1-Flash-Q8_0-00006-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:19a2b0e85cce09a47c826d8a670f832792752fdb5a996445fee797e0ce0d100f
|
| 3 |
+
size 43316676032
|
DeepSeek-V4.1-Flash-Q8_0-00007-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f04e8d27188e9a9cb4f7999a7fc099c5f52e043e23dd1b333a2294f1c1a0af84
|
| 3 |
+
size 28877784064
|
DeepSeek-V4.1-Flash-Q8_0-00008-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:dc05657987ace747fabdf6c9c9b498fd46253329c78e7e795533b1885c292330
|
| 3 |
+
size 104449677888
|
DeepSeek-V4.1-Flash-Q8_0-00009-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f8fe6989ba5956981e1f896167b495b343ce184c24bfdff9eec981c8c541da9d
|
| 3 |
+
size 104452537696
|
DeepSeek-V4.1-Flash-Q8_0-00010-of-00010.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:f7f00c58e282623f08e43544dc31581f0e03a527bd05330054bb6bc2cfce384b
|
| 3 |
+
size 10268402880
|
README.md
ADDED
|
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: mit
|
| 3 |
+
base_model: deepseek-ai/DeepSeek-V4.1-Flash
|
| 4 |
+
base_model_relation: quantized
|
| 5 |
+
library_name: gguf
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
tags:
|
| 8 |
+
- gguf
|
| 9 |
+
- deepseek
|
| 10 |
+
- deepseek-v4.1
|
| 11 |
+
- llama.cpp
|
| 12 |
+
quantized_by: vcruz305
|
| 13 |
+
---
|
| 14 |
+
|
| 15 |
+
# DeepSeek-V4.1-Flash GGUF
|
| 16 |
+
|
| 17 |
+
llama.cpp GGUF of [deepseek-ai/DeepSeek-V4.1-Flash](https://huggingface.co/deepseek-ai/DeepSeek-V4.1-Flash).
|
| 18 |
+
|
| 19 |
+
This is **V4.1-Flash** (`DeepseekV41ForCausalLM`), a causal decoder with engram n-gram lookup
|
| 20 |
+
tables, hyper-connections and sparse attention. It is not V4-Flash-0731.
|
| 21 |
+
|
| 22 |
+
## Recipe
|
| 23 |
+
|
| 24 |
+
How to build the engine, serve it, and the gotchas, plus the current status:
|
| 25 |
+
[vcruz305/DeepSeek-V4.1-Flash-GGUF-DGX-Spark-recipe](https://github.com/vcruz305/DeepSeek-V4.1-Flash-GGUF-DGX-Spark-recipe)
|
| 26 |
+
|
| 27 |
+
## Status
|
| 28 |
+
|
| 29 |
+
**These files do not run on upstream llama.cpp yet.** Conversion works and is open as
|
| 30 |
+
[ggml-org/llama.cpp#28696](https://github.com/ggml-org/llama.cpp/pull/28696). The runtime is in
|
| 31 |
+
progress on the `runtime/deepseek41` branch of
|
| 32 |
+
[vcruz305/llama.cpp](https://github.com/vcruz305/llama.cpp): the loader, the engram tables and the
|
| 33 |
+
hyper-connections work and are verified against the reference implementation, and the sparse
|
| 34 |
+
attention is the remaining piece.
|
| 35 |
+
|
| 36 |
+
Weights land here as each rung finishes. Anything converted before 2026-09-10 carries
|
| 37 |
+
`general.architecture = deepseek4` and is being redone as `deepseek41`.
|
| 38 |
+
|
| 39 |
+
The architecture string is `deepseek41`, following llama.cpp's habit of dropping the `_v`
|
| 40 |
+
(`deepseek_v2` became `deepseek2`, `deepseek_v3.2` became `deepseek32`).
|
| 41 |
+
|
| 42 |
+
**2026-09-11 fix:** the 4 Engram KV keys (`head_count`, `key_length`, `max_ngram_size`,
|
| 43 |
+
`layer_ids`) were written with a hardcoded `deepseek4.engram.*` prefix instead of resolving
|
| 44 |
+
`{arch}.engram.*` like every other arch-scoped key in the file. `general.architecture` and all
|
| 45 |
+
38 other arch-scoped keys were already correct (`deepseek41.*`); only these 4 were wrong, which
|
| 46 |
+
would have made the `runtime/deepseek41` loader fail to find Engram config on an otherwise
|
| 47 |
+
loadable file. Fixed in place via a KV-only rewrite (tensor data untouched, verified
|
| 48 |
+
byte-identical by SHA-256) on all five quant rungs' first shard, where GGUF split files store
|
| 49 |
+
metadata. Confirmed live: all five now read `deepseek41.engram.*`.
|
| 50 |
+
|
| 51 |
+
## Files
|
| 52 |
+
|
| 53 |
+
Ladder in order: **Q2_K, Q3_K_M, Q4_K_M**. Measured tensor payload:
|
| 54 |
+
|
| 55 |
+
| File | Quant | Bytes | GiB |
|
| 56 |
+
| --- | --- | ---: | ---: |
|
| 57 |
+
| `DeepSeek-V4.1-Flash-Q2_K.gguf` | Q2_K | 264,514,761,248 | 246.3 |
|
| 58 |
+
| `DeepSeek-V4.1-Flash-Q3_K_M.gguf` | Q3_K_M | 347,270,954,112 | 323.4 |
|
| 59 |
+
| `DeepSeek-V4.1-Flash-Q4_K_M.gguf` | Q4_K_M | pending | |
|
| 60 |
+
|
| 61 |
+
Split into parts, since each exceeds the Hub's single file limit.
|
| 62 |
+
|
| 63 |
+
Q5_K_M is skipped unless asked for. The routed experts arrive as MXFP4 at 4.25 bpw, so higher rungs
|
| 64 |
+
move parts of the mixture *up* rather than down: Q3_K_M already lands at 0.684 of the Q8_0 staging
|
| 65 |
+
file, and Q5_K_M would be close enough to Q8_0 to be poor value.
|
| 66 |
+
|
| 67 |
+
Most of the file is the two engram tables, roughly 196.6B parameters between them. They follow the
|
| 68 |
+
rung, 99,611 to 40,284 MiB each between q8_0 and q3_K.
|
| 69 |
+
|
| 70 |
+
Apache/MIT from upstream. Credit: DeepSeek. GGUF pack: Victor Cruz (`vcruz305`).
|
llama.cpp/patches/README.md
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# llama.cpp conversion patch for DeepSeek-V4.1
|
| 2 |
+
|
| 3 |
+
The GGUFs in this repo were converted with a patched llama.cpp. Upstream does not yet know
|
| 4 |
+
`DeepseekV41ForCausalLM`, so a stock checkout cannot produce them.
|
| 5 |
+
|
| 6 |
+
The same change is submitted upstream as
|
| 7 |
+
[ggml-org/llama.cpp#28696](https://github.com/ggml-org/llama.cpp/pull/28696). This copy is here so
|
| 8 |
+
you can convert V4.1 yourself before that lands.
|
| 9 |
+
|
| 10 |
+
## Apply
|
| 11 |
+
|
| 12 |
+
```sh
|
| 13 |
+
python patch_llamacpp_v41.py /path/to/llama.cpp # apply
|
| 14 |
+
python patch_llamacpp_v41.py /path/to/llama.cpp --check # report status, change nothing
|
| 15 |
+
python patch_llamacpp_v41.py /path/to/llama.cpp --revert # undo
|
| 16 |
+
```
|
| 17 |
+
|
| 18 |
+
It is idempotent, and it writes a `.py.v41orig` backup beside every file it edits.
|
| 19 |
+
|
| 20 |
+
## What it touches
|
| 21 |
+
|
| 22 |
+
| file | change |
|
| 23 |
+
|---|---|
|
| 24 |
+
| `conversion/deepseek.py` | `DeepseekV41Model`, subclassing the existing `DeepseekV4Model` |
|
| 25 |
+
| `gguf-py/gguf/constants.py` | the `deepseek41` arch, its tensor list, and four engram tensor entries |
|
| 26 |
+
| `conversion/__init__.py` | one registry line |
|
| 27 |
+
|
| 28 |
+
## Architecture name
|
| 29 |
+
|
| 30 |
+
Files produced by this patch carry `general.architecture = deepseek41`.
|
| 31 |
+
|
| 32 |
+
llama.cpp does not mirror the HF `model_type`, it drops the `_v`: `deepseek_v2` became
|
| 33 |
+
`deepseek2`, `deepseek_v3.2` became `deepseek32`, `qwen2_moe` became `qwen2moe`. Only 10 of the
|
| 34 |
+
150 arch strings in `constants.py` contain an underscore at all, so V4.1 is `deepseek41`.
|
| 35 |
+
vLLM's `deepseek_v41` names a set of vLLM plugins, a tokenizer mode and two parsers, and is not
|
| 36 |
+
a GGUF architecture value.
|
| 37 |
+
|
| 38 |
+
The behavioural reason matters more than the convention. Riding on `deepseek4` sends a V4.1 file
|
| 39 |
+
to the V4 loader, which then asks for `output_hc_fn`, `output_hc_base` and `output_hc_scale`.
|
| 40 |
+
V4.1 ships none of the three, while it does ship the per-layer `hc_attn_*` and `hc_ffn_*`, so the
|
| 41 |
+
loader sees a confusing partial match rather than refusing the file. `deepseek4` was also not
|
| 42 |
+
strictly correct: V4.1 emits `attn_kv_a_norm`, which `DEEPSEEK4`'s own declared tensor list does
|
| 43 |
+
not contain.
|
| 44 |
+
|
| 45 |
+
The `deepseek41` tensor list is the 39 families the converter actually writes. It differs from
|
| 46 |
+
`DEEPSEEK4` by dropping `HC_HEAD_{FN,BASE,SCALE}`, `FFN_GATE_TID2EID`, `ATTN_KV_NORM`,
|
| 47 |
+
`ATTN_COMPRESSOR_APE`, `INDEXER_COMPRESSOR_*` and all six `NEXTN_*`, and by adding the four
|
| 48 |
+
engram entries plus `ATTN_KV_A_NORM`. This patch leaves `DEEPSEEK4` itself untouched.
|
| 49 |
+
|
| 50 |
+
This name is not yet settled upstream. It is proposed on the PR, and if the maintainers choose
|
| 51 |
+
differently the arch string in already-converted files can be restamped with
|
| 52 |
+
`gguf-py/gguf/scripts/gguf_new_metadata.py` without re-quantizing.
|
| 53 |
+
|
| 54 |
+
## Why a subclass is not enough on its own
|
| 55 |
+
|
| 56 |
+
Four things differ from V4 and each one is quiet rather than loud:
|
| 57 |
+
|
| 58 |
+
- **FP8 scale block size.** V4 hardcodes `repeat_interleave(128, ...)` to match its
|
| 59 |
+
`weight_block_size` of `[128, 128]`. V4.1 declares `[32, 32]`. Running the V4 path unchanged
|
| 60 |
+
rescales every dequantized weight, raises nothing, and yields a model that loads and reads
|
| 61 |
+
fluently while being numerically wrong. The block size is read from `quantization_config`.
|
| 62 |
+
- **`num_hash_layers`** is absent in V4.1 while the V4 path reads it unconditionally.
|
| 63 |
+
- **Nested config.** V4.1 puts text parameters under `text_config` and vision under
|
| 64 |
+
`vision_config`. Overriding `load_hparams` does not work, because `ModelBase.__init__` calls it
|
| 65 |
+
explicitly rather than through the instance, so they are promoted in `index_tensors`.
|
| 66 |
+
- **The engram tables.** Two of them, on layers 1 and 14, each `384,006,168 x 256`. The inherited
|
| 67 |
+
dequant computes `weight.float() * scale` over the whole tensor, about 393 GB as float32 for a
|
| 68 |
+
single table. They get a streaming path instead: read in row blocks straight from the
|
| 69 |
+
safetensors shard, quantized per block, accumulated into a disk backed memmap. Their scale
|
| 70 |
+
layout also differs from the rest of the checkpoint, `[rows, 8]` rather than the
|
| 71 |
+
`[rows/32, cols/32]` tiling the linear weights use.
|
| 72 |
+
|
| 73 |
+
Tunable through `_V41_ENGRAM_CHUNK_ROWS` and `V41_ENGRAM_TMPDIR`.
|
| 74 |
+
|
| 75 |
+
## Status
|
| 76 |
+
|
| 77 |
+
Conversion only. A converted file does not load yet: the `deepseek4` runtime wants
|
| 78 |
+
`output_hc_fn`, `output_hc_base` and `output_hc_scale`, and V4.1 does not ship those tensors.
|
| 79 |
+
Runtime support is separate work and is not in this patch.
|
llama.cpp/patches/fix_gguf_engram_kv.py
ADDED
|
@@ -0,0 +1,290 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
"""Repair the engram metadata of a DeepSeek-V4.1 GGUF that was written before the converter fix.
|
| 3 |
+
|
| 4 |
+
Two things went wrong in those files and both live in the header of the first shard:
|
| 5 |
+
|
| 6 |
+
1. the four engram keys carry a hardcoded `deepseek4.` prefix, so a `deepseek41` model looks for
|
| 7 |
+
`deepseek41.engram.head_count` and finds nothing
|
| 8 |
+
2. the five constants the hash actually needs are absent, because gguf-py's add_array() maps every
|
| 9 |
+
Python int to INT32, the 47 bit multipliers raised struct.error, and a broad except downgraded
|
| 10 |
+
that to a warning
|
| 11 |
+
|
| 12 |
+
Tensor data is untouched. Existing key/value pairs are re-emitted byte for byte, apart from the
|
| 13 |
+
four that get renamed, so nothing this script does not understand can be corrupted by it.
|
| 14 |
+
|
| 15 |
+
python fix_gguf_engram_kv.py shard1.gguf out.gguf --model-dir /path/to/DeepSeek-V4.1-Flash
|
| 16 |
+
"""
|
| 17 |
+
import argparse
|
| 18 |
+
import os
|
| 19 |
+
import struct
|
| 20 |
+
import sys
|
| 21 |
+
|
| 22 |
+
GGUF_MAGIC = b"GGUF"
|
| 23 |
+
|
| 24 |
+
# value type tags
|
| 25 |
+
T_UINT32 = 4
|
| 26 |
+
T_INT32 = 5
|
| 27 |
+
T_STRING = 8
|
| 28 |
+
T_ARRAY = 9
|
| 29 |
+
T_UINT64 = 10
|
| 30 |
+
|
| 31 |
+
FIXED = {0: 1, 1: 1, 2: 2, 3: 2, 4: 4, 5: 4, 6: 4, 7: 1, 10: 8, 11: 8, 12: 8}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _is_prime(n: int) -> bool:
|
| 35 |
+
if n < 2:
|
| 36 |
+
return False
|
| 37 |
+
for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
| 38 |
+
if n % p == 0:
|
| 39 |
+
return n == p
|
| 40 |
+
i = 41
|
| 41 |
+
while i * i <= n:
|
| 42 |
+
if n % i == 0 or n % (i + 2) == 0:
|
| 43 |
+
return False
|
| 44 |
+
i += 6
|
| 45 |
+
return True
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _next_prime(start: int, seen: set) -> int:
|
| 49 |
+
c = start + 1
|
| 50 |
+
while not _is_prime(c) or c in seen:
|
| 51 |
+
c += 1
|
| 52 |
+
return c
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def build_token_map(model_dir):
|
| 56 |
+
"""Case folded, accent stripped vocabulary, exactly as the reference builds it."""
|
| 57 |
+
from tokenizers import Regex, normalizers
|
| 58 |
+
from transformers import AutoTokenizer
|
| 59 |
+
|
| 60 |
+
tok = AutoTokenizer.from_pretrained(model_dir, trust_remote_code=True)
|
| 61 |
+
sentinel = "" # private use char, so a lone space survives Strip()
|
| 62 |
+
norm = normalizers.Sequence([
|
| 63 |
+
normalizers.NFKC(),
|
| 64 |
+
normalizers.NFD(),
|
| 65 |
+
normalizers.StripAccents(),
|
| 66 |
+
normalizers.Lowercase(),
|
| 67 |
+
normalizers.Replace(Regex(r"[ \t\r\n]+"), " "),
|
| 68 |
+
normalizers.Replace(Regex(r"^ $"), sentinel),
|
| 69 |
+
normalizers.Strip(),
|
| 70 |
+
normalizers.Replace(sentinel, " "),
|
| 71 |
+
])
|
| 72 |
+
backend = tok.backend_tokenizer
|
| 73 |
+
key_to_new, lookup = {}, [0] * len(tok)
|
| 74 |
+
for tid in range(len(tok)):
|
| 75 |
+
text = backend.decode([tid], skip_special_tokens=False)
|
| 76 |
+
if "�" in text:
|
| 77 |
+
key = backend.id_to_token(tid)
|
| 78 |
+
else:
|
| 79 |
+
normalized = norm.normalize_str(text)
|
| 80 |
+
key = normalized if normalized else text
|
| 81 |
+
new = key_to_new.get(key)
|
| 82 |
+
if new is None:
|
| 83 |
+
new = len(key_to_new)
|
| 84 |
+
key_to_new[key] = new
|
| 85 |
+
lookup[tid] = new
|
| 86 |
+
return lookup, len(key_to_new)
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def build_constants(model_dir, layer_ids, max_ngram, n_heads, vocab_size, pad_raw):
|
| 90 |
+
import numpy as np
|
| 91 |
+
|
| 92 |
+
token_map, compressed = build_token_map(model_dir)
|
| 93 |
+
|
| 94 |
+
max_long = np.iinfo(np.int64).max
|
| 95 |
+
bound = max(1, (max_long // compressed) // 2)
|
| 96 |
+
mults = []
|
| 97 |
+
for lid in layer_ids:
|
| 98 |
+
rng = np.random.default_rng(10007 * lid)
|
| 99 |
+
mults.extend(int(v) * 2 + 1 for v in rng.integers(0, bound, size=(max_ngram,), dtype=np.int64))
|
| 100 |
+
|
| 101 |
+
primes, seen = [], set()
|
| 102 |
+
for _ in layer_ids:
|
| 103 |
+
for _ in range(max_ngram - 1):
|
| 104 |
+
cur = vocab_size - 1
|
| 105 |
+
for _ in range(n_heads):
|
| 106 |
+
cur = _next_prime(cur, seen)
|
| 107 |
+
seen.add(cur)
|
| 108 |
+
primes.append(cur)
|
| 109 |
+
|
| 110 |
+
per_layer = (max_ngram - 1) * n_heads
|
| 111 |
+
offsets = []
|
| 112 |
+
for l in range(len(layer_ids)):
|
| 113 |
+
acc = 0
|
| 114 |
+
for b in range(per_layer):
|
| 115 |
+
offsets.append(acc)
|
| 116 |
+
acc += primes[l * per_layer + b]
|
| 117 |
+
|
| 118 |
+
return {
|
| 119 |
+
"multipliers": mults,
|
| 120 |
+
"primes": primes,
|
| 121 |
+
"offsets": offsets,
|
| 122 |
+
"token_map": token_map,
|
| 123 |
+
"pad_id": token_map[pad_raw],
|
| 124 |
+
"compressed_vocab": compressed,
|
| 125 |
+
}
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def kv_uint32(v):
|
| 129 |
+
return struct.pack("<I", T_UINT32) + struct.pack("<I", v)
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def kv_array(elem_type, values):
|
| 133 |
+
fmt = {T_INT32: "<i", T_UINT64: "<Q"}[elem_type]
|
| 134 |
+
out = [struct.pack("<I", T_ARRAY), struct.pack("<I", elem_type), struct.pack("<Q", len(values))]
|
| 135 |
+
out.extend(struct.pack(fmt, int(v)) for v in values)
|
| 136 |
+
return b"".join(out)
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
def kv_entry(key, value_bytes):
|
| 140 |
+
k = key.encode("utf-8")
|
| 141 |
+
return struct.pack("<Q", len(k)) + k + value_bytes
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def main():
|
| 145 |
+
ap = argparse.ArgumentParser()
|
| 146 |
+
ap.add_argument("src")
|
| 147 |
+
ap.add_argument("dst")
|
| 148 |
+
ap.add_argument("--model-dir", required=True, help="the original checkpoint, for its tokenizer")
|
| 149 |
+
ap.add_argument("--arch", default="deepseek41")
|
| 150 |
+
ap.add_argument("--engram-vocab", type=int, default=16_000_000)
|
| 151 |
+
ap.add_argument("--engram-pad-id", type=int, default=2)
|
| 152 |
+
args = ap.parse_args()
|
| 153 |
+
|
| 154 |
+
f = open(args.src, "rb")
|
| 155 |
+
assert f.read(4) == GGUF_MAGIC, "not a gguf"
|
| 156 |
+
version, = struct.unpack("<I", f.read(4))
|
| 157 |
+
n_tensors, = struct.unpack("<Q", f.read(8))
|
| 158 |
+
n_kv, = struct.unpack("<Q", f.read(8))
|
| 159 |
+
|
| 160 |
+
def rstr():
|
| 161 |
+
n, = struct.unpack("<Q", f.read(8))
|
| 162 |
+
return f.read(n).decode("utf-8")
|
| 163 |
+
|
| 164 |
+
def skip_value(t):
|
| 165 |
+
if t == T_STRING:
|
| 166 |
+
n, = struct.unpack("<Q", f.read(8))
|
| 167 |
+
f.seek(n, os.SEEK_CUR)
|
| 168 |
+
elif t == T_ARRAY:
|
| 169 |
+
et, = struct.unpack("<I", f.read(4))
|
| 170 |
+
cnt, = struct.unpack("<Q", f.read(8))
|
| 171 |
+
if et == T_STRING:
|
| 172 |
+
for _ in range(cnt):
|
| 173 |
+
n, = struct.unpack("<Q", f.read(8))
|
| 174 |
+
f.seek(n, os.SEEK_CUR)
|
| 175 |
+
else:
|
| 176 |
+
f.seek(FIXED[et] * cnt, os.SEEK_CUR)
|
| 177 |
+
else:
|
| 178 |
+
f.seek(FIXED[t], os.SEEK_CUR)
|
| 179 |
+
|
| 180 |
+
kvs = [] # (key, raw value bytes including the type tag)
|
| 181 |
+
seen_keys = set()
|
| 182 |
+
for _ in range(n_kv):
|
| 183 |
+
key = rstr()
|
| 184 |
+
vstart = f.tell()
|
| 185 |
+
t, = struct.unpack("<I", f.read(4))
|
| 186 |
+
skip_value(t)
|
| 187 |
+
vend = f.tell()
|
| 188 |
+
f.seek(vstart)
|
| 189 |
+
raw = f.read(vend - vstart)
|
| 190 |
+
kvs.append([key, raw])
|
| 191 |
+
seen_keys.add(key)
|
| 192 |
+
|
| 193 |
+
tensor_info_start = f.tell()
|
| 194 |
+
for _ in range(n_tensors):
|
| 195 |
+
rstr()
|
| 196 |
+
ndim, = struct.unpack("<I", f.read(4))
|
| 197 |
+
f.seek(8 * ndim, os.SEEK_CUR)
|
| 198 |
+
f.seek(4, os.SEEK_CUR) # ggml type
|
| 199 |
+
f.seek(8, os.SEEK_CUR) # offset
|
| 200 |
+
tensor_info_end = f.tell()
|
| 201 |
+
f.seek(tensor_info_start)
|
| 202 |
+
tensor_info_raw = f.read(tensor_info_end - tensor_info_start)
|
| 203 |
+
|
| 204 |
+
alignment = 32
|
| 205 |
+
for key, raw in kvs:
|
| 206 |
+
if key == "general.alignment":
|
| 207 |
+
alignment, = struct.unpack("<I", raw[4:8])
|
| 208 |
+
|
| 209 |
+
data_start = (tensor_info_end + alignment - 1) // alignment * alignment
|
| 210 |
+
|
| 211 |
+
# --- rename the mis-prefixed keys -------------------------------------------------
|
| 212 |
+
renamed = 0
|
| 213 |
+
for kv in kvs:
|
| 214 |
+
if kv[0].startswith("deepseek4.engram."):
|
| 215 |
+
kv[0] = args.arch + "." + kv[0][len("deepseek4."):]
|
| 216 |
+
renamed += 1
|
| 217 |
+
|
| 218 |
+
def get_scalar(name):
|
| 219 |
+
for key, raw in kvs:
|
| 220 |
+
if key == name:
|
| 221 |
+
t, = struct.unpack("<I", raw[:4])
|
| 222 |
+
return struct.unpack("<I" if t in (T_UINT32,) else "<i", raw[4:8])[0]
|
| 223 |
+
return None
|
| 224 |
+
|
| 225 |
+
layer_ids = None
|
| 226 |
+
for key, raw in kvs:
|
| 227 |
+
if key == f"{args.arch}.engram.layer_ids":
|
| 228 |
+
et, = struct.unpack("<I", raw[4:8])
|
| 229 |
+
cnt, = struct.unpack("<Q", raw[8:16])
|
| 230 |
+
fmt = {T_INT32: "<i", T_UINT32: "<I", T_UINT64: "<Q"}[et]
|
| 231 |
+
sz = FIXED[et]
|
| 232 |
+
layer_ids = [struct.unpack(fmt, raw[16 + i * sz: 16 + (i + 1) * sz])[0] for i in range(cnt)]
|
| 233 |
+
|
| 234 |
+
n_heads = get_scalar(f"{args.arch}.engram.head_count")
|
| 235 |
+
max_ngram = get_scalar(f"{args.arch}.engram.max_ngram_size")
|
| 236 |
+
if layer_ids is None or n_heads is None or max_ngram is None:
|
| 237 |
+
sys.exit("could not read the engram layer ids, head count or ngram size from the header")
|
| 238 |
+
|
| 239 |
+
print(f" arch={args.arch} layer_ids={layer_ids} heads={n_heads} max_ngram={max_ngram}")
|
| 240 |
+
print(f" renamed {renamed} mis-prefixed keys")
|
| 241 |
+
|
| 242 |
+
const = build_constants(args.model_dir, layer_ids, max_ngram, n_heads,
|
| 243 |
+
args.engram_vocab, args.engram_pad_id)
|
| 244 |
+
print(f" compressed vocab {const['compressed_vocab']}, token map {len(const['token_map'])}, "
|
| 245 |
+
f"{len(const['primes'])} primes, pad_id {const['pad_id']}")
|
| 246 |
+
print(f" first multipliers {const['multipliers'][:3]} (max bits "
|
| 247 |
+
f"{max(const['multipliers']).bit_length()})")
|
| 248 |
+
|
| 249 |
+
additions = [
|
| 250 |
+
(f"{args.arch}.engram.multipliers", kv_array(T_UINT64, const["multipliers"])),
|
| 251 |
+
(f"{args.arch}.engram.primes", kv_array(T_UINT64, const["primes"])),
|
| 252 |
+
(f"{args.arch}.engram.offsets", kv_array(T_UINT64, const["offsets"])),
|
| 253 |
+
(f"{args.arch}.engram.token_map", kv_array(T_INT32, const["token_map"])),
|
| 254 |
+
(f"{args.arch}.engram.pad_id", kv_uint32(const["pad_id"])),
|
| 255 |
+
]
|
| 256 |
+
additions = [(k, v) for k, v in additions if k not in {kv[0] for kv in kvs}]
|
| 257 |
+
print(f" adding {len(additions)} keys")
|
| 258 |
+
|
| 259 |
+
header = bytearray()
|
| 260 |
+
header += GGUF_MAGIC
|
| 261 |
+
header += struct.pack("<I", version)
|
| 262 |
+
header += struct.pack("<Q", n_tensors)
|
| 263 |
+
header += struct.pack("<Q", len(kvs) + len(additions))
|
| 264 |
+
for key, raw in kvs:
|
| 265 |
+
header += kv_entry(key, raw)
|
| 266 |
+
for key, raw in additions:
|
| 267 |
+
header += kv_entry(key, raw)
|
| 268 |
+
header += tensor_info_raw
|
| 269 |
+
|
| 270 |
+
pad = (-len(header)) % alignment
|
| 271 |
+
header += b"\x00" * pad
|
| 272 |
+
|
| 273 |
+
src_size = os.path.getsize(args.src)
|
| 274 |
+
print(f" header {tensor_info_end} -> {len(header)} bytes, copying "
|
| 275 |
+
f"{(src_size - data_start)/1e9:.1f} GB of tensor data")
|
| 276 |
+
|
| 277 |
+
f.seek(data_start)
|
| 278 |
+
with open(args.dst, "wb") as out:
|
| 279 |
+
out.write(header)
|
| 280 |
+
while True:
|
| 281 |
+
chunk = f.read(64 << 20)
|
| 282 |
+
if not chunk:
|
| 283 |
+
break
|
| 284 |
+
out.write(chunk)
|
| 285 |
+
|
| 286 |
+
print(f" wrote {args.dst} ({os.path.getsize(args.dst)/1e9:.1f} GB)")
|
| 287 |
+
|
| 288 |
+
|
| 289 |
+
if __name__ == "__main__":
|
| 290 |
+
main()
|
llama.cpp/patches/patch_llamacpp_v41.py
ADDED
|
@@ -0,0 +1,701 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Add DeepSeek V4.1 (DeepseekV41ForCausalLM) conversion support to llama.cpp.
|
| 2 |
+
|
| 3 |
+
Upstream llama.cpp master carries a full DeepSeek V4 implementation in conversion/deepseek.py
|
| 4 |
+
(DeepseekV4Model, DeepseekV4DSparkModel, DeepseekV4FlashVisionModel). V4.1 is close enough to
|
| 5 |
+
subclass rather than reimplement. This patch adds the V4.1 pieces and fixes one bug that would
|
| 6 |
+
otherwise corrupt V4.1 weights silently.
|
| 7 |
+
|
| 8 |
+
Differences handled, each verified against the published DeepSeek-V4.1-Flash config.json and
|
| 9 |
+
model.safetensors.index.json rather than assumed:
|
| 10 |
+
|
| 11 |
+
1. FP8 dequantization block size. V4's dequant_model hardcodes repeat_interleave(128, ...),
|
| 12 |
+
matching V4's weight_block_size of [128, 128]. V4.1 declares [32, 32]. Running the V4 path
|
| 13 |
+
unchanged produces wrong weights with no error and fluent but incorrect output, so the block
|
| 14 |
+
size is read from quantization_config instead.
|
| 15 |
+
|
| 16 |
+
2. num_hash_layers is absent from the V4.1 config. V4 reads it unconditionally and would raise
|
| 17 |
+
KeyError, so it defaults to 0 here.
|
| 18 |
+
|
| 19 |
+
3. The V4.1 config nests its text parameters under text_config and its vision parameters under
|
| 20 |
+
vision_config. V4 expects them flat.
|
| 21 |
+
|
| 22 |
+
4. Six tensor families exist in V4.1 that V4 does not map. Four need new enum entries;
|
| 23 |
+
INDEXER_K_NORM and INDEXER_ATTN_K already exist upstream and are reused:
|
| 24 |
+
layers.N.engram.embed.weight layers.N.engram.k_weight
|
| 25 |
+
layers.N.engram.q_weight layers.N.engram.wkv.weight
|
| 26 |
+
layers.N.attn.indexer.k_norm.weight
|
| 27 |
+
layers.N.attn.indexer.wk.weight
|
| 28 |
+
The engram tables are the largest single component of the model at roughly 196.6B parameters
|
| 29 |
+
across layers 1 and 14, which is about 36 percent of the checkpoint.
|
| 30 |
+
|
| 31 |
+
5. The two engram tables need their own write path. Each is 384,006,168 x 256, so 98.3
|
| 32 |
+
billion elements, and the inherited FP8 dequant materializes 393 GB of float32 per
|
| 33 |
+
table. They are quantized in row blocks into a disk-backed memmap instead. Their scale
|
| 34 |
+
layout also differs: [rows, 8], one scale per 32 columns of a single row, rather than
|
| 35 |
+
the [rows/32, cols/32] tiling the generic path assumes.
|
| 36 |
+
|
| 37 |
+
6. V4.1 lacks attn.compressor.ape and the attn.indexer.compressor.* family that V4 maps. Those
|
| 38 |
+
entries stay in the inherited map and simply go unused.
|
| 39 |
+
|
| 40 |
+
This patch covers CONVERSION only. Running the resulting GGUF additionally requires a llama.cpp
|
| 41 |
+
runtime graph for V4.1, which is separate work.
|
| 42 |
+
|
| 43 |
+
usage: python patch_llamacpp_v41.py <llama.cpp checkout> [--revert] [--check]
|
| 44 |
+
"""
|
| 45 |
+
|
| 46 |
+
import pathlib
|
| 47 |
+
import shutil
|
| 48 |
+
import sys
|
| 49 |
+
|
| 50 |
+
# ---------------------------------------------------------------- constants.py
|
| 51 |
+
|
| 52 |
+
CONST_TENSOR_ENUM_ANCHOR = " INDEXER_PROJ "
|
| 53 |
+
CONST_TENSOR_ENUM_NEW = """ ENGRAM_EMBD = auto()
|
| 54 |
+
ENGRAM_K = auto()
|
| 55 |
+
ENGRAM_Q = auto()
|
| 56 |
+
ENGRAM_WKV = auto()
|
| 57 |
+
"""
|
| 58 |
+
|
| 59 |
+
CONST_TENSOR_NAME_ANCHOR = " MODEL_TENSOR.INDEXER_PROJ:"
|
| 60 |
+
CONST_TENSOR_NAME_NEW = """ MODEL_TENSOR.ENGRAM_EMBD: "blk.{bid}.engram_embd",
|
| 61 |
+
MODEL_TENSOR.ENGRAM_K: "blk.{bid}.engram_k",
|
| 62 |
+
MODEL_TENSOR.ENGRAM_Q: "blk.{bid}.engram_q",
|
| 63 |
+
MODEL_TENSOR.ENGRAM_WKV: "blk.{bid}.engram_wkv",
|
| 64 |
+
"""
|
| 65 |
+
|
| 66 |
+
# V4.1 gets its own architecture rather than riding on DEEPSEEK4.
|
| 67 |
+
#
|
| 68 |
+
# llama.cpp does not mirror the HF model_type, it drops the "_v": deepseek_v2 became
|
| 69 |
+
# deepseek2, deepseek_v3.2 became deepseek32, qwen2_moe became qwen2moe. Only 10 of the
|
| 70 |
+
# 150 arch strings in constants.py contain an underscore at all, so V4.1 is "deepseek41".
|
| 71 |
+
#
|
| 72 |
+
# The behavioural reason matters more than the convention. Sharing deepseek4 sends a V4.1
|
| 73 |
+
# file to the V4 loader, which asks for output_hc_fn, output_hc_base and output_hc_scale.
|
| 74 |
+
# V4.1 ships none of the three, while it does ship the per-layer hc_attn_* and hc_ffn_*,
|
| 75 |
+
# so the loader sees a confusing partial match instead of refusing the file. Riding on
|
| 76 |
+
# DEEPSEEK4 was also not strictly correct: V4.1 emits attn_kv_a_norm, which DEEPSEEK4's
|
| 77 |
+
# own declared tensor list does not contain.
|
| 78 |
+
#
|
| 79 |
+
# The list below is derived from the 39 tensor families the converter actually wrote,
|
| 80 |
+
# reverse mapped through TENSOR_NAMES, rather than copied from DEEPSEEK4 and trimmed.
|
| 81 |
+
|
| 82 |
+
# The engram KV keys, declared the way every other arch-scoped key is: with an {arch}
|
| 83 |
+
# placeholder. PerLayerEmbedding directly below is the closest existing analogue, and llama.cpp's
|
| 84 |
+
# own lazy-read comment pairs PLE and engrams for the same reason.
|
| 85 |
+
CONST_KV_ANCHOR = " class PerLayerEmbedding:\n"
|
| 86 |
+
CONST_KV_NEW = ''' class Engram:
|
| 87 |
+
LAYER_IDS = "{arch}.engram.layer_ids"
|
| 88 |
+
HEAD_COUNT = "{arch}.engram.head_count"
|
| 89 |
+
KEY_LENGTH = "{arch}.engram.key_length"
|
| 90 |
+
MAX_NGRAM_SIZE = "{arch}.engram.max_ngram_size"
|
| 91 |
+
MULTIPLIERS = "{arch}.engram.multipliers"
|
| 92 |
+
PRIMES = "{arch}.engram.primes"
|
| 93 |
+
OFFSETS = "{arch}.engram.offsets"
|
| 94 |
+
TOKEN_MAP = "{arch}.engram.token_map"
|
| 95 |
+
PAD_ID = "{arch}.engram.pad_id"
|
| 96 |
+
|
| 97 |
+
class PerLayerEmbedding:
|
| 98 |
+
'''
|
| 99 |
+
|
| 100 |
+
CONST_ARCH_ENUM_ANCHOR = " DEEPSEEK4 = auto()\n"
|
| 101 |
+
CONST_ARCH_ENUM_NEW = """ DEEPSEEK4 = auto()
|
| 102 |
+
DEEPSEEK41 = auto()
|
| 103 |
+
"""
|
| 104 |
+
|
| 105 |
+
CONST_ARCH_NAME_ANCHOR = ' MODEL_ARCH.DEEPSEEK4: "deepseek4",\n'
|
| 106 |
+
CONST_ARCH_NAME_NEW = ''' MODEL_ARCH.DEEPSEEK4: "deepseek4",
|
| 107 |
+
MODEL_ARCH.DEEPSEEK41: "deepseek41",
|
| 108 |
+
'''
|
| 109 |
+
|
| 110 |
+
CONST_ARCH_TENSORS_ANCHOR = " MODEL_ARCH.DEEPSEEK4: [\n"
|
| 111 |
+
CONST_ARCH_TENSORS_NEW = """ MODEL_ARCH.DEEPSEEK41: [
|
| 112 |
+
MODEL_TENSOR.TOKEN_EMBD,
|
| 113 |
+
MODEL_TENSOR.OUTPUT,
|
| 114 |
+
MODEL_TENSOR.OUTPUT_NORM,
|
| 115 |
+
MODEL_TENSOR.ATTN_NORM,
|
| 116 |
+
MODEL_TENSOR.ATTN_SINKS,
|
| 117 |
+
MODEL_TENSOR.FFN_GATE_INP,
|
| 118 |
+
MODEL_TENSOR.FFN_NORM,
|
| 119 |
+
MODEL_TENSOR.FFN_GATE_EXP,
|
| 120 |
+
MODEL_TENSOR.FFN_DOWN_EXP,
|
| 121 |
+
MODEL_TENSOR.FFN_UP_EXP,
|
| 122 |
+
MODEL_TENSOR.FFN_GATE_SHEXP,
|
| 123 |
+
MODEL_TENSOR.FFN_DOWN_SHEXP,
|
| 124 |
+
MODEL_TENSOR.FFN_UP_SHEXP,
|
| 125 |
+
MODEL_TENSOR.FFN_EXP_PROBS_B,
|
| 126 |
+
MODEL_TENSOR.FFN_EXP_PROBS_B_VL,
|
| 127 |
+
MODEL_TENSOR.ATTN_Q_A,
|
| 128 |
+
MODEL_TENSOR.ATTN_Q_B,
|
| 129 |
+
MODEL_TENSOR.ATTN_Q_A_NORM,
|
| 130 |
+
MODEL_TENSOR.ATTN_KV_A_NORM,
|
| 131 |
+
MODEL_TENSOR.ATTN_KV,
|
| 132 |
+
MODEL_TENSOR.ATTN_OUT_A,
|
| 133 |
+
MODEL_TENSOR.ATTN_OUT_B,
|
| 134 |
+
MODEL_TENSOR.HC_ATTN_FN,
|
| 135 |
+
MODEL_TENSOR.HC_ATTN_BASE,
|
| 136 |
+
MODEL_TENSOR.HC_ATTN_SCALE,
|
| 137 |
+
MODEL_TENSOR.HC_FFN_FN,
|
| 138 |
+
MODEL_TENSOR.HC_FFN_BASE,
|
| 139 |
+
MODEL_TENSOR.HC_FFN_SCALE,
|
| 140 |
+
MODEL_TENSOR.ATTN_COMPRESSOR_WKV,
|
| 141 |
+
MODEL_TENSOR.ATTN_COMPRESSOR_WGATE,
|
| 142 |
+
MODEL_TENSOR.ATTN_COMPRESSOR_NORM,
|
| 143 |
+
MODEL_TENSOR.INDEXER_K_NORM,
|
| 144 |
+
MODEL_TENSOR.ENGRAM_EMBD,
|
| 145 |
+
MODEL_TENSOR.ENGRAM_K,
|
| 146 |
+
MODEL_TENSOR.ENGRAM_Q,
|
| 147 |
+
MODEL_TENSOR.ENGRAM_WKV,
|
| 148 |
+
MODEL_TENSOR.INDEXER_PROJ,
|
| 149 |
+
MODEL_TENSOR.INDEXER_ATTN_K,
|
| 150 |
+
MODEL_TENSOR.INDEXER_ATTN_Q_B,
|
| 151 |
+
],
|
| 152 |
+
MODEL_ARCH.DEEPSEEK4: [
|
| 153 |
+
"""
|
| 154 |
+
|
| 155 |
+
# ---------------------------------------------------------------- deepseek.py
|
| 156 |
+
|
| 157 |
+
V41_CLASS = '''
|
| 158 |
+
|
| 159 |
+
def _v41_is_prime(n: int) -> bool:
|
| 160 |
+
"""Trial division, deliberately not sympy.
|
| 161 |
+
|
| 162 |
+
The reference uses sympy.isprime, but sympy is not a llama.cpp conversion dependency and
|
| 163 |
+
pulling in a computer algebra system to test primality would be hard to justify. The
|
| 164 |
+
candidates here sit just above engram_vocab_size, about 16 million, so trial division runs
|
| 165 |
+
to sqrt(n) which is around 4000 and costs nothing. There are 48 primes to find in total.
|
| 166 |
+
"""
|
| 167 |
+
if n < 2:
|
| 168 |
+
return False
|
| 169 |
+
for p in (2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37):
|
| 170 |
+
if n % p == 0:
|
| 171 |
+
return n == p
|
| 172 |
+
f = 41
|
| 173 |
+
while f * f <= n:
|
| 174 |
+
# 6k +/- 1 wheel, having already cleared the small primes above
|
| 175 |
+
if n % f == 0 or n % (f + 2) == 0:
|
| 176 |
+
return False
|
| 177 |
+
f += 6
|
| 178 |
+
return True
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _v41_find_next_prime(start: int, seen_primes: set[int]) -> int:
|
| 182 |
+
"""The smallest prime above start that has not been handed out yet."""
|
| 183 |
+
candidate = start + 1
|
| 184 |
+
while not _v41_is_prime(candidate) or candidate in seen_primes:
|
| 185 |
+
candidate += 1
|
| 186 |
+
return candidate
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _v41_build_compressed_token_map(tokenizer) -> tuple[list[int], int]:
|
| 190 |
+
"""Map token ids to a compressed id space where normalized tokens collapse together."""
|
| 191 |
+
from tokenizers import Regex, normalizers
|
| 192 |
+
|
| 193 |
+
sentinel = "\\ue000" # private-use char to preserve single spaces
|
| 194 |
+
normalizer = normalizers.Sequence([
|
| 195 |
+
normalizers.NFKC(),
|
| 196 |
+
normalizers.NFD(),
|
| 197 |
+
normalizers.StripAccents(),
|
| 198 |
+
normalizers.Lowercase(),
|
| 199 |
+
normalizers.Replace(Regex(r"[ \\t\\r\\n]+"), " "),
|
| 200 |
+
normalizers.Replace(Regex(r"^ $"), sentinel),
|
| 201 |
+
normalizers.Strip(),
|
| 202 |
+
normalizers.Replace(sentinel, " "),
|
| 203 |
+
])
|
| 204 |
+
|
| 205 |
+
backend = tokenizer.backend_tokenizer
|
| 206 |
+
key_to_new: dict[str, int] = {}
|
| 207 |
+
lookup = [0] * len(tokenizer)
|
| 208 |
+
for token_id in range(len(tokenizer)):
|
| 209 |
+
text = backend.decode([token_id], skip_special_tokens=False)
|
| 210 |
+
if "\\ufffd" in text:
|
| 211 |
+
key = backend.id_to_token(token_id)
|
| 212 |
+
else:
|
| 213 |
+
normalized = normalizer.normalize_str(text)
|
| 214 |
+
key = normalized if normalized else text
|
| 215 |
+
|
| 216 |
+
new_id = key_to_new.get(key)
|
| 217 |
+
if new_id is None:
|
| 218 |
+
new_id = len(key_to_new)
|
| 219 |
+
key_to_new[key] = new_id
|
| 220 |
+
lookup[token_id] = new_id
|
| 221 |
+
|
| 222 |
+
return lookup, len(key_to_new)
|
| 223 |
+
|
| 224 |
+
|
| 225 |
+
def _v41_compute_hash_multipliers(layer_ids: tuple[int, ...], max_ngram_size: int, tokenizer_vocab_size: int):
|
| 226 |
+
"""Generate odd multipliers for n-gram hashing, one per (layer, lookback)."""
|
| 227 |
+
import numpy as np
|
| 228 |
+
import torch
|
| 229 |
+
|
| 230 |
+
max_long = np.iinfo(np.int64).max
|
| 231 |
+
multiplier_bound = max(1, (max_long // tokenizer_vocab_size) // 2)
|
| 232 |
+
rows = []
|
| 233 |
+
for layer_id in layer_ids:
|
| 234 |
+
generator = np.random.default_rng(10007 * layer_id)
|
| 235 |
+
values = generator.integers(low=0, high=multiplier_bound, size=(max_ngram_size,), dtype=np.int64)
|
| 236 |
+
rows.append(torch.tensor(values * 2 + 1))
|
| 237 |
+
return torch.stack(rows)
|
| 238 |
+
|
| 239 |
+
|
| 240 |
+
@ModelBase.register("DeepseekV41ForCausalLM")
|
| 241 |
+
@ModelBase.example("deepseek-ai/DeepSeek-V4.1-Flash")
|
| 242 |
+
class DeepseekV41Model(DeepseekV4Model):
|
| 243 |
+
"""DeepSeek V4.1. Subclasses V4 and overrides only where the checkpoint differs.
|
| 244 |
+
|
| 245 |
+
See patch_llamacpp_v41.py for the verified list of differences. The important one is the
|
| 246 |
+
FP8 block size: V4 is [128, 128] and V4.1 is [32, 32], and using the wrong value corrupts
|
| 247 |
+
every dequantized weight without raising.
|
| 248 |
+
"""
|
| 249 |
+
|
| 250 |
+
model_arch = gguf.MODEL_ARCH.DEEPSEEK41
|
| 251 |
+
|
| 252 |
+
def _v41_flatten_hparams(self):
|
| 253 |
+
"""Promote the nested text_config to the top level.
|
| 254 |
+
|
| 255 |
+
V4.1 nests its text parameters under text_config while the inherited V4 code expects
|
| 256 |
+
them flat. Overriding load_hparams does not work, because base.__init__ calls
|
| 257 |
+
ModelBase.load_hparams explicitly rather than through the instance, so the seam is the
|
| 258 |
+
first consumer of hparams instead, which is index_tensors.
|
| 259 |
+
"""
|
| 260 |
+
for key, value in (self.hparams.get("text_config") or {}).items():
|
| 261 |
+
self.hparams.setdefault(key, value)
|
| 262 |
+
# absent in V4.1; V4 reads it unconditionally
|
| 263 |
+
self.hparams.setdefault("num_hash_layers", 0)
|
| 264 |
+
|
| 265 |
+
def index_tensors(self, remote_hf_model_id=None):
|
| 266 |
+
self._v41_flatten_hparams()
|
| 267 |
+
return super().index_tensors(remote_hf_model_id=remote_hf_model_id)
|
| 268 |
+
|
| 269 |
+
def __init__(self, *args, **kwargs):
|
| 270 |
+
super().__init__(*args, **kwargs)
|
| 271 |
+
|
| 272 |
+
with open(self.dir_model / "config.json", "r", encoding="utf-8") as f:
|
| 273 |
+
raw = json.load(f)
|
| 274 |
+
|
| 275 |
+
# the FP8 scale block size, read rather than assumed
|
| 276 |
+
qcfg = raw.get("quantization_config") or {}
|
| 277 |
+
block = qcfg.get("weight_block_size") or [128, 128]
|
| 278 |
+
self._v41_block_rows = int(block[0])
|
| 279 |
+
self._v41_block_cols = int(block[1] if len(block) > 1 else block[0])
|
| 280 |
+
logger.info(
|
| 281 |
+
"DeepSeek V4.1: fp8 weight_block_size %dx%d, engram layers %s",
|
| 282 |
+
self._v41_block_rows, self._v41_block_cols,
|
| 283 |
+
self.hparams.get("engram_layer_ids"),
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
self.block_count = self.hparams["num_hidden_layers"]
|
| 287 |
+
if self.mtp_only:
|
| 288 |
+
self.block_count += self.hparams.get("num_nextn_predict_layers", 0)
|
| 289 |
+
self.tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
|
| 290 |
+
|
| 291 |
+
@classmethod
|
| 292 |
+
def filter_tensors(cls, item):
|
| 293 |
+
name, _ = item
|
| 294 |
+
# the vision tower and its aligner are exported separately as an mmproj file
|
| 295 |
+
if name.startswith(("vision.", "aligner.", "image_")):
|
| 296 |
+
return None
|
| 297 |
+
return super().filter_tensors(item)
|
| 298 |
+
|
| 299 |
+
def dequant_model(self):
|
| 300 |
+
"""Same as V4 but with the block size taken from the checkpoint."""
|
| 301 |
+
fp8_dtypes = self._float8_dtypes()
|
| 302 |
+
tensors_to_remove: list[str] = []
|
| 303 |
+
rows, cols = self._v41_block_rows, self._v41_block_cols
|
| 304 |
+
|
| 305 |
+
def dequant_fp8_weight(weight: Tensor, scale: Tensor) -> Tensor:
|
| 306 |
+
out_features, in_features = weight.shape
|
| 307 |
+
scale_f = self._e8m0_to_float(scale)
|
| 308 |
+
scale_f = scale_f.repeat_interleave(rows, 0)[:out_features]
|
| 309 |
+
scale_f = scale_f.repeat_interleave(cols, 1)[:, :in_features]
|
| 310 |
+
return weight.float() * scale_f
|
| 311 |
+
|
| 312 |
+
for name in list(self.model_tensors.keys()):
|
| 313 |
+
if not name.endswith(".scale"):
|
| 314 |
+
continue
|
| 315 |
+
weight_name = name.removesuffix(".scale") + ".weight"
|
| 316 |
+
if weight_name not in self.model_tensors:
|
| 317 |
+
continue
|
| 318 |
+
weight = self.model_tensors[weight_name]
|
| 319 |
+
scale = self.model_tensors[name]
|
| 320 |
+
if weight().dtype not in fp8_dtypes:
|
| 321 |
+
continue
|
| 322 |
+
self.model_tensors[weight_name] = lambda w=weight, s=scale: dequant_fp8_weight(w(), s())
|
| 323 |
+
self._dsv4_fp8_dequantized.add(weight_name)
|
| 324 |
+
tensors_to_remove.append(name)
|
| 325 |
+
|
| 326 |
+
for name in tensors_to_remove:
|
| 327 |
+
del self.model_tensors[name]
|
| 328 |
+
|
| 329 |
+
def set_gguf_parameters(self):
|
| 330 |
+
super().set_gguf_parameters()
|
| 331 |
+
hparams = self.hparams
|
| 332 |
+
if (engram_ids := hparams.get("engram_layer_ids")) is not None:
|
| 333 |
+
# These MUST carry the arch prefix, not a literal "deepseek4.". llama.cpp resolves
|
| 334 |
+
# every LLM_KV_* as "{arch}.{key}", so a hardcoded prefix means the runtime looks up
|
| 335 |
+
# deepseek41.engram.head_count and finds nothing, on a file that otherwise loads.
|
| 336 |
+
arch = self.gguf_writer.arch
|
| 337 |
+
self.gguf_writer.add_uint32(gguf.Keys.Engram.HEAD_COUNT.format(arch=arch), hparams["engram_n_heads"])
|
| 338 |
+
self.gguf_writer.add_uint32(gguf.Keys.Engram.KEY_LENGTH.format(arch=arch), hparams["engram_head_dim"])
|
| 339 |
+
self.gguf_writer.add_uint32(gguf.Keys.Engram.MAX_NGRAM_SIZE.format(arch=arch), hparams["engram_max_ngram_size"])
|
| 340 |
+
self.gguf_writer.add_array(gguf.Keys.Engram.LAYER_IDS.format(arch=arch), engram_ids)
|
| 341 |
+
|
| 342 |
+
# Generate and write engram hash constants
|
| 343 |
+
import numpy as _np
|
| 344 |
+
|
| 345 |
+
# A model with engram layers cannot run without these constants, so every step below
|
| 346 |
+
# raises rather than warns: a file that is missing them loads and then hashes wrong.
|
| 347 |
+
from transformers import AutoTokenizer
|
| 348 |
+
tokenizer = AutoTokenizer.from_pretrained(self.dir_model, trust_remote_code=True)
|
| 349 |
+
|
| 350 |
+
# Build compressed token map
|
| 351 |
+
token_map, compressed_vocab_size = _v41_build_compressed_token_map(tokenizer)
|
| 352 |
+
expected_vocab = hparams.get("engram_compressed_vocab_size")
|
| 353 |
+
if compressed_vocab_size != expected_vocab:
|
| 354 |
+
# every multiplier derives from this size, so a mismatch rehashes the whole table
|
| 355 |
+
raise ValueError(f"compressed vocab size is {compressed_vocab_size}, config says {expected_vocab}")
|
| 356 |
+
|
| 357 |
+
# Compute multipliers
|
| 358 |
+
layer_ids = tuple(engram_ids)
|
| 359 |
+
multipliers = _v41_compute_hash_multipliers(layer_ids, hparams["engram_max_ngram_size"], compressed_vocab_size)
|
| 360 |
+
|
| 361 |
+
# Compute primes and offsets. Every (n-gram size, head) pair gets its own bucket, and
|
| 362 |
+
# the search starts over at engram_vocab_size - 1 for each n-gram size, so the shared
|
| 363 |
+
# `seen` set is what keeps the buckets distinct.
|
| 364 |
+
max_ngram_size = hparams["engram_max_ngram_size"]
|
| 365 |
+
n_heads = hparams["engram_n_heads"]
|
| 366 |
+
primes_list, seen_primes = [], set()
|
| 367 |
+
|
| 368 |
+
for layer_id in layer_ids:
|
| 369 |
+
per_ngram = []
|
| 370 |
+
for ngram_idx in range(max_ngram_size - 1):
|
| 371 |
+
current_search = hparams["engram_vocab_size"] - 1
|
| 372 |
+
sizes = []
|
| 373 |
+
for head_idx in range(n_heads):
|
| 374 |
+
current_search = _v41_find_next_prime(current_search, seen_primes)
|
| 375 |
+
seen_primes.add(current_search)
|
| 376 |
+
sizes.append(current_search)
|
| 377 |
+
per_ngram.append(sizes)
|
| 378 |
+
primes_list.append(per_ngram)
|
| 379 |
+
|
| 380 |
+
# [n_engram_layers, max_ngram_size - 1, n_heads]
|
| 381 |
+
primes_array = _np.array(primes_list, dtype=_np.uint64)
|
| 382 |
+
|
| 383 |
+
# each bucket starts where the previous one ended, in that same order flattened
|
| 384 |
+
offsets_list = []
|
| 385 |
+
for layer_primes in primes_array:
|
| 386 |
+
flat_primes = layer_primes.flatten()
|
| 387 |
+
offsets = _np.cumsum(_np.concatenate(([0], flat_primes[:-1])))
|
| 388 |
+
offsets_list.append(offsets.reshape(layer_primes.shape))
|
| 389 |
+
offsets_array = _np.array(offsets_list, dtype=_np.uint64)
|
| 390 |
+
|
| 391 |
+
# Write constants to GGUF.
|
| 392 |
+
# add_array() infers the element type from the first item and maps every Python int to
|
| 393 |
+
# INT32, which would truncate the multipliers, so pass the element type explicitly and
|
| 394 |
+
# flatten by hand: a gguf array is one dimensional.
|
| 395 |
+
def add_u64(key, arr):
|
| 396 |
+
self.gguf_writer.add_key_value(
|
| 397 |
+
key,
|
| 398 |
+
[int(x) for x in _np.asarray(arr).reshape(-1)],
|
| 399 |
+
gguf.GGUFValueType.ARRAY,
|
| 400 |
+
gguf.GGUFValueType.UINT64,
|
| 401 |
+
)
|
| 402 |
+
|
| 403 |
+
add_u64(gguf.Keys.Engram.MULTIPLIERS.format(arch=arch), multipliers.numpy())
|
| 404 |
+
add_u64(gguf.Keys.Engram.PRIMES.format(arch=arch), primes_array)
|
| 405 |
+
add_u64(gguf.Keys.Engram.OFFSETS.format(arch=arch), offsets_array)
|
| 406 |
+
self.gguf_writer.add_key_value(
|
| 407 |
+
gguf.Keys.Engram.TOKEN_MAP.format(arch=arch),
|
| 408 |
+
[int(x) for x in token_map],
|
| 409 |
+
gguf.GGUFValueType.ARRAY,
|
| 410 |
+
gguf.GGUFValueType.INT32,
|
| 411 |
+
)
|
| 412 |
+
# the reference stores the padding token already mapped, so do the same here
|
| 413 |
+
self.gguf_writer.add_uint32(
|
| 414 |
+
gguf.Keys.Engram.PAD_ID.format(arch=arch),
|
| 415 |
+
int(token_map[hparams.get("engram_pad_id", 2)]),
|
| 416 |
+
)
|
| 417 |
+
logger.info("Engram constants written: multipliers %s, primes %s, offsets %s, token_map %d",
|
| 418 |
+
multipliers.shape, primes_array.shape, offsets_array.shape, len(token_map))
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
# rows per block when rewriting an engram table; 1M rows is about 1 GB of float32 scratch
|
| 422 |
+
_V41_ENGRAM_CHUNK_ROWS = 1_000_000
|
| 423 |
+
|
| 424 |
+
def _write_engram_table(self, bid: int) -> list[str]:
|
| 425 |
+
"""Quantize one engram table in row blocks, accumulating into a disk-backed memmap.
|
| 426 |
+
|
| 427 |
+
The inherited FP8 path cannot be used here. It computes weight.float() * scale over the
|
| 428 |
+
whole tensor, and one engram table is 384,006,168 x 256, so 98.3 billion elements, which
|
| 429 |
+
is 393 GB as float32. A run that reaches this tensor collapses from 118 GiB free to 13 GiB
|
| 430 |
+
and is killed. Every other tensor in the model converts normally.
|
| 431 |
+
|
| 432 |
+
The scale layout also differs from the rest of the checkpoint. Linear weights carry a
|
| 433 |
+
[rows/32, cols/32] scale matching weight_block_size [32, 32], while the engram scale is
|
| 434 |
+
[rows, 8], which is one scale per 32 columns within a single row. Broadcasting it the way
|
| 435 |
+
the generic path does would corrupt the table, so it is expanded along columns only.
|
| 436 |
+
|
| 437 |
+
Reading is done straight from the safetensors shard rather than through the lazy tensor
|
| 438 |
+
wrapper, because to_eager materializes the whole tensor before any slicing takes effect.
|
| 439 |
+
"""
|
| 440 |
+
import json as _json
|
| 441 |
+
import os as _os
|
| 442 |
+
import tempfile as _tempfile
|
| 443 |
+
|
| 444 |
+
import numpy as _np
|
| 445 |
+
from safetensors import safe_open as _safe_open
|
| 446 |
+
|
| 447 |
+
weight_name = f"layers.{bid}.engram.embed.weight"
|
| 448 |
+
scale_name = f"layers.{bid}.engram.embed.scale"
|
| 449 |
+
|
| 450 |
+
index_path = self.dir_model / "model.safetensors.index.json"
|
| 451 |
+
with open(index_path, "r", encoding="utf-8") as f:
|
| 452 |
+
weight_map = _json.load(f)["weight_map"]
|
| 453 |
+
shard = self.dir_model / weight_map[weight_name]
|
| 454 |
+
|
| 455 |
+
qtype = gguf.GGMLQuantizationType.Q8_0
|
| 456 |
+
block_elems = gguf.GGML_QUANT_SIZES[qtype][0]
|
| 457 |
+
|
| 458 |
+
with _safe_open(str(shard), framework="pt") as f:
|
| 459 |
+
wsl = f.get_slice(weight_name)
|
| 460 |
+
n_rows, n_cols = (int(x) for x in wsl.get_shape())
|
| 461 |
+
has_scale = scale_name in f.keys()
|
| 462 |
+
ssl = f.get_slice(scale_name) if has_scale else None
|
| 463 |
+
scale_groups = int(ssl.get_shape()[1]) if has_scale else 0
|
| 464 |
+
|
| 465 |
+
if n_cols % block_elems:
|
| 466 |
+
raise ValueError(
|
| 467 |
+
f"engram row width {n_cols} is not a multiple of the {qtype.name} block {block_elems}"
|
| 468 |
+
)
|
| 469 |
+
if has_scale and n_cols % scale_groups:
|
| 470 |
+
raise ValueError(
|
| 471 |
+
f"engram row width {n_cols} is not divisible by its {scale_groups} scale groups"
|
| 472 |
+
)
|
| 473 |
+
per_group = n_cols // scale_groups if has_scale else 0
|
| 474 |
+
|
| 475 |
+
row_bytes = int(gguf.quantize(_np.zeros((1, n_cols), dtype=_np.float32), qtype).nbytes)
|
| 476 |
+
rows_per_chunk = min(int(self._V41_ENGRAM_CHUNK_ROWS), n_rows)
|
| 477 |
+
n_chunks = (n_rows + rows_per_chunk - 1) // rows_per_chunk
|
| 478 |
+
|
| 479 |
+
tmp_dir = _os.environ.get("V41_ENGRAM_TMPDIR") or _tempfile.gettempdir()
|
| 480 |
+
tmp_path = _os.path.join(tmp_dir, f"engram_{bid}_{qtype.name}.bin")
|
| 481 |
+
logger.info(
|
| 482 |
+
"engram layer %d: %d x %d, scale groups %d, %s in %d blocks of %d rows, staging %.1f GB at %s",
|
| 483 |
+
bid, n_rows, n_cols, scale_groups, qtype.name, n_chunks, rows_per_chunk,
|
| 484 |
+
n_rows * row_bytes / 1e9, tmp_path,
|
| 485 |
+
)
|
| 486 |
+
|
| 487 |
+
out = _np.memmap(tmp_path, dtype=_np.uint8, mode="w+", shape=(n_rows, row_bytes))
|
| 488 |
+
for ci, start in enumerate(range(0, n_rows, rows_per_chunk)):
|
| 489 |
+
stop = min(start + rows_per_chunk, n_rows)
|
| 490 |
+
chunk = wsl[start:stop, :].float()
|
| 491 |
+
if has_scale:
|
| 492 |
+
s = self._e8m0_to_float(ssl[start:stop, :])
|
| 493 |
+
chunk = chunk * s.repeat_interleave(per_group, 1)[:, :n_cols]
|
| 494 |
+
out[start:stop] = gguf.quantize(
|
| 495 |
+
chunk.cpu().numpy().astype(_np.float32), qtype
|
| 496 |
+
).reshape(stop - start, row_bytes)
|
| 497 |
+
del chunk
|
| 498 |
+
if ci % 25 == 0:
|
| 499 |
+
logger.info(" engram layer %d: %d / %d rows", bid, stop, n_rows)
|
| 500 |
+
out.flush()
|
| 501 |
+
|
| 502 |
+
new_name = self.format_tensor_name(gguf.MODEL_TENSOR.ENGRAM_EMBD, bid, ".weight")
|
| 503 |
+
self.gguf_writer.add_tensor(new_name, out, raw_dtype=qtype)
|
| 504 |
+
logger.info("engram layer %d: wrote %s as %s", bid, new_name, qtype.name)
|
| 505 |
+
|
| 506 |
+
consumed = [weight_name]
|
| 507 |
+
if has_scale:
|
| 508 |
+
consumed.append(scale_name)
|
| 509 |
+
return consumed
|
| 510 |
+
|
| 511 |
+
def generate_extra_tensors(self):
|
| 512 |
+
yield from super().generate_extra_tensors()
|
| 513 |
+
|
| 514 |
+
consumed: list[str] = []
|
| 515 |
+
for bid in (self.hparams.get("engram_layer_ids") or []):
|
| 516 |
+
if f"layers.{bid}.engram.embed.weight" in self.model_tensors:
|
| 517 |
+
consumed.extend(self._write_engram_table(int(bid)))
|
| 518 |
+
for name in consumed:
|
| 519 |
+
if name in self.model_tensors:
|
| 520 |
+
del self.model_tensors[name]
|
| 521 |
+
|
| 522 |
+
def _map_dsv4_tensor_name(self, name: str, bid):
|
| 523 |
+
match = re.match(r"layers\\.(\\d+)\\.(.+)$", name)
|
| 524 |
+
if match is not None:
|
| 525 |
+
v41_only = {
|
| 526 |
+
"engram.embed.weight": (gguf.MODEL_TENSOR.ENGRAM_EMBD, ".weight"),
|
| 527 |
+
"engram.k_weight": (gguf.MODEL_TENSOR.ENGRAM_K, ".weight"),
|
| 528 |
+
"engram.q_weight": (gguf.MODEL_TENSOR.ENGRAM_Q, ".weight"),
|
| 529 |
+
"engram.wkv.weight": (gguf.MODEL_TENSOR.ENGRAM_WKV, ".weight"),
|
| 530 |
+
"attn.indexer.k_norm.weight": (gguf.MODEL_TENSOR.INDEXER_K_NORM, ".weight"),
|
| 531 |
+
"attn.indexer.wk.weight": (gguf.MODEL_TENSOR.INDEXER_ATTN_K, ".weight"),
|
| 532 |
+
}
|
| 533 |
+
tensor_name = match.group(2)
|
| 534 |
+
if tensor_name in v41_only:
|
| 535 |
+
return v41_only[tensor_name]
|
| 536 |
+
return super()._map_dsv4_tensor_name(name, bid)
|
| 537 |
+
'''
|
| 538 |
+
|
| 539 |
+
|
| 540 |
+
def patch_constants(path: pathlib.Path, revert: bool, check: bool) -> int:
|
| 541 |
+
text = path.read_text(encoding="utf-8")
|
| 542 |
+
backup = path.with_suffix(".py.v41orig")
|
| 543 |
+
|
| 544 |
+
if revert:
|
| 545 |
+
if backup.exists():
|
| 546 |
+
shutil.copy2(backup, path)
|
| 547 |
+
print(" reverted gguf/constants.py")
|
| 548 |
+
return 0
|
| 549 |
+
print(" no backup gguf/constants.py")
|
| 550 |
+
return 4
|
| 551 |
+
|
| 552 |
+
# Check if ALL expected changes are already present
|
| 553 |
+
if "DEEPSEEK41" in text and "PAD_ID = \"{arch}.engram.pad_id\"" in text:
|
| 554 |
+
print(" ok gguf/constants.py (already has all engram constants)")
|
| 555 |
+
return 0
|
| 556 |
+
|
| 557 |
+
anchors = (
|
| 558 |
+
CONST_TENSOR_ENUM_ANCHOR,
|
| 559 |
+
CONST_TENSOR_NAME_ANCHOR,
|
| 560 |
+
CONST_KV_ANCHOR,
|
| 561 |
+
CONST_ARCH_ENUM_ANCHOR,
|
| 562 |
+
CONST_ARCH_NAME_ANCHOR,
|
| 563 |
+
CONST_ARCH_TENSORS_ANCHOR,
|
| 564 |
+
)
|
| 565 |
+
for anchor in anchors:
|
| 566 |
+
if anchor not in text:
|
| 567 |
+
print(f" NO MATCH gguf/constants.py, missing anchor: {anchor.strip()!r}")
|
| 568 |
+
return 5
|
| 569 |
+
|
| 570 |
+
if check:
|
| 571 |
+
print(" would patch gguf/constants.py")
|
| 572 |
+
return 0
|
| 573 |
+
|
| 574 |
+
# the engram tensor enum and its names are shared, the arch entries are new
|
| 575 |
+
if "ENGRAM_EMBD" not in text:
|
| 576 |
+
text = text.replace(CONST_TENSOR_ENUM_ANCHOR, CONST_TENSOR_ENUM_NEW + CONST_TENSOR_ENUM_ANCHOR, 1)
|
| 577 |
+
text = text.replace(CONST_TENSOR_NAME_ANCHOR, CONST_TENSOR_NAME_NEW + CONST_TENSOR_NAME_ANCHOR, 1)
|
| 578 |
+
|
| 579 |
+
# Handle Engram class: either add it or add the missing KV entries
|
| 580 |
+
if "class Engram:" not in text:
|
| 581 |
+
text = text.replace(CONST_KV_ANCHOR, CONST_KV_NEW, 1)
|
| 582 |
+
else:
|
| 583 |
+
# An older run of this patcher left an Engram class with only some of the keys.
|
| 584 |
+
# Add the missing ones one at a time, so re-running never duplicates a line.
|
| 585 |
+
anchor = " MAX_NGRAM_SIZE = \"{arch}.engram.max_ngram_size\""
|
| 586 |
+
for name, key in (
|
| 587 |
+
("MULTIPLIERS ", "multipliers"),
|
| 588 |
+
("PRIMES ", "primes"),
|
| 589 |
+
("OFFSETS ", "offsets"),
|
| 590 |
+
("TOKEN_MAP ", "token_map"),
|
| 591 |
+
("PAD_ID ", "pad_id"),
|
| 592 |
+
):
|
| 593 |
+
line = " %s = \"{arch}.engram.%s\"" % (name, key)
|
| 594 |
+
if line not in text:
|
| 595 |
+
text = text.replace(anchor, anchor + "\n" + line, 1)
|
| 596 |
+
|
| 597 |
+
# Add arch enum, name, and tensor map entries (only if not already present)
|
| 598 |
+
if "DEEPSEEK41 = auto()" not in text:
|
| 599 |
+
text = text.replace(CONST_ARCH_ENUM_ANCHOR, CONST_ARCH_ENUM_NEW, 1)
|
| 600 |
+
if 'MODEL_ARCH.DEEPSEEK41:' not in text:
|
| 601 |
+
text = text.replace(CONST_ARCH_NAME_ANCHOR, CONST_ARCH_NAME_NEW, 1)
|
| 602 |
+
if "MODEL_ARCH.DEEPSEEK41: [" not in text:
|
| 603 |
+
text = text.replace(CONST_ARCH_TENSORS_ANCHOR, CONST_ARCH_TENSORS_NEW, 1)
|
| 604 |
+
|
| 605 |
+
if not backup.exists():
|
| 606 |
+
shutil.copy2(path, backup)
|
| 607 |
+
path.write_text(text, encoding="utf-8")
|
| 608 |
+
print(" patched gguf/constants.py")
|
| 609 |
+
return 0
|
| 610 |
+
|
| 611 |
+
|
| 612 |
+
def patch_init(path: pathlib.Path, revert: bool, check: bool) -> int:
|
| 613 |
+
"""conversion/__init__.py maps an architecture name to the module that implements it.
|
| 614 |
+
|
| 615 |
+
The @ModelBase.register decorator only runs once that module is imported, and the importer
|
| 616 |
+
is driven by this map, so a class registered in deepseek.py stays invisible until the
|
| 617 |
+
architecture appears here.
|
| 618 |
+
"""
|
| 619 |
+
text = path.read_text(encoding="utf-8")
|
| 620 |
+
backup = path.with_suffix(".py.v41orig")
|
| 621 |
+
key = ' "DeepseekV41ForCausalLM": "deepseek",\n'
|
| 622 |
+
anchor = ' "DeepseekV4ForCausalLM": "deepseek",\n'
|
| 623 |
+
|
| 624 |
+
if revert:
|
| 625 |
+
if backup.exists():
|
| 626 |
+
shutil.copy2(backup, path)
|
| 627 |
+
print(" reverted conversion/__init__.py")
|
| 628 |
+
return 0
|
| 629 |
+
print(" no backup conversion/__init__.py")
|
| 630 |
+
return 4
|
| 631 |
+
|
| 632 |
+
if key in text:
|
| 633 |
+
print(" ok conversion/__init__.py (already maps V4.1)")
|
| 634 |
+
return 0
|
| 635 |
+
if anchor not in text:
|
| 636 |
+
print(" NO MATCH conversion/__init__.py has no DeepseekV4ForCausalLM entry to anchor on")
|
| 637 |
+
return 5
|
| 638 |
+
if check:
|
| 639 |
+
print(" would patch conversion/__init__.py")
|
| 640 |
+
return 0
|
| 641 |
+
|
| 642 |
+
if not backup.exists():
|
| 643 |
+
shutil.copy2(path, backup)
|
| 644 |
+
path.write_text(text.replace(anchor, anchor + key, 1), encoding="utf-8")
|
| 645 |
+
print(" patched conversion/__init__.py")
|
| 646 |
+
return 0
|
| 647 |
+
|
| 648 |
+
|
| 649 |
+
def patch_deepseek(path: pathlib.Path, revert: bool, check: bool) -> int:
|
| 650 |
+
text = path.read_text(encoding="utf-8")
|
| 651 |
+
backup = path.with_suffix(".py.v41orig")
|
| 652 |
+
|
| 653 |
+
if revert:
|
| 654 |
+
if backup.exists():
|
| 655 |
+
shutil.copy2(backup, path)
|
| 656 |
+
print(" reverted conversion/deepseek.py")
|
| 657 |
+
return 0
|
| 658 |
+
print(" no backup conversion/deepseek.py")
|
| 659 |
+
return 4
|
| 660 |
+
|
| 661 |
+
if "DeepseekV41ForCausalLM" in text:
|
| 662 |
+
print(" ok conversion/deepseek.py (already registers V4.1)")
|
| 663 |
+
return 0
|
| 664 |
+
if "class DeepseekV4Model" not in text:
|
| 665 |
+
print(" NO MATCH conversion/deepseek.py has no DeepseekV4Model to subclass")
|
| 666 |
+
return 5
|
| 667 |
+
if check:
|
| 668 |
+
print(" would patch conversion/deepseek.py")
|
| 669 |
+
return 0
|
| 670 |
+
|
| 671 |
+
if not backup.exists():
|
| 672 |
+
shutil.copy2(path, backup)
|
| 673 |
+
path.write_text(text.rstrip("\n") + "\n" + V41_CLASS, encoding="utf-8")
|
| 674 |
+
print(" patched conversion/deepseek.py")
|
| 675 |
+
return 0
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
def main() -> int:
|
| 679 |
+
if len(sys.argv) < 2:
|
| 680 |
+
print(__doc__)
|
| 681 |
+
return 2
|
| 682 |
+
root = pathlib.Path(sys.argv[1])
|
| 683 |
+
revert = "--revert" in sys.argv
|
| 684 |
+
check = "--check" in sys.argv
|
| 685 |
+
|
| 686 |
+
constants = root / "gguf-py" / "gguf" / "constants.py"
|
| 687 |
+
deepseek = root / "conversion" / "deepseek.py"
|
| 688 |
+
init = root / "conversion" / "__init__.py"
|
| 689 |
+
for p in (constants, deepseek, init):
|
| 690 |
+
if not p.exists():
|
| 691 |
+
print(f" MISSING {p}")
|
| 692 |
+
return 3
|
| 693 |
+
|
| 694 |
+
rc = patch_constants(constants, revert, check)
|
| 695 |
+
rc = patch_deepseek(deepseek, revert, check) or rc
|
| 696 |
+
rc = patch_init(init, revert, check) or rc
|
| 697 |
+
return rc
|
| 698 |
+
|
| 699 |
+
|
| 700 |
+
if __name__ == "__main__":
|
| 701 |
+
sys.exit(main())
|