Text Generation
PyTorch
Safetensors
GGUF
qwen3_5_text
deltanet
cpu
efficient
low-memory
ternary
bitnet
jirack
web-ui
routing
tool-call
robotics
ollama
ternary-weights
ternary-transformer
quantization
1.58-bit
conversational
Instructions to use CMSManhattan/JiRackDeltaNet_70b 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 CMSManhattan/JiRackDeltaNet_70b 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 CMSManhattan/JiRackDeltaNet_70b:Q4_K_M # Run inference directly in the terminal: llama cli -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
Install from WinGet (Windows)
winget install llama.cpp # Start a local OpenAI-compatible server with a web UI: llama serve -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M # Run inference directly in the terminal: llama cli -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
Build from source code
git clone https://github.com/ggml-org/llama.cpp.git cd llama.cpp cmake -B build cmake --build build -j --target llama-app # Start a local OpenAI-compatible server with a web UI: ./build/bin/llama serve -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M # Run inference directly in the terminal: ./build/bin/llama cli -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
Use Docker
docker model run hf.co/CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
- Llama new
- LM Studio
- Jan
- vLLM
How to use CMSManhattan/JiRackDeltaNet_70b with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "CMSManhattan/JiRackDeltaNet_70b" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/chat/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "CMSManhattan/JiRackDeltaNet_70b", "messages": [ { "role": "user", "content": "What is the capital of France?" } ] }'Use Docker
docker model run hf.co/CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
- Ollama
How to use CMSManhattan/JiRackDeltaNet_70b with Ollama:
ollama run hf.co/CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
- Unsloth Desktop
- Pi
How to use CMSManhattan/JiRackDeltaNet_70b with Pi:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
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:9931/v1", "api": "openai-completions", "apiKey": "none", "models": [ { "id": "CMSManhattan/JiRackDeltaNet_70b:Q4_K_M" } ] } } }Run Pi
# Start Pi in your project directory: pi
- Docker Model Runner
How to use CMSManhattan/JiRackDeltaNet_70b with Docker Model Runner:
docker model run hf.co/CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
- Lemonade
How to use CMSManhattan/JiRackDeltaNet_70b with Lemonade:
Pull the model
# Download Lemonade from https://lemonade-server.ai/ lemonade pull CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
Run and chat with the model
lemonade run user.JiRackDeltaNet_70b-Q4_K_M
List all available models
lemonade list
- Hermes Agent
How to use CMSManhattan/JiRackDeltaNet_70b with Hermes Agent:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
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:9931/v1 hermes config set model.default CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
Run Hermes
hermes
- Atomic Chat
- OpenClaw
How to use CMSManhattan/JiRackDeltaNet_70b with OpenClaw:
Start the llama.cpp server
# Install llama.cpp: brew install llama.cpp # Start a local OpenAI-compatible server: llama serve -hf CMSManhattan/JiRackDeltaNet_70b:Q4_K_M
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:9931/v1 \ --custom-model-id "CMSManhattan/JiRackDeltaNet_70b:Q4_K_M" \ --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"
Commit ·
15d54ec
0
Parent(s):
JiRack DeltaNet 70B
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +42 -0
- JiRackDeltaNet_70b.py +619 -0
- LICENSE +107 -0
- LICENSE-APACHE +202 -0
- NOTICE.md +16 -0
- README.md +215 -0
- chat_jirack.py +279 -0
- chat_template.jinja +171 -0
- config.json +178 -0
- gate_logits_fp32blocks_L128.npz +3 -0
- gate_logits_fp32blocks_L8.npz +3 -0
- gguf/JiRackDeltaNet_70b_with_prompt.Q3_K_M.gguf +3 -0
- gguf/JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf +3 -0
- gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00001-of-00002.gguf +3 -0
- gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00002-of-00002.gguf +3 -0
- gguf/README.md +128 -0
- model-00001-of-00027.safetensors +3 -0
- model-00002-of-00027.safetensors +3 -0
- model-00003-of-00027.safetensors +3 -0
- model-00004-of-00027.safetensors +3 -0
- model-00005-of-00027.safetensors +3 -0
- model-00006-of-00027.safetensors +3 -0
- model-00007-of-00027.safetensors +3 -0
- model-00008-of-00027.safetensors +3 -0
- model-00009-of-00027.safetensors +3 -0
- model-00010-of-00027.safetensors +3 -0
- model-00011-of-00027.safetensors +3 -0
- model-00012-of-00027.safetensors +3 -0
- model-00013-of-00027.safetensors +3 -0
- model-00014-of-00027.safetensors +3 -0
- model-00015-of-00027.safetensors +3 -0
- model-00016-of-00027.safetensors +3 -0
- model-00017-of-00027.safetensors +3 -0
- model-00018-of-00027.safetensors +3 -0
- model-00019-of-00027.safetensors +3 -0
- model-00020-of-00027.safetensors +3 -0
- model-00021-of-00027.safetensors +3 -0
- model-00022-of-00027.safetensors +3 -0
- model-00023-of-00027.safetensors +3 -0
- model-00024-of-00027.safetensors +3 -0
- model-00025-of-00027.safetensors +3 -0
- model-00026-of-00027.safetensors +3 -0
- model-00027-of-00027.safetensors +3 -0
- model.safetensors.index.json +0 -0
- sft_final_fp8/.gitattributes +36 -0
- sft_final_fp8/JiRackDeltaNet_70b.py +619 -0
- sft_final_fp8/chat_fp8.py +69 -0
- sft_final_fp8/chat_jirack.py +279 -0
- sft_final_fp8/chat_template.jinja +171 -0
- sft_final_fp8/config.json +201 -0
.gitattributes
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
sft_final/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 37 |
+
sft_final_fp8/tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 38 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
| 39 |
+
gguf/JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf filter=lfs diff=lfs merge=lfs -text
|
| 40 |
+
gguf/JiRackDeltaNet_70b_with_prompt.Q3_K_M.gguf filter=lfs diff=lfs merge=lfs -text
|
| 41 |
+
gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00001-of-00002.gguf filter=lfs diff=lfs merge=lfs -text
|
| 42 |
+
gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00002-of-00002.gguf filter=lfs diff=lfs merge=lfs -text
|
JiRackDeltaNet_70b.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# JiRackDeltaNet_70b.py - JiRack DeltaNet 70B
|
| 3 |
+
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
|
| 4 |
+
# All rights reserved. Proprietary JiRack license, see LICENSE.
|
| 5 |
+
# =============================================================================
|
| 6 |
+
|
| 7 |
+
""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
HIDDEN_SIZE = 5120
|
| 16 |
+
VOCAB_SIZE = 248320
|
| 17 |
+
INTERMEDIATE_SIZE = 26624
|
| 18 |
+
NUM_LAYERS = 128
|
| 19 |
+
RMS_NORM_EPS = 1e-6
|
| 20 |
+
|
| 21 |
+
LAYER_TYPES = ["linear_attention"] * 3 + ["full_attention"]
|
| 22 |
+
LAYER_TYPES = (LAYER_TYPES * (NUM_LAYERS // len(LAYER_TYPES) + 1))[:NUM_LAYERS]
|
| 23 |
+
|
| 24 |
+
LINEAR_NUM_KEY_HEADS = 16
|
| 25 |
+
LINEAR_KEY_HEAD_DIM = 128
|
| 26 |
+
LINEAR_NUM_VALUE_HEADS = 48
|
| 27 |
+
LINEAR_VALUE_HEAD_DIM = 128
|
| 28 |
+
LINEAR_CONV_KERNEL_DIM = 4
|
| 29 |
+
DELTA_KEY_DIM = LINEAR_NUM_KEY_HEADS * LINEAR_KEY_HEAD_DIM
|
| 30 |
+
DELTA_VALUE_DIM = LINEAR_NUM_VALUE_HEADS * LINEAR_VALUE_HEAD_DIM
|
| 31 |
+
DELTA_CONV_DIM = DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM
|
| 32 |
+
DELTA_CHUNK_SIZE = 64
|
| 33 |
+
|
| 34 |
+
NUM_ATTENTION_HEADS = 24
|
| 35 |
+
NUM_KEY_VALUE_HEADS = 4
|
| 36 |
+
HEAD_DIM = 256
|
| 37 |
+
PARTIAL_ROTARY_FACTOR = 0.25
|
| 38 |
+
ROPE_THETA = 1e7
|
| 39 |
+
MROPE_SECTION = [11, 11, 10]
|
| 40 |
+
ATTENTION_BIAS = False
|
| 41 |
+
|
| 42 |
+
ARCH_SUMMARY = f"""
|
| 43 |
+
JiRack hybrid layout, hand-rolled JiRack TransformerBlock, text-only.
|
| 44 |
+
hidden_size={HIDDEN_SIZE}, vocab_size={VOCAB_SIZE},
|
| 45 |
+
intermediate_size={INTERMEDIATE_SIZE}, num_hidden_layers={NUM_LAYERS}
|
| 46 |
+
Interleaving (interval=4): 3x linear_attention (DeltaNet), 1x full_attention
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
KEPT_FULL_PRECISION = """
|
| 50 |
+
Always kept in full precision (not GEMMs, or too sensitive):
|
| 51 |
+
- dt_bias, A_log (raw Parameters, DeltaNet decay)
|
| 52 |
+
- linear_attn.in_proj_b/in_proj_a (by default, see GATE_PROJ_PATTERNS)
|
| 53 |
+
- conv1d (depthwise grouped conv, not a GEMM)
|
| 54 |
+
- all norms: RMSNormGated, q_norm/k_norm, model.norm
|
| 55 |
+
- embed_tokens, lm_head
|
| 56 |
+
- mtp.* (the whole MTP/NextN head) (the draft layer of speculative decoding;
|
| 57 |
+
ternarization kills the acceptance rate,
|
| 58 |
+
community GGUFs keep it in Q8_0)
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
class BitLinear(nn.Linear):
|
| 62 |
+
""
|
| 63 |
+
|
| 64 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 65 |
+
super().__init__(in_features, out_features, bias=bias)
|
| 66 |
+
self.eps = 1e-5
|
| 67 |
+
self.register_buffer("lambda_", torch.zeros(()), persistent=True)
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def from_linear(cls, lin: nn.Linear) -> "BitLinear":
|
| 71 |
+
bl = cls(lin.in_features, lin.out_features, bias=lin.bias is not None)
|
| 72 |
+
bl = bl.to(dtype=lin.weight.dtype, device=lin.weight.device)
|
| 73 |
+
with torch.no_grad():
|
| 74 |
+
bl.weight.copy_(lin.weight)
|
| 75 |
+
if lin.bias is not None:
|
| 76 |
+
bl.bias.copy_(lin.bias)
|
| 77 |
+
return bl
|
| 78 |
+
|
| 79 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 80 |
+
if not self.training and float(self.lambda_) < 1e-6:
|
| 81 |
+
return F.linear(x, self.weight, self.bias)
|
| 82 |
+
|
| 83 |
+
lam = self.lambda_.to(x.dtype)
|
| 84 |
+
w = self.weight
|
| 85 |
+
gamma = w.float().abs().mean().clamp(min=self.eps).to(w.dtype)
|
| 86 |
+
w_quant = torch.clamp(torch.round(w / gamma), -1.0, 1.0) * gamma
|
| 87 |
+
w_effective = w + lam * (w_quant - w).detach()
|
| 88 |
+
|
| 89 |
+
x_scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp(min=self.eps)
|
| 90 |
+
x_quant = torch.clamp(torch.round(x * x_scale), -128.0, 127.0) / x_scale
|
| 91 |
+
x_effective = x + lam * (x_quant - x).detach()
|
| 92 |
+
|
| 93 |
+
return F.linear(x_effective, w_effective, self.bias)
|
| 94 |
+
|
| 95 |
+
def set_lambda(self, v: float):
|
| 96 |
+
self.lambda_.fill_(v)
|
| 97 |
+
|
| 98 |
+
TERNARIZE_PATTERNS = [
|
| 99 |
+
r"linear_attn\.in_proj_qkv$",
|
| 100 |
+
r"linear_attn\.in_proj_z$",
|
| 101 |
+
r"linear_attn\.out_proj$",
|
| 102 |
+
r"self_attn\.q_proj$",
|
| 103 |
+
r"self_attn\.k_proj$",
|
| 104 |
+
r"self_attn\.v_proj$",
|
| 105 |
+
r"self_attn\.o_proj$",
|
| 106 |
+
r"mlp\.gate_proj$",
|
| 107 |
+
r"mlp\.up_proj$",
|
| 108 |
+
r"mlp\.down_proj$",
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
GATE_PROJ_PATTERNS = [
|
| 112 |
+
r"linear_attn\.in_proj_b$",
|
| 113 |
+
r"linear_attn\.in_proj_a$",
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
def apply_bitlinear_patch(model: nn.Module, include_gate_proj: bool = False):
|
| 117 |
+
""
|
| 118 |
+
patterns = list(TERNARIZE_PATTERNS)
|
| 119 |
+
if include_gate_proj:
|
| 120 |
+
patterns += GATE_PROJ_PATTERNS
|
| 121 |
+
compiled = [re.compile(p) for p in patterns]
|
| 122 |
+
|
| 123 |
+
patched = []
|
| 124 |
+
for name, module in list(model.named_modules()):
|
| 125 |
+
if not isinstance(module, nn.Linear):
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
if name.startswith("mtp"):
|
| 129 |
+
continue
|
| 130 |
+
if any(p.search(name) for p in compiled):
|
| 131 |
+
parent_name, _, child_name = name.rpartition(".")
|
| 132 |
+
parent = model.get_submodule(parent_name) if parent_name else model
|
| 133 |
+
setattr(parent, child_name, BitLinear.from_linear(module))
|
| 134 |
+
patched.append(name)
|
| 135 |
+
return patched
|
| 136 |
+
|
| 137 |
+
class RMSNorm(nn.Module):
|
| 138 |
+
""
|
| 139 |
+
|
| 140 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.eps = eps
|
| 143 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
| 144 |
+
|
| 145 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 146 |
+
dtype = x.dtype
|
| 147 |
+
x = x.float()
|
| 148 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 149 |
+
x = x * (1.0 + self.weight.float())
|
| 150 |
+
return x.to(dtype)
|
| 151 |
+
|
| 152 |
+
class RMSNormGated(nn.Module):
|
| 153 |
+
""
|
| 154 |
+
|
| 155 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 156 |
+
super().__init__()
|
| 157 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 158 |
+
self.eps = eps
|
| 159 |
+
|
| 160 |
+
def forward(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
|
| 161 |
+
dtype = x.dtype
|
| 162 |
+
x = x.float()
|
| 163 |
+
var = x.pow(2).mean(-1, keepdim=True)
|
| 164 |
+
x = x * torch.rsqrt(var + self.eps)
|
| 165 |
+
x = self.weight * x.to(dtype)
|
| 166 |
+
x = x * F.silu(gate.float())
|
| 167 |
+
return x.to(dtype)
|
| 168 |
+
|
| 169 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 170 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 171 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 172 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 173 |
+
|
| 174 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 175 |
+
""
|
| 176 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 177 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 178 |
+
rotary_dim = cos.shape[-1]
|
| 179 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 180 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 181 |
+
q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
|
| 182 |
+
k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
|
| 183 |
+
return q_embed, k_embed
|
| 184 |
+
|
| 185 |
+
class TextRotaryEmbedding(nn.Module):
|
| 186 |
+
""
|
| 187 |
+
|
| 188 |
+
def __init__(self, head_dim=HEAD_DIM, partial_rotary_factor=PARTIAL_ROTARY_FACTOR,
|
| 189 |
+
theta=ROPE_THETA, mrope_section=MROPE_SECTION):
|
| 190 |
+
super().__init__()
|
| 191 |
+
self.rotary_dim = int(head_dim * partial_rotary_factor)
|
| 192 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, self.rotary_dim, 2, dtype=torch.float32) / self.rotary_dim))
|
| 193 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 194 |
+
self.mrope_section = mrope_section
|
| 195 |
+
|
| 196 |
+
def _apply_interleaved_mrope(self, freqs: torch.Tensor) -> torch.Tensor:
|
| 197 |
+
|
| 198 |
+
freqs_t = freqs[0].clone()
|
| 199 |
+
for dim, offset in enumerate((1, 2), start=1):
|
| 200 |
+
length = self.mrope_section[dim] * 3
|
| 201 |
+
idx = slice(offset, length, 3)
|
| 202 |
+
freqs_t[..., idx] = freqs[dim, ..., idx]
|
| 203 |
+
return freqs_t
|
| 204 |
+
|
| 205 |
+
@torch.no_grad()
|
| 206 |
+
def forward(self, x: torch.Tensor, position_ids: torch.LongTensor):
|
| 207 |
+
|
| 208 |
+
if position_ids.ndim == 2:
|
| 209 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 210 |
+
inv_freq_exp = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
| 211 |
+
pos_exp = position_ids[:, :, None, :].float()
|
| 212 |
+
freqs = (inv_freq_exp @ pos_exp).transpose(2, 3)
|
| 213 |
+
freqs = self._apply_interleaved_mrope(freqs)
|
| 214 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 215 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 216 |
+
|
| 217 |
+
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6):
|
| 218 |
+
return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
| 219 |
+
|
| 220 |
+
def causal_conv1d(hidden_states: torch.Tensor, weight: torch.Tensor, activation: str = "silu"):
|
| 221 |
+
""
|
| 222 |
+
channels, seq_len = hidden_states.shape[1], hidden_states.shape[2]
|
| 223 |
+
padding = weight.shape[-1] - 1
|
| 224 |
+
out = F.conv1d(hidden_states, weight=weight.unsqueeze(1), bias=None, padding=padding, groups=channels)
|
| 225 |
+
out = out[:, :, :seq_len]
|
| 226 |
+
return F.silu(out) if activation == "silu" else out
|
| 227 |
+
|
| 228 |
+
def chunked_gated_delta_rule(query, key, value, g, beta, chunk_size=DELTA_CHUNK_SIZE):
|
| 229 |
+
""
|
| 230 |
+
initial_dtype = query.dtype
|
| 231 |
+
query = l2norm(query, dim=-1, eps=1e-6)
|
| 232 |
+
key = l2norm(key, dim=-1, eps=1e-6)
|
| 233 |
+
query, key, value, beta, g = [x.contiguous().to(torch.float32) for x in (query, key, value, beta, g)]
|
| 234 |
+
|
| 235 |
+
b, h, t, k_dim = key.shape
|
| 236 |
+
v_dim = value.shape[-1]
|
| 237 |
+
pad = (chunk_size - t % chunk_size) % chunk_size
|
| 238 |
+
query = F.pad(query, (0, 0, 0, pad))
|
| 239 |
+
key = F.pad(key, (0, 0, 0, pad))
|
| 240 |
+
value = F.pad(value, (0, 0, 0, pad))
|
| 241 |
+
beta = F.pad(beta, (0, pad))
|
| 242 |
+
g = F.pad(g, (0, pad))
|
| 243 |
+
total_t = t + pad
|
| 244 |
+
scale = 1 / (query.shape[-1] ** 0.5)
|
| 245 |
+
query = query * scale
|
| 246 |
+
|
| 247 |
+
v_beta = value * beta.unsqueeze(-1)
|
| 248 |
+
k_beta = key * beta.unsqueeze(-1)
|
| 249 |
+
query, key, value, k_beta, v_beta = [
|
| 250 |
+
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
|
| 251 |
+
]
|
| 252 |
+
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
|
| 253 |
+
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
|
| 254 |
+
|
| 255 |
+
g = g.cumsum(dim=-1)
|
| 256 |
+
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
|
| 257 |
+
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
|
| 258 |
+
for i in range(1, chunk_size):
|
| 259 |
+
row = attn[..., i, :i].clone()
|
| 260 |
+
sub = attn[..., :i, :i].clone()
|
| 261 |
+
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
|
| 262 |
+
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
|
| 263 |
+
value = attn @ v_beta
|
| 264 |
+
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
|
| 265 |
+
|
| 266 |
+
last_state = torch.zeros(b, h, k_dim, v_dim, dtype=value.dtype, device=value.device)
|
| 267 |
+
core_out = torch.zeros_like(value)
|
| 268 |
+
|
| 269 |
+
for i in range(total_t // chunk_size):
|
| 270 |
+
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
|
| 271 |
+
attn_i = q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]
|
| 272 |
+
v_prime = k_cumdecay[:, :, i] @ last_state
|
| 273 |
+
v_new = v_i - v_prime
|
| 274 |
+
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_state
|
| 275 |
+
core_out[:, :, i] = attn_inter + attn_i @ v_new
|
| 276 |
+
last_state = (
|
| 277 |
+
last_state * g[:, :, i, -1, None, None].exp()
|
| 278 |
+
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
core_out = core_out.reshape(core_out.shape[0], core_out.shape[1], -1, core_out.shape[-1])
|
| 282 |
+
core_out = core_out[:, :, :t]
|
| 283 |
+
core_out = core_out.transpose(1, 2).contiguous().to(initial_dtype)
|
| 284 |
+
return core_out
|
| 285 |
+
|
| 286 |
+
class GatedDeltaNetBlock(nn.Module):
|
| 287 |
+
""
|
| 288 |
+
|
| 289 |
+
def __init__(self):
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.conv1d = nn.Conv1d(
|
| 292 |
+
in_channels=DELTA_CONV_DIM, out_channels=DELTA_CONV_DIM, bias=False,
|
| 293 |
+
kernel_size=LINEAR_CONV_KERNEL_DIM, groups=DELTA_CONV_DIM,
|
| 294 |
+
padding=LINEAR_CONV_KERNEL_DIM - 1,
|
| 295 |
+
)
|
| 296 |
+
self.dt_bias = nn.Parameter(torch.ones(LINEAR_NUM_VALUE_HEADS))
|
| 297 |
+
A = torch.empty(LINEAR_NUM_VALUE_HEADS).uniform_(0.01, 16)
|
| 298 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 299 |
+
self.norm = RMSNormGated(LINEAR_VALUE_HEAD_DIM, eps=RMS_NORM_EPS)
|
| 300 |
+
self.out_proj = nn.Linear(DELTA_VALUE_DIM, HIDDEN_SIZE, bias=False)
|
| 301 |
+
self.in_proj_qkv = nn.Linear(HIDDEN_SIZE, DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM, bias=False)
|
| 302 |
+
self.in_proj_z = nn.Linear(HIDDEN_SIZE, DELTA_VALUE_DIM, bias=False)
|
| 303 |
+
self.in_proj_b = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 304 |
+
self.in_proj_a = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 305 |
+
|
| 306 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 307 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 308 |
+
|
| 309 |
+
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
|
| 310 |
+
z = self.in_proj_z(hidden_states).reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 311 |
+
b = self.in_proj_b(hidden_states)
|
| 312 |
+
a = self.in_proj_a(hidden_states)
|
| 313 |
+
|
| 314 |
+
mixed_qkv = causal_conv1d(mixed_qkv, self.conv1d.weight.squeeze(1), activation="silu")
|
| 315 |
+
mixed_qkv = mixed_qkv.transpose(1, 2)
|
| 316 |
+
|
| 317 |
+
query, key, value = torch.split(mixed_qkv, [DELTA_KEY_DIM, DELTA_KEY_DIM, DELTA_VALUE_DIM], dim=-1)
|
| 318 |
+
query = query.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 319 |
+
key = key.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 320 |
+
value = value.reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 321 |
+
|
| 322 |
+
beta = b.sigmoid()
|
| 323 |
+
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
| 324 |
+
|
| 325 |
+
rep = LINEAR_NUM_VALUE_HEADS // LINEAR_NUM_KEY_HEADS
|
| 326 |
+
if rep > 1:
|
| 327 |
+
query = query.repeat_interleave(rep, dim=2)
|
| 328 |
+
key = key.repeat_interleave(rep, dim=2)
|
| 329 |
+
|
| 330 |
+
query_h = query.transpose(1, 2)
|
| 331 |
+
key_h = key.transpose(1, 2)
|
| 332 |
+
value_h = value.transpose(1, 2)
|
| 333 |
+
beta_h = beta.transpose(1, 2)
|
| 334 |
+
g_h = g.transpose(1, 2)
|
| 335 |
+
|
| 336 |
+
core_attn_out = chunked_gated_delta_rule(query_h, key_h, value_h, g_h, beta_h)
|
| 337 |
+
|
| 338 |
+
core_attn_out = core_attn_out.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 339 |
+
z_flat = z.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 340 |
+
core_attn_out = self.norm(core_attn_out, z_flat)
|
| 341 |
+
core_attn_out = core_attn_out.reshape(bsz, seq_len, -1)
|
| 342 |
+
|
| 343 |
+
return self.out_proj(core_attn_out)
|
| 344 |
+
|
| 345 |
+
class AttentionBlock(nn.Module):
|
| 346 |
+
""
|
| 347 |
+
|
| 348 |
+
def __init__(self):
|
| 349 |
+
super().__init__()
|
| 350 |
+
self.num_key_value_groups = NUM_ATTENTION_HEADS // NUM_KEY_VALUE_HEADS
|
| 351 |
+
self.scaling = HEAD_DIM ** -0.5
|
| 352 |
+
self.q_proj = nn.Linear(HIDDEN_SIZE, NUM_ATTENTION_HEADS * HEAD_DIM * 2, bias=ATTENTION_BIAS)
|
| 353 |
+
self.k_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 354 |
+
self.v_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 355 |
+
self.o_proj = nn.Linear(NUM_ATTENTION_HEADS * HEAD_DIM, HIDDEN_SIZE, bias=ATTENTION_BIAS)
|
| 356 |
+
self.q_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 357 |
+
self.k_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 358 |
+
|
| 359 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 360 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 361 |
+
hidden_shape = (bsz, seq_len, -1, HEAD_DIM)
|
| 362 |
+
|
| 363 |
+
query_states, gate = torch.chunk(
|
| 364 |
+
self.q_proj(hidden_states).view(bsz, seq_len, -1, HEAD_DIM * 2), 2, dim=-1
|
| 365 |
+
)
|
| 366 |
+
gate = gate.reshape(bsz, seq_len, -1)
|
| 367 |
+
|
| 368 |
+
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
|
| 369 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 370 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 371 |
+
|
| 372 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 373 |
+
|
| 374 |
+
rep = self.num_key_value_groups
|
| 375 |
+
key_states = key_states.repeat_interleave(rep, dim=1)
|
| 376 |
+
value_states = value_states.repeat_interleave(rep, dim=1)
|
| 377 |
+
|
| 378 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
|
| 379 |
+
attn_weights = attn_weights + causal_mask
|
| 380 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 381 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 382 |
+
attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1)
|
| 383 |
+
attn_output = attn_output * torch.sigmoid(gate)
|
| 384 |
+
|
| 385 |
+
return self.o_proj(attn_output)
|
| 386 |
+
|
| 387 |
+
class MLPBlock(nn.Module):
|
| 388 |
+
def __init__(self):
|
| 389 |
+
super().__init__()
|
| 390 |
+
self.gate_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 391 |
+
self.up_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 392 |
+
self.down_proj = nn.Linear(INTERMEDIATE_SIZE, HIDDEN_SIZE, bias=False)
|
| 393 |
+
|
| 394 |
+
def forward(self, x):
|
| 395 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 396 |
+
|
| 397 |
+
class TransformerBlock(nn.Module):
|
| 398 |
+
""
|
| 399 |
+
|
| 400 |
+
def __init__(self, layer_idx: int, layer_type: str = None):
|
| 401 |
+
super().__init__()
|
| 402 |
+
|
| 403 |
+
self.block_type = layer_type if layer_type is not None else LAYER_TYPES[layer_idx]
|
| 404 |
+
if self.block_type == "linear_attention":
|
| 405 |
+
self.linear_attn = GatedDeltaNetBlock()
|
| 406 |
+
else:
|
| 407 |
+
self.self_attn = AttentionBlock()
|
| 408 |
+
self.mlp = MLPBlock()
|
| 409 |
+
self.input_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 410 |
+
self.post_attention_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 411 |
+
|
| 412 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 413 |
+
residual = hidden_states
|
| 414 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 415 |
+
if self.block_type == "linear_attention":
|
| 416 |
+
hidden_states = self.linear_attn(hidden_states)
|
| 417 |
+
else:
|
| 418 |
+
hidden_states = self.self_attn(hidden_states, cos, sin, causal_mask)
|
| 419 |
+
hidden_states = residual + hidden_states
|
| 420 |
+
|
| 421 |
+
residual = hidden_states
|
| 422 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 423 |
+
hidden_states = self.mlp(hidden_states)
|
| 424 |
+
hidden_states = residual + hidden_states
|
| 425 |
+
return hidden_states
|
| 426 |
+
|
| 427 |
+
class MTPBlock(nn.Module):
|
| 428 |
+
""
|
| 429 |
+
|
| 430 |
+
def __init__(self):
|
| 431 |
+
super().__init__()
|
| 432 |
+
self.pre_fc_norm_embedding = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 433 |
+
self.pre_fc_norm_hidden = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 434 |
+
self.fc = nn.Linear(2 * HIDDEN_SIZE, HIDDEN_SIZE, bias=False)
|
| 435 |
+
self.layers = nn.ModuleList([
|
| 436 |
+
TransformerBlock(layer_idx=NUM_LAYERS, layer_type="full_attention"),
|
| 437 |
+
])
|
| 438 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 439 |
+
|
| 440 |
+
def forward(self, inputs_embeds, previous_hidden, cos, sin, causal_mask):
|
| 441 |
+
""
|
| 442 |
+
h = self.fc(torch.cat(
|
| 443 |
+
(self.pre_fc_norm_embedding(inputs_embeds),
|
| 444 |
+
self.pre_fc_norm_hidden(previous_hidden)),
|
| 445 |
+
dim=-1,
|
| 446 |
+
))
|
| 447 |
+
h = self.layers[0](h, cos, sin, causal_mask)
|
| 448 |
+
return self.norm(h)
|
| 449 |
+
|
| 450 |
+
class JiRackDeltaNetModel(nn.Module):
|
| 451 |
+
def __init__(self):
|
| 452 |
+
super().__init__()
|
| 453 |
+
self.embed_tokens = nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
|
| 454 |
+
self.layers = nn.ModuleList([TransformerBlock(i) for i in range(NUM_LAYERS)])
|
| 455 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 456 |
+
self.rotary_emb = TextRotaryEmbedding()
|
| 457 |
+
|
| 458 |
+
def forward(self, input_ids: torch.LongTensor, return_prenorm: bool = False):
|
| 459 |
+
bsz, seq_len = input_ids.shape
|
| 460 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 461 |
+
|
| 462 |
+
position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(bsz, -1)
|
| 463 |
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
| 464 |
+
|
| 465 |
+
causal_mask = torch.full((seq_len, seq_len), float("-inf"), device=input_ids.device, dtype=torch.float32)
|
| 466 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)[None, None, :, :].to(hidden_states.dtype)
|
| 467 |
+
|
| 468 |
+
for layer in self.layers:
|
| 469 |
+
hidden_states = layer(hidden_states, cos, sin, causal_mask)
|
| 470 |
+
|
| 471 |
+
if return_prenorm:
|
| 472 |
+
|
| 473 |
+
return self.norm(hidden_states), hidden_states, (cos, sin, causal_mask)
|
| 474 |
+
return self.norm(hidden_states)
|
| 475 |
+
|
| 476 |
+
class JiRackDeltaNetForCausalLM(nn.Module):
|
| 477 |
+
""
|
| 478 |
+
|
| 479 |
+
def __init__(self):
|
| 480 |
+
super().__init__()
|
| 481 |
+
self.model = JiRackDeltaNetModel()
|
| 482 |
+
self.lm_head = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False)
|
| 483 |
+
|
| 484 |
+
self.mtp = MTPBlock()
|
| 485 |
+
|
| 486 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
|
| 487 |
+
hidden_states = self.model(input_ids)
|
| 488 |
+
return self.lm_head(hidden_states)
|
| 489 |
+
|
| 490 |
+
def mtp_forward(self, input_ids: torch.LongTensor):
|
| 491 |
+
""
|
| 492 |
+
_, prenorm_hidden, (cos, sin, causal_mask) = self.model(
|
| 493 |
+
input_ids, return_prenorm=True)
|
| 494 |
+
logits_t1 = self.lm_head(self.model.norm(prenorm_hidden))
|
| 495 |
+
|
| 496 |
+
shifted = torch.cat([input_ids[:, 1:], input_ids[:, -1:]], dim=1)
|
| 497 |
+
emb_next = self.model.embed_tokens(shifted)
|
| 498 |
+
h2 = self.mtp(emb_next, prenorm_hidden, cos, sin, causal_mask)
|
| 499 |
+
logits_t2 = self.lm_head(h2)
|
| 500 |
+
return logits_t1, logits_t2
|
| 501 |
+
|
| 502 |
+
def load_hf_state_dict(self, state_dict: dict, strict: bool = False):
|
| 503 |
+
""
|
| 504 |
+
missing, unexpected = self.load_state_dict(state_dict, strict=strict)
|
| 505 |
+
real_missing = [k for k in missing if not k.endswith("lambda_")]
|
| 506 |
+
if real_missing:
|
| 507 |
+
print(f"⚠️ {len(real_missing)} missing keys (first 10): {real_missing[:10]}")
|
| 508 |
+
if unexpected:
|
| 509 |
+
print(f"⚠️ {len(unexpected)} unexpected keys (first 10): {unexpected[:10]}")
|
| 510 |
+
return missing, unexpected
|
| 511 |
+
|
| 512 |
+
def load_mtp_from_hf_dir(self, hf_dir: str):
|
| 513 |
+
""
|
| 514 |
+
import glob
|
| 515 |
+
import json as _json
|
| 516 |
+
from safetensors import safe_open
|
| 517 |
+
|
| 518 |
+
index_path = os.path.join(hf_dir, "model.safetensors.index.json")
|
| 519 |
+
mtp_map = {}
|
| 520 |
+
if os.path.exists(index_path):
|
| 521 |
+
with open(index_path) as f:
|
| 522 |
+
weight_map = _json.load(f)["weight_map"]
|
| 523 |
+
for k, shard in weight_map.items():
|
| 524 |
+
if k.startswith("mtp."):
|
| 525 |
+
mtp_map[k] = os.path.join(hf_dir, shard)
|
| 526 |
+
else:
|
| 527 |
+
for shard in glob.glob(os.path.join(hf_dir, "*.safetensors")):
|
| 528 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 529 |
+
for k in f.keys():
|
| 530 |
+
if k.startswith("mtp."):
|
| 531 |
+
mtp_map[k] = shard
|
| 532 |
+
|
| 533 |
+
if not mtp_map:
|
| 534 |
+
raise FileNotFoundError(
|
| 535 |
+
f"In {hf_dir}: no mtp.* tensor found. Needed: "
|
| 536 |
+
f"the source HF checkpoint (not a JiRack export!). "
|
| 537 |
+
f"If the source shards were deleted, download again from the HF Hub "
|
| 538 |
+
f"only the shards with mtp.* listed in model.safetensors.index.json.")
|
| 539 |
+
|
| 540 |
+
own_dtype = next(self.mtp.parameters()).dtype
|
| 541 |
+
loaded = {}
|
| 542 |
+
by_shard = {}
|
| 543 |
+
for k, shard in mtp_map.items():
|
| 544 |
+
by_shard.setdefault(shard, []).append(k)
|
| 545 |
+
for shard, keys in by_shard.items():
|
| 546 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 547 |
+
for k in keys:
|
| 548 |
+
loaded[k] = f.get_tensor(k).to(own_dtype)
|
| 549 |
+
|
| 550 |
+
missing, unexpected = self.load_state_dict(loaded, strict=False)
|
| 551 |
+
n_ok = len(loaded)
|
| 552 |
+
print(f"✅ MTP: loaded {n_ok} tensors from {len(by_shard)} shards ({hf_dir})")
|
| 553 |
+
if unexpected:
|
| 554 |
+
print(f"⚠️ MTP: unexpected keys: {unexpected[:10]}")
|
| 555 |
+
return n_ok
|
| 556 |
+
|
| 557 |
+
def save_checkpoint(self, path: str, lam: float, global_step: int = 0, patched_linear_names=None):
|
| 558 |
+
torch.save({
|
| 559 |
+
"model": self.state_dict(),
|
| 560 |
+
"lambda": lam,
|
| 561 |
+
"global_step": global_step,
|
| 562 |
+
"patched_linear_names": patched_linear_names or [],
|
| 563 |
+
}, path)
|
| 564 |
+
|
| 565 |
+
@classmethod
|
| 566 |
+
def load_checkpoint(cls, path: str, dtype=torch.bfloat16, include_gate_proj: bool = False):
|
| 567 |
+
ckpt = torch.load(path, map_location="cpu", weights_only=False)
|
| 568 |
+
model = cls()
|
| 569 |
+
patched_names = ckpt.get("patched_linear_names", [])
|
| 570 |
+
if patched_names:
|
| 571 |
+
for name in patched_names:
|
| 572 |
+
*parent_path, leaf = name.split(".")
|
| 573 |
+
parent = model
|
| 574 |
+
for p in parent_path:
|
| 575 |
+
parent = getattr(parent, p)
|
| 576 |
+
old = getattr(parent, leaf)
|
| 577 |
+
if not isinstance(old, BitLinear):
|
| 578 |
+
setattr(parent, leaf, BitLinear.from_linear(old))
|
| 579 |
+
else:
|
| 580 |
+
apply_bitlinear_patch(model, include_gate_proj=include_gate_proj)
|
| 581 |
+
|
| 582 |
+
has_mtp_in_ckpt = any(k.startswith("mtp.") for k in ckpt["model"])
|
| 583 |
+
model.load_state_dict(ckpt["model"], strict=False)
|
| 584 |
+
model = model.to(dtype)
|
| 585 |
+
|
| 586 |
+
if not has_mtp_in_ckpt:
|
| 587 |
+
print(
|
| 588 |
+
"⚠️ This .pt has NO mtp.* weights (the checkpoint was saved before "
|
| 589 |
+
"MTPBlock existed). The head is now RANDOMLY "
|
| 590 |
+
"initialized! Before exporting, be sure to call "
|
| 591 |
+
"model.load_mtp_from_hf_dir('<folder of the source HF checkpoint>')."
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
lam = ckpt.get("lambda", 0.0)
|
| 595 |
+
for m in model.modules():
|
| 596 |
+
if isinstance(m, BitLinear):
|
| 597 |
+
m.set_lambda(lam)
|
| 598 |
+
|
| 599 |
+
print(f"✅ Loaded. global_step={ckpt.get('global_step', 0)}, lambda={lam}")
|
| 600 |
+
return model
|
| 601 |
+
|
| 602 |
+
if __name__ == "__main__":
|
| 603 |
+
print(ARCH_SUMMARY)
|
| 604 |
+
print(KEPT_FULL_PRECISION)
|
| 605 |
+
|
| 606 |
+
model = JiRackDeltaNetForCausalLM()
|
| 607 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 608 |
+
print(f"✅ Model built (random weights). Parameters: {n_params / 1e9:.2f}B")
|
| 609 |
+
|
| 610 |
+
patched = apply_bitlinear_patch(model)
|
| 611 |
+
print(f"✅ Submodules replaced by BitLinear: {len(patched)}")
|
| 612 |
+
print("First 10 examples:")
|
| 613 |
+
for n in patched[:10]:
|
| 614 |
+
print(f" {n}")
|
| 615 |
+
|
| 616 |
+
ids = torch.randint(0, VOCAB_SIZE, (1, 8))
|
| 617 |
+
with torch.no_grad():
|
| 618 |
+
logits = model(ids)
|
| 619 |
+
print(f"✅ Test forward (random weights) -> logits shape: {tuple(logits.shape)}")
|
LICENSE
ADDED
|
@@ -0,0 +1,107 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
JiRack Proprietary Model License
|
| 2 |
+
Copyright (c) 2026 Konstantin Grabko, d/b/a CMS Manhattan. All rights reserved.
|
| 3 |
+
|
| 4 |
+
This License governs access to and use of the Software. By downloading,
|
| 5 |
+
installing, copying, or otherwise using the Software, you agree to these terms.
|
| 6 |
+
If you do not agree, do not download or use the Software.
|
| 7 |
+
|
| 8 |
+
1. Definitions
|
| 9 |
+
"Licensor" means Konstantin Grabko, doing business as CMS Manhattan, New York, NY, USA.
|
| 10 |
+
"Software" means JiRack, including model weights, source code, scripts, configuration
|
| 11 |
+
files, and documentation, together with all modifications, derivative works, and
|
| 12 |
+
fine-tuned versions, whether created by the Licensor or by any other person,
|
| 13 |
+
excluding the Base Model Components described in Section 2.4.
|
| 14 |
+
"Non-Commercial User" means (a) an individual using the Software for personal,
|
| 15 |
+
non-commercial purposes, or (b) an accredited academic institution or a non-profit
|
| 16 |
+
organization using the Software solely for research, education, or evaluation.
|
| 17 |
+
"Company" means any corporation, partnership, government body, or other organization
|
| 18 |
+
that is not a Non-Commercial User.
|
| 19 |
+
"Commercial Use" means any use of the Software by or on behalf of a Company,
|
| 20 |
+
including internal use, testing, development, production use, integration into
|
| 21 |
+
products or services, hosting, or access through an API or cloud service, whether
|
| 22 |
+
or not a fee is charged.
|
| 23 |
+
"Integrator" means any person that embeds the Software into a product or service
|
| 24 |
+
intended for third parties.
|
| 25 |
+
"Reseller" means any person that sells, leases, sublicenses, or otherwise makes the
|
| 26 |
+
Software available to third parties.
|
| 27 |
+
"Commercial Agreement" means a separate written agreement signed by the Licensor and
|
| 28 |
+
a licensee that permits Commercial Use.
|
| 29 |
+
"Authorized Territory" means worldwide, excluding jurisdictions subject to
|
| 30 |
+
comprehensive U.S. sanctions.
|
| 31 |
+
|
| 32 |
+
2. Ownership and Reservation of Rights
|
| 33 |
+
2.1. The Licensor owns all right, title, and interest in the Software, including the
|
| 34 |
+
Licensor's modifications, architecture changes, training, and resulting model weights.
|
| 35 |
+
2.2. This License grants only the limited rights expressly set out below. No
|
| 36 |
+
ownership interest is transferred.
|
| 37 |
+
2.3. All rights not expressly granted are reserved by the Licensor.
|
| 38 |
+
2.4. Base Model Components. The Software is a derivative work of a Qwen model
|
| 39 |
+
released under the Apache License, Version 2.0. Components originating from that
|
| 40 |
+
base model remain subject to the Apache License 2.0. See LICENSE-APACHE and NOTICE.md.
|
| 41 |
+
Nothing in this License restricts any right granted to you by the Apache License 2.0
|
| 42 |
+
with respect to those components.
|
| 43 |
+
|
| 44 |
+
3. Free Non-Commercial License
|
| 45 |
+
3.1. The Licensor grants each Non-Commercial User a free, non-exclusive,
|
| 46 |
+
non-transferable, revocable license to download, install, use, and modify the
|
| 47 |
+
Software solely for non-commercial research, education, evaluation, and personal use.
|
| 48 |
+
3.2. A Non-Commercial User may publish research results, benchmarks, and papers
|
| 49 |
+
based on the Software, provided the Software is credited as "JiRack by CMS Manhattan".
|
| 50 |
+
3.3. A Non-Commercial User may not distribute the Software or modified versions of it
|
| 51 |
+
without the Licensor's prior written consent.
|
| 52 |
+
3.4. All copies must retain copyright notices and the terms of this License.
|
| 53 |
+
|
| 54 |
+
4. Commercial Use
|
| 55 |
+
4.1. Any Commercial Use, including internal use within a Company, requires a signed
|
| 56 |
+
Commercial Agreement and payment of the applicable fees.
|
| 57 |
+
4.2. An Integrator may not embed the Software into any product or service without a
|
| 58 |
+
Commercial Agreement.
|
| 59 |
+
4.3. A Reseller may not make the Software available to third parties without the
|
| 60 |
+
Licensor's prior written consent.
|
| 61 |
+
4.4. No person may provide access to the Software through an API, cloud service, or
|
| 62 |
+
hosting unless a Commercial Agreement expressly grants that right.
|
| 63 |
+
4.5. Upon written request, a commercial licensee must provide information reasonably
|
| 64 |
+
necessary to verify compliance with this License.
|
| 65 |
+
4.6. Circumventing technical protection measures, license keys, or usage tracking
|
| 66 |
+
is prohibited.
|
| 67 |
+
|
| 68 |
+
5. Commercial Agreements
|
| 69 |
+
5.1. A Commercial Agreement must be in writing and signed by both parties, and shall
|
| 70 |
+
specify the scope of rights, term, territory, and fees.
|
| 71 |
+
5.2. The Licensor may offer different terms to different licensees.
|
| 72 |
+
|
| 73 |
+
6. Termination
|
| 74 |
+
6.1. This License terminates automatically if a licensee breaches any of its terms
|
| 75 |
+
and fails to cure the breach within thirty (30) days after written notice.
|
| 76 |
+
6.2. Upon termination, the licensee must stop using the Software and delete all copies.
|
| 77 |
+
6.3. Sections 2, 4.5, 4.6, 6.2, 7, 8, and 9 survive termination.
|
| 78 |
+
|
| 79 |
+
7. Disclaimer of Warranties
|
| 80 |
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
|
| 81 |
+
INCLUDING WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND
|
| 82 |
+
NON-INFRINGEMENT. THE LICENSOR DOES NOT WARRANT THAT OUTPUTS WILL BE ACCURATE OR
|
| 83 |
+
COMPLETE.
|
| 84 |
+
|
| 85 |
+
8. Limitation of Liability
|
| 86 |
+
TO THE MAXIMUM EXTENT PERMITTED BY LAW, THE LICENSOR SHALL NOT BE LIABLE FOR ANY
|
| 87 |
+
INDIRECT, INCIDENTAL, SPECIAL, PUNITIVE, OR CONSEQUENTIAL DAMAGES. THE LICENSOR'S
|
| 88 |
+
AGGREGATE LIABILITY SHALL NOT EXCEED THE AMOUNTS PAID TO THE LICENSOR BY THE
|
| 89 |
+
RELEVANT PERSON DURING THE TWELVE (12) MONTHS PRECEDING THE CLAIM.
|
| 90 |
+
|
| 91 |
+
9. General
|
| 92 |
+
9.1. Governing Law: This License is governed by the laws of the State of New York,
|
| 93 |
+
without regard to its conflict-of-laws principles.
|
| 94 |
+
9.2. Venue: Disputes shall be brought exclusively in the state or federal courts
|
| 95 |
+
located in New York County, New York.
|
| 96 |
+
9.3. Entire Agreement: This License, together with any Commercial Agreement,
|
| 97 |
+
constitutes the entire agreement regarding the Software.
|
| 98 |
+
9.4. Severability: If any provision is held unenforceable, the remaining provisions
|
| 99 |
+
remain in effect.
|
| 100 |
+
9.5. No Waiver: Failure to enforce a provision is not a waiver of it.
|
| 101 |
+
9.6. Export: No person may use or export the Software in violation of export control
|
| 102 |
+
or sanctions laws.
|
| 103 |
+
|
| 104 |
+
Contact & Licensing
|
| 105 |
+
Email: grabko@cmsmanhattan.com
|
| 106 |
+
Phone: +1 (516) 777-0945
|
| 107 |
+
Location: New York, USA
|
LICENSE-APACHE
ADDED
|
@@ -0,0 +1,202 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
|
| 2 |
+
Apache License
|
| 3 |
+
Version 2.0, January 2004
|
| 4 |
+
http://www.apache.org/licenses/
|
| 5 |
+
|
| 6 |
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
| 7 |
+
|
| 8 |
+
1. Definitions.
|
| 9 |
+
|
| 10 |
+
"License" shall mean the terms and conditions for use, reproduction,
|
| 11 |
+
and distribution as defined by Sections 1 through 9 of this document.
|
| 12 |
+
|
| 13 |
+
"Licensor" shall mean the copyright owner or entity authorized by
|
| 14 |
+
the copyright owner that is granting the License.
|
| 15 |
+
|
| 16 |
+
"Legal Entity" shall mean the union of the acting entity and all
|
| 17 |
+
other entities that control, are controlled by, or are under common
|
| 18 |
+
control with that entity. For the purposes of this definition,
|
| 19 |
+
"control" means (i) the power, direct or indirect, to cause the
|
| 20 |
+
direction or management of such entity, whether by contract or
|
| 21 |
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
| 22 |
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
| 23 |
+
|
| 24 |
+
"You" (or "Your") shall mean an individual or Legal Entity
|
| 25 |
+
exercising permissions granted by this License.
|
| 26 |
+
|
| 27 |
+
"Source" form shall mean the preferred form for making modifications,
|
| 28 |
+
including but not limited to software source code, documentation
|
| 29 |
+
source, and configuration files.
|
| 30 |
+
|
| 31 |
+
"Object" form shall mean any form resulting from mechanical
|
| 32 |
+
transformation or translation of a Source form, including but
|
| 33 |
+
not limited to compiled object code, generated documentation,
|
| 34 |
+
and conversions to other media types.
|
| 35 |
+
|
| 36 |
+
"Work" shall mean the work of authorship, whether in Source or
|
| 37 |
+
Object form, made available under the License, as indicated by a
|
| 38 |
+
copyright notice that is included in or attached to the work
|
| 39 |
+
(an example is provided in the Appendix below).
|
| 40 |
+
|
| 41 |
+
"Derivative Works" shall mean any work, whether in Source or Object
|
| 42 |
+
form, that is based on (or derived from) the Work and for which the
|
| 43 |
+
editorial revisions, annotations, elaborations, or other modifications
|
| 44 |
+
represent, as a whole, an original work of authorship. For the purposes
|
| 45 |
+
of this License, Derivative Works shall not include works that remain
|
| 46 |
+
separable from, or merely link (or bind by name) to the interfaces of,
|
| 47 |
+
the Work and Derivative Works thereof.
|
| 48 |
+
|
| 49 |
+
"Contribution" shall mean any work of authorship, including
|
| 50 |
+
the original version of the Work and any modifications or additions
|
| 51 |
+
to that Work or Derivative Works thereof, that is intentionally
|
| 52 |
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
| 53 |
+
or by an individual or Legal Entity authorized to submit on behalf of
|
| 54 |
+
the copyright owner. For the purposes of this definition, "submitted"
|
| 55 |
+
means any form of electronic, verbal, or written communication sent
|
| 56 |
+
to the Licensor or its representatives, including but not limited to
|
| 57 |
+
communication on electronic mailing lists, source code control systems,
|
| 58 |
+
and issue tracking systems that are managed by, or on behalf of, the
|
| 59 |
+
Licensor for the purpose of discussing and improving the Work, but
|
| 60 |
+
excluding communication that is conspicuously marked or otherwise
|
| 61 |
+
designated in writing by the copyright owner as "Not a Contribution."
|
| 62 |
+
|
| 63 |
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
| 64 |
+
on behalf of whom a Contribution has been received by Licensor and
|
| 65 |
+
subsequently incorporated within the Work.
|
| 66 |
+
|
| 67 |
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
| 68 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 69 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 70 |
+
copyright license to reproduce, prepare Derivative Works of,
|
| 71 |
+
publicly display, publicly perform, sublicense, and distribute the
|
| 72 |
+
Work and such Derivative Works in Source or Object form.
|
| 73 |
+
|
| 74 |
+
3. Grant of Patent License. Subject to the terms and conditions of
|
| 75 |
+
this License, each Contributor hereby grants to You a perpetual,
|
| 76 |
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
| 77 |
+
(except as stated in this section) patent license to make, have made,
|
| 78 |
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
| 79 |
+
where such license applies only to those patent claims licensable
|
| 80 |
+
by such Contributor that are necessarily infringed by their
|
| 81 |
+
Contribution(s) alone or by combination of their Contribution(s)
|
| 82 |
+
with the Work to which such Contribution(s) was submitted. If You
|
| 83 |
+
institute patent litigation against any entity (including a
|
| 84 |
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
| 85 |
+
or a Contribution incorporated within the Work constitutes direct
|
| 86 |
+
or contributory patent infringement, then any patent licenses
|
| 87 |
+
granted to You under this License for that Work shall terminate
|
| 88 |
+
as of the date such litigation is filed.
|
| 89 |
+
|
| 90 |
+
4. Redistribution. You may reproduce and distribute copies of the
|
| 91 |
+
Work or Derivative Works thereof in any medium, with or without
|
| 92 |
+
modifications, and in Source or Object form, provided that You
|
| 93 |
+
meet the following conditions:
|
| 94 |
+
|
| 95 |
+
(a) You must give any other recipients of the Work or
|
| 96 |
+
Derivative Works a copy of this License; and
|
| 97 |
+
|
| 98 |
+
(b) You must cause any modified files to carry prominent notices
|
| 99 |
+
stating that You changed the files; and
|
| 100 |
+
|
| 101 |
+
(c) You must retain, in the Source form of any Derivative Works
|
| 102 |
+
that You distribute, all copyright, patent, trademark, and
|
| 103 |
+
attribution notices from the Source form of the Work,
|
| 104 |
+
excluding those notices that do not pertain to any part of
|
| 105 |
+
the Derivative Works; and
|
| 106 |
+
|
| 107 |
+
(d) If the Work includes a "NOTICE" text file as part of its
|
| 108 |
+
distribution, then any Derivative Works that You distribute must
|
| 109 |
+
include a readable copy of the attribution notices contained
|
| 110 |
+
within such NOTICE file, excluding those notices that do not
|
| 111 |
+
pertain to any part of the Derivative Works, in at least one
|
| 112 |
+
of the following places: within a NOTICE text file distributed
|
| 113 |
+
as part of the Derivative Works; within the Source form or
|
| 114 |
+
documentation, if provided along with the Derivative Works; or,
|
| 115 |
+
within a display generated by the Derivative Works, if and
|
| 116 |
+
wherever such third-party notices normally appear. The contents
|
| 117 |
+
of the NOTICE file are for informational purposes only and
|
| 118 |
+
do not modify the License. You may add Your own attribution
|
| 119 |
+
notices within Derivative Works that You distribute, alongside
|
| 120 |
+
or as an addendum to the NOTICE text from the Work, provided
|
| 121 |
+
that such additional attribution notices cannot be construed
|
| 122 |
+
as modifying the License.
|
| 123 |
+
|
| 124 |
+
You may add Your own copyright statement to Your modifications and
|
| 125 |
+
may provide additional or different license terms and conditions
|
| 126 |
+
for use, reproduction, or distribution of Your modifications, or
|
| 127 |
+
for any such Derivative Works as a whole, provided Your use,
|
| 128 |
+
reproduction, and distribution of the Work otherwise complies with
|
| 129 |
+
the conditions stated in this License.
|
| 130 |
+
|
| 131 |
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
| 132 |
+
any Contribution intentionally submitted for inclusion in the Work
|
| 133 |
+
by You to the Licensor shall be under the terms and conditions of
|
| 134 |
+
this License, without any additional terms or conditions.
|
| 135 |
+
Notwithstanding the above, nothing herein shall supersede or modify
|
| 136 |
+
the terms of any separate license agreement you may have executed
|
| 137 |
+
with Licensor regarding such Contributions.
|
| 138 |
+
|
| 139 |
+
6. Trademarks. This License does not grant permission to use the trade
|
| 140 |
+
names, trademarks, service marks, or product names of the Licensor,
|
| 141 |
+
except as required for reasonable and customary use in describing the
|
| 142 |
+
origin of the Work and reproducing the content of the NOTICE file.
|
| 143 |
+
|
| 144 |
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
| 145 |
+
agreed to in writing, Licensor provides the Work (and each
|
| 146 |
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
| 147 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
| 148 |
+
implied, including, without limitation, any warranties or conditions
|
| 149 |
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
| 150 |
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
| 151 |
+
appropriateness of using or redistributing the Work and assume any
|
| 152 |
+
risks associated with Your exercise of permissions under this License.
|
| 153 |
+
|
| 154 |
+
8. Limitation of Liability. In no event and under no legal theory,
|
| 155 |
+
whether in tort (including negligence), contract, or otherwise,
|
| 156 |
+
unless required by applicable law (such as deliberate and grossly
|
| 157 |
+
negligent acts) or agreed to in writing, shall any Contributor be
|
| 158 |
+
liable to You for damages, including any direct, indirect, special,
|
| 159 |
+
incidental, or consequential damages of any character arising as a
|
| 160 |
+
result of this License or out of the use or inability to use the
|
| 161 |
+
Work (including but not limited to damages for loss of goodwill,
|
| 162 |
+
work stoppage, computer failure or malfunction, or any and all
|
| 163 |
+
other commercial damages or losses), even if such Contributor
|
| 164 |
+
has been advised of the possibility of such damages.
|
| 165 |
+
|
| 166 |
+
9. Accepting Warranty or Additional Liability. While redistributing
|
| 167 |
+
the Work or Derivative Works thereof, You may choose to offer,
|
| 168 |
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
| 169 |
+
or other liability obligations and/or rights consistent with this
|
| 170 |
+
License. However, in accepting such obligations, You may act only
|
| 171 |
+
on Your own behalf and on Your sole responsibility, not on behalf
|
| 172 |
+
of any other Contributor, and only if You agree to indemnify,
|
| 173 |
+
defend, and hold each Contributor harmless for any liability
|
| 174 |
+
incurred by, or claims asserted against, such Contributor by reason
|
| 175 |
+
of your accepting any such warranty or additional liability.
|
| 176 |
+
|
| 177 |
+
END OF TERMS AND CONDITIONS
|
| 178 |
+
|
| 179 |
+
APPENDIX: How to apply the Apache License to your work.
|
| 180 |
+
|
| 181 |
+
To apply the Apache License to your work, attach the following
|
| 182 |
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
| 183 |
+
replaced with your own identifying information. (Don't include
|
| 184 |
+
the brackets!) The text should be enclosed in the appropriate
|
| 185 |
+
comment syntax for the file format. We also recommend that a
|
| 186 |
+
file or class name and description of purpose be included on the
|
| 187 |
+
same "printed page" as the copyright notice for easier
|
| 188 |
+
identification within third-party archives.
|
| 189 |
+
|
| 190 |
+
Copyright 2026 Alibaba Cloud
|
| 191 |
+
|
| 192 |
+
Licensed under the Apache License, Version 2.0 (the "License");
|
| 193 |
+
you may not use this file except in compliance with the License.
|
| 194 |
+
You may obtain a copy of the License at
|
| 195 |
+
|
| 196 |
+
http://www.apache.org/licenses/LICENSE-2.0
|
| 197 |
+
|
| 198 |
+
Unless required by applicable law or agreed to in writing, software
|
| 199 |
+
distributed under the License is distributed on an "AS IS" BASIS,
|
| 200 |
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 201 |
+
See the License for the specific language governing permissions and
|
| 202 |
+
limitations under the License.
|
NOTICE.md
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Notices
|
| 2 |
+
|
| 3 |
+
**JiRackDeltaNet 70B**
|
| 4 |
+
Copyright 2026 Konstantin Vladimirovich Grabko (CMSManhattan)
|
| 5 |
+
|
| 6 |
+
The model is distributed under the Business Source License 1.2 (see `LICENSE`).
|
| 7 |
+
|
| 8 |
+
This model is a modified version of a Qwen model by the Qwen team, Alibaba Cloud, licensed under the Apache License,
|
| 9 |
+
Version 2.0 (a copy is in `LICENSE-APACHE`). CMSManhattan modified the architecture and the weights and fine-tuned the
|
| 10 |
+
model; the weights in this repository are modified files.
|
| 11 |
+
|
| 12 |
+
The fine-tuning data includes publicly available datasets used under their licenses, among them data from NVIDIA and
|
| 13 |
+
Salesforce licensed under CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/) and data from the Allen Institute
|
| 14 |
+
for AI licensed under ODC-BY 1.0, together with data created by CMSManhattan.
|
| 15 |
+
|
| 16 |
+
Keep this file with any copy of the model.
|
README.md
ADDED
|
@@ -0,0 +1,215 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
license: other
|
| 3 |
+
license_name: jirack-proprietary
|
| 4 |
+
license_link: LICENSE
|
| 5 |
+
library_name: pytorch
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
|
| 8 |
+
language:
|
| 9 |
+
- en
|
| 10 |
+
- zh
|
| 11 |
+
- ja
|
| 12 |
+
- ko
|
| 13 |
+
- fr
|
| 14 |
+
- es
|
| 15 |
+
- pt
|
| 16 |
+
- de
|
| 17 |
+
- it
|
| 18 |
+
- ru
|
| 19 |
+
- ar
|
| 20 |
+
- vi
|
| 21 |
+
- th
|
| 22 |
+
tags:
|
| 23 |
+
- text-generation
|
| 24 |
+
- deltanet
|
| 25 |
+
- gguf
|
| 26 |
+
- cpu
|
| 27 |
+
- efficient
|
| 28 |
+
- low-memory
|
| 29 |
+
- ternary
|
| 30 |
+
- bitnet
|
| 31 |
+
- jirack
|
| 32 |
+
- web-ui
|
| 33 |
+
- routing
|
| 34 |
+
- tool-call
|
| 35 |
+
- robotics
|
| 36 |
+
- ollama
|
| 37 |
+
- ternary-weights
|
| 38 |
+
- ternary-transformer
|
| 39 |
+
- quantization
|
| 40 |
+
- 1.58-bit
|
| 41 |
+
|
| 42 |
+
---
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
## JiRackDeltaNet 70B
|
| 46 |
+
|
| 47 |
+
> **Beta release.** Tool calling already works through any OpenAI-compatible client (109/117 on our internal test), but when a required argument is missing the model often calls the tool instead of asking. The next version improves clarifying questions, and GSM8K / HumanEval results will be added. Feedback is welcome.
|
| 48 |
+
|
| 49 |
+
**JiRackDeltaNet 70B** is a **69.93B-parameter hybrid language model** by CMSManhattan (Konstantin Grabko): a Gated DeltaNet / gated full-attention model (Qwen hybrid layout) built in our own JiRack code and fine-tuned on our own data (chat, reasoning, code, math, tool calling).
|
| 50 |
+
|
| 51 |
+
> Status: beta release; see Limitations.
|
| 52 |
+
|
| 53 |
+
So it is good coding and agentic model with robotics tokenizer for next model upgrade
|
| 54 |
+
|
| 55 |
+
## Model
|
| 56 |
+
|
| 57 |
+
| | |
|
| 58 |
+
| --- | --- |
|
| 59 |
+
| Architecture | hybrid decoder, 128 layers: 96 **Gated DeltaNet** (linear attention) + 32 **gated full attention**, every 4th layer full attention |
|
| 60 |
+
| Parameters | 69.93B |
|
| 61 |
+
| Hidden / FFN | 5120 / 26624 (SwiGLU) |
|
| 62 |
+
| Full attention | 24 heads / 4 KV heads, head dim 256, output gate, partial RoPE (25 %), interleaved mRoPE sections \[11, 11, 10\], RoPE theta 1e7 |
|
| 63 |
+
| Gated DeltaNet | 16 key heads / 48 value heads, head dim 128, causal conv kernel 4 |
|
| 64 |
+
| Vocabulary | 248,320 (Qwen tokenizer and chat template), untied input / output embeddings |
|
| 65 |
+
| Extra head | 1-layer MTP (multi-token prediction) head |
|
| 66 |
+
| Code | `JiRackDeltaNet_70b.py`: single-file PyTorch model; parameter names match the Hugging Face state dict of Qwen's hybrid Gated DeltaNet architecture |
|
| 67 |
+
| Weights | bf16 (repository root), an FP8 block-quantized copy in `sft_final_fp8/` and GGUF quantizations (Q3\_K\_M, Q4\_K\_M, Q6\_K) in `gguf/` (see below) |
|
| 68 |
+
|
| 69 |
+
## DEMO Chat
|
| 70 |
+
- https://huggingface.co/spaces/CMSManhattan/JiRackDeltaNet-70B-demo
|
| 71 |
+
|
| 72 |
+
## How it was built
|
| 73 |
+
|
| 74 |
+
JiRackDeltaNet 70B is a modified version of a Qwen model (Apache 2.0). CMSManhattan changed the architecture and the weights in its own JiRack code and fine-tuned the model on its own data (chat, reasoning, code, math, tool calling). The training recipe and data are not published.
|
| 75 |
+
|
| 76 |
+
## Custom training
|
| 77 |
+
|
| 78 |
+
Contact us if you want a JiRack model adapted and fine-tuned on your own data.
|
| 79 |
+
|
| 80 |
+
## Results
|
| 81 |
+
|
| 82 |
+
GSM8K and HumanEval are not measured yet; tool calling is measured below.
|
| 83 |
+
|
| 84 |
+
### Tool calling (GGUF Q3_K_M)
|
| 85 |
+
|
| 86 |
+
Our internal 117-case tool-calling test on the smallest GGUF file, `JiRackDeltaNet_70b_with_prompt.Q3_K_M.gguf`, served by `llama-server` as an OpenAI-compatible API: tools are passed as standard OpenAI `tools` and parsed by llama.cpp's built-in template for this architecture, temperature 0, reasoning off. The cases are written by us and are not in the training data.
|
| 87 |
+
|
| 88 |
+
| Category | Q3_K_M |
|
| 89 |
+
| --- | --- |
|
| 90 |
+
| Single call (one tool, all arguments given) | 38/38 |
|
| 91 |
+
| Parallel calls | 19/19 |
|
| 92 |
+
| Follow-up (answer from a tool result) | 20/20 |
|
| 93 |
+
| No tool needed | 25/25 |
|
| 94 |
+
| Clarify a missing argument | 7/15 |
|
| 95 |
+
| **Total** | **109/117 (93.2%)** |
|
| 96 |
+
|
| 97 |
+
All 8 misses are in clarify: the model called the tool instead of asking for the missing argument.
|
| 98 |
+
|
| 99 |
+
Sample (greedy, thinking off):
|
| 100 |
+
|
| 101 |
+
```
|
| 102 |
+
You: A store sells pens at $3 each. Tom buys 7 pens and pays with a $50 bill. How much change does he get?
|
| 103 |
+
Assistant: Tom buys 7 pens at $3 each, so he spends 7 x $3 = $21. He pays with a $50 bill, so his change is $50 - $21 = $29.
|
| 104 |
+
```
|
| 105 |
+
|
| 106 |
+
## FP8 copy
|
| 107 |
+
|
| 108 |
+
`sft_final_fp8/`: the large GEMMs of every layer (DeltaNet `in_proj_qkv` / `in_proj_z` / `out_proj`, attention `q/k/v/o_proj`, MLP `gate/up/down_proj`; 800 tensors) in **FP8 e4m3 with 128 × 128 block scales** (`weight_scale_inv`, the same layout as the official Qwen / DeepSeek FP8 releases, `quantization_config` in `config.json`). Embeddings, `lm_head`, norms, conv, decay parameters, `in_proj_a/b` and the MTP head stay bf16.
|
| 109 |
+
|
| 110 |
+
| | bf16 | FP8 |
|
| 111 |
+
| --- | --- | --- |
|
| 112 |
+
| Size | 140 GB | 73 GB |
|
| 113 |
+
| Mean relative weight error | — | 2.65 % |
|
| 114 |
+
| Pens question above | $29 | $29 |
|
| 115 |
+
|
| 116 |
+
73 GB fits on a single 96 GB GPU.
|
| 117 |
+
|
| 118 |
+
## GGUF (llama.cpp)
|
| 119 |
+
|
| 120 |
+
Three GGUF quantizations in `gguf/`, each with a built-in system prompt (direct answers, no reasoning block). If a request has no system message, the chat template in the GGUF adds the prompt; your own system message replaces it. The prompt text, commands and checks are in [gguf/README.md](gguf/README.md).
|
| 121 |
+
|
| 122 |
+
```bash
|
| 123 |
+
llama-server -m JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf -c 8192 --jinja --reasoning off --port 8080
|
| 124 |
+
```
|
| 125 |
+
|
| 126 |
+
| | Q3\_K\_M | Q4\_K\_M | Q6\_K |
|
| 127 |
+
| --- | --- | --- | --- |
|
| 128 |
+
| Size | 33.89 GB | 42.65 GB | 57.40 GB (2 parts) |
|
| 129 |
+
| CPU speed, prompt / generation (GH200 Grace, 64 threads, `llama-bench`) | 20.1 / 5.17 tokens/s | 50.2 / 5.04 tokens/s | 45.3 / 4.11 tokens/s |
|
| 130 |
+
| Pens question above | $29 | $29 | $29 |
|
| 131 |
+
| Tool-calling test (117 cases) | 109/117 (93.2%) | — | — |
|
| 132 |
+
|
| 133 |
+
## Usage
|
| 134 |
+
|
| 135 |
+
The repository ships its own PyTorch code; no `transformers` model class is needed.
|
| 136 |
+
|
| 137 |
+
```bash
|
| 138 |
+
pip install torch safetensors tokenizers jinja2
|
| 139 |
+
# bf16, splits the 128 blocks over all visible GPUs (>= 2 x 80 GB)
|
| 140 |
+
python3 chat_jirack.py --model-dir . --no-think --temperature 0
|
| 141 |
+
# FP8 copy (weights stay FP8 in memory, dequantized per layer call; one 96 GB GPU)
|
| 142 |
+
python3 sft_final_fp8/chat_fp8.py --model-dir sft_final_fp8 --no-think --temperature 0
|
| 143 |
+
```
|
| 144 |
+
|
| 145 |
+
Commands in the chat: `/think` (reasoning on / off), `/reset`, `exit`. Prompts use the chat template in `chat_template.jinja` (tools are passed in the `<tools>` system block and called with `<tool_call><function=…><parameter=…>`).
|
| 146 |
+
|
| 147 |
+
The reference chat scripts recompute the whole sequence for every new token (no KV cache), so they are slow (\~1 token/s on 8 × A100); they are meant for checking the model, not for serving. The parameter names follow the Hugging Face naming of this hybrid Gated DeltaNet architecture, so the weights should also load in Hugging Face / vLLM implementations of it; this is **not verified** yet.
|
| 148 |
+
|
| 149 |
+
## Limitations
|
| 150 |
+
|
| 151 |
+
- **Missing arguments**: when a required argument is missing, the model often calls the tool anyway instead of asking (7/15 on our test); validate tool calls before executing them.
|
| 152 |
+
- **Early release**: further training is planned.
|
| 153 |
+
- **Not ternary yet**: JiRack's BitLinear (b1.58) path is present in the code but off (lambda = 0); ternary QAT is a planned later stage.
|
| 154 |
+
- Tested with contexts up to 8,192 tokens.
|
| 155 |
+
- The model may occasionally misstate who made it.
|
| 156 |
+
- Not for medical, legal or financial advice.
|
| 157 |
+
|
| 158 |
+
## License
|
| 159 |
+
|
| 160 |
+
This project is a derivative work based on a Qwen model originally released under the **Apache License, Version 2.0**.
|
| 161 |
+
|
| 162 |
+
### 1. Proprietary Terms for JiRack
|
| 163 |
+
All modifications, proprietary additions, architectural extensions, derived model weights, and scripts developed by **CMS Manhattan (Konstantin Grabko)** — including but not limited to:
|
| 164 |
+
* JiRack custom model code and architecture modifications,
|
| 165 |
+
* changes to the model architecture,
|
| 166 |
+
* fine-tuning on JiRack data,
|
| 167 |
+
* Quantized weights and conversions (FP8, GGUF, BitNet/ternary formats),
|
| 168 |
+
|
| 169 |
+
are licensed under the **JiRack Proprietary Model License (BSL)** (see `LICENSE` file for full terms).
|
| 170 |
+
|
| 171 |
+
* **Permitted Use:** Free for non-commercial, evaluation, research, and internal organizational use.
|
| 172 |
+
* **Commercial / Integration / Redistribution:** Requires a separate written **Commercial Agreement** with the Licensor (Konstantin Grabko / CMS Manhattan).
|
| 173 |
+
|
| 174 |
+
### 2. Third-Party Attribution & Compliance
|
| 175 |
+
In accordance with Section 4 of the Apache License 2.0, the original copyright, attribution, and license notices of the base model are preserved. When redistributing or using this repository, you must retain:
|
| 176 |
+
* The Apache 2.0 license text of the base model (`LICENSE-APACHE`),
|
| 177 |
+
* The `NOTICE.md` file accompanying this repository,
|
| 178 |
+
* All copyright and attribution notices attached to the original components.
|
| 179 |
+
|
| 180 |
+
# Live chat on HF Space
|
| 181 |
+
- https://huggingface.co/spaces/CMSManhattan/JiRackDeltaNet_27b
|
| 182 |
+
- https://huggingface.co/spaces/CMSManhattan/JiRack-16B-Chat
|
| 183 |
+
- https://huggingface.co/spaces/CMSManhattan/JiRack-8B-Chat
|
| 184 |
+
- https://huggingface.co/spaces/CMSManhattan/JiRack-2B-Chat
|
| 185 |
+
---
|
| 186 |
+
|
| 187 |
+
## JiRack Codding Agent IDE
|
| 188 |
+
- It is Agent Coding IDE for JiRack Models to run via Ollama on home PC
|
| 189 |
+
- It good choose for Agent Coding IDE such as Cursor , Windsurf IDE or Devin IDE etc but more safe that ask you to apply changes and review.
|
| 190 |
+
- Web site https://www.jirack.com
|
| 191 |
+
- Eclise Plugin site https://marketplace.eclipse.org/content/jirack-coding-agent
|
| 192 |
+
- Jetbrain Plugin site https://plugins.jetbrains.com/plugin/35073-jirack-agent
|
| 193 |
+
- VS Code Plugin site https://marketplace.visualstudio.com/items?itemName=JiRackautomationCodingAgentIDE.jirack-agent
|
| 194 |
+
|
| 195 |
+
## JiRack Codding Agent IDE files
|
| 196 |
+
- Eclise Final release version https://huggingface.co/CMSManhattan/JiRackDeltaNet_27b/resolve/main/jirack_ide_final.zip
|
| 197 |
+
- Microsoft VS Code plugin https://huggingface.co/spaces/CMSManhattan/README/blob/main/jirack-agent-0.9.0.vsix
|
| 198 |
+
- Jetbrain plugin https://huggingface.co/spaces/CMSManhattan/README/resolve/main/jirack-jetbrains-0.11.0.zip
|
| 199 |
+
- JiRack DeskTop UI https://huggingface.co/spaces/CMSManhattan/README/resolve/main/windows_v11.zip
|
| 200 |
+
|
| 201 |
+
---
|
| 202 |
+
|
| 203 |
+
|
| 204 |
+
## ROBOS HUMANOID Project
|
| 205 |
+
|
| 206 |
+
- https://github.com/cmsmanhattan/ROBOS
|
| 207 |
+
|
| 208 |
+
## Licensing.
|
| 209 |
+
You are free to download JiRackDeltaNet 70B and try it for evaluation, testing and research, side by side with JiRackDeltaNet 27B. Commercial or production use of the 70B model requires a commercial license from CMS Manhattan. For pricing and terms, please contact us.
|
| 210 |
+
|
| 211 |
+
## 📧 Contact
|
| 212 |
+
For joint venture opportunities, hardware integration, or licensing inquiries:
|
| 213 |
+
- **Email:** grabko@cmsmanhattan.com
|
| 214 |
+
- **Phone:** +1 (516) 777-0945
|
| 215 |
+
- **Location:** New York, USA
|
chat_jirack.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# chat_jirack.py - JiRack DeltaNet 70B
|
| 4 |
+
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
|
| 5 |
+
# All rights reserved. Proprietary JiRack license, see LICENSE.
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import glob
|
| 10 |
+
import importlib.util
|
| 11 |
+
import itertools
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
|
| 20 |
+
INIT_FNS = ("uniform_", "normal_", "trunc_normal_", "kaiming_uniform_", "kaiming_normal_",
|
| 21 |
+
"xavier_uniform_", "xavier_normal_", "orthogonal_")
|
| 22 |
+
|
| 23 |
+
def find_model_file(d):
|
| 24 |
+
files = sorted(glob.glob(os.path.join(d, "JiRackDeltaNet_*.py")))
|
| 25 |
+
if not files:
|
| 26 |
+
sys.exit(f"❌ no JiRackDeltaNet_*.py in {d}; pass --model-file")
|
| 27 |
+
return files[-1]
|
| 28 |
+
|
| 29 |
+
def load_module(path):
|
| 30 |
+
spec = importlib.util.spec_from_file_location("jirack_chat_model", path)
|
| 31 |
+
mod = importlib.util.module_from_spec(spec)
|
| 32 |
+
sys.modules["jirack_chat_model"] = mod
|
| 33 |
+
spec.loader.exec_module(mod)
|
| 34 |
+
return mod
|
| 35 |
+
|
| 36 |
+
def build(mod):
|
| 37 |
+
""
|
| 38 |
+
saved = {n: getattr(nn.init, n) for n in INIT_FNS if hasattr(nn.init, n)}
|
| 39 |
+
for n in saved:
|
| 40 |
+
setattr(nn.init, n, lambda t, *a, **k: t)
|
| 41 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 42 |
+
try:
|
| 43 |
+
model = mod.JiRackDeltaNetForCausalLM()
|
| 44 |
+
finally:
|
| 45 |
+
torch.set_default_dtype(torch.float32)
|
| 46 |
+
for n, f in saved.items():
|
| 47 |
+
setattr(nn.init, n, f)
|
| 48 |
+
return model.eval()
|
| 49 |
+
|
| 50 |
+
def load_weights(model, d):
|
| 51 |
+
from safetensors import safe_open
|
| 52 |
+
idx = os.path.join(d, "model.safetensors.index.json")
|
| 53 |
+
files = sorted(set(json.load(open(idx))["weight_map"].values())) if os.path.exists(idx) else \
|
| 54 |
+
sorted(os.path.basename(p) for p in glob.glob(os.path.join(d, "*.safetensors")))
|
| 55 |
+
sd = model.state_dict()
|
| 56 |
+
params = {n for n, _ in model.named_parameters()}
|
| 57 |
+
loaded = set()
|
| 58 |
+
t0 = time.time()
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
for i, f in enumerate(files):
|
| 61 |
+
with safe_open(os.path.join(d, f), framework="pt", device="cpu") as h:
|
| 62 |
+
for k in h.keys():
|
| 63 |
+
if k in sd:
|
| 64 |
+
sd[k].copy_(h.get_tensor(k))
|
| 65 |
+
loaded.add(k)
|
| 66 |
+
print(f" {i + 1}/{len(files)} {f} {time.time() - t0:.0f} s", flush=True)
|
| 67 |
+
missing = sorted(params - loaded)
|
| 68 |
+
if missing:
|
| 69 |
+
sys.exit(f"❌ {len(missing)} parameters not in {d}: {missing[:5]}")
|
| 70 |
+
|
| 71 |
+
class ChatTokenizer:
|
| 72 |
+
""
|
| 73 |
+
|
| 74 |
+
def __init__(self, d):
|
| 75 |
+
import jinja2
|
| 76 |
+
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
| 77 |
+
from tokenizers import Tokenizer
|
| 78 |
+
self.tk = Tokenizer.from_file(os.path.join(d, "tokenizer.json"))
|
| 79 |
+
cfg = {}
|
| 80 |
+
if os.path.exists(os.path.join(d, "tokenizer_config.json")):
|
| 81 |
+
cfg = json.load(open(os.path.join(d, "tokenizer_config.json"), encoding="utf-8"))
|
| 82 |
+
path = os.path.join(d, "chat_template.jinja")
|
| 83 |
+
text = open(path, encoding="utf-8").read() if os.path.exists(path) else cfg.get("chat_template")
|
| 84 |
+
if isinstance(text, list):
|
| 85 |
+
text = next(t["template"] for t in text if t.get("name") == "default")
|
| 86 |
+
if not text:
|
| 87 |
+
sys.exit(f"❌ no chat template in {d}")
|
| 88 |
+
|
| 89 |
+
def raise_exception(msg):
|
| 90 |
+
raise jinja2.exceptions.TemplateError(msg)
|
| 91 |
+
|
| 92 |
+
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
|
| 93 |
+
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators,
|
| 94 |
+
sort_keys=sort_keys)
|
| 95 |
+
|
| 96 |
+
env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
|
| 97 |
+
env.filters["tojson"] = tojson
|
| 98 |
+
env.globals["raise_exception"] = raise_exception
|
| 99 |
+
self.tmpl = env.from_string(text)
|
| 100 |
+
s = lambda v: v.get("content") if isinstance(v, dict) else v
|
| 101 |
+
self.bos, self.eos = s(cfg.get("bos_token")) or "", s(cfg.get("eos_token")) or ""
|
| 102 |
+
self.special = [t.content for t in self.tk.get_added_tokens_decoder().values() if t.special]
|
| 103 |
+
self.stop_ids = {i for i in (self.tk.token_to_id("<|im_end|>"), self.tk.token_to_id("<|endoftext|>"),
|
| 104 |
+
self.tk.token_to_id(self.eos) if self.eos else None) if i is not None}
|
| 105 |
+
|
| 106 |
+
def prompt_ids(self, msgs, think):
|
| 107 |
+
text = self.tmpl.render(messages=msgs, add_generation_prompt=True, enable_thinking=think,
|
| 108 |
+
bos_token=self.bos, eos_token=self.eos)
|
| 109 |
+
return self.tk.encode(text, add_special_tokens=False).ids
|
| 110 |
+
|
| 111 |
+
def decode(self, ids):
|
| 112 |
+
return self.tk.decode(ids, skip_special_tokens=False)
|
| 113 |
+
|
| 114 |
+
def _to(x, dev):
|
| 115 |
+
if torch.is_tensor(x):
|
| 116 |
+
return x.to(dev)
|
| 117 |
+
if isinstance(x, (tuple, list)):
|
| 118 |
+
return type(x)(_to(v, dev) for v in x)
|
| 119 |
+
if isinstance(x, dict):
|
| 120 |
+
return {k: _to(v, dev) for k, v in x.items()}
|
| 121 |
+
return x
|
| 122 |
+
|
| 123 |
+
def place(model, devices):
|
| 124 |
+
""
|
| 125 |
+
blocks = [m for m in model.modules() if type(m).__name__ == "TransformerBlock"]
|
| 126 |
+
in_block = {id(x) for b in blocks for x in b.modules()}
|
| 127 |
+
for i, b in enumerate(blocks):
|
| 128 |
+
dev = devices[i * len(devices) // len(blocks)]
|
| 129 |
+
b.to(dev)
|
| 130 |
+
if len(devices) > 1:
|
| 131 |
+
b.register_forward_pre_hook(lambda m, a, k, dev=dev: (_to(a, dev), _to(k, dev)), with_kwargs=True)
|
| 132 |
+
for m in model.modules():
|
| 133 |
+
if id(m) in in_block:
|
| 134 |
+
continue
|
| 135 |
+
m._apply(lambda t: t.to(devices[0]), recurse=False)
|
| 136 |
+
if len(devices) > 1 and not list(m.children()):
|
| 137 |
+
m.register_forward_pre_hook(lambda mm, a, k: (_to(a, devices[0]), _to(k, devices[0])),
|
| 138 |
+
with_kwargs=True)
|
| 139 |
+
return devices[0]
|
| 140 |
+
|
| 141 |
+
def _cast(x, dtype):
|
| 142 |
+
if torch.is_tensor(x):
|
| 143 |
+
return x.to(dtype) if x.is_floating_point() and x.dtype != dtype else x
|
| 144 |
+
if isinstance(x, (tuple, list)):
|
| 145 |
+
return type(x)(_cast(v, dtype) for v in x)
|
| 146 |
+
if isinstance(x, dict):
|
| 147 |
+
return {k: _cast(v, dtype) for k, v in x.items()}
|
| 148 |
+
return x
|
| 149 |
+
|
| 150 |
+
def fp32_blocks(model):
|
| 151 |
+
""
|
| 152 |
+
def pre(mod, args, kwargs):
|
| 153 |
+
saved = []
|
| 154 |
+
for t in itertools.chain(mod.parameters(), mod.buffers()):
|
| 155 |
+
if t.is_floating_point() and t.dtype != torch.float32:
|
| 156 |
+
saved.append((t, t.data))
|
| 157 |
+
t.data = t.data.float()
|
| 158 |
+
mod._jr_saved = saved
|
| 159 |
+
return _cast(args, torch.float32), _cast(kwargs, torch.float32)
|
| 160 |
+
|
| 161 |
+
def post(mod, args, out, back=torch.bfloat16):
|
| 162 |
+
for t, d in mod._jr_saved:
|
| 163 |
+
t.data = d
|
| 164 |
+
mod._jr_saved = []
|
| 165 |
+
return _cast(out, back) if back is not None else out
|
| 166 |
+
|
| 167 |
+
for m in model.modules():
|
| 168 |
+
if type(m).__name__ == "TransformerBlock":
|
| 169 |
+
m.register_forward_pre_hook(pre, with_kwargs=True)
|
| 170 |
+
m.register_forward_hook(post)
|
| 171 |
+
head = getattr(model, "lm_head", None)
|
| 172 |
+
if isinstance(head, nn.Module):
|
| 173 |
+
head.register_forward_pre_hook(pre, with_kwargs=True)
|
| 174 |
+
head.register_forward_hook(lambda m, a, o: post(m, a, o, None))
|
| 175 |
+
|
| 176 |
+
def logits_of(out):
|
| 177 |
+
if isinstance(out, (tuple, list)):
|
| 178 |
+
return out[0]
|
| 179 |
+
return out.logits if hasattr(out, "logits") else out
|
| 180 |
+
|
| 181 |
+
def sample(logits, temperature, top_p):
|
| 182 |
+
if temperature <= 0:
|
| 183 |
+
return int(logits.argmax())
|
| 184 |
+
probs = torch.softmax(logits.float() / temperature, dim=-1)
|
| 185 |
+
sp, si = probs.sort(descending=True)
|
| 186 |
+
cut = (sp.cumsum(-1) - sp) > top_p
|
| 187 |
+
sp[cut] = 0
|
| 188 |
+
return int(si[torch.multinomial(sp / sp.sum(), 1)])
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
p = argparse.ArgumentParser()
|
| 192 |
+
p.add_argument("--model-dir", default=".")
|
| 193 |
+
p.add_argument("--model-file", default=None)
|
| 194 |
+
p.add_argument("--tokenizer-dir", default=None, help="default: --model-dir")
|
| 195 |
+
p.add_argument("--max-new", type=int, default=2048)
|
| 196 |
+
p.add_argument("--temperature", type=float, default=0.6, help="0 = greedy")
|
| 197 |
+
p.add_argument("--top-p", type=float, default=0.95)
|
| 198 |
+
p.add_argument("--system", default=None, help="file with a system prompt")
|
| 199 |
+
p.add_argument("--no-think", action="store_true", help="start with thinking off")
|
| 200 |
+
p.add_argument("--cpu", action="store_true")
|
| 201 |
+
p.add_argument("--cpu-bf16", action="store_true", help="CPU: plain bf16 instead of fp32 blocks")
|
| 202 |
+
a = p.parse_args()
|
| 203 |
+
|
| 204 |
+
tok = ChatTokenizer(a.tokenizer_dir or a.model_dir)
|
| 205 |
+
stop = tok.stop_ids
|
| 206 |
+
print(f"stop tokens {sorted(stop)}", flush=True)
|
| 207 |
+
|
| 208 |
+
mf = a.model_file or find_model_file(a.model_dir)
|
| 209 |
+
print(f"model file {mf}\nweights {a.model_dir}", flush=True)
|
| 210 |
+
model = build(load_module(mf))
|
| 211 |
+
load_weights(model, a.model_dir)
|
| 212 |
+
n = sum(q.numel() for q in model.parameters())
|
| 213 |
+
if a.cpu or not torch.cuda.is_available():
|
| 214 |
+
dev = torch.device("cpu")
|
| 215 |
+
try:
|
| 216 |
+
torch.backends.nnpack.set_flags(False)
|
| 217 |
+
except Exception:
|
| 218 |
+
pass
|
| 219 |
+
if not a.cpu_bf16:
|
| 220 |
+
fp32_blocks(model)
|
| 221 |
+
print(f"⚠️ CPU: {n / 1e9:.1f}B params, compute {'bf16' if a.cpu_bf16 else 'fp32 blocks'} - "
|
| 222 |
+
f"every token is a full forward pass, expect minutes per token. Ctrl+C stops the answer.")
|
| 223 |
+
else:
|
| 224 |
+
devs = [torch.device("cuda", i) for i in range(torch.cuda.device_count())]
|
| 225 |
+
dev = place(model, devs)
|
| 226 |
+
print(f"on {len(devs)} GPU(s): {n / 1e9:.1f}B params, "
|
| 227 |
+
f"{[round(torch.cuda.memory_allocated(d) / 2 ** 30) for d in devs]} GB")
|
| 228 |
+
|
| 229 |
+
system = open(a.system, encoding="utf-8").read().strip() if a.system else None
|
| 230 |
+
think = not a.no_think
|
| 231 |
+
history = []
|
| 232 |
+
print("\nReady. /reset - clear history, /think - thinking on/off, exit - quit")
|
| 233 |
+
while True:
|
| 234 |
+
try:
|
| 235 |
+
user = input("\nYou: ").strip()
|
| 236 |
+
except (EOFError, KeyboardInterrupt):
|
| 237 |
+
break
|
| 238 |
+
if not user:
|
| 239 |
+
continue
|
| 240 |
+
if user.lower() in ("exit", "quit"):
|
| 241 |
+
break
|
| 242 |
+
if user == "/reset":
|
| 243 |
+
history = []
|
| 244 |
+
print("(history cleared)")
|
| 245 |
+
continue
|
| 246 |
+
if user == "/think":
|
| 247 |
+
think = not think
|
| 248 |
+
print(f"(thinking {'on' if think else 'off'})")
|
| 249 |
+
continue
|
| 250 |
+
history.append({"role": "user", "content": user})
|
| 251 |
+
msgs = ([{"role": "system", "content": system}] if system else []) + history
|
| 252 |
+
ids = torch.tensor([tok.prompt_ids(msgs, think)], dtype=torch.long, device=dev)
|
| 253 |
+
start = ids.shape[1]
|
| 254 |
+
print("\nAssistant: ", end="", flush=True)
|
| 255 |
+
printed, t0 = "", time.time()
|
| 256 |
+
try:
|
| 257 |
+
with torch.no_grad():
|
| 258 |
+
for _ in range(a.max_new):
|
| 259 |
+
nxt = sample(logits_of(model(ids))[0, -1], a.temperature, a.top_p)
|
| 260 |
+
if nxt in stop:
|
| 261 |
+
break
|
| 262 |
+
ids = torch.cat([ids, torch.tensor([[nxt]], device=ids.device)], dim=1)
|
| 263 |
+
text = tok.decode(ids[0, start:].tolist())
|
| 264 |
+
if not text.endswith("�"):
|
| 265 |
+
print(text[len(printed):], end="", flush=True)
|
| 266 |
+
printed = text
|
| 267 |
+
except KeyboardInterrupt:
|
| 268 |
+
print(" [stopped]", end="")
|
| 269 |
+
gen = ids.shape[1] - start
|
| 270 |
+
raw = tok.decode(ids[0, start:].tolist())
|
| 271 |
+
print(f"\n [{gen} tokens, {gen / max(time.time() - t0, 1e-6):.2f} tok/s]")
|
| 272 |
+
|
| 273 |
+
reply = raw.split("</think>")[-1]
|
| 274 |
+
for t in tok.special:
|
| 275 |
+
reply = reply.replace(t, "")
|
| 276 |
+
history.append({"role": "assistant", "content": reply.strip()})
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
main()
|
chat_template.jinja
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}
|
| 2 |
+
{%- set video_count = namespace(value=0) %}
|
| 3 |
+
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
+
{%- if content is string %}
|
| 5 |
+
{{- content }}
|
| 6 |
+
{%- elif content is iterable and content is not mapping %}
|
| 7 |
+
{%- for item in content %}
|
| 8 |
+
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
|
| 9 |
+
{%- if is_system_content %}
|
| 10 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 11 |
+
{%- endif %}
|
| 12 |
+
{%- if do_vision_count %}
|
| 13 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 14 |
+
{%- endif %}
|
| 15 |
+
{%- if add_vision_id %}
|
| 16 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 19 |
+
{%- elif 'video' in item or item.type == 'video' %}
|
| 20 |
+
{%- if is_system_content %}
|
| 21 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
{%- if do_vision_count %}
|
| 24 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 25 |
+
{%- endif %}
|
| 26 |
+
{%- if add_vision_id %}
|
| 27 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
+
{%- elif 'text' in item %}
|
| 31 |
+
{{- item.text }}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endfor %}
|
| 36 |
+
{%- elif content is none or content is undefined %}
|
| 37 |
+
{{- '' }}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endmacro %}
|
| 42 |
+
{%- if not messages %}
|
| 43 |
+
{{- raise_exception('No messages provided.') }}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
{%- set reasoning_instructions = '' %}
|
| 46 |
+
{%- if enable_thinking is defined and enable_thinking is true %}
|
| 47 |
+
{%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
|
| 48 |
+
{%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
|
| 49 |
+
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
|
| 50 |
+
{%- endif %}
|
| 51 |
+
{%- if resolved_reasoning_effort == 'xhigh' %}
|
| 52 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
|
| 53 |
+
{%- elif resolved_reasoning_effort == 'low' %}
|
| 54 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
|
| 55 |
+
{%- endif %}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tools and tools is iterable and tools is not mapping %}
|
| 58 |
+
{{- '<|im_start|>system\n' }}
|
| 59 |
+
{%- if reasoning_instructions %}
|
| 60 |
+
{{- reasoning_instructions + '\n\n' }}
|
| 61 |
+
{%- endif %}
|
| 62 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
|
| 63 |
+
{%- for tool in tools %}
|
| 64 |
+
{{- "\n" }}
|
| 65 |
+
{{- tool | tojson }}
|
| 66 |
+
{%- endfor %}
|
| 67 |
+
{{- "\n</tools>" }}
|
| 68 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 69 |
+
{%- if messages[0].role == 'system' %}
|
| 70 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 71 |
+
{%- if content %}
|
| 72 |
+
{{- '\n\n' + content }}
|
| 73 |
+
{%- endif %}
|
| 74 |
+
{%- endif %}
|
| 75 |
+
{{- '<|im_end|>\n' }}
|
| 76 |
+
{%- else %}
|
| 77 |
+
{%- if messages[0].role == 'system' %}
|
| 78 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 79 |
+
{%- if content %}
|
| 80 |
+
{{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
|
| 81 |
+
{%- elif reasoning_instructions %}
|
| 82 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 83 |
+
{%- endif %}
|
| 84 |
+
{%- elif reasoning_instructions %}
|
| 85 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 86 |
+
{%- endif %}
|
| 87 |
+
{%- endif %}
|
| 88 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 89 |
+
{%- for message in messages[::-1] %}
|
| 90 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 91 |
+
{%- if ns.multi_step_tool and message.role == "user" %}
|
| 92 |
+
{%- set content = render_content(message.content, false)|trim %}
|
| 93 |
+
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
|
| 94 |
+
{%- set ns.multi_step_tool = false %}
|
| 95 |
+
{%- set ns.last_query_index = index %}
|
| 96 |
+
{%- endif %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{%- endfor %}
|
| 99 |
+
{%- if ns.multi_step_tool %}
|
| 100 |
+
{{- raise_exception('No user query found in messages.') }}
|
| 101 |
+
{%- endif %}
|
| 102 |
+
{%- for message in messages %}
|
| 103 |
+
{%- set content = render_content(message.content, true)|trim %}
|
| 104 |
+
{%- if message.role == "system" %}
|
| 105 |
+
{%- if not loop.first %}
|
| 106 |
+
{{- raise_exception('System message must be at the beginning.') }}
|
| 107 |
+
{%- endif %}
|
| 108 |
+
{%- elif message.role == "user" %}
|
| 109 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 110 |
+
{%- elif message.role == "assistant" %}
|
| 111 |
+
{%- set reasoning_content = '' %}
|
| 112 |
+
{%- if message.reasoning_content is string %}
|
| 113 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 114 |
+
{%- endif %}
|
| 115 |
+
{%- set reasoning_content = reasoning_content|trim %}
|
| 116 |
+
{%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
|
| 117 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
|
| 118 |
+
{%- else %}
|
| 119 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 120 |
+
{%- endif %}
|
| 121 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 122 |
+
{%- for tool_call in message.tool_calls %}
|
| 123 |
+
{%- if tool_call.function is defined %}
|
| 124 |
+
{%- set tool_call = tool_call.function %}
|
| 125 |
+
{%- endif %}
|
| 126 |
+
{%- if loop.first %}
|
| 127 |
+
{%- if content|trim %}
|
| 128 |
+
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 129 |
+
{%- else %}
|
| 130 |
+
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 131 |
+
{%- endif %}
|
| 132 |
+
{%- else %}
|
| 133 |
+
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 134 |
+
{%- endif %}
|
| 135 |
+
{%- if tool_call.arguments is defined and tool_call.arguments != '' %}
|
| 136 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 137 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 138 |
+
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
|
| 139 |
+
{{- args_value }}
|
| 140 |
+
{{- '\n</parameter>\n' }}
|
| 141 |
+
{%- endfor %}
|
| 142 |
+
{%- endif %}
|
| 143 |
+
{{- '</function>\n</tool_call>' }}
|
| 144 |
+
{%- endfor %}
|
| 145 |
+
{%- endif %}
|
| 146 |
+
{{- '<|im_end|>\n' }}
|
| 147 |
+
{%- elif message.role == "tool" %}
|
| 148 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 149 |
+
{{- '<|im_start|>user' }}
|
| 150 |
+
{%- endif %}
|
| 151 |
+
{{- '\n<tool_response>\n' }}
|
| 152 |
+
{{- content }}
|
| 153 |
+
{{- '\n</tool_response>' }}
|
| 154 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 155 |
+
{{- '<|im_end|>\n' }}
|
| 156 |
+
{%- elif loop.last %}
|
| 157 |
+
{{- '<|im_end|>\n' }}
|
| 158 |
+
{%- endif %}
|
| 159 |
+
{%- else %}
|
| 160 |
+
{{- raise_exception('Unexpected message role.') }}
|
| 161 |
+
{%- endif %}
|
| 162 |
+
{%- endfor %}
|
| 163 |
+
{%- if add_generation_prompt %}
|
| 164 |
+
{{- '<|im_start|>assistant\n' }}
|
| 165 |
+
{%- if enable_thinking is defined and enable_thinking is true %}
|
| 166 |
+
{{- '<think>\n' }}
|
| 167 |
+
{%- else %}
|
| 168 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 169 |
+
{%- endif %}
|
| 170 |
+
{%- endif %}
|
| 171 |
+
|
config.json
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"attention_dropout": 0.0,
|
| 4 |
+
"attn_output_gate": true,
|
| 5 |
+
"bos_token_id": 248044,
|
| 6 |
+
"dtype": "bfloat16",
|
| 7 |
+
"eos_token_id": 248044,
|
| 8 |
+
"full_attention_interval": 4,
|
| 9 |
+
"head_dim": 256,
|
| 10 |
+
"hidden_act": "silu",
|
| 11 |
+
"hidden_size": 5120,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": 26624,
|
| 14 |
+
"layer_types": [
|
| 15 |
+
"linear_attention",
|
| 16 |
+
"linear_attention",
|
| 17 |
+
"linear_attention",
|
| 18 |
+
"full_attention",
|
| 19 |
+
"linear_attention",
|
| 20 |
+
"linear_attention",
|
| 21 |
+
"linear_attention",
|
| 22 |
+
"full_attention",
|
| 23 |
+
"linear_attention",
|
| 24 |
+
"linear_attention",
|
| 25 |
+
"linear_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"linear_attention",
|
| 28 |
+
"linear_attention",
|
| 29 |
+
"linear_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"linear_attention",
|
| 32 |
+
"linear_attention",
|
| 33 |
+
"linear_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"linear_attention",
|
| 36 |
+
"linear_attention",
|
| 37 |
+
"linear_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"linear_attention",
|
| 40 |
+
"linear_attention",
|
| 41 |
+
"linear_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"linear_attention",
|
| 44 |
+
"linear_attention",
|
| 45 |
+
"linear_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"linear_attention",
|
| 48 |
+
"linear_attention",
|
| 49 |
+
"linear_attention",
|
| 50 |
+
"full_attention",
|
| 51 |
+
"linear_attention",
|
| 52 |
+
"linear_attention",
|
| 53 |
+
"linear_attention",
|
| 54 |
+
"full_attention",
|
| 55 |
+
"linear_attention",
|
| 56 |
+
"linear_attention",
|
| 57 |
+
"linear_attention",
|
| 58 |
+
"full_attention",
|
| 59 |
+
"linear_attention",
|
| 60 |
+
"linear_attention",
|
| 61 |
+
"linear_attention",
|
| 62 |
+
"full_attention",
|
| 63 |
+
"linear_attention",
|
| 64 |
+
"linear_attention",
|
| 65 |
+
"linear_attention",
|
| 66 |
+
"full_attention",
|
| 67 |
+
"linear_attention",
|
| 68 |
+
"linear_attention",
|
| 69 |
+
"linear_attention",
|
| 70 |
+
"full_attention",
|
| 71 |
+
"linear_attention",
|
| 72 |
+
"linear_attention",
|
| 73 |
+
"linear_attention",
|
| 74 |
+
"full_attention",
|
| 75 |
+
"linear_attention",
|
| 76 |
+
"linear_attention",
|
| 77 |
+
"linear_attention",
|
| 78 |
+
"full_attention",
|
| 79 |
+
"linear_attention",
|
| 80 |
+
"linear_attention",
|
| 81 |
+
"linear_attention",
|
| 82 |
+
"full_attention",
|
| 83 |
+
"linear_attention",
|
| 84 |
+
"linear_attention",
|
| 85 |
+
"linear_attention",
|
| 86 |
+
"full_attention",
|
| 87 |
+
"linear_attention",
|
| 88 |
+
"linear_attention",
|
| 89 |
+
"linear_attention",
|
| 90 |
+
"full_attention",
|
| 91 |
+
"linear_attention",
|
| 92 |
+
"linear_attention",
|
| 93 |
+
"linear_attention",
|
| 94 |
+
"full_attention",
|
| 95 |
+
"linear_attention",
|
| 96 |
+
"linear_attention",
|
| 97 |
+
"linear_attention",
|
| 98 |
+
"full_attention",
|
| 99 |
+
"linear_attention",
|
| 100 |
+
"linear_attention",
|
| 101 |
+
"linear_attention",
|
| 102 |
+
"full_attention",
|
| 103 |
+
"linear_attention",
|
| 104 |
+
"linear_attention",
|
| 105 |
+
"linear_attention",
|
| 106 |
+
"full_attention",
|
| 107 |
+
"linear_attention",
|
| 108 |
+
"linear_attention",
|
| 109 |
+
"linear_attention",
|
| 110 |
+
"full_attention",
|
| 111 |
+
"linear_attention",
|
| 112 |
+
"linear_attention",
|
| 113 |
+
"linear_attention",
|
| 114 |
+
"full_attention",
|
| 115 |
+
"linear_attention",
|
| 116 |
+
"linear_attention",
|
| 117 |
+
"linear_attention",
|
| 118 |
+
"full_attention",
|
| 119 |
+
"linear_attention",
|
| 120 |
+
"linear_attention",
|
| 121 |
+
"linear_attention",
|
| 122 |
+
"full_attention",
|
| 123 |
+
"linear_attention",
|
| 124 |
+
"linear_attention",
|
| 125 |
+
"linear_attention",
|
| 126 |
+
"full_attention",
|
| 127 |
+
"linear_attention",
|
| 128 |
+
"linear_attention",
|
| 129 |
+
"linear_attention",
|
| 130 |
+
"full_attention",
|
| 131 |
+
"linear_attention",
|
| 132 |
+
"linear_attention",
|
| 133 |
+
"linear_attention",
|
| 134 |
+
"full_attention",
|
| 135 |
+
"linear_attention",
|
| 136 |
+
"linear_attention",
|
| 137 |
+
"linear_attention",
|
| 138 |
+
"full_attention",
|
| 139 |
+
"linear_attention",
|
| 140 |
+
"linear_attention",
|
| 141 |
+
"linear_attention",
|
| 142 |
+
"full_attention"
|
| 143 |
+
],
|
| 144 |
+
"linear_conv_kernel_dim": 4,
|
| 145 |
+
"linear_key_head_dim": 128,
|
| 146 |
+
"linear_num_key_heads": 16,
|
| 147 |
+
"linear_num_value_heads": 48,
|
| 148 |
+
"linear_value_head_dim": 128,
|
| 149 |
+
"mamba_ssm_dtype": "float32",
|
| 150 |
+
"max_position_embeddings": 262144,
|
| 151 |
+
"model_type": "qwen3_5_text",
|
| 152 |
+
"mtp_num_hidden_layers": 1,
|
| 153 |
+
"mtp_use_dedicated_embeddings": false,
|
| 154 |
+
"num_attention_heads": 24,
|
| 155 |
+
"num_hidden_layers": 128,
|
| 156 |
+
"num_key_value_heads": 4,
|
| 157 |
+
"output_gate_type": "swish",
|
| 158 |
+
"pad_token_id": null,
|
| 159 |
+
"partial_rotary_factor": 0.25,
|
| 160 |
+
"rms_norm_eps": 1e-06,
|
| 161 |
+
"rope_parameters": {
|
| 162 |
+
"mrope_interleaved": true,
|
| 163 |
+
"mrope_section": [
|
| 164 |
+
11,
|
| 165 |
+
11,
|
| 166 |
+
10
|
| 167 |
+
],
|
| 168 |
+
"partial_rotary_factor": 0.25,
|
| 169 |
+
"rope_theta": 10000000,
|
| 170 |
+
"rope_type": "default"
|
| 171 |
+
},
|
| 172 |
+
"tie_word_embeddings": false,
|
| 173 |
+
"use_cache": true,
|
| 174 |
+
"vocab_size": 248320,
|
| 175 |
+
"architectures": [
|
| 176 |
+
"Qwen3_5ForCausalLM"
|
| 177 |
+
]
|
| 178 |
+
}
|
gate_logits_fp32blocks_L128.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a589ae8136832e11c0c408e43a560cf110f011e3ecef3b60852db63eb256d025
|
| 3 |
+
size 14900556
|
gate_logits_fp32blocks_L8.npz
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:8975717cc37cabfaffcea30896d5aaefceb526cb2d0b1a0b993830d57358e29e
|
| 3 |
+
size 14900556
|
gguf/JiRackDeltaNet_70b_with_prompt.Q3_K_M.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:40319b3187561e415b4c3dd63ba92a6046d56f9846e405b3facb18ad5773cea4
|
| 3 |
+
size 33890977344
|
gguf/JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d2f889b643cb6d75152e7138170be2f21849ce09288e4dc92ec9fc90e8cf1513
|
| 3 |
+
size 42651563584
|
gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00001-of-00002.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:d162bf2db45a3bcc51c4e8771d00cee4566d1d70c9b08a7e3d78432bbc056d3a
|
| 3 |
+
size 45005467584
|
gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00002-of-00002.gguf
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:a6a2450f5e2419433046c3ea36f363292b4027b683c23497cfe18e1f60f160b0
|
| 3 |
+
size 12390897472
|
gguf/README.md
ADDED
|
@@ -0,0 +1,128 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# JiRackDeltaNet 70B: GGUF for llama.cpp
|
| 2 |
+
|
| 3 |
+
> **Beta release.** Tool calling already works through any OpenAI-compatible client (109/117 on our internal test), but when a required argument is missing the model often calls the tool instead of asking. The next version improves clarifying questions, and GSM8K / HumanEval results will be added. Feedback is welcome.
|
| 4 |
+
|
| 5 |
+
GGUF quantizations of **JiRackDeltaNet 70B** (the bf16 SFT release in the root of this repository). Each file has the
|
| 6 |
+
same **built-in system prompt**.
|
| 7 |
+
|
| 8 |
+
| File | Size | Notes |
|
| 9 |
+
|---|---|---|
|
| 10 |
+
| `JiRackDeltaNet_70b_with_prompt.Q3_K_M.gguf` | 33.89 GB | smallest; on the ARM CPU we tested, prompt processing is 2.5× slower than Q4_K_M |
|
| 11 |
+
| `JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf` | 42.65 GB | recommended balance of size, speed and quality |
|
| 12 |
+
| `JiRackDeltaNet_70b_with_prompt.Q6_K-00001-of-00002.gguf` + `-00002-of-00002.gguf` | 57.40 GB (45.01 + 12.39) | closest to bf16; split in two parts, load the first one |
|
| 13 |
+
|
| 14 |
+
| | |
|
| 15 |
+
|---|---|
|
| 16 |
+
| Model | 69.93B parameters, 1,714 tensors |
|
| 17 |
+
| Quantization | `convert_hf_to_gguf.py` (bf16 GGUF) → `llama-quantize`, no importance matrix |
|
| 18 |
+
| llama.cpp architecture | `qwen35` (Qwen layout: 96 Gated DeltaNet + 32 gated full-attention layers, 128 in total) |
|
| 19 |
+
| Built and tested with | llama.cpp build `5d7793d` (October 28, 2026) |
|
| 20 |
+
| Context | tested with contexts up to 8,192 tokens |
|
| 21 |
+
|
| 22 |
+
## Run
|
| 23 |
+
|
| 24 |
+
You need a llama.cpp build with Qwen (`qwen35`) support.
|
| 25 |
+
|
| 26 |
+
```bash
|
| 27 |
+
git clone https://github.com/ggml-org/llama.cpp
|
| 28 |
+
cd llama.cpp
|
| 29 |
+
cmake -B build # add -DGGML_CUDA=ON for NVIDIA GPUs
|
| 30 |
+
cmake --build build -j --config Release
|
| 31 |
+
hf download CMSManhattan/JiRackDeltaNet_70b gguf/JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf --local-dir .
|
| 32 |
+
# Q6_K: both parts
|
| 33 |
+
# hf download CMSManhattan/JiRackDeltaNet_70b --include "gguf/*Q6_K*" --local-dir .
|
| 34 |
+
```
|
| 35 |
+
|
| 36 |
+
OpenAI-compatible server:
|
| 37 |
+
|
| 38 |
+
```bash
|
| 39 |
+
./build/bin/llama-server -m gguf/JiRackDeltaNet_70b_with_prompt.Q4_K_M.gguf \
|
| 40 |
+
-c 8192 --jinja --reasoning off --port 8080
|
| 41 |
+
# Q6_K: -m gguf/JiRackDeltaNet_70b_with_prompt.Q6_K-00001-of-00002.gguf (the second part is found automatically)
|
| 42 |
+
```
|
| 43 |
+
|
| 44 |
+
```bash
|
| 45 |
+
curl http://localhost:8080/v1/chat/completions -H "Content-Type: application/json" -d '{
|
| 46 |
+
"messages": [{"role": "user", "content": "A store sells pens at $3 each. Tom buys 7 pens and pays with a $50 bill. How much change does he get?"}],
|
| 47 |
+
"temperature": 0
|
| 48 |
+
}'
|
| 49 |
+
```
|
| 50 |
+
|
| 51 |
+
Interactive chat in the terminal: `./build/bin/llama-cli` with the same `-m`, `-c`, `--jinja` and `--reasoning off` flags.
|
| 52 |
+
|
| 53 |
+
With a GPU build, `-ngl 999` puts all layers on the GPU, which needs the file size in GPU memory plus the context. On a
|
| 54 |
+
smaller GPU, offload part of the layers with `-ngl N`. GPU speed is not measured yet.
|
| 55 |
+
|
| 56 |
+
## Built-in system prompt
|
| 57 |
+
|
| 58 |
+
When a request has no system message, the chat template stored in the GGUF adds this one:
|
| 59 |
+
|
| 60 |
+
```
|
| 61 |
+
You are JiRack, an assistant that answers immediately and to the point.
|
| 62 |
+
Never use a reasoning block wrapped in think tags.
|
| 63 |
+
Do not show internal reasoning, drafts, or step-by-step thought process.
|
| 64 |
+
Give the final, ready answer right away, with no preliminary explanation of your reasoning.
|
| 65 |
+
If you feel the need to think through the question, do it silently, internally,
|
| 66 |
+
and output only the final answer to the user.
|
| 67 |
+
```
|
| 68 |
+
|
| 69 |
+
- If you send your own system message, it replaces the built-in one.
|
| 70 |
+
- When tools are passed, the prompt goes after the `<tools>` block, as in the Qwen template.
|
| 71 |
+
- The rest of the template is the unchanged Qwen chat template. Tools are listed in `<tools>` and called with
|
| 72 |
+
`<tool_call><function=…><parameter=…>`.
|
| 73 |
+
|
| 74 |
+
## Reasoning (thinking)
|
| 75 |
+
|
| 76 |
+
llama.cpp turns reasoning on by default for templates that support it, but this model is meant to answer directly.
|
| 77 |
+
Start the server with `--reasoning off`, or turn reasoning off per request with
|
| 78 |
+
`"chat_template_kwargs": {"enable_thinking": false}` or `"reasoning_effort": "none"`. To try reasoning, send your own
|
| 79 |
+
system message together with `"chat_template_kwargs": {"enable_thinking": true}`.
|
| 80 |
+
|
| 81 |
+
## Measured
|
| 82 |
+
|
| 83 |
+
CPU speed: `llama-bench` on the CPU of an NVIDIA GH200 node (Grace, 64 threads), CPU-only llama.cpp build, nothing else
|
| 84 |
+
running. Answers: `llama-server --reasoning off`, greedy, built-in prompt.
|
| 85 |
+
|
| 86 |
+
| | Q3_K_M | Q4_K_M | Q6_K |
|
| 87 |
+
|---|---|---|---|
|
| 88 |
+
| Prompt processing (pp512) | 20.1 tokens/s | 50.2 tokens/s | 45.3 tokens/s |
|
| 89 |
+
| Generation (tg128) | 5.17 tokens/s | 5.04 tokens/s | 4.11 tokens/s |
|
| 90 |
+
| Pens question | $29 | $29 | $29 |
|
| 91 |
+
| Tool-calling test (117 cases) | 109/117 (93.2%) | — | — |
|
| 92 |
+
|
| 93 |
+
Q4_K_M answer: "Tom buys 7 pens at $3 each, so the total cost is 7 * 3 = $21. He pays with a $50 bill, so the change
|
| 94 |
+
he gets is 50 - 21 = $29."
|
| 95 |
+
|
| 96 |
+
Tool calling (Q3_K_M): **109/117 (93.2%)** on our internal 117-case test through the OpenAI-compatible API of `llama-server` (standard `tools`, llama.cpp's Qwen tool-call parser, temperature 0, reasoning off): single call 38/38, parallel calls 19/19, follow-up 20/20, no tool needed 25/25, clarify a missing argument 7/15 (it called the tool instead of asking).
|
| 97 |
+
|
| 98 |
+
On an older server CPU without AVX2 (2 × Xeon E5-2697 v2, 24 cores), Q3_K_M runs at 2.06 tokens/s prompt processing and 0.86 tokens/s generation.
|
| 99 |
+
|
| 100 |
+
Each file was checked against the GGUF it was made from:
|
| 101 |
+
- the only changed metadata key is the chat template;
|
| 102 |
+
- all 1,714 tensors have the same names, types and shapes;
|
| 103 |
+
- 8 of the tensors were compared byte for byte.
|
| 104 |
+
|
| 105 |
+
Template checks through `llama-server` (on Q4_K_M; the template is byte-identical in all three files):
|
| 106 |
+
|
| 107 |
+
| Request | Result |
|
| 108 |
+
|---|---|
|
| 109 |
+
| no system message | built-in prompt added; the reply starts after an empty `<think></think>` block |
|
| 110 |
+
| own system message | built-in prompt not added |
|
| 111 |
+
| with tools | built-in prompt added after the tools block |
|
| 112 |
+
| `enable_thinking: true` | the reply starts inside `<think>` |
|
| 113 |
+
|
| 114 |
+
Generation reads the whole file once per token, so on CPUs with less memory bandwidth than Grace it is proportionally
|
| 115 |
+
slower.
|
| 116 |
+
|
| 117 |
+
## Limitations
|
| 118 |
+
|
| 119 |
+
- Early release; see the main model card.
|
| 120 |
+
- These are lossy quantizations of the bf16 weights, made without an importance matrix. GSM8K and HumanEval
|
| 121 |
+
of the GGUF files are not measured yet; tool calling is measured on Q3_K_M (above).
|
| 122 |
+
- Not ternary yet: ternary QAT (and a TQ2_0 GGUF) is a planned later stage.
|
| 123 |
+
- An Ollama build is not published yet.
|
| 124 |
+
- Not for medical, legal or financial advice.
|
| 125 |
+
|
| 126 |
+
## License
|
| 127 |
+
|
| 128 |
+
Same license as the main model (see `LICENSE` and `NOTICE.md` in the root of this repository). The weights are derived from a Qwen model released under Apache 2.0. Changes by CMSManhattan (Konstantin Grabko): model code, architecture and weights, fine-tuning, GGUF conversion and the built-in system prompt.
|
model-00001-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c1360d4af0ce009aaa30a0159a667ddc59298e927a8cdf820f015db8d17eba0a
|
| 3 |
+
size 5146507008
|
model-00002-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:2b88380f4538c1d5a023e89b795fb9e3aa7d1887ea8e14edd20ee451bc55a075
|
| 3 |
+
size 5204245040
|
model-00003-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:07ee192c49b4fa41f8236a3b92153820c42cc4bc4ee8cfdb985eeded7cd48127
|
| 3 |
+
size 5226281296
|
model-00004-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:55e52de05145920a220e89bb564adf50e43ea99597e6a566dcc5744b9066807c
|
| 3 |
+
size 5226281352
|
model-00005-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ebb1ecb964ee82f89f796796689e767c876440672c90f6a1c0793405c42cd2f0
|
| 3 |
+
size 5226281352
|
model-00006-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:57ca557f3b558c080e8bde31c87e4214099995e408df8d9d207ef5260d05f70c
|
| 3 |
+
size 5204245104
|
model-00007-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:e4bd5929c8cb98f744f8d0d6a82adc3c21960dcfc357c8db9ba11d10cbcdd2ba
|
| 3 |
+
size 5226281352
|
model-00008-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:de56d111c6e08a02a5d7c863adf0c05980c4efa23e742113caacda1d248eb304
|
| 3 |
+
size 5226281352
|
model-00009-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:0cb7e2b4989b3be6bfd0ba94bd84c14b06356cb76aa199e9f788af3ce12ac73c
|
| 3 |
+
size 5226281352
|
model-00010-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd4c4509fdf30a4404d16d7d3c734eb28bc8bafe1864a1759b9c0dc33e66da62
|
| 3 |
+
size 5204245104
|
model-00011-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ce3bc4cc3bbf0f02ae4ee3f703df6fc824ffc1a55086421f8c7ca7f8d00bdd3c
|
| 3 |
+
size 5226281352
|
model-00012-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:3fecbfb15b8e92fd41b22d3509a178572764b6ffd39b4142dc190e466e925dfc
|
| 3 |
+
size 5226281352
|
model-00013-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:27236071639417aaa92d756239fc403f2b6ab72d3fef247a614a2f681f107796
|
| 3 |
+
size 5226281352
|
model-00014-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:47c992e281a5387c19de30b86c344b3d3b0649ab2d11977b9c294d49cee53ed1
|
| 3 |
+
size 5204245104
|
model-00015-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:5d7e1f039d216da37c40e655775534c52210ca7bb08b90d902459be52b39959d
|
| 3 |
+
size 5226281352
|
model-00016-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fcb1983d57449ce9af7f702cf5db51cedae41df04c418acdc2c7e78852a8af9b
|
| 3 |
+
size 5226281352
|
model-00017-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:b0fb91fdf474b9f2f0b7e404b304a126047fb9da957934a70ff658a107d9ecfd
|
| 3 |
+
size 5226281352
|
model-00018-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:fd5eb70f5171fb1dceba0d0277bfc5af75fa895952bd646717bfd6a25958f017
|
| 3 |
+
size 5204245104
|
model-00019-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:49e77b4426051b3fc8c7c18da83d48288f3ca4b694fc687a92d903fdd5a07063
|
| 3 |
+
size 5226281352
|
model-00020-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:4fe115d9440d1732381ee44bbc07e142d5871c1e288bcdf3598273261daace87
|
| 3 |
+
size 5226281352
|
model-00021-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:22652bf288a10fa233fcf7adcc9d02d4309643badbd0c8cce1274c0cf9ec715b
|
| 3 |
+
size 5226281360
|
model-00022-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6db8017e7414d546907bd8ebb90458e9932b4b8d5dfcbe071ecf4f5d982aa289
|
| 3 |
+
size 5204245168
|
model-00023-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:50cc1a1b337270c327cb90566b1fd99c9c3e42f08e96f148fca6c1f8c432c7c1
|
| 3 |
+
size 5226281424
|
model-00024-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:24b94858756a2c0ad41faf3f33fc6a15e3406844288896336cd12112e79755ac
|
| 3 |
+
size 5226281424
|
model-00025-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:ca3ab652f04c9b441244c00fe1a50304309c6a7486c2f37cafd0ceb22ae86208
|
| 3 |
+
size 5226281424
|
model-00026-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:360f47926cc9428ee23e4fb75ea1911ed4f0970a19679ce5ed80338f15409328
|
| 3 |
+
size 5204245168
|
model-00027-of-00027.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:16fe0a0184cdf5468f0e406cba58990cc930932519bbd5bd5ac3163261ffb41b
|
| 3 |
+
size 4220603664
|
model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sft_final_fp8/.gitattributes
ADDED
|
@@ -0,0 +1,36 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
tokenizer.json filter=lfs diff=lfs merge=lfs -text
|
sft_final_fp8/JiRackDeltaNet_70b.py
ADDED
|
@@ -0,0 +1,619 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# =============================================================================
|
| 2 |
+
# JiRackDeltaNet_70b.py - JiRack DeltaNet 70B
|
| 3 |
+
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
|
| 4 |
+
# All rights reserved. Proprietary JiRack license, see LICENSE.
|
| 5 |
+
# =============================================================================
|
| 6 |
+
|
| 7 |
+
""
|
| 8 |
+
|
| 9 |
+
import os
|
| 10 |
+
import re
|
| 11 |
+
import torch
|
| 12 |
+
import torch.nn as nn
|
| 13 |
+
import torch.nn.functional as F
|
| 14 |
+
|
| 15 |
+
HIDDEN_SIZE = 5120
|
| 16 |
+
VOCAB_SIZE = 248320
|
| 17 |
+
INTERMEDIATE_SIZE = 26624
|
| 18 |
+
NUM_LAYERS = 128
|
| 19 |
+
RMS_NORM_EPS = 1e-6
|
| 20 |
+
|
| 21 |
+
LAYER_TYPES = ["linear_attention"] * 3 + ["full_attention"]
|
| 22 |
+
LAYER_TYPES = (LAYER_TYPES * (NUM_LAYERS // len(LAYER_TYPES) + 1))[:NUM_LAYERS]
|
| 23 |
+
|
| 24 |
+
LINEAR_NUM_KEY_HEADS = 16
|
| 25 |
+
LINEAR_KEY_HEAD_DIM = 128
|
| 26 |
+
LINEAR_NUM_VALUE_HEADS = 48
|
| 27 |
+
LINEAR_VALUE_HEAD_DIM = 128
|
| 28 |
+
LINEAR_CONV_KERNEL_DIM = 4
|
| 29 |
+
DELTA_KEY_DIM = LINEAR_NUM_KEY_HEADS * LINEAR_KEY_HEAD_DIM
|
| 30 |
+
DELTA_VALUE_DIM = LINEAR_NUM_VALUE_HEADS * LINEAR_VALUE_HEAD_DIM
|
| 31 |
+
DELTA_CONV_DIM = DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM
|
| 32 |
+
DELTA_CHUNK_SIZE = 64
|
| 33 |
+
|
| 34 |
+
NUM_ATTENTION_HEADS = 24
|
| 35 |
+
NUM_KEY_VALUE_HEADS = 4
|
| 36 |
+
HEAD_DIM = 256
|
| 37 |
+
PARTIAL_ROTARY_FACTOR = 0.25
|
| 38 |
+
ROPE_THETA = 1e7
|
| 39 |
+
MROPE_SECTION = [11, 11, 10]
|
| 40 |
+
ATTENTION_BIAS = False
|
| 41 |
+
|
| 42 |
+
ARCH_SUMMARY = f"""
|
| 43 |
+
JiRack hybrid layout, hand-rolled JiRack TransformerBlock, text-only.
|
| 44 |
+
hidden_size={HIDDEN_SIZE}, vocab_size={VOCAB_SIZE},
|
| 45 |
+
intermediate_size={INTERMEDIATE_SIZE}, num_hidden_layers={NUM_LAYERS}
|
| 46 |
+
Interleaving (interval=4): 3x linear_attention (DeltaNet), 1x full_attention
|
| 47 |
+
"""
|
| 48 |
+
|
| 49 |
+
KEPT_FULL_PRECISION = """
|
| 50 |
+
Always kept in full precision (not GEMMs, or too sensitive):
|
| 51 |
+
- dt_bias, A_log (raw Parameters, DeltaNet decay)
|
| 52 |
+
- linear_attn.in_proj_b/in_proj_a (by default, see GATE_PROJ_PATTERNS)
|
| 53 |
+
- conv1d (depthwise grouped conv, not a GEMM)
|
| 54 |
+
- all norms: RMSNormGated, q_norm/k_norm, model.norm
|
| 55 |
+
- embed_tokens, lm_head
|
| 56 |
+
- mtp.* (the whole MTP/NextN head) (the draft layer of speculative decoding;
|
| 57 |
+
ternarization kills the acceptance rate,
|
| 58 |
+
community GGUFs keep it in Q8_0)
|
| 59 |
+
"""
|
| 60 |
+
|
| 61 |
+
class BitLinear(nn.Linear):
|
| 62 |
+
""
|
| 63 |
+
|
| 64 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 65 |
+
super().__init__(in_features, out_features, bias=bias)
|
| 66 |
+
self.eps = 1e-5
|
| 67 |
+
self.register_buffer("lambda_", torch.zeros(()), persistent=True)
|
| 68 |
+
|
| 69 |
+
@classmethod
|
| 70 |
+
def from_linear(cls, lin: nn.Linear) -> "BitLinear":
|
| 71 |
+
bl = cls(lin.in_features, lin.out_features, bias=lin.bias is not None)
|
| 72 |
+
bl = bl.to(dtype=lin.weight.dtype, device=lin.weight.device)
|
| 73 |
+
with torch.no_grad():
|
| 74 |
+
bl.weight.copy_(lin.weight)
|
| 75 |
+
if lin.bias is not None:
|
| 76 |
+
bl.bias.copy_(lin.bias)
|
| 77 |
+
return bl
|
| 78 |
+
|
| 79 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 80 |
+
if not self.training and float(self.lambda_) < 1e-6:
|
| 81 |
+
return F.linear(x, self.weight, self.bias)
|
| 82 |
+
|
| 83 |
+
lam = self.lambda_.to(x.dtype)
|
| 84 |
+
w = self.weight
|
| 85 |
+
gamma = w.float().abs().mean().clamp(min=self.eps).to(w.dtype)
|
| 86 |
+
w_quant = torch.clamp(torch.round(w / gamma), -1.0, 1.0) * gamma
|
| 87 |
+
w_effective = w + lam * (w_quant - w).detach()
|
| 88 |
+
|
| 89 |
+
x_scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp(min=self.eps)
|
| 90 |
+
x_quant = torch.clamp(torch.round(x * x_scale), -128.0, 127.0) / x_scale
|
| 91 |
+
x_effective = x + lam * (x_quant - x).detach()
|
| 92 |
+
|
| 93 |
+
return F.linear(x_effective, w_effective, self.bias)
|
| 94 |
+
|
| 95 |
+
def set_lambda(self, v: float):
|
| 96 |
+
self.lambda_.fill_(v)
|
| 97 |
+
|
| 98 |
+
TERNARIZE_PATTERNS = [
|
| 99 |
+
r"linear_attn\.in_proj_qkv$",
|
| 100 |
+
r"linear_attn\.in_proj_z$",
|
| 101 |
+
r"linear_attn\.out_proj$",
|
| 102 |
+
r"self_attn\.q_proj$",
|
| 103 |
+
r"self_attn\.k_proj$",
|
| 104 |
+
r"self_attn\.v_proj$",
|
| 105 |
+
r"self_attn\.o_proj$",
|
| 106 |
+
r"mlp\.gate_proj$",
|
| 107 |
+
r"mlp\.up_proj$",
|
| 108 |
+
r"mlp\.down_proj$",
|
| 109 |
+
]
|
| 110 |
+
|
| 111 |
+
GATE_PROJ_PATTERNS = [
|
| 112 |
+
r"linear_attn\.in_proj_b$",
|
| 113 |
+
r"linear_attn\.in_proj_a$",
|
| 114 |
+
]
|
| 115 |
+
|
| 116 |
+
def apply_bitlinear_patch(model: nn.Module, include_gate_proj: bool = False):
|
| 117 |
+
""
|
| 118 |
+
patterns = list(TERNARIZE_PATTERNS)
|
| 119 |
+
if include_gate_proj:
|
| 120 |
+
patterns += GATE_PROJ_PATTERNS
|
| 121 |
+
compiled = [re.compile(p) for p in patterns]
|
| 122 |
+
|
| 123 |
+
patched = []
|
| 124 |
+
for name, module in list(model.named_modules()):
|
| 125 |
+
if not isinstance(module, nn.Linear):
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
if name.startswith("mtp"):
|
| 129 |
+
continue
|
| 130 |
+
if any(p.search(name) for p in compiled):
|
| 131 |
+
parent_name, _, child_name = name.rpartition(".")
|
| 132 |
+
parent = model.get_submodule(parent_name) if parent_name else model
|
| 133 |
+
setattr(parent, child_name, BitLinear.from_linear(module))
|
| 134 |
+
patched.append(name)
|
| 135 |
+
return patched
|
| 136 |
+
|
| 137 |
+
class RMSNorm(nn.Module):
|
| 138 |
+
""
|
| 139 |
+
|
| 140 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 141 |
+
super().__init__()
|
| 142 |
+
self.eps = eps
|
| 143 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
| 144 |
+
|
| 145 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 146 |
+
dtype = x.dtype
|
| 147 |
+
x = x.float()
|
| 148 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 149 |
+
x = x * (1.0 + self.weight.float())
|
| 150 |
+
return x.to(dtype)
|
| 151 |
+
|
| 152 |
+
class RMSNormGated(nn.Module):
|
| 153 |
+
""
|
| 154 |
+
|
| 155 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 156 |
+
super().__init__()
|
| 157 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 158 |
+
self.eps = eps
|
| 159 |
+
|
| 160 |
+
def forward(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
|
| 161 |
+
dtype = x.dtype
|
| 162 |
+
x = x.float()
|
| 163 |
+
var = x.pow(2).mean(-1, keepdim=True)
|
| 164 |
+
x = x * torch.rsqrt(var + self.eps)
|
| 165 |
+
x = self.weight * x.to(dtype)
|
| 166 |
+
x = x * F.silu(gate.float())
|
| 167 |
+
return x.to(dtype)
|
| 168 |
+
|
| 169 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 170 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 171 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 172 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 173 |
+
|
| 174 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 175 |
+
""
|
| 176 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 177 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 178 |
+
rotary_dim = cos.shape[-1]
|
| 179 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 180 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 181 |
+
q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
|
| 182 |
+
k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
|
| 183 |
+
return q_embed, k_embed
|
| 184 |
+
|
| 185 |
+
class TextRotaryEmbedding(nn.Module):
|
| 186 |
+
""
|
| 187 |
+
|
| 188 |
+
def __init__(self, head_dim=HEAD_DIM, partial_rotary_factor=PARTIAL_ROTARY_FACTOR,
|
| 189 |
+
theta=ROPE_THETA, mrope_section=MROPE_SECTION):
|
| 190 |
+
super().__init__()
|
| 191 |
+
self.rotary_dim = int(head_dim * partial_rotary_factor)
|
| 192 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, self.rotary_dim, 2, dtype=torch.float32) / self.rotary_dim))
|
| 193 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 194 |
+
self.mrope_section = mrope_section
|
| 195 |
+
|
| 196 |
+
def _apply_interleaved_mrope(self, freqs: torch.Tensor) -> torch.Tensor:
|
| 197 |
+
|
| 198 |
+
freqs_t = freqs[0].clone()
|
| 199 |
+
for dim, offset in enumerate((1, 2), start=1):
|
| 200 |
+
length = self.mrope_section[dim] * 3
|
| 201 |
+
idx = slice(offset, length, 3)
|
| 202 |
+
freqs_t[..., idx] = freqs[dim, ..., idx]
|
| 203 |
+
return freqs_t
|
| 204 |
+
|
| 205 |
+
@torch.no_grad()
|
| 206 |
+
def forward(self, x: torch.Tensor, position_ids: torch.LongTensor):
|
| 207 |
+
|
| 208 |
+
if position_ids.ndim == 2:
|
| 209 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 210 |
+
inv_freq_exp = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
| 211 |
+
pos_exp = position_ids[:, :, None, :].float()
|
| 212 |
+
freqs = (inv_freq_exp @ pos_exp).transpose(2, 3)
|
| 213 |
+
freqs = self._apply_interleaved_mrope(freqs)
|
| 214 |
+
emb = torch.cat((freqs, freqs), dim=-1)
|
| 215 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 216 |
+
|
| 217 |
+
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6):
|
| 218 |
+
return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
| 219 |
+
|
| 220 |
+
def causal_conv1d(hidden_states: torch.Tensor, weight: torch.Tensor, activation: str = "silu"):
|
| 221 |
+
""
|
| 222 |
+
channels, seq_len = hidden_states.shape[1], hidden_states.shape[2]
|
| 223 |
+
padding = weight.shape[-1] - 1
|
| 224 |
+
out = F.conv1d(hidden_states, weight=weight.unsqueeze(1), bias=None, padding=padding, groups=channels)
|
| 225 |
+
out = out[:, :, :seq_len]
|
| 226 |
+
return F.silu(out) if activation == "silu" else out
|
| 227 |
+
|
| 228 |
+
def chunked_gated_delta_rule(query, key, value, g, beta, chunk_size=DELTA_CHUNK_SIZE):
|
| 229 |
+
""
|
| 230 |
+
initial_dtype = query.dtype
|
| 231 |
+
query = l2norm(query, dim=-1, eps=1e-6)
|
| 232 |
+
key = l2norm(key, dim=-1, eps=1e-6)
|
| 233 |
+
query, key, value, beta, g = [x.contiguous().to(torch.float32) for x in (query, key, value, beta, g)]
|
| 234 |
+
|
| 235 |
+
b, h, t, k_dim = key.shape
|
| 236 |
+
v_dim = value.shape[-1]
|
| 237 |
+
pad = (chunk_size - t % chunk_size) % chunk_size
|
| 238 |
+
query = F.pad(query, (0, 0, 0, pad))
|
| 239 |
+
key = F.pad(key, (0, 0, 0, pad))
|
| 240 |
+
value = F.pad(value, (0, 0, 0, pad))
|
| 241 |
+
beta = F.pad(beta, (0, pad))
|
| 242 |
+
g = F.pad(g, (0, pad))
|
| 243 |
+
total_t = t + pad
|
| 244 |
+
scale = 1 / (query.shape[-1] ** 0.5)
|
| 245 |
+
query = query * scale
|
| 246 |
+
|
| 247 |
+
v_beta = value * beta.unsqueeze(-1)
|
| 248 |
+
k_beta = key * beta.unsqueeze(-1)
|
| 249 |
+
query, key, value, k_beta, v_beta = [
|
| 250 |
+
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
|
| 251 |
+
]
|
| 252 |
+
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
|
| 253 |
+
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
|
| 254 |
+
|
| 255 |
+
g = g.cumsum(dim=-1)
|
| 256 |
+
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
|
| 257 |
+
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
|
| 258 |
+
for i in range(1, chunk_size):
|
| 259 |
+
row = attn[..., i, :i].clone()
|
| 260 |
+
sub = attn[..., :i, :i].clone()
|
| 261 |
+
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
|
| 262 |
+
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
|
| 263 |
+
value = attn @ v_beta
|
| 264 |
+
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
|
| 265 |
+
|
| 266 |
+
last_state = torch.zeros(b, h, k_dim, v_dim, dtype=value.dtype, device=value.device)
|
| 267 |
+
core_out = torch.zeros_like(value)
|
| 268 |
+
|
| 269 |
+
for i in range(total_t // chunk_size):
|
| 270 |
+
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
|
| 271 |
+
attn_i = q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]
|
| 272 |
+
v_prime = k_cumdecay[:, :, i] @ last_state
|
| 273 |
+
v_new = v_i - v_prime
|
| 274 |
+
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_state
|
| 275 |
+
core_out[:, :, i] = attn_inter + attn_i @ v_new
|
| 276 |
+
last_state = (
|
| 277 |
+
last_state * g[:, :, i, -1, None, None].exp()
|
| 278 |
+
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
|
| 279 |
+
)
|
| 280 |
+
|
| 281 |
+
core_out = core_out.reshape(core_out.shape[0], core_out.shape[1], -1, core_out.shape[-1])
|
| 282 |
+
core_out = core_out[:, :, :t]
|
| 283 |
+
core_out = core_out.transpose(1, 2).contiguous().to(initial_dtype)
|
| 284 |
+
return core_out
|
| 285 |
+
|
| 286 |
+
class GatedDeltaNetBlock(nn.Module):
|
| 287 |
+
""
|
| 288 |
+
|
| 289 |
+
def __init__(self):
|
| 290 |
+
super().__init__()
|
| 291 |
+
self.conv1d = nn.Conv1d(
|
| 292 |
+
in_channels=DELTA_CONV_DIM, out_channels=DELTA_CONV_DIM, bias=False,
|
| 293 |
+
kernel_size=LINEAR_CONV_KERNEL_DIM, groups=DELTA_CONV_DIM,
|
| 294 |
+
padding=LINEAR_CONV_KERNEL_DIM - 1,
|
| 295 |
+
)
|
| 296 |
+
self.dt_bias = nn.Parameter(torch.ones(LINEAR_NUM_VALUE_HEADS))
|
| 297 |
+
A = torch.empty(LINEAR_NUM_VALUE_HEADS).uniform_(0.01, 16)
|
| 298 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 299 |
+
self.norm = RMSNormGated(LINEAR_VALUE_HEAD_DIM, eps=RMS_NORM_EPS)
|
| 300 |
+
self.out_proj = nn.Linear(DELTA_VALUE_DIM, HIDDEN_SIZE, bias=False)
|
| 301 |
+
self.in_proj_qkv = nn.Linear(HIDDEN_SIZE, DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM, bias=False)
|
| 302 |
+
self.in_proj_z = nn.Linear(HIDDEN_SIZE, DELTA_VALUE_DIM, bias=False)
|
| 303 |
+
self.in_proj_b = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 304 |
+
self.in_proj_a = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 305 |
+
|
| 306 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 307 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 308 |
+
|
| 309 |
+
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2)
|
| 310 |
+
z = self.in_proj_z(hidden_states).reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 311 |
+
b = self.in_proj_b(hidden_states)
|
| 312 |
+
a = self.in_proj_a(hidden_states)
|
| 313 |
+
|
| 314 |
+
mixed_qkv = causal_conv1d(mixed_qkv, self.conv1d.weight.squeeze(1), activation="silu")
|
| 315 |
+
mixed_qkv = mixed_qkv.transpose(1, 2)
|
| 316 |
+
|
| 317 |
+
query, key, value = torch.split(mixed_qkv, [DELTA_KEY_DIM, DELTA_KEY_DIM, DELTA_VALUE_DIM], dim=-1)
|
| 318 |
+
query = query.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 319 |
+
key = key.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 320 |
+
value = value.reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 321 |
+
|
| 322 |
+
beta = b.sigmoid()
|
| 323 |
+
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
| 324 |
+
|
| 325 |
+
rep = LINEAR_NUM_VALUE_HEADS // LINEAR_NUM_KEY_HEADS
|
| 326 |
+
if rep > 1:
|
| 327 |
+
query = query.repeat_interleave(rep, dim=2)
|
| 328 |
+
key = key.repeat_interleave(rep, dim=2)
|
| 329 |
+
|
| 330 |
+
query_h = query.transpose(1, 2)
|
| 331 |
+
key_h = key.transpose(1, 2)
|
| 332 |
+
value_h = value.transpose(1, 2)
|
| 333 |
+
beta_h = beta.transpose(1, 2)
|
| 334 |
+
g_h = g.transpose(1, 2)
|
| 335 |
+
|
| 336 |
+
core_attn_out = chunked_gated_delta_rule(query_h, key_h, value_h, g_h, beta_h)
|
| 337 |
+
|
| 338 |
+
core_attn_out = core_attn_out.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 339 |
+
z_flat = z.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 340 |
+
core_attn_out = self.norm(core_attn_out, z_flat)
|
| 341 |
+
core_attn_out = core_attn_out.reshape(bsz, seq_len, -1)
|
| 342 |
+
|
| 343 |
+
return self.out_proj(core_attn_out)
|
| 344 |
+
|
| 345 |
+
class AttentionBlock(nn.Module):
|
| 346 |
+
""
|
| 347 |
+
|
| 348 |
+
def __init__(self):
|
| 349 |
+
super().__init__()
|
| 350 |
+
self.num_key_value_groups = NUM_ATTENTION_HEADS // NUM_KEY_VALUE_HEADS
|
| 351 |
+
self.scaling = HEAD_DIM ** -0.5
|
| 352 |
+
self.q_proj = nn.Linear(HIDDEN_SIZE, NUM_ATTENTION_HEADS * HEAD_DIM * 2, bias=ATTENTION_BIAS)
|
| 353 |
+
self.k_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 354 |
+
self.v_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 355 |
+
self.o_proj = nn.Linear(NUM_ATTENTION_HEADS * HEAD_DIM, HIDDEN_SIZE, bias=ATTENTION_BIAS)
|
| 356 |
+
self.q_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 357 |
+
self.k_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 358 |
+
|
| 359 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 360 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 361 |
+
hidden_shape = (bsz, seq_len, -1, HEAD_DIM)
|
| 362 |
+
|
| 363 |
+
query_states, gate = torch.chunk(
|
| 364 |
+
self.q_proj(hidden_states).view(bsz, seq_len, -1, HEAD_DIM * 2), 2, dim=-1
|
| 365 |
+
)
|
| 366 |
+
gate = gate.reshape(bsz, seq_len, -1)
|
| 367 |
+
|
| 368 |
+
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
|
| 369 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 370 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 371 |
+
|
| 372 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 373 |
+
|
| 374 |
+
rep = self.num_key_value_groups
|
| 375 |
+
key_states = key_states.repeat_interleave(rep, dim=1)
|
| 376 |
+
value_states = value_states.repeat_interleave(rep, dim=1)
|
| 377 |
+
|
| 378 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
|
| 379 |
+
attn_weights = attn_weights + causal_mask
|
| 380 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 381 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 382 |
+
attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1)
|
| 383 |
+
attn_output = attn_output * torch.sigmoid(gate)
|
| 384 |
+
|
| 385 |
+
return self.o_proj(attn_output)
|
| 386 |
+
|
| 387 |
+
class MLPBlock(nn.Module):
|
| 388 |
+
def __init__(self):
|
| 389 |
+
super().__init__()
|
| 390 |
+
self.gate_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 391 |
+
self.up_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 392 |
+
self.down_proj = nn.Linear(INTERMEDIATE_SIZE, HIDDEN_SIZE, bias=False)
|
| 393 |
+
|
| 394 |
+
def forward(self, x):
|
| 395 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 396 |
+
|
| 397 |
+
class TransformerBlock(nn.Module):
|
| 398 |
+
""
|
| 399 |
+
|
| 400 |
+
def __init__(self, layer_idx: int, layer_type: str = None):
|
| 401 |
+
super().__init__()
|
| 402 |
+
|
| 403 |
+
self.block_type = layer_type if layer_type is not None else LAYER_TYPES[layer_idx]
|
| 404 |
+
if self.block_type == "linear_attention":
|
| 405 |
+
self.linear_attn = GatedDeltaNetBlock()
|
| 406 |
+
else:
|
| 407 |
+
self.self_attn = AttentionBlock()
|
| 408 |
+
self.mlp = MLPBlock()
|
| 409 |
+
self.input_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 410 |
+
self.post_attention_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 411 |
+
|
| 412 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 413 |
+
residual = hidden_states
|
| 414 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 415 |
+
if self.block_type == "linear_attention":
|
| 416 |
+
hidden_states = self.linear_attn(hidden_states)
|
| 417 |
+
else:
|
| 418 |
+
hidden_states = self.self_attn(hidden_states, cos, sin, causal_mask)
|
| 419 |
+
hidden_states = residual + hidden_states
|
| 420 |
+
|
| 421 |
+
residual = hidden_states
|
| 422 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 423 |
+
hidden_states = self.mlp(hidden_states)
|
| 424 |
+
hidden_states = residual + hidden_states
|
| 425 |
+
return hidden_states
|
| 426 |
+
|
| 427 |
+
class MTPBlock(nn.Module):
|
| 428 |
+
""
|
| 429 |
+
|
| 430 |
+
def __init__(self):
|
| 431 |
+
super().__init__()
|
| 432 |
+
self.pre_fc_norm_embedding = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 433 |
+
self.pre_fc_norm_hidden = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 434 |
+
self.fc = nn.Linear(2 * HIDDEN_SIZE, HIDDEN_SIZE, bias=False)
|
| 435 |
+
self.layers = nn.ModuleList([
|
| 436 |
+
TransformerBlock(layer_idx=NUM_LAYERS, layer_type="full_attention"),
|
| 437 |
+
])
|
| 438 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 439 |
+
|
| 440 |
+
def forward(self, inputs_embeds, previous_hidden, cos, sin, causal_mask):
|
| 441 |
+
""
|
| 442 |
+
h = self.fc(torch.cat(
|
| 443 |
+
(self.pre_fc_norm_embedding(inputs_embeds),
|
| 444 |
+
self.pre_fc_norm_hidden(previous_hidden)),
|
| 445 |
+
dim=-1,
|
| 446 |
+
))
|
| 447 |
+
h = self.layers[0](h, cos, sin, causal_mask)
|
| 448 |
+
return self.norm(h)
|
| 449 |
+
|
| 450 |
+
class JiRackDeltaNetModel(nn.Module):
|
| 451 |
+
def __init__(self):
|
| 452 |
+
super().__init__()
|
| 453 |
+
self.embed_tokens = nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
|
| 454 |
+
self.layers = nn.ModuleList([TransformerBlock(i) for i in range(NUM_LAYERS)])
|
| 455 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 456 |
+
self.rotary_emb = TextRotaryEmbedding()
|
| 457 |
+
|
| 458 |
+
def forward(self, input_ids: torch.LongTensor, return_prenorm: bool = False):
|
| 459 |
+
bsz, seq_len = input_ids.shape
|
| 460 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 461 |
+
|
| 462 |
+
position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(bsz, -1)
|
| 463 |
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
| 464 |
+
|
| 465 |
+
causal_mask = torch.full((seq_len, seq_len), float("-inf"), device=input_ids.device, dtype=torch.float32)
|
| 466 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)[None, None, :, :].to(hidden_states.dtype)
|
| 467 |
+
|
| 468 |
+
for layer in self.layers:
|
| 469 |
+
hidden_states = layer(hidden_states, cos, sin, causal_mask)
|
| 470 |
+
|
| 471 |
+
if return_prenorm:
|
| 472 |
+
|
| 473 |
+
return self.norm(hidden_states), hidden_states, (cos, sin, causal_mask)
|
| 474 |
+
return self.norm(hidden_states)
|
| 475 |
+
|
| 476 |
+
class JiRackDeltaNetForCausalLM(nn.Module):
|
| 477 |
+
""
|
| 478 |
+
|
| 479 |
+
def __init__(self):
|
| 480 |
+
super().__init__()
|
| 481 |
+
self.model = JiRackDeltaNetModel()
|
| 482 |
+
self.lm_head = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False)
|
| 483 |
+
|
| 484 |
+
self.mtp = MTPBlock()
|
| 485 |
+
|
| 486 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
|
| 487 |
+
hidden_states = self.model(input_ids)
|
| 488 |
+
return self.lm_head(hidden_states)
|
| 489 |
+
|
| 490 |
+
def mtp_forward(self, input_ids: torch.LongTensor):
|
| 491 |
+
""
|
| 492 |
+
_, prenorm_hidden, (cos, sin, causal_mask) = self.model(
|
| 493 |
+
input_ids, return_prenorm=True)
|
| 494 |
+
logits_t1 = self.lm_head(self.model.norm(prenorm_hidden))
|
| 495 |
+
|
| 496 |
+
shifted = torch.cat([input_ids[:, 1:], input_ids[:, -1:]], dim=1)
|
| 497 |
+
emb_next = self.model.embed_tokens(shifted)
|
| 498 |
+
h2 = self.mtp(emb_next, prenorm_hidden, cos, sin, causal_mask)
|
| 499 |
+
logits_t2 = self.lm_head(h2)
|
| 500 |
+
return logits_t1, logits_t2
|
| 501 |
+
|
| 502 |
+
def load_hf_state_dict(self, state_dict: dict, strict: bool = False):
|
| 503 |
+
""
|
| 504 |
+
missing, unexpected = self.load_state_dict(state_dict, strict=strict)
|
| 505 |
+
real_missing = [k for k in missing if not k.endswith("lambda_")]
|
| 506 |
+
if real_missing:
|
| 507 |
+
print(f"⚠️ {len(real_missing)} missing keys (first 10): {real_missing[:10]}")
|
| 508 |
+
if unexpected:
|
| 509 |
+
print(f"⚠️ {len(unexpected)} unexpected keys (first 10): {unexpected[:10]}")
|
| 510 |
+
return missing, unexpected
|
| 511 |
+
|
| 512 |
+
def load_mtp_from_hf_dir(self, hf_dir: str):
|
| 513 |
+
""
|
| 514 |
+
import glob
|
| 515 |
+
import json as _json
|
| 516 |
+
from safetensors import safe_open
|
| 517 |
+
|
| 518 |
+
index_path = os.path.join(hf_dir, "model.safetensors.index.json")
|
| 519 |
+
mtp_map = {}
|
| 520 |
+
if os.path.exists(index_path):
|
| 521 |
+
with open(index_path) as f:
|
| 522 |
+
weight_map = _json.load(f)["weight_map"]
|
| 523 |
+
for k, shard in weight_map.items():
|
| 524 |
+
if k.startswith("mtp."):
|
| 525 |
+
mtp_map[k] = os.path.join(hf_dir, shard)
|
| 526 |
+
else:
|
| 527 |
+
for shard in glob.glob(os.path.join(hf_dir, "*.safetensors")):
|
| 528 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 529 |
+
for k in f.keys():
|
| 530 |
+
if k.startswith("mtp."):
|
| 531 |
+
mtp_map[k] = shard
|
| 532 |
+
|
| 533 |
+
if not mtp_map:
|
| 534 |
+
raise FileNotFoundError(
|
| 535 |
+
f"In {hf_dir}: no mtp.* tensor found. Needed: "
|
| 536 |
+
f"the source HF checkpoint (not a JiRack export!). "
|
| 537 |
+
f"If the source shards were deleted, download again from the HF Hub "
|
| 538 |
+
f"only the shards with mtp.* listed in model.safetensors.index.json.")
|
| 539 |
+
|
| 540 |
+
own_dtype = next(self.mtp.parameters()).dtype
|
| 541 |
+
loaded = {}
|
| 542 |
+
by_shard = {}
|
| 543 |
+
for k, shard in mtp_map.items():
|
| 544 |
+
by_shard.setdefault(shard, []).append(k)
|
| 545 |
+
for shard, keys in by_shard.items():
|
| 546 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 547 |
+
for k in keys:
|
| 548 |
+
loaded[k] = f.get_tensor(k).to(own_dtype)
|
| 549 |
+
|
| 550 |
+
missing, unexpected = self.load_state_dict(loaded, strict=False)
|
| 551 |
+
n_ok = len(loaded)
|
| 552 |
+
print(f"✅ MTP: loaded {n_ok} tensors from {len(by_shard)} shards ({hf_dir})")
|
| 553 |
+
if unexpected:
|
| 554 |
+
print(f"⚠️ MTP: unexpected keys: {unexpected[:10]}")
|
| 555 |
+
return n_ok
|
| 556 |
+
|
| 557 |
+
def save_checkpoint(self, path: str, lam: float, global_step: int = 0, patched_linear_names=None):
|
| 558 |
+
torch.save({
|
| 559 |
+
"model": self.state_dict(),
|
| 560 |
+
"lambda": lam,
|
| 561 |
+
"global_step": global_step,
|
| 562 |
+
"patched_linear_names": patched_linear_names or [],
|
| 563 |
+
}, path)
|
| 564 |
+
|
| 565 |
+
@classmethod
|
| 566 |
+
def load_checkpoint(cls, path: str, dtype=torch.bfloat16, include_gate_proj: bool = False):
|
| 567 |
+
ckpt = torch.load(path, map_location="cpu", weights_only=False)
|
| 568 |
+
model = cls()
|
| 569 |
+
patched_names = ckpt.get("patched_linear_names", [])
|
| 570 |
+
if patched_names:
|
| 571 |
+
for name in patched_names:
|
| 572 |
+
*parent_path, leaf = name.split(".")
|
| 573 |
+
parent = model
|
| 574 |
+
for p in parent_path:
|
| 575 |
+
parent = getattr(parent, p)
|
| 576 |
+
old = getattr(parent, leaf)
|
| 577 |
+
if not isinstance(old, BitLinear):
|
| 578 |
+
setattr(parent, leaf, BitLinear.from_linear(old))
|
| 579 |
+
else:
|
| 580 |
+
apply_bitlinear_patch(model, include_gate_proj=include_gate_proj)
|
| 581 |
+
|
| 582 |
+
has_mtp_in_ckpt = any(k.startswith("mtp.") for k in ckpt["model"])
|
| 583 |
+
model.load_state_dict(ckpt["model"], strict=False)
|
| 584 |
+
model = model.to(dtype)
|
| 585 |
+
|
| 586 |
+
if not has_mtp_in_ckpt:
|
| 587 |
+
print(
|
| 588 |
+
"⚠️ This .pt has NO mtp.* weights (the checkpoint was saved before "
|
| 589 |
+
"MTPBlock existed). The head is now RANDOMLY "
|
| 590 |
+
"initialized! Before exporting, be sure to call "
|
| 591 |
+
"model.load_mtp_from_hf_dir('<folder of the source HF checkpoint>')."
|
| 592 |
+
)
|
| 593 |
+
|
| 594 |
+
lam = ckpt.get("lambda", 0.0)
|
| 595 |
+
for m in model.modules():
|
| 596 |
+
if isinstance(m, BitLinear):
|
| 597 |
+
m.set_lambda(lam)
|
| 598 |
+
|
| 599 |
+
print(f"✅ Loaded. global_step={ckpt.get('global_step', 0)}, lambda={lam}")
|
| 600 |
+
return model
|
| 601 |
+
|
| 602 |
+
if __name__ == "__main__":
|
| 603 |
+
print(ARCH_SUMMARY)
|
| 604 |
+
print(KEPT_FULL_PRECISION)
|
| 605 |
+
|
| 606 |
+
model = JiRackDeltaNetForCausalLM()
|
| 607 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 608 |
+
print(f"✅ Model built (random weights). Parameters: {n_params / 1e9:.2f}B")
|
| 609 |
+
|
| 610 |
+
patched = apply_bitlinear_patch(model)
|
| 611 |
+
print(f"✅ Submodules replaced by BitLinear: {len(patched)}")
|
| 612 |
+
print("First 10 examples:")
|
| 613 |
+
for n in patched[:10]:
|
| 614 |
+
print(f" {n}")
|
| 615 |
+
|
| 616 |
+
ids = torch.randint(0, VOCAB_SIZE, (1, 8))
|
| 617 |
+
with torch.no_grad():
|
| 618 |
+
logits = model(ids)
|
| 619 |
+
print(f"✅ Test forward (random weights) -> logits shape: {tuple(logits.shape)}")
|
sft_final_fp8/chat_fp8.py
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# chat_fp8.py - JiRack DeltaNet 70B
|
| 4 |
+
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
|
| 5 |
+
# All rights reserved. Proprietary JiRack license, see LICENSE.
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import json
|
| 10 |
+
import os
|
| 11 |
+
import sys
|
| 12 |
+
|
| 13 |
+
import torch
|
| 14 |
+
import torch.nn as nn
|
| 15 |
+
import torch.nn.functional as F
|
| 16 |
+
|
| 17 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 18 |
+
import chat_jirack as cj
|
| 19 |
+
|
| 20 |
+
B = 128
|
| 21 |
+
|
| 22 |
+
class FP8Linear(nn.Module):
|
| 23 |
+
def __init__(self, in_features, out_features):
|
| 24 |
+
super().__init__()
|
| 25 |
+
assert in_features % B == 0 and out_features % B == 0, (in_features, out_features)
|
| 26 |
+
self.in_features, self.out_features = in_features, out_features
|
| 27 |
+
self.register_buffer("weight", torch.empty(out_features, in_features, dtype=torch.float8_e4m3fn))
|
| 28 |
+
self.register_buffer("weight_scale_inv", torch.empty(out_features // B, in_features // B,
|
| 29 |
+
dtype=torch.float32))
|
| 30 |
+
|
| 31 |
+
def forward(self, x):
|
| 32 |
+
R, C = self.out_features, self.in_features
|
| 33 |
+
w = self.weight.to(x.dtype).view(R // B, B, C // B, B) * self.weight_scale_inv.to(x.dtype)[:, None, :, None]
|
| 34 |
+
return F.linear(x, w.view(R, C))
|
| 35 |
+
|
| 36 |
+
def _model_dir():
|
| 37 |
+
p = argparse.ArgumentParser(add_help=False)
|
| 38 |
+
p.add_argument("--model-dir", default=".")
|
| 39 |
+
return p.parse_known_args()[0].model_dir
|
| 40 |
+
|
| 41 |
+
def build_fp8(mod):
|
| 42 |
+
d = _model_dir()
|
| 43 |
+
wm = json.load(open(os.path.join(d, "model.safetensors.index.json")))["weight_map"]
|
| 44 |
+
qnames = {k[:-len(".weight_scale_inv")] for k in wm if k.endswith(".weight_scale_inv")}
|
| 45 |
+
if not qnames:
|
| 46 |
+
sys.exit(f"❌ no *.weight_scale_inv in {d} - not an FP8 copy, use chat_jirack.py")
|
| 47 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 48 |
+
try:
|
| 49 |
+
with torch.device("meta"):
|
| 50 |
+
model = mod.JiRackDeltaNetForCausalLM()
|
| 51 |
+
for name in qnames:
|
| 52 |
+
parent, _, leaf = name.rpartition(".")
|
| 53 |
+
pm = model.get_submodule(parent)
|
| 54 |
+
old = getattr(pm, leaf)
|
| 55 |
+
setattr(pm, leaf, FP8Linear(old.in_features, old.out_features))
|
| 56 |
+
finally:
|
| 57 |
+
torch.set_default_dtype(torch.float32)
|
| 58 |
+
model.to_empty(device="cpu")
|
| 59 |
+
for m in model.modules():
|
| 60 |
+
if isinstance(m, mod.TextRotaryEmbedding):
|
| 61 |
+
m.inv_freq = 1.0 / (mod.ROPE_THETA ** (torch.arange(0, m.rotary_dim, 2, dtype=torch.float32)
|
| 62 |
+
/ m.rotary_dim))
|
| 63 |
+
print(f"🧮 FP8: {len(qnames)} linear layers kept in FP8 (block {B}x{B})", flush=True)
|
| 64 |
+
return model.eval()
|
| 65 |
+
|
| 66 |
+
cj.build = build_fp8
|
| 67 |
+
|
| 68 |
+
if __name__ == "__main__":
|
| 69 |
+
cj.main()
|
sft_final_fp8/chat_jirack.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# chat_jirack.py - JiRack DeltaNet 70B
|
| 4 |
+
# Copyright (c) 2025-2026 Konstantin Vladimirovich Grabko (CMSManhattan).
|
| 5 |
+
# All rights reserved. Proprietary JiRack license, see LICENSE.
|
| 6 |
+
# =============================================================================
|
| 7 |
+
|
| 8 |
+
import argparse
|
| 9 |
+
import glob
|
| 10 |
+
import importlib.util
|
| 11 |
+
import itertools
|
| 12 |
+
import json
|
| 13 |
+
import os
|
| 14 |
+
import sys
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
import torch.nn as nn
|
| 19 |
+
|
| 20 |
+
INIT_FNS = ("uniform_", "normal_", "trunc_normal_", "kaiming_uniform_", "kaiming_normal_",
|
| 21 |
+
"xavier_uniform_", "xavier_normal_", "orthogonal_")
|
| 22 |
+
|
| 23 |
+
def find_model_file(d):
|
| 24 |
+
files = sorted(glob.glob(os.path.join(d, "JiRackDeltaNet_*.py")))
|
| 25 |
+
if not files:
|
| 26 |
+
sys.exit(f"❌ no JiRackDeltaNet_*.py in {d}; pass --model-file")
|
| 27 |
+
return files[-1]
|
| 28 |
+
|
| 29 |
+
def load_module(path):
|
| 30 |
+
spec = importlib.util.spec_from_file_location("jirack_chat_model", path)
|
| 31 |
+
mod = importlib.util.module_from_spec(spec)
|
| 32 |
+
sys.modules["jirack_chat_model"] = mod
|
| 33 |
+
spec.loader.exec_module(mod)
|
| 34 |
+
return mod
|
| 35 |
+
|
| 36 |
+
def build(mod):
|
| 37 |
+
""
|
| 38 |
+
saved = {n: getattr(nn.init, n) for n in INIT_FNS if hasattr(nn.init, n)}
|
| 39 |
+
for n in saved:
|
| 40 |
+
setattr(nn.init, n, lambda t, *a, **k: t)
|
| 41 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 42 |
+
try:
|
| 43 |
+
model = mod.JiRackDeltaNetForCausalLM()
|
| 44 |
+
finally:
|
| 45 |
+
torch.set_default_dtype(torch.float32)
|
| 46 |
+
for n, f in saved.items():
|
| 47 |
+
setattr(nn.init, n, f)
|
| 48 |
+
return model.eval()
|
| 49 |
+
|
| 50 |
+
def load_weights(model, d):
|
| 51 |
+
from safetensors import safe_open
|
| 52 |
+
idx = os.path.join(d, "model.safetensors.index.json")
|
| 53 |
+
files = sorted(set(json.load(open(idx))["weight_map"].values())) if os.path.exists(idx) else \
|
| 54 |
+
sorted(os.path.basename(p) for p in glob.glob(os.path.join(d, "*.safetensors")))
|
| 55 |
+
sd = model.state_dict()
|
| 56 |
+
params = {n for n, _ in model.named_parameters()}
|
| 57 |
+
loaded = set()
|
| 58 |
+
t0 = time.time()
|
| 59 |
+
with torch.no_grad():
|
| 60 |
+
for i, f in enumerate(files):
|
| 61 |
+
with safe_open(os.path.join(d, f), framework="pt", device="cpu") as h:
|
| 62 |
+
for k in h.keys():
|
| 63 |
+
if k in sd:
|
| 64 |
+
sd[k].copy_(h.get_tensor(k))
|
| 65 |
+
loaded.add(k)
|
| 66 |
+
print(f" {i + 1}/{len(files)} {f} {time.time() - t0:.0f} s", flush=True)
|
| 67 |
+
missing = sorted(params - loaded)
|
| 68 |
+
if missing:
|
| 69 |
+
sys.exit(f"❌ {len(missing)} parameters not in {d}: {missing[:5]}")
|
| 70 |
+
|
| 71 |
+
class ChatTokenizer:
|
| 72 |
+
""
|
| 73 |
+
|
| 74 |
+
def __init__(self, d):
|
| 75 |
+
import jinja2
|
| 76 |
+
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
| 77 |
+
from tokenizers import Tokenizer
|
| 78 |
+
self.tk = Tokenizer.from_file(os.path.join(d, "tokenizer.json"))
|
| 79 |
+
cfg = {}
|
| 80 |
+
if os.path.exists(os.path.join(d, "tokenizer_config.json")):
|
| 81 |
+
cfg = json.load(open(os.path.join(d, "tokenizer_config.json"), encoding="utf-8"))
|
| 82 |
+
path = os.path.join(d, "chat_template.jinja")
|
| 83 |
+
text = open(path, encoding="utf-8").read() if os.path.exists(path) else cfg.get("chat_template")
|
| 84 |
+
if isinstance(text, list):
|
| 85 |
+
text = next(t["template"] for t in text if t.get("name") == "default")
|
| 86 |
+
if not text:
|
| 87 |
+
sys.exit(f"❌ no chat template in {d}")
|
| 88 |
+
|
| 89 |
+
def raise_exception(msg):
|
| 90 |
+
raise jinja2.exceptions.TemplateError(msg)
|
| 91 |
+
|
| 92 |
+
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
|
| 93 |
+
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators,
|
| 94 |
+
sort_keys=sort_keys)
|
| 95 |
+
|
| 96 |
+
env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
|
| 97 |
+
env.filters["tojson"] = tojson
|
| 98 |
+
env.globals["raise_exception"] = raise_exception
|
| 99 |
+
self.tmpl = env.from_string(text)
|
| 100 |
+
s = lambda v: v.get("content") if isinstance(v, dict) else v
|
| 101 |
+
self.bos, self.eos = s(cfg.get("bos_token")) or "", s(cfg.get("eos_token")) or ""
|
| 102 |
+
self.special = [t.content for t in self.tk.get_added_tokens_decoder().values() if t.special]
|
| 103 |
+
self.stop_ids = {i for i in (self.tk.token_to_id("<|im_end|>"), self.tk.token_to_id("<|endoftext|>"),
|
| 104 |
+
self.tk.token_to_id(self.eos) if self.eos else None) if i is not None}
|
| 105 |
+
|
| 106 |
+
def prompt_ids(self, msgs, think):
|
| 107 |
+
text = self.tmpl.render(messages=msgs, add_generation_prompt=True, enable_thinking=think,
|
| 108 |
+
bos_token=self.bos, eos_token=self.eos)
|
| 109 |
+
return self.tk.encode(text, add_special_tokens=False).ids
|
| 110 |
+
|
| 111 |
+
def decode(self, ids):
|
| 112 |
+
return self.tk.decode(ids, skip_special_tokens=False)
|
| 113 |
+
|
| 114 |
+
def _to(x, dev):
|
| 115 |
+
if torch.is_tensor(x):
|
| 116 |
+
return x.to(dev)
|
| 117 |
+
if isinstance(x, (tuple, list)):
|
| 118 |
+
return type(x)(_to(v, dev) for v in x)
|
| 119 |
+
if isinstance(x, dict):
|
| 120 |
+
return {k: _to(v, dev) for k, v in x.items()}
|
| 121 |
+
return x
|
| 122 |
+
|
| 123 |
+
def place(model, devices):
|
| 124 |
+
""
|
| 125 |
+
blocks = [m for m in model.modules() if type(m).__name__ == "TransformerBlock"]
|
| 126 |
+
in_block = {id(x) for b in blocks for x in b.modules()}
|
| 127 |
+
for i, b in enumerate(blocks):
|
| 128 |
+
dev = devices[i * len(devices) // len(blocks)]
|
| 129 |
+
b.to(dev)
|
| 130 |
+
if len(devices) > 1:
|
| 131 |
+
b.register_forward_pre_hook(lambda m, a, k, dev=dev: (_to(a, dev), _to(k, dev)), with_kwargs=True)
|
| 132 |
+
for m in model.modules():
|
| 133 |
+
if id(m) in in_block:
|
| 134 |
+
continue
|
| 135 |
+
m._apply(lambda t: t.to(devices[0]), recurse=False)
|
| 136 |
+
if len(devices) > 1 and not list(m.children()):
|
| 137 |
+
m.register_forward_pre_hook(lambda mm, a, k: (_to(a, devices[0]), _to(k, devices[0])),
|
| 138 |
+
with_kwargs=True)
|
| 139 |
+
return devices[0]
|
| 140 |
+
|
| 141 |
+
def _cast(x, dtype):
|
| 142 |
+
if torch.is_tensor(x):
|
| 143 |
+
return x.to(dtype) if x.is_floating_point() and x.dtype != dtype else x
|
| 144 |
+
if isinstance(x, (tuple, list)):
|
| 145 |
+
return type(x)(_cast(v, dtype) for v in x)
|
| 146 |
+
if isinstance(x, dict):
|
| 147 |
+
return {k: _cast(v, dtype) for k, v in x.items()}
|
| 148 |
+
return x
|
| 149 |
+
|
| 150 |
+
def fp32_blocks(model):
|
| 151 |
+
""
|
| 152 |
+
def pre(mod, args, kwargs):
|
| 153 |
+
saved = []
|
| 154 |
+
for t in itertools.chain(mod.parameters(), mod.buffers()):
|
| 155 |
+
if t.is_floating_point() and t.dtype != torch.float32:
|
| 156 |
+
saved.append((t, t.data))
|
| 157 |
+
t.data = t.data.float()
|
| 158 |
+
mod._jr_saved = saved
|
| 159 |
+
return _cast(args, torch.float32), _cast(kwargs, torch.float32)
|
| 160 |
+
|
| 161 |
+
def post(mod, args, out, back=torch.bfloat16):
|
| 162 |
+
for t, d in mod._jr_saved:
|
| 163 |
+
t.data = d
|
| 164 |
+
mod._jr_saved = []
|
| 165 |
+
return _cast(out, back) if back is not None else out
|
| 166 |
+
|
| 167 |
+
for m in model.modules():
|
| 168 |
+
if type(m).__name__ == "TransformerBlock":
|
| 169 |
+
m.register_forward_pre_hook(pre, with_kwargs=True)
|
| 170 |
+
m.register_forward_hook(post)
|
| 171 |
+
head = getattr(model, "lm_head", None)
|
| 172 |
+
if isinstance(head, nn.Module):
|
| 173 |
+
head.register_forward_pre_hook(pre, with_kwargs=True)
|
| 174 |
+
head.register_forward_hook(lambda m, a, o: post(m, a, o, None))
|
| 175 |
+
|
| 176 |
+
def logits_of(out):
|
| 177 |
+
if isinstance(out, (tuple, list)):
|
| 178 |
+
return out[0]
|
| 179 |
+
return out.logits if hasattr(out, "logits") else out
|
| 180 |
+
|
| 181 |
+
def sample(logits, temperature, top_p):
|
| 182 |
+
if temperature <= 0:
|
| 183 |
+
return int(logits.argmax())
|
| 184 |
+
probs = torch.softmax(logits.float() / temperature, dim=-1)
|
| 185 |
+
sp, si = probs.sort(descending=True)
|
| 186 |
+
cut = (sp.cumsum(-1) - sp) > top_p
|
| 187 |
+
sp[cut] = 0
|
| 188 |
+
return int(si[torch.multinomial(sp / sp.sum(), 1)])
|
| 189 |
+
|
| 190 |
+
def main():
|
| 191 |
+
p = argparse.ArgumentParser()
|
| 192 |
+
p.add_argument("--model-dir", default=".")
|
| 193 |
+
p.add_argument("--model-file", default=None)
|
| 194 |
+
p.add_argument("--tokenizer-dir", default=None, help="default: --model-dir")
|
| 195 |
+
p.add_argument("--max-new", type=int, default=2048)
|
| 196 |
+
p.add_argument("--temperature", type=float, default=0.6, help="0 = greedy")
|
| 197 |
+
p.add_argument("--top-p", type=float, default=0.95)
|
| 198 |
+
p.add_argument("--system", default=None, help="file with a system prompt")
|
| 199 |
+
p.add_argument("--no-think", action="store_true", help="start with thinking off")
|
| 200 |
+
p.add_argument("--cpu", action="store_true")
|
| 201 |
+
p.add_argument("--cpu-bf16", action="store_true", help="CPU: plain bf16 instead of fp32 blocks")
|
| 202 |
+
a = p.parse_args()
|
| 203 |
+
|
| 204 |
+
tok = ChatTokenizer(a.tokenizer_dir or a.model_dir)
|
| 205 |
+
stop = tok.stop_ids
|
| 206 |
+
print(f"stop tokens {sorted(stop)}", flush=True)
|
| 207 |
+
|
| 208 |
+
mf = a.model_file or find_model_file(a.model_dir)
|
| 209 |
+
print(f"model file {mf}\nweights {a.model_dir}", flush=True)
|
| 210 |
+
model = build(load_module(mf))
|
| 211 |
+
load_weights(model, a.model_dir)
|
| 212 |
+
n = sum(q.numel() for q in model.parameters())
|
| 213 |
+
if a.cpu or not torch.cuda.is_available():
|
| 214 |
+
dev = torch.device("cpu")
|
| 215 |
+
try:
|
| 216 |
+
torch.backends.nnpack.set_flags(False)
|
| 217 |
+
except Exception:
|
| 218 |
+
pass
|
| 219 |
+
if not a.cpu_bf16:
|
| 220 |
+
fp32_blocks(model)
|
| 221 |
+
print(f"⚠️ CPU: {n / 1e9:.1f}B params, compute {'bf16' if a.cpu_bf16 else 'fp32 blocks'} - "
|
| 222 |
+
f"every token is a full forward pass, expect minutes per token. Ctrl+C stops the answer.")
|
| 223 |
+
else:
|
| 224 |
+
devs = [torch.device("cuda", i) for i in range(torch.cuda.device_count())]
|
| 225 |
+
dev = place(model, devs)
|
| 226 |
+
print(f"on {len(devs)} GPU(s): {n / 1e9:.1f}B params, "
|
| 227 |
+
f"{[round(torch.cuda.memory_allocated(d) / 2 ** 30) for d in devs]} GB")
|
| 228 |
+
|
| 229 |
+
system = open(a.system, encoding="utf-8").read().strip() if a.system else None
|
| 230 |
+
think = not a.no_think
|
| 231 |
+
history = []
|
| 232 |
+
print("\nReady. /reset - clear history, /think - thinking on/off, exit - quit")
|
| 233 |
+
while True:
|
| 234 |
+
try:
|
| 235 |
+
user = input("\nYou: ").strip()
|
| 236 |
+
except (EOFError, KeyboardInterrupt):
|
| 237 |
+
break
|
| 238 |
+
if not user:
|
| 239 |
+
continue
|
| 240 |
+
if user.lower() in ("exit", "quit"):
|
| 241 |
+
break
|
| 242 |
+
if user == "/reset":
|
| 243 |
+
history = []
|
| 244 |
+
print("(history cleared)")
|
| 245 |
+
continue
|
| 246 |
+
if user == "/think":
|
| 247 |
+
think = not think
|
| 248 |
+
print(f"(thinking {'on' if think else 'off'})")
|
| 249 |
+
continue
|
| 250 |
+
history.append({"role": "user", "content": user})
|
| 251 |
+
msgs = ([{"role": "system", "content": system}] if system else []) + history
|
| 252 |
+
ids = torch.tensor([tok.prompt_ids(msgs, think)], dtype=torch.long, device=dev)
|
| 253 |
+
start = ids.shape[1]
|
| 254 |
+
print("\nAssistant: ", end="", flush=True)
|
| 255 |
+
printed, t0 = "", time.time()
|
| 256 |
+
try:
|
| 257 |
+
with torch.no_grad():
|
| 258 |
+
for _ in range(a.max_new):
|
| 259 |
+
nxt = sample(logits_of(model(ids))[0, -1], a.temperature, a.top_p)
|
| 260 |
+
if nxt in stop:
|
| 261 |
+
break
|
| 262 |
+
ids = torch.cat([ids, torch.tensor([[nxt]], device=ids.device)], dim=1)
|
| 263 |
+
text = tok.decode(ids[0, start:].tolist())
|
| 264 |
+
if not text.endswith("�"):
|
| 265 |
+
print(text[len(printed):], end="", flush=True)
|
| 266 |
+
printed = text
|
| 267 |
+
except KeyboardInterrupt:
|
| 268 |
+
print(" [stopped]", end="")
|
| 269 |
+
gen = ids.shape[1] - start
|
| 270 |
+
raw = tok.decode(ids[0, start:].tolist())
|
| 271 |
+
print(f"\n [{gen} tokens, {gen / max(time.time() - t0, 1e-6):.2f} tok/s]")
|
| 272 |
+
|
| 273 |
+
reply = raw.split("</think>")[-1]
|
| 274 |
+
for t in tok.special:
|
| 275 |
+
reply = reply.replace(t, "")
|
| 276 |
+
history.append({"role": "assistant", "content": reply.strip()})
|
| 277 |
+
|
| 278 |
+
if __name__ == "__main__":
|
| 279 |
+
main()
|
sft_final_fp8/chat_template.jinja
ADDED
|
@@ -0,0 +1,171 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{%- set image_count = namespace(value=0) %}
|
| 2 |
+
{%- set video_count = namespace(value=0) %}
|
| 3 |
+
{%- macro render_content(content, do_vision_count, is_system_content=false) %}
|
| 4 |
+
{%- if content is string %}
|
| 5 |
+
{{- content }}
|
| 6 |
+
{%- elif content is iterable and content is not mapping %}
|
| 7 |
+
{%- for item in content %}
|
| 8 |
+
{%- if 'image' in item or 'image_url' in item or item.type == 'image' %}
|
| 9 |
+
{%- if is_system_content %}
|
| 10 |
+
{{- raise_exception('System message cannot contain images.') }}
|
| 11 |
+
{%- endif %}
|
| 12 |
+
{%- if do_vision_count %}
|
| 13 |
+
{%- set image_count.value = image_count.value + 1 %}
|
| 14 |
+
{%- endif %}
|
| 15 |
+
{%- if add_vision_id %}
|
| 16 |
+
{{- 'Picture ' ~ image_count.value ~ ': ' }}
|
| 17 |
+
{%- endif %}
|
| 18 |
+
{{- '<|vision_start|><|image_pad|><|vision_end|>' }}
|
| 19 |
+
{%- elif 'video' in item or item.type == 'video' %}
|
| 20 |
+
{%- if is_system_content %}
|
| 21 |
+
{{- raise_exception('System message cannot contain videos.') }}
|
| 22 |
+
{%- endif %}
|
| 23 |
+
{%- if do_vision_count %}
|
| 24 |
+
{%- set video_count.value = video_count.value + 1 %}
|
| 25 |
+
{%- endif %}
|
| 26 |
+
{%- if add_vision_id %}
|
| 27 |
+
{{- 'Video ' ~ video_count.value ~ ': ' }}
|
| 28 |
+
{%- endif %}
|
| 29 |
+
{{- '<|vision_start|><|video_pad|><|vision_end|>' }}
|
| 30 |
+
{%- elif 'text' in item %}
|
| 31 |
+
{{- item.text }}
|
| 32 |
+
{%- else %}
|
| 33 |
+
{{- raise_exception('Unexpected item type in content.') }}
|
| 34 |
+
{%- endif %}
|
| 35 |
+
{%- endfor %}
|
| 36 |
+
{%- elif content is none or content is undefined %}
|
| 37 |
+
{{- '' }}
|
| 38 |
+
{%- else %}
|
| 39 |
+
{{- raise_exception('Unexpected content type.') }}
|
| 40 |
+
{%- endif %}
|
| 41 |
+
{%- endmacro %}
|
| 42 |
+
{%- if not messages %}
|
| 43 |
+
{{- raise_exception('No messages provided.') }}
|
| 44 |
+
{%- endif %}
|
| 45 |
+
{%- set reasoning_instructions = '' %}
|
| 46 |
+
{%- if enable_thinking is defined and enable_thinking is true %}
|
| 47 |
+
{%- set resolved_reasoning_effort = reasoning_effort|default('xhigh') %}
|
| 48 |
+
{%- if resolved_reasoning_effort not in ('xhigh', 'medium', 'low') %}
|
| 49 |
+
{{- raise_exception('Unexpected reasoning effort ' ~ reasoning_effort ~ '. Supported types are xhigh (default), medium, and low.') }}
|
| 50 |
+
{%- endif %}
|
| 51 |
+
{%- if resolved_reasoning_effort == 'xhigh' %}
|
| 52 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to xhigh. Please think carefully through the task, validate key assumptions, consider plausible alternatives, and prioritize correctness, consistency, and clarity in the final answer.' %}
|
| 53 |
+
{%- elif resolved_reasoning_effort == 'low' %}
|
| 54 |
+
{%- set reasoning_instructions = 'Reasoning effort is set to low. Keep your thinking brief and focused, moving directly to the conclusion without unnecessary elaboration.' %}
|
| 55 |
+
{%- endif %}
|
| 56 |
+
{%- endif %}
|
| 57 |
+
{%- if tools and tools is iterable and tools is not mapping %}
|
| 58 |
+
{{- '<|im_start|>system\n' }}
|
| 59 |
+
{%- if reasoning_instructions %}
|
| 60 |
+
{{- reasoning_instructions + '\n\n' }}
|
| 61 |
+
{%- endif %}
|
| 62 |
+
{{- "# Tools\n\nYou have access to the following functions:\n\n<tools>" }}
|
| 63 |
+
{%- for tool in tools %}
|
| 64 |
+
{{- "\n" }}
|
| 65 |
+
{{- tool | tojson }}
|
| 66 |
+
{%- endfor %}
|
| 67 |
+
{{- "\n</tools>" }}
|
| 68 |
+
{{- '\n\nIf you choose to call a function ONLY reply in the following format with NO suffix:\n\n<tool_call>\n<function=example_function_name>\n<parameter=example_parameter_1>\nvalue_1\n</parameter>\n<parameter=example_parameter_2>\nThis is the value for the second parameter\nthat can span\nmultiple lines\n</parameter>\n</function>\n</tool_call>\n\n<IMPORTANT>\nReminder:\n- Function calls MUST follow the specified format: an inner <function=...></function> block must be nested within <tool_call></tool_call> XML tags\n- Required parameters MUST be specified\n- You may provide optional reasoning for your function call in natural language BEFORE the function call, but NOT after\n- If there is no function call available, answer the question like normal with your current knowledge and do not tell the user about function calls\n</IMPORTANT>' }}
|
| 69 |
+
{%- if messages[0].role == 'system' %}
|
| 70 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 71 |
+
{%- if content %}
|
| 72 |
+
{{- '\n\n' + content }}
|
| 73 |
+
{%- endif %}
|
| 74 |
+
{%- endif %}
|
| 75 |
+
{{- '<|im_end|>\n' }}
|
| 76 |
+
{%- else %}
|
| 77 |
+
{%- if messages[0].role == 'system' %}
|
| 78 |
+
{%- set content = render_content(messages[0].content, false, true)|trim %}
|
| 79 |
+
{%- if content %}
|
| 80 |
+
{{- '<|im_start|>system\n' + (reasoning_instructions + '\n\n' if reasoning_instructions else '') + content + '<|im_end|>\n' }}
|
| 81 |
+
{%- elif reasoning_instructions %}
|
| 82 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 83 |
+
{%- endif %}
|
| 84 |
+
{%- elif reasoning_instructions %}
|
| 85 |
+
{{- '<|im_start|>system\n' + reasoning_instructions + '<|im_end|>\n' }}
|
| 86 |
+
{%- endif %}
|
| 87 |
+
{%- endif %}
|
| 88 |
+
{%- set ns = namespace(multi_step_tool=true, last_query_index=messages|length - 1) %}
|
| 89 |
+
{%- for message in messages[::-1] %}
|
| 90 |
+
{%- set index = (messages|length - 1) - loop.index0 %}
|
| 91 |
+
{%- if ns.multi_step_tool and message.role == "user" %}
|
| 92 |
+
{%- set content = render_content(message.content, false)|trim %}
|
| 93 |
+
{%- if not(content.startswith('<tool_response>') and content.endswith('</tool_response>')) %}
|
| 94 |
+
{%- set ns.multi_step_tool = false %}
|
| 95 |
+
{%- set ns.last_query_index = index %}
|
| 96 |
+
{%- endif %}
|
| 97 |
+
{%- endif %}
|
| 98 |
+
{%- endfor %}
|
| 99 |
+
{%- if ns.multi_step_tool %}
|
| 100 |
+
{{- raise_exception('No user query found in messages.') }}
|
| 101 |
+
{%- endif %}
|
| 102 |
+
{%- for message in messages %}
|
| 103 |
+
{%- set content = render_content(message.content, true)|trim %}
|
| 104 |
+
{%- if message.role == "system" %}
|
| 105 |
+
{%- if not loop.first %}
|
| 106 |
+
{{- raise_exception('System message must be at the beginning.') }}
|
| 107 |
+
{%- endif %}
|
| 108 |
+
{%- elif message.role == "user" %}
|
| 109 |
+
{{- '<|im_start|>' + message.role + '\n' + content + '<|im_end|>' + '\n' }}
|
| 110 |
+
{%- elif message.role == "assistant" %}
|
| 111 |
+
{%- set reasoning_content = '' %}
|
| 112 |
+
{%- if message.reasoning_content is string %}
|
| 113 |
+
{%- set reasoning_content = message.reasoning_content %}
|
| 114 |
+
{%- endif %}
|
| 115 |
+
{%- set reasoning_content = reasoning_content|trim %}
|
| 116 |
+
{%- if preserve_thinking is undefined or preserve_thinking is true or loop.index0 > ns.last_query_index %}
|
| 117 |
+
{{- '<|im_start|>' + message.role + '\n<think>\n' + reasoning_content + '\n</think>\n\n' + content }}
|
| 118 |
+
{%- else %}
|
| 119 |
+
{{- '<|im_start|>' + message.role + '\n' + content }}
|
| 120 |
+
{%- endif %}
|
| 121 |
+
{%- if message.tool_calls and message.tool_calls is iterable and message.tool_calls is not mapping %}
|
| 122 |
+
{%- for tool_call in message.tool_calls %}
|
| 123 |
+
{%- if tool_call.function is defined %}
|
| 124 |
+
{%- set tool_call = tool_call.function %}
|
| 125 |
+
{%- endif %}
|
| 126 |
+
{%- if loop.first %}
|
| 127 |
+
{%- if content|trim %}
|
| 128 |
+
{{- '\n\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 129 |
+
{%- else %}
|
| 130 |
+
{{- '<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 131 |
+
{%- endif %}
|
| 132 |
+
{%- else %}
|
| 133 |
+
{{- '\n<tool_call>\n<function=' + tool_call.name + '>\n' }}
|
| 134 |
+
{%- endif %}
|
| 135 |
+
{%- if tool_call.arguments is defined and tool_call.arguments != '' %}
|
| 136 |
+
{%- for args_name, args_value in tool_call.arguments|items %}
|
| 137 |
+
{{- '<parameter=' + args_name + '>\n' }}
|
| 138 |
+
{%- set args_value = args_value | string if args_value is string else args_value | tojson | safe %}
|
| 139 |
+
{{- args_value }}
|
| 140 |
+
{{- '\n</parameter>\n' }}
|
| 141 |
+
{%- endfor %}
|
| 142 |
+
{%- endif %}
|
| 143 |
+
{{- '</function>\n</tool_call>' }}
|
| 144 |
+
{%- endfor %}
|
| 145 |
+
{%- endif %}
|
| 146 |
+
{{- '<|im_end|>\n' }}
|
| 147 |
+
{%- elif message.role == "tool" %}
|
| 148 |
+
{%- if loop.previtem and loop.previtem.role != "tool" %}
|
| 149 |
+
{{- '<|im_start|>user' }}
|
| 150 |
+
{%- endif %}
|
| 151 |
+
{{- '\n<tool_response>\n' }}
|
| 152 |
+
{{- content }}
|
| 153 |
+
{{- '\n</tool_response>' }}
|
| 154 |
+
{%- if not loop.last and loop.nextitem.role != "tool" %}
|
| 155 |
+
{{- '<|im_end|>\n' }}
|
| 156 |
+
{%- elif loop.last %}
|
| 157 |
+
{{- '<|im_end|>\n' }}
|
| 158 |
+
{%- endif %}
|
| 159 |
+
{%- else %}
|
| 160 |
+
{{- raise_exception('Unexpected message role.') }}
|
| 161 |
+
{%- endif %}
|
| 162 |
+
{%- endfor %}
|
| 163 |
+
{%- if add_generation_prompt %}
|
| 164 |
+
{{- '<|im_start|>assistant\n' }}
|
| 165 |
+
{%- if enable_thinking is defined and enable_thinking is true %}
|
| 166 |
+
{{- '<think>\n' }}
|
| 167 |
+
{%- else %}
|
| 168 |
+
{{- '<think>\n\n</think>\n\n' }}
|
| 169 |
+
{%- endif %}
|
| 170 |
+
{%- endif %}
|
| 171 |
+
|
sft_final_fp8/config.json
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"attention_bias": false,
|
| 3 |
+
"attention_dropout": 0.0,
|
| 4 |
+
"attn_output_gate": true,
|
| 5 |
+
"bos_token_id": 248044,
|
| 6 |
+
"dtype": "bfloat16",
|
| 7 |
+
"eos_token_id": 248044,
|
| 8 |
+
"full_attention_interval": 4,
|
| 9 |
+
"head_dim": 256,
|
| 10 |
+
"hidden_act": "silu",
|
| 11 |
+
"hidden_size": 5120,
|
| 12 |
+
"initializer_range": 0.02,
|
| 13 |
+
"intermediate_size": 26624,
|
| 14 |
+
"layer_types": [
|
| 15 |
+
"linear_attention",
|
| 16 |
+
"linear_attention",
|
| 17 |
+
"linear_attention",
|
| 18 |
+
"full_attention",
|
| 19 |
+
"linear_attention",
|
| 20 |
+
"linear_attention",
|
| 21 |
+
"linear_attention",
|
| 22 |
+
"full_attention",
|
| 23 |
+
"linear_attention",
|
| 24 |
+
"linear_attention",
|
| 25 |
+
"linear_attention",
|
| 26 |
+
"full_attention",
|
| 27 |
+
"linear_attention",
|
| 28 |
+
"linear_attention",
|
| 29 |
+
"linear_attention",
|
| 30 |
+
"full_attention",
|
| 31 |
+
"linear_attention",
|
| 32 |
+
"linear_attention",
|
| 33 |
+
"linear_attention",
|
| 34 |
+
"full_attention",
|
| 35 |
+
"linear_attention",
|
| 36 |
+
"linear_attention",
|
| 37 |
+
"linear_attention",
|
| 38 |
+
"full_attention",
|
| 39 |
+
"linear_attention",
|
| 40 |
+
"linear_attention",
|
| 41 |
+
"linear_attention",
|
| 42 |
+
"full_attention",
|
| 43 |
+
"linear_attention",
|
| 44 |
+
"linear_attention",
|
| 45 |
+
"linear_attention",
|
| 46 |
+
"full_attention",
|
| 47 |
+
"linear_attention",
|
| 48 |
+
"linear_attention",
|
| 49 |
+
"linear_attention",
|
| 50 |
+
"full_attention",
|
| 51 |
+
"linear_attention",
|
| 52 |
+
"linear_attention",
|
| 53 |
+
"linear_attention",
|
| 54 |
+
"full_attention",
|
| 55 |
+
"linear_attention",
|
| 56 |
+
"linear_attention",
|
| 57 |
+
"linear_attention",
|
| 58 |
+
"full_attention",
|
| 59 |
+
"linear_attention",
|
| 60 |
+
"linear_attention",
|
| 61 |
+
"linear_attention",
|
| 62 |
+
"full_attention",
|
| 63 |
+
"linear_attention",
|
| 64 |
+
"linear_attention",
|
| 65 |
+
"linear_attention",
|
| 66 |
+
"full_attention",
|
| 67 |
+
"linear_attention",
|
| 68 |
+
"linear_attention",
|
| 69 |
+
"linear_attention",
|
| 70 |
+
"full_attention",
|
| 71 |
+
"linear_attention",
|
| 72 |
+
"linear_attention",
|
| 73 |
+
"linear_attention",
|
| 74 |
+
"full_attention",
|
| 75 |
+
"linear_attention",
|
| 76 |
+
"linear_attention",
|
| 77 |
+
"linear_attention",
|
| 78 |
+
"full_attention",
|
| 79 |
+
"linear_attention",
|
| 80 |
+
"linear_attention",
|
| 81 |
+
"linear_attention",
|
| 82 |
+
"full_attention",
|
| 83 |
+
"linear_attention",
|
| 84 |
+
"linear_attention",
|
| 85 |
+
"linear_attention",
|
| 86 |
+
"full_attention",
|
| 87 |
+
"linear_attention",
|
| 88 |
+
"linear_attention",
|
| 89 |
+
"linear_attention",
|
| 90 |
+
"full_attention",
|
| 91 |
+
"linear_attention",
|
| 92 |
+
"linear_attention",
|
| 93 |
+
"linear_attention",
|
| 94 |
+
"full_attention",
|
| 95 |
+
"linear_attention",
|
| 96 |
+
"linear_attention",
|
| 97 |
+
"linear_attention",
|
| 98 |
+
"full_attention",
|
| 99 |
+
"linear_attention",
|
| 100 |
+
"linear_attention",
|
| 101 |
+
"linear_attention",
|
| 102 |
+
"full_attention",
|
| 103 |
+
"linear_attention",
|
| 104 |
+
"linear_attention",
|
| 105 |
+
"linear_attention",
|
| 106 |
+
"full_attention",
|
| 107 |
+
"linear_attention",
|
| 108 |
+
"linear_attention",
|
| 109 |
+
"linear_attention",
|
| 110 |
+
"full_attention",
|
| 111 |
+
"linear_attention",
|
| 112 |
+
"linear_attention",
|
| 113 |
+
"linear_attention",
|
| 114 |
+
"full_attention",
|
| 115 |
+
"linear_attention",
|
| 116 |
+
"linear_attention",
|
| 117 |
+
"linear_attention",
|
| 118 |
+
"full_attention",
|
| 119 |
+
"linear_attention",
|
| 120 |
+
"linear_attention",
|
| 121 |
+
"linear_attention",
|
| 122 |
+
"full_attention",
|
| 123 |
+
"linear_attention",
|
| 124 |
+
"linear_attention",
|
| 125 |
+
"linear_attention",
|
| 126 |
+
"full_attention",
|
| 127 |
+
"linear_attention",
|
| 128 |
+
"linear_attention",
|
| 129 |
+
"linear_attention",
|
| 130 |
+
"full_attention",
|
| 131 |
+
"linear_attention",
|
| 132 |
+
"linear_attention",
|
| 133 |
+
"linear_attention",
|
| 134 |
+
"full_attention",
|
| 135 |
+
"linear_attention",
|
| 136 |
+
"linear_attention",
|
| 137 |
+
"linear_attention",
|
| 138 |
+
"full_attention",
|
| 139 |
+
"linear_attention",
|
| 140 |
+
"linear_attention",
|
| 141 |
+
"linear_attention",
|
| 142 |
+
"full_attention"
|
| 143 |
+
],
|
| 144 |
+
"linear_conv_kernel_dim": 4,
|
| 145 |
+
"linear_key_head_dim": 128,
|
| 146 |
+
"linear_num_key_heads": 16,
|
| 147 |
+
"linear_num_value_heads": 48,
|
| 148 |
+
"linear_value_head_dim": 128,
|
| 149 |
+
"mamba_ssm_dtype": "float32",
|
| 150 |
+
"max_position_embeddings": 262144,
|
| 151 |
+
"model_type": "qwen3_5_text",
|
| 152 |
+
"mtp_num_hidden_layers": 1,
|
| 153 |
+
"mtp_use_dedicated_embeddings": false,
|
| 154 |
+
"num_attention_heads": 24,
|
| 155 |
+
"num_hidden_layers": 128,
|
| 156 |
+
"num_key_value_heads": 4,
|
| 157 |
+
"output_gate_type": "swish",
|
| 158 |
+
"pad_token_id": null,
|
| 159 |
+
"partial_rotary_factor": 0.25,
|
| 160 |
+
"rms_norm_eps": 1e-06,
|
| 161 |
+
"rope_parameters": {
|
| 162 |
+
"mrope_interleaved": true,
|
| 163 |
+
"mrope_section": [
|
| 164 |
+
11,
|
| 165 |
+
11,
|
| 166 |
+
10
|
| 167 |
+
],
|
| 168 |
+
"partial_rotary_factor": 0.25,
|
| 169 |
+
"rope_theta": 10000000,
|
| 170 |
+
"rope_type": "default"
|
| 171 |
+
},
|
| 172 |
+
"tie_word_embeddings": false,
|
| 173 |
+
"use_cache": true,
|
| 174 |
+
"vocab_size": 248320,
|
| 175 |
+
"architectures": [
|
| 176 |
+
"Qwen3_5ForCausalLM"
|
| 177 |
+
],
|
| 178 |
+
"quantization_config": {
|
| 179 |
+
"quant_method": "fp8",
|
| 180 |
+
"fmt": "e4m3",
|
| 181 |
+
"activation_scheme": "dynamic",
|
| 182 |
+
"weight_block_size": [
|
| 183 |
+
128,
|
| 184 |
+
128
|
| 185 |
+
],
|
| 186 |
+
"modules_to_not_convert": [
|
| 187 |
+
"lm_head",
|
| 188 |
+
"model.embed_tokens",
|
| 189 |
+
"mtp",
|
| 190 |
+
"in_proj_a",
|
| 191 |
+
"in_proj_b"
|
| 192 |
+
],
|
| 193 |
+
"ignored_layers": [
|
| 194 |
+
"lm_head",
|
| 195 |
+
"model.embed_tokens",
|
| 196 |
+
"mtp",
|
| 197 |
+
"in_proj_a",
|
| 198 |
+
"in_proj_b"
|
| 199 |
+
]
|
| 200 |
+
}
|
| 201 |
+
}
|