Text Generation
PyTorch
Safetensors
GGUF
qwen3_5_text
deltanet
qwen3.8
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:8080/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:8080/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:8080/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"
JiRackDeltaNet 70B SFT: bf16, FP8, card
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .gitattributes +2 -0
- README.md +14 -16
- sft_final/.gitattributes +36 -0
- sft_final/JiRackDeltaNet_70b.py +766 -0
- sft_final/audit_depth.json +14 -0
- sft_final/chat_jirack.py +303 -0
- sft_final/chat_template.jinja +171 -0
- sft_final/config.json +178 -0
- sft_final/expansion_depth.json +0 -0
- sft_final/gate_full.json +81 -0
- sft_final/gate_logits_fp32blocks_L128.npz +3 -0
- sft_final/gate_logits_fp32blocks_L8.npz +3 -0
- sft_final/gate_mini.json +81 -0
- sft_final/gguf.txt +35 -0
- sft_final/jirack_sft_state.json +9 -0
- sft_final/model-00001-of-00027.safetensors +3 -0
- sft_final/model-00002-of-00027.safetensors +3 -0
- sft_final/model-00003-of-00027.safetensors +3 -0
- sft_final/model-00004-of-00027.safetensors +3 -0
- sft_final/model-00005-of-00027.safetensors +3 -0
- sft_final/model-00006-of-00027.safetensors +3 -0
- sft_final/model-00007-of-00027.safetensors +3 -0
- sft_final/model-00008-of-00027.safetensors +3 -0
- sft_final/model-00009-of-00027.safetensors +3 -0
- sft_final/model-00010-of-00027.safetensors +3 -0
- sft_final/model-00011-of-00027.safetensors +3 -0
- sft_final/model-00012-of-00027.safetensors +3 -0
- sft_final/model-00013-of-00027.safetensors +3 -0
- sft_final/model-00014-of-00027.safetensors +3 -0
- sft_final/model-00015-of-00027.safetensors +3 -0
- sft_final/model-00016-of-00027.safetensors +3 -0
- sft_final/model-00017-of-00027.safetensors +3 -0
- sft_final/model-00018-of-00027.safetensors +3 -0
- sft_final/model-00019-of-00027.safetensors +3 -0
- sft_final/model-00020-of-00027.safetensors +3 -0
- sft_final/model-00021-of-00027.safetensors +3 -0
- sft_final/model-00022-of-00027.safetensors +3 -0
- sft_final/model-00023-of-00027.safetensors +3 -0
- sft_final/model-00024-of-00027.safetensors +3 -0
- sft_final/model-00025-of-00027.safetensors +3 -0
- sft_final/model-00026-of-00027.safetensors +3 -0
- sft_final/model-00027-of-00027.safetensors +3 -0
- sft_final/model.safetensors.index.json +0 -0
- sft_final/system_prompt.txt +6 -0
- sft_final/tokenizer.json +3 -0
- sft_final/tokenizer_config.json +148 -0
- sft_final_fp8/.gitattributes +36 -0
- sft_final_fp8/JiRackDeltaNet_70b.py +766 -0
- sft_final_fp8/audit_depth.json +14 -0
- sft_final_fp8/chat_fp8.py +75 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,5 @@ saved_model/**/* 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
|
|
|
|
|
|
|
|
|
| 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
|
README.md
CHANGED
|
@@ -1,17 +1,15 @@
|
|
| 1 |
---
|
| 2 |
-
|
| 3 |
-
license: bsl-1.0
|
| 4 |
library_name: pytorch
|
| 5 |
pipeline_tag: text-generation
|
| 6 |
tags:
|
| 7 |
-
- gated-deltanet
|
| 8 |
-
- linear-attention
|
| 9 |
-
- hybrid-attention
|
| 10 |
-
- depth-expansion
|
| 11 |
-
- function-calling
|
| 12 |
-
- reasoning
|
| 13 |
-
- fp8
|
| 14 |
-
|
| 15 |
---
|
| 16 |
|
| 17 |
# JiRackDeltaNet 70B
|
|
@@ -21,7 +19,7 @@ Gated DeltaNet / gated full-attention model (Qwen 3.5 layout) built in our own J
|
|
| 21 |
**64 to 128 layers**, and fine-tuned on our own SFT mix (chat, reasoning, code, math, tool calling).
|
| 22 |
|
| 23 |
> Status: SFT release. The 64 added layers have been trained only by this SFT run (~45 M tokens), so most of the
|
| 24 |
-
> model's ability still comes from the base model; see
|
| 25 |
|
| 26 |
## Model
|
| 27 |
|
|
@@ -111,9 +109,9 @@ The repository ships its own PyTorch code; no `transformers` model class is need
|
|
| 111 |
```bash
|
| 112 |
pip install torch safetensors tokenizers jinja2
|
| 113 |
# bf16, splits the 128 blocks over all visible GPUs (>= 2 x 80 GB)
|
| 114 |
-
python3 chat_jirack.py --model-dir
|
| 115 |
-
# FP8 copy (weights stay FP8 in memory, dequantized per layer call;
|
| 116 |
-
python3 chat_fp8.py --model-dir
|
| 117 |
```
|
| 118 |
|
| 119 |
Commands in the chat: `/think` (reasoning on / off), `/reset`, `exit`. Prompts use the Qwen 3.5 chat template in
|
|
@@ -138,6 +136,6 @@ this is **not verified** yet.
|
|
| 138 |
|
| 139 |
## License
|
| 140 |
|
| 141 |
-
|
| 142 |
(Konstantin Grabko): JiRack model code, FFN widening, depth expansion to 128 layers, SFT on the JiRack SFT mix and the
|
| 143 |
-
FP8 conversion. Keep this notice and the license text when redistributing.
|
|
|
|
| 1 |
---
|
| 2 |
+
license: apache-2.0
|
|
|
|
| 3 |
library_name: pytorch
|
| 4 |
pipeline_tag: text-generation
|
| 5 |
tags:
|
| 6 |
+
- gated-deltanet
|
| 7 |
+
- linear-attention
|
| 8 |
+
- hybrid-attention
|
| 9 |
+
- depth-expansion
|
| 10 |
+
- function-calling
|
| 11 |
+
- reasoning
|
| 12 |
+
- fp8
|
|
|
|
| 13 |
---
|
| 14 |
|
| 15 |
# JiRackDeltaNet 70B
|
|
|
|
| 19 |
**64 to 128 layers**, and fine-tuned on our own SFT mix (chat, reasoning, code, math, tool calling).
|
| 20 |
|
| 21 |
> Status: SFT release. The 64 added layers have been trained only by this SFT run (~45 M tokens), so most of the
|
| 22 |
+
> model's ability still comes from the base model; see Limitations.
|
| 23 |
|
| 24 |
## Model
|
| 25 |
|
|
|
|
| 109 |
```bash
|
| 110 |
pip install torch safetensors tokenizers jinja2
|
| 111 |
# bf16, splits the 128 blocks over all visible GPUs (>= 2 x 80 GB)
|
| 112 |
+
python3 sft_final/chat_jirack.py --model-dir sft_final --no-think --temperature 0
|
| 113 |
+
# FP8 copy (weights stay FP8 in memory, dequantized per layer call; one 96 GB GPU)
|
| 114 |
+
python3 sft_final_fp8/chat_fp8.py --model-dir sft_final_fp8 --no-think --temperature 0
|
| 115 |
```
|
| 116 |
|
| 117 |
Commands in the chat: `/think` (reasoning on / off), `/reset`, `exit`. Prompts use the Qwen 3.5 chat template in
|
|
|
|
| 136 |
|
| 137 |
## License
|
| 138 |
|
| 139 |
+
Apache License 2.0. The weights are derived from a Qwen model released under Apache 2.0. Changes by CMSManhattan
|
| 140 |
(Konstantin Grabko): JiRack model code, FFN widening, depth expansion to 128 layers, SFT on the JiRack SFT mix and the
|
| 141 |
+
FP8 conversion. Keep this notice and the license text when redistributing.
|
sft_final/.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/JiRackDeltaNet_70b.py
ADDED
|
@@ -0,0 +1,766 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JiRackDeltaNet_27b.py
|
| 3 |
+
=============================
|
| 4 |
+
|
| 5 |
+
Собственная (hand-rolled) архитектура "JiRack Qwen3.8-27B" -- в стиле
|
| 6 |
+
прежнего DS32B-проекта: один файл, свой TransformerBlock, никакого
|
| 7 |
+
AutoConfig/AutoModelForCausalLM внутри класса архитектуры, никакого
|
| 8 |
+
model_id в конструкторе. Все размерности зашиты константами ниже --
|
| 9 |
+
подтверждены живым инспектом реального checkpoint'а (inspect_qwen38_keys.py,
|
| 10 |
+
851 тензор, сверено).
|
| 11 |
+
|
| 12 |
+
Математика DeltaNet-рекуррентности, свёртки, гейтинга и partial-rotary
|
| 13 |
+
mRoPE-attention ПОРТИРОВАНА из реального modeling_qwen3_5.py (Apache 2.0,
|
| 14 |
+
HuggingFace/Qwen), а не переизобретена -- чтобы не рисковать тихой
|
| 15 |
+
числовой ошибкой в тонкой рекуррентной формуле. Портирован смысл, но
|
| 16 |
+
код переписан под наши имена/стиль и урезан: без vision-башни, без
|
| 17 |
+
KV-cache классов transformers (для тренировки полный форвард по
|
| 18 |
+
последовательности не нужен; для генерации -- полный recompute на
|
| 19 |
+
каждом шаге, без инкрементального кэша; это сознательное упрощение,
|
| 20 |
+
при желании кэш можно добавить отдельно).
|
| 21 |
+
|
| 22 |
+
Имена подмодулей (`linear_attn` / `self_attn`, `in_proj_qkv`, `out_proj`,
|
| 23 |
+
`mlp.gate_proj` и т.д.) намеренно СОВПАДАЮТ с именами в реальном
|
| 24 |
+
state_dict Qwen3_5ForCausalLM -- поэтому веса из HF-чекпоинта грузятся
|
| 25 |
+
напрямую через load_state_dict(), без ручного key-mapping.
|
| 26 |
+
|
| 27 |
+
Файл умеет:
|
| 28 |
+
- собрать модель (JiRackQwen38ForCausalLM) с нуля, случайные веса;
|
| 29 |
+
- принять state_dict в формате HF Qwen3_5ForCausalLM (после
|
| 30 |
+
AutoModelForCausalLM.from_pretrained(...).state_dict() в конвертере)
|
| 31 |
+
и загрузить его напрямую;
|
| 32 |
+
- пропатчить нужные nn.Linear -> BitLinear (TERNARIZE_PATTERNS);
|
| 33 |
+
- сохранить/загрузить свой JiRack-чекпоинт (save_checkpoint/load_checkpoint).
|
| 34 |
+
|
| 35 |
+
Конвертер (convert_qwen38_to_jirack.py) по-прежнему знает про model_id
|
| 36 |
+
и HF Hub -- но это знание живёт ТОЛЬКО в конвертере, не в архитектуре.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import os
|
| 40 |
+
import re
|
| 41 |
+
import torch
|
| 42 |
+
import torch.nn as nn
|
| 43 |
+
import torch.nn.functional as F
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# =====================================================================
|
| 47 |
+
# 1. CONFIRMED АРХИТЕКТУРА -- жёстко зашитые константы (не AutoConfig)
|
| 48 |
+
# =====================================================================
|
| 49 |
+
|
| 50 |
+
HIDDEN_SIZE = 5120
|
| 51 |
+
VOCAB_SIZE = 248320
|
| 52 |
+
INTERMEDIATE_SIZE = 26624
|
| 53 |
+
NUM_LAYERS = 128
|
| 54 |
+
RMS_NORM_EPS = 1e-6
|
| 55 |
+
|
| 56 |
+
# Чередование слоёв: full_attention_interval = 4 ->
|
| 57 |
+
# 3x linear_attention, 1x full_attention, повторяется на все 64 слоя.
|
| 58 |
+
LAYER_TYPES = ["linear_attention"] * 3 + ["full_attention"]
|
| 59 |
+
LAYER_TYPES = (LAYER_TYPES * (NUM_LAYERS // len(LAYER_TYPES) + 1))[:NUM_LAYERS]
|
| 60 |
+
|
| 61 |
+
# --- Gated DeltaNet (linear_attention) ---
|
| 62 |
+
LINEAR_NUM_KEY_HEADS = 16
|
| 63 |
+
LINEAR_KEY_HEAD_DIM = 128
|
| 64 |
+
LINEAR_NUM_VALUE_HEADS = 48
|
| 65 |
+
LINEAR_VALUE_HEAD_DIM = 128
|
| 66 |
+
LINEAR_CONV_KERNEL_DIM = 4
|
| 67 |
+
DELTA_KEY_DIM = LINEAR_NUM_KEY_HEADS * LINEAR_KEY_HEAD_DIM # 2048
|
| 68 |
+
DELTA_VALUE_DIM = LINEAR_NUM_VALUE_HEADS * LINEAR_VALUE_HEAD_DIM # 6144
|
| 69 |
+
DELTA_CONV_DIM = DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM # 10240
|
| 70 |
+
DELTA_CHUNK_SIZE = 64
|
| 71 |
+
|
| 72 |
+
# --- Gated Attention (full_attention) ---
|
| 73 |
+
NUM_ATTENTION_HEADS = 24
|
| 74 |
+
NUM_KEY_VALUE_HEADS = 4
|
| 75 |
+
HEAD_DIM = 256
|
| 76 |
+
PARTIAL_ROTARY_FACTOR = 0.25
|
| 77 |
+
ROPE_THETA = 1e7
|
| 78 |
+
MROPE_SECTION = [11, 11, 10]
|
| 79 |
+
ATTENTION_BIAS = False
|
| 80 |
+
|
| 81 |
+
ARCH_SUMMARY = f"""
|
| 82 |
+
Qwen3.8-27B (qwen3_5), hand-rolled JiRack TransformerBlock, text-only.
|
| 83 |
+
hidden_size={HIDDEN_SIZE}, vocab_size={VOCAB_SIZE},
|
| 84 |
+
intermediate_size={INTERMEDIATE_SIZE}, num_hidden_layers={NUM_LAYERS}
|
| 85 |
+
Чередование (interval=4): 3x linear_attention (DeltaNet), 1x full_attention
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
KEPT_FULL_PRECISION = """
|
| 89 |
+
Всегда остаются full precision (не GEMM, либо слишком чувствительны):
|
| 90 |
+
- dt_bias, A_log (сырые Parameters, decay DeltaNet)
|
| 91 |
+
- linear_attn.in_proj_b/in_proj_a (по умолчанию, см. GATE_PROJ_PATTERNS)
|
| 92 |
+
- conv1d (depthwise grouped conv, не GEMM)
|
| 93 |
+
- все нормы: RMSNormGated, q_norm/k_norm, model.norm
|
| 94 |
+
- embed_tokens, lm_head
|
| 95 |
+
- mtp.* (вся MTP/NextN-голова) (draft-слой спекулятивного декода;
|
| 96 |
+
тернаризация убивает acceptance rate,
|
| 97 |
+
комьюнити-GGUF держат её в Q8_0)
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# =====================================================================
|
| 102 |
+
# 2. BitLinear -- наш тернарный слой
|
| 103 |
+
# =====================================================================
|
| 104 |
+
|
| 105 |
+
class BitLinear(nn.Linear):
|
| 106 |
+
"""b1.58-style per-tensor absmean ternary weights, per-token int8
|
| 107 |
+
activations, непрерывный lambda-warmup (STE)."""
|
| 108 |
+
|
| 109 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 110 |
+
super().__init__(in_features, out_features, bias=bias)
|
| 111 |
+
self.eps = 1e-5
|
| 112 |
+
self.register_buffer("lambda_", torch.zeros(()), persistent=True)
|
| 113 |
+
|
| 114 |
+
@classmethod
|
| 115 |
+
def from_linear(cls, lin: nn.Linear) -> "BitLinear":
|
| 116 |
+
bl = cls(lin.in_features, lin.out_features, bias=lin.bias is not None)
|
| 117 |
+
bl = bl.to(dtype=lin.weight.dtype, device=lin.weight.device)
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
bl.weight.copy_(lin.weight)
|
| 120 |
+
if lin.bias is not None:
|
| 121 |
+
bl.bias.copy_(lin.bias)
|
| 122 |
+
return bl
|
| 123 |
+
|
| 124 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 125 |
+
if not self.training and float(self.lambda_) < 1e-6:
|
| 126 |
+
return F.linear(x, self.weight, self.bias)
|
| 127 |
+
|
| 128 |
+
lam = self.lambda_.to(x.dtype)
|
| 129 |
+
w = self.weight
|
| 130 |
+
gamma = w.float().abs().mean().clamp(min=self.eps).to(w.dtype)
|
| 131 |
+
w_quant = torch.clamp(torch.round(w / gamma), -1.0, 1.0) * gamma
|
| 132 |
+
w_effective = w + lam * (w_quant - w).detach()
|
| 133 |
+
|
| 134 |
+
x_scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp(min=self.eps)
|
| 135 |
+
x_quant = torch.clamp(torch.round(x * x_scale), -128.0, 127.0) / x_scale
|
| 136 |
+
x_effective = x + lam * (x_quant - x).detach()
|
| 137 |
+
|
| 138 |
+
return F.linear(x_effective, w_effective, self.bias)
|
| 139 |
+
|
| 140 |
+
def set_lambda(self, v: float):
|
| 141 |
+
self.lambda_.fill_(v)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# =====================================================================
|
| 145 |
+
# 3. Карта: что тернаризуем, что оставляем full precision
|
| 146 |
+
# =====================================================================
|
| 147 |
+
|
| 148 |
+
TERNARIZE_PATTERNS = [
|
| 149 |
+
r"linear_attn\.in_proj_qkv$",
|
| 150 |
+
r"linear_attn\.in_proj_z$",
|
| 151 |
+
r"linear_attn\.out_proj$",
|
| 152 |
+
r"self_attn\.q_proj$",
|
| 153 |
+
r"self_attn\.k_proj$",
|
| 154 |
+
r"self_attn\.v_proj$",
|
| 155 |
+
r"self_attn\.o_proj$",
|
| 156 |
+
r"mlp\.gate_proj$",
|
| 157 |
+
r"mlp\.up_proj$",
|
| 158 |
+
r"mlp\.down_proj$",
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
GATE_PROJ_PATTERNS = [
|
| 162 |
+
r"linear_attn\.in_proj_b$",
|
| 163 |
+
r"linear_attn\.in_proj_a$",
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def apply_bitlinear_patch(model: nn.Module, include_gate_proj: bool = False):
|
| 168 |
+
"""Точечная замена nn.Linear -> BitLinear по TERNARIZE_PATTERNS."""
|
| 169 |
+
patterns = list(TERNARIZE_PATTERNS)
|
| 170 |
+
if include_gate_proj:
|
| 171 |
+
patterns += GATE_PROJ_PATTERNS
|
| 172 |
+
compiled = [re.compile(p) for p in patterns]
|
| 173 |
+
|
| 174 |
+
patched = []
|
| 175 |
+
for name, module in list(model.named_modules()):
|
| 176 |
+
if not isinstance(module, nn.Linear):
|
| 177 |
+
continue
|
| 178 |
+
# MTP/NextN-голова НЕ тернаризуется -- всегда full precision.
|
| 179 |
+
# Суффиксные паттерны (self_attn.q_proj$ и т.п.) иначе зацепили бы
|
| 180 |
+
# mtp.layers.0.self_attn.q_proj.
|
| 181 |
+
if name.startswith("mtp"):
|
| 182 |
+
continue
|
| 183 |
+
if any(p.search(name) for p in compiled):
|
| 184 |
+
parent_name, _, child_name = name.rpartition(".")
|
| 185 |
+
parent = model.get_submodule(parent_name) if parent_name else model
|
| 186 |
+
setattr(parent, child_name, BitLinear.from_linear(module))
|
| 187 |
+
patched.append(name)
|
| 188 |
+
return patched
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# =====================================================================
|
| 192 |
+
# 4. Общие блоки (порт математики из реального modeling_qwen3_5.py)
|
| 193 |
+
# =====================================================================
|
| 194 |
+
|
| 195 |
+
class RMSNorm(nn.Module):
|
| 196 |
+
"""(x * w).to(dtype), w хранится как (weight) с offset +1 -- как в
|
| 197 |
+
оригинале Qwen3_5RMSNorm (инициализация нулями, эффективный вес 1+w)."""
|
| 198 |
+
|
| 199 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.eps = eps
|
| 202 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
| 203 |
+
|
| 204 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 205 |
+
dtype = x.dtype
|
| 206 |
+
x = x.float()
|
| 207 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 208 |
+
x = x * (1.0 + self.weight.float())
|
| 209 |
+
return x.to(dtype)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class RMSNormGated(nn.Module):
|
| 213 |
+
"""RMSNorm с гейтингом через SiLU(gate), применяется ПЕРЕД гейтингом
|
| 214 |
+
(норма считается по hidden_states, гейт применяется после)."""
|
| 215 |
+
|
| 216 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 219 |
+
self.eps = eps
|
| 220 |
+
|
| 221 |
+
def forward(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
|
| 222 |
+
dtype = x.dtype
|
| 223 |
+
x = x.float()
|
| 224 |
+
var = x.pow(2).mean(-1, keepdim=True)
|
| 225 |
+
x = x * torch.rsqrt(var + self.eps)
|
| 226 |
+
x = self.weight * x.to(dtype)
|
| 227 |
+
x = x * F.silu(gate.float())
|
| 228 |
+
return x.to(dtype)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 232 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 233 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 234 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 238 |
+
"""Partial rotary: только первые cos.shape[-1] каналов вращаются,
|
| 239 |
+
остальное (q_pass/k_pass) проходит без изменений."""
|
| 240 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 241 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 242 |
+
rotary_dim = cos.shape[-1]
|
| 243 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 244 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 245 |
+
q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
|
| 246 |
+
k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
|
| 247 |
+
return q_embed, k_embed
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class TextRotaryEmbedding(nn.Module):
|
| 251 |
+
"""mRoPE с partial_rotary_factor. Для чистого текста (без vision)
|
| 252 |
+
3 позиционные "оси" (T,H,W) совпадают -> interleaved mRoPE
|
| 253 |
+
вырождается в обычный RoPE, но мы всё равно считаем честно тем же
|
| 254 |
+
путём, что и оригинал, для полной числовой идентичности."""
|
| 255 |
+
|
| 256 |
+
def __init__(self, head_dim=HEAD_DIM, partial_rotary_factor=PARTIAL_ROTARY_FACTOR,
|
| 257 |
+
theta=ROPE_THETA, mrope_section=MROPE_SECTION):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.rotary_dim = int(head_dim * partial_rotary_factor)
|
| 260 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, self.rotary_dim, 2, dtype=torch.float32) / self.rotary_dim))
|
| 261 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 262 |
+
self.mrope_section = mrope_section
|
| 263 |
+
|
| 264 |
+
def _apply_interleaved_mrope(self, freqs: torch.Tensor) -> torch.Tensor:
|
| 265 |
+
# freqs: (3, bs, seq, rotary_dim // 2)
|
| 266 |
+
freqs_t = freqs[0].clone()
|
| 267 |
+
for dim, offset in enumerate((1, 2), start=1):
|
| 268 |
+
length = self.mrope_section[dim] * 3
|
| 269 |
+
idx = slice(offset, length, 3)
|
| 270 |
+
freqs_t[..., idx] = freqs[dim, ..., idx]
|
| 271 |
+
return freqs_t
|
| 272 |
+
|
| 273 |
+
@torch.no_grad()
|
| 274 |
+
def forward(self, x: torch.Tensor, position_ids: torch.LongTensor):
|
| 275 |
+
# position_ids: (bs, seq) -> реплицируем в 3 идентичные оси (text-only)
|
| 276 |
+
if position_ids.ndim == 2:
|
| 277 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 278 |
+
inv_freq_exp = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
| 279 |
+
pos_exp = position_ids[:, :, None, :].float()
|
| 280 |
+
freqs = (inv_freq_exp @ pos_exp).transpose(2, 3) # (3, bs, seq, rotary_dim//2)
|
| 281 |
+
freqs = self._apply_interleaved_mrope(freqs) # (bs, seq, rotary_dim//2)
|
| 282 |
+
emb = torch.cat((freqs, freqs), dim=-1) # (bs, seq, rotary_dim)
|
| 283 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6):
|
| 287 |
+
return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def causal_conv1d(hidden_states: torch.Tensor, weight: torch.Tensor, activation: str = "silu"):
|
| 291 |
+
"""hidden_states: (batch, channels, seq_len). Depthwise causal conv,
|
| 292 |
+
left-padded by kernel_size - 1, затем активация."""
|
| 293 |
+
channels, seq_len = hidden_states.shape[1], hidden_states.shape[2]
|
| 294 |
+
padding = weight.shape[-1] - 1
|
| 295 |
+
out = F.conv1d(hidden_states, weight=weight.unsqueeze(1), bias=None, padding=padding, groups=channels)
|
| 296 |
+
out = out[:, :, :seq_len]
|
| 297 |
+
return F.silu(out) if activation == "silu" else out
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def chunked_gated_delta_rule(query, key, value, g, beta, chunk_size=DELTA_CHUNK_SIZE):
|
| 301 |
+
"""Порт torch_chunk_gated_delta_rule из modeling_qwen3_5.py -- без
|
| 302 |
+
initial_state/output_final_state (тренировка/полный форвард без
|
| 303 |
+
инкрементального кэша). query/key/value: (b, h, t, d), g/beta: (b, h, t)."""
|
| 304 |
+
initial_dtype = query.dtype
|
| 305 |
+
query = l2norm(query, dim=-1, eps=1e-6)
|
| 306 |
+
key = l2norm(key, dim=-1, eps=1e-6)
|
| 307 |
+
query, key, value, beta, g = [x.contiguous().to(torch.float32) for x in (query, key, value, beta, g)]
|
| 308 |
+
|
| 309 |
+
b, h, t, k_dim = key.shape
|
| 310 |
+
v_dim = value.shape[-1]
|
| 311 |
+
pad = (chunk_size - t % chunk_size) % chunk_size
|
| 312 |
+
query = F.pad(query, (0, 0, 0, pad))
|
| 313 |
+
key = F.pad(key, (0, 0, 0, pad))
|
| 314 |
+
value = F.pad(value, (0, 0, 0, pad))
|
| 315 |
+
beta = F.pad(beta, (0, pad))
|
| 316 |
+
g = F.pad(g, (0, pad))
|
| 317 |
+
total_t = t + pad
|
| 318 |
+
scale = 1 / (query.shape[-1] ** 0.5)
|
| 319 |
+
query = query * scale
|
| 320 |
+
|
| 321 |
+
v_beta = value * beta.unsqueeze(-1)
|
| 322 |
+
k_beta = key * beta.unsqueeze(-1)
|
| 323 |
+
query, key, value, k_beta, v_beta = [
|
| 324 |
+
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
|
| 325 |
+
]
|
| 326 |
+
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
|
| 327 |
+
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
|
| 328 |
+
|
| 329 |
+
g = g.cumsum(dim=-1)
|
| 330 |
+
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
|
| 331 |
+
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
|
| 332 |
+
for i in range(1, chunk_size):
|
| 333 |
+
row = attn[..., i, :i].clone()
|
| 334 |
+
sub = attn[..., :i, :i].clone()
|
| 335 |
+
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
|
| 336 |
+
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
|
| 337 |
+
value = attn @ v_beta
|
| 338 |
+
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
|
| 339 |
+
|
| 340 |
+
last_state = torch.zeros(b, h, k_dim, v_dim, dtype=value.dtype, device=value.device)
|
| 341 |
+
core_out = torch.zeros_like(value)
|
| 342 |
+
|
| 343 |
+
for i in range(total_t // chunk_size):
|
| 344 |
+
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
|
| 345 |
+
attn_i = q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]
|
| 346 |
+
v_prime = k_cumdecay[:, :, i] @ last_state
|
| 347 |
+
v_new = v_i - v_prime
|
| 348 |
+
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_state
|
| 349 |
+
core_out[:, :, i] = attn_inter + attn_i @ v_new
|
| 350 |
+
last_state = (
|
| 351 |
+
last_state * g[:, :, i, -1, None, None].exp()
|
| 352 |
+
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
core_out = core_out.reshape(core_out.shape[0], core_out.shape[1], -1, core_out.shape[-1])
|
| 356 |
+
core_out = core_out[:, :, :t]
|
| 357 |
+
core_out = core_out.transpose(1, 2).contiguous().to(initial_dtype)
|
| 358 |
+
return core_out
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
# =====================================================================
|
| 362 |
+
# 5. Наш собственный TransformerBlock (и подмодули linear_attn/self_attn)
|
| 363 |
+
# =====================================================================
|
| 364 |
+
|
| 365 |
+
class GatedDeltaNetBlock(nn.Module):
|
| 366 |
+
"""linear_attention слой (Gated DeltaNet). Имена подмодулей совпадают
|
| 367 |
+
с HF state_dict, чтобы веса грузились напрямую."""
|
| 368 |
+
|
| 369 |
+
def __init__(self):
|
| 370 |
+
super().__init__()
|
| 371 |
+
self.conv1d = nn.Conv1d(
|
| 372 |
+
in_channels=DELTA_CONV_DIM, out_channels=DELTA_CONV_DIM, bias=False,
|
| 373 |
+
kernel_size=LINEAR_CONV_KERNEL_DIM, groups=DELTA_CONV_DIM,
|
| 374 |
+
padding=LINEAR_CONV_KERNEL_DIM - 1,
|
| 375 |
+
)
|
| 376 |
+
self.dt_bias = nn.Parameter(torch.ones(LINEAR_NUM_VALUE_HEADS))
|
| 377 |
+
A = torch.empty(LINEAR_NUM_VALUE_HEADS).uniform_(0.01, 16)
|
| 378 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 379 |
+
self.norm = RMSNormGated(LINEAR_VALUE_HEAD_DIM, eps=RMS_NORM_EPS)
|
| 380 |
+
self.out_proj = nn.Linear(DELTA_VALUE_DIM, HIDDEN_SIZE, bias=False)
|
| 381 |
+
self.in_proj_qkv = nn.Linear(HIDDEN_SIZE, DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM, bias=False)
|
| 382 |
+
self.in_proj_z = nn.Linear(HIDDEN_SIZE, DELTA_VALUE_DIM, bias=False)
|
| 383 |
+
self.in_proj_b = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 384 |
+
self.in_proj_a = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 385 |
+
|
| 386 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 387 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 388 |
+
|
| 389 |
+
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2) # (b, conv_dim, t)
|
| 390 |
+
z = self.in_proj_z(hidden_states).reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 391 |
+
b = self.in_proj_b(hidden_states)
|
| 392 |
+
a = self.in_proj_a(hidden_states)
|
| 393 |
+
|
| 394 |
+
mixed_qkv = causal_conv1d(mixed_qkv, self.conv1d.weight.squeeze(1), activation="silu")
|
| 395 |
+
mixed_qkv = mixed_qkv.transpose(1, 2) # (b, t, conv_dim)
|
| 396 |
+
|
| 397 |
+
query, key, value = torch.split(mixed_qkv, [DELTA_KEY_DIM, DELTA_KEY_DIM, DELTA_VALUE_DIM], dim=-1)
|
| 398 |
+
query = query.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 399 |
+
key = key.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 400 |
+
value = value.reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 401 |
+
|
| 402 |
+
beta = b.sigmoid()
|
| 403 |
+
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
| 404 |
+
|
| 405 |
+
rep = LINEAR_NUM_VALUE_HEADS // LINEAR_NUM_KEY_HEADS
|
| 406 |
+
if rep > 1:
|
| 407 |
+
query = query.repeat_interleave(rep, dim=2)
|
| 408 |
+
key = key.repeat_interleave(rep, dim=2)
|
| 409 |
+
|
| 410 |
+
# -> (b, h, t, d) for the chunked kernel
|
| 411 |
+
query_h = query.transpose(1, 2)
|
| 412 |
+
key_h = key.transpose(1, 2)
|
| 413 |
+
value_h = value.transpose(1, 2)
|
| 414 |
+
beta_h = beta.transpose(1, 2)
|
| 415 |
+
g_h = g.transpose(1, 2)
|
| 416 |
+
|
| 417 |
+
core_attn_out = chunked_gated_delta_rule(query_h, key_h, value_h, g_h, beta_h)
|
| 418 |
+
|
| 419 |
+
core_attn_out = core_attn_out.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 420 |
+
z_flat = z.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 421 |
+
core_attn_out = self.norm(core_attn_out, z_flat)
|
| 422 |
+
core_attn_out = core_attn_out.reshape(bsz, seq_len, -1)
|
| 423 |
+
|
| 424 |
+
return self.out_proj(core_attn_out)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class AttentionBlock(nn.Module):
|
| 428 |
+
"""full_attention слой (Gated Attention + partial rotary mRoPE)."""
|
| 429 |
+
|
| 430 |
+
def __init__(self):
|
| 431 |
+
super().__init__()
|
| 432 |
+
self.num_key_value_groups = NUM_ATTENTION_HEADS // NUM_KEY_VALUE_HEADS
|
| 433 |
+
self.scaling = HEAD_DIM ** -0.5
|
| 434 |
+
self.q_proj = nn.Linear(HIDDEN_SIZE, NUM_ATTENTION_HEADS * HEAD_DIM * 2, bias=ATTENTION_BIAS)
|
| 435 |
+
self.k_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 436 |
+
self.v_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 437 |
+
self.o_proj = nn.Linear(NUM_ATTENTION_HEADS * HEAD_DIM, HIDDEN_SIZE, bias=ATTENTION_BIAS)
|
| 438 |
+
self.q_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 439 |
+
self.k_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 440 |
+
|
| 441 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 442 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 443 |
+
hidden_shape = (bsz, seq_len, -1, HEAD_DIM)
|
| 444 |
+
|
| 445 |
+
query_states, gate = torch.chunk(
|
| 446 |
+
self.q_proj(hidden_states).view(bsz, seq_len, -1, HEAD_DIM * 2), 2, dim=-1
|
| 447 |
+
)
|
| 448 |
+
gate = gate.reshape(bsz, seq_len, -1)
|
| 449 |
+
|
| 450 |
+
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
|
| 451 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 452 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 453 |
+
|
| 454 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 455 |
+
|
| 456 |
+
rep = self.num_key_value_groups
|
| 457 |
+
key_states = key_states.repeat_interleave(rep, dim=1)
|
| 458 |
+
value_states = value_states.repeat_interleave(rep, dim=1)
|
| 459 |
+
|
| 460 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
|
| 461 |
+
attn_weights = attn_weights + causal_mask
|
| 462 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 463 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 464 |
+
attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1)
|
| 465 |
+
attn_output = attn_output * torch.sigmoid(gate)
|
| 466 |
+
|
| 467 |
+
return self.o_proj(attn_output)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class MLPBlock(nn.Module):
|
| 471 |
+
def __init__(self):
|
| 472 |
+
super().__init__()
|
| 473 |
+
self.gate_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 474 |
+
self.up_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 475 |
+
self.down_proj = nn.Linear(INTERMEDIATE_SIZE, HIDDEN_SIZE, bias=False)
|
| 476 |
+
|
| 477 |
+
def forward(self, x):
|
| 478 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class TransformerBlock(nn.Module):
|
| 482 |
+
"""Наш decoder layer -- linear_attn ИЛИ self_attn, в зависимости от
|
| 483 |
+
layer_type, + общий MLP. Имена атрибутов совпадают с HF state_dict."""
|
| 484 |
+
|
| 485 |
+
def __init__(self, layer_idx: int, layer_type: str = None):
|
| 486 |
+
super().__init__()
|
| 487 |
+
# layer_type задан явно -> используем его (нужно для MTP-слоя,
|
| 488 |
+
# который всегда full_attention и лежит ВНЕ LAYER_TYPES).
|
| 489 |
+
self.block_type = layer_type if layer_type is not None else LAYER_TYPES[layer_idx]
|
| 490 |
+
if self.block_type == "linear_attention":
|
| 491 |
+
self.linear_attn = GatedDeltaNetBlock()
|
| 492 |
+
else:
|
| 493 |
+
self.self_attn = AttentionBlock()
|
| 494 |
+
self.mlp = MLPBlock()
|
| 495 |
+
self.input_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 496 |
+
self.post_attention_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 497 |
+
|
| 498 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 499 |
+
residual = hidden_states
|
| 500 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 501 |
+
if self.block_type == "linear_attention":
|
| 502 |
+
hidden_states = self.linear_attn(hidden_states)
|
| 503 |
+
else:
|
| 504 |
+
hidden_states = self.self_attn(hidden_states, cos, sin, causal_mask)
|
| 505 |
+
hidden_states = residual + hidden_states
|
| 506 |
+
|
| 507 |
+
residual = hidden_states
|
| 508 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 509 |
+
hidden_states = self.mlp(hidden_states)
|
| 510 |
+
hidden_states = residual + hidden_states
|
| 511 |
+
return hidden_states
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
# =====================================================================
|
| 515 |
+
# 5b. MTP / NextN-голова (draft-слой спекулятивного декода)
|
| 516 |
+
# =====================================================================
|
| 517 |
+
|
| 518 |
+
class MTPBlock(nn.Module):
|
| 519 |
+
"""Multi-Token Prediction голова -- ровно как в реальном чекпоинте
|
| 520 |
+
Qwen3.5/3.8 (mtp_num_hidden_layers=1, mtp_use_dedicated_embeddings=false).
|
| 521 |
+
|
| 522 |
+
Имена подмодулей СОВПАДАЮТ с ключами HF state_dict (top-level `mtp.`):
|
| 523 |
+
mtp.pre_fc_norm_embedding.weight
|
| 524 |
+
mtp.pre_fc_norm_hidden.weight
|
| 525 |
+
mtp.fc.weight [HIDDEN, 2*HIDDEN]
|
| 526 |
+
mtp.layers.0.* (обычный full_attention decoder)
|
| 527 |
+
mtp.norm.weight (final norm перед общим lm_head)
|
| 528 |
+
|
| 529 |
+
embed_tokens и lm_head ОБЩИЕ со стволом (dedicated embeddings = false),
|
| 530 |
+
здесь их нет. В GGUF это blk.{NUM_LAYERS}.nextn.eh_proj /
|
| 531 |
+
shared_head_norm + тензоры draft-слоя.
|
| 532 |
+
|
| 533 |
+
Механика (DeepSeek-style, порядок как в vLLM Qwen3NextMTP):
|
| 534 |
+
h = fc(cat(pre_fc_norm_embedding(emb_next), pre_fc_norm_hidden(h_prev)))
|
| 535 |
+
h = layers[0](h) # full attention
|
| 536 |
+
logits2 = lm_head(norm(h))
|
| 537 |
+
"""
|
| 538 |
+
|
| 539 |
+
def __init__(self):
|
| 540 |
+
super().__init__()
|
| 541 |
+
self.pre_fc_norm_embedding = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 542 |
+
self.pre_fc_norm_hidden = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 543 |
+
self.fc = nn.Linear(2 * HIDDEN_SIZE, HIDDEN_SIZE, bias=False)
|
| 544 |
+
self.layers = nn.ModuleList([
|
| 545 |
+
TransformerBlock(layer_idx=NUM_LAYERS, layer_type="full_attention"),
|
| 546 |
+
])
|
| 547 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 548 |
+
|
| 549 |
+
def forward(self, inputs_embeds, previous_hidden, cos, sin, causal_mask):
|
| 550 |
+
"""inputs_embeds -- embed_tokens(токены, сдвинутые на +1)
|
| 551 |
+
previous_hidden -- hidden ствола ДО финального model.norm
|
| 552 |
+
(см. контракт: MTP сам применяет pre_fc_norm_hidden)."""
|
| 553 |
+
h = self.fc(torch.cat(
|
| 554 |
+
(self.pre_fc_norm_embedding(inputs_embeds),
|
| 555 |
+
self.pre_fc_norm_hidden(previous_hidden)),
|
| 556 |
+
dim=-1,
|
| 557 |
+
))
|
| 558 |
+
h = self.layers[0](h, cos, sin, causal_mask)
|
| 559 |
+
return self.norm(h)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# =====================================================================
|
| 563 |
+
# 6. Полная модель
|
| 564 |
+
# =====================================================================
|
| 565 |
+
|
| 566 |
+
class JiRackQwen38Model(nn.Module):
|
| 567 |
+
def __init__(self):
|
| 568 |
+
super().__init__()
|
| 569 |
+
self.embed_tokens = nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
|
| 570 |
+
self.layers = nn.ModuleList([TransformerBlock(i) for i in range(NUM_LAYERS)])
|
| 571 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 572 |
+
self.rotary_emb = TextRotaryEmbedding()
|
| 573 |
+
|
| 574 |
+
def forward(self, input_ids: torch.LongTensor, return_prenorm: bool = False):
|
| 575 |
+
bsz, seq_len = input_ids.shape
|
| 576 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 577 |
+
|
| 578 |
+
position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(bsz, -1)
|
| 579 |
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
| 580 |
+
|
| 581 |
+
causal_mask = torch.full((seq_len, seq_len), float("-inf"), device=input_ids.device, dtype=torch.float32)
|
| 582 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)[None, None, :, :].to(hidden_states.dtype)
|
| 583 |
+
|
| 584 |
+
for layer in self.layers:
|
| 585 |
+
hidden_states = layer(hidden_states, cos, sin, causal_mask)
|
| 586 |
+
|
| 587 |
+
if return_prenorm:
|
| 588 |
+
# Для MTP: голова сама применяет pre_fc_norm_hidden, финальный
|
| 589 |
+
# model.norm сюда НЕ входит (иначе двойная нормализация).
|
| 590 |
+
return self.norm(hidden_states), hidden_states, (cos, sin, causal_mask)
|
| 591 |
+
return self.norm(hidden_states)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class JiRackQwen38ForCausalLM(nn.Module):
|
| 595 |
+
"""Верхнеуровневая модель. Имена атрибутов (`model`, `lm_head`)
|
| 596 |
+
совпадают с HF Qwen3_5ForCausalLM -- state_dict грузится напрямую."""
|
| 597 |
+
|
| 598 |
+
def __init__(self):
|
| 599 |
+
super().__init__()
|
| 600 |
+
self.model = JiRackQwen38Model()
|
| 601 |
+
self.lm_head = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False)
|
| 602 |
+
# MTP/NextN-голова: top-level атрибут `mtp` -- ключи state_dict
|
| 603 |
+
# получаются ровно mtp.*, как в реальном HF-чекпоинте.
|
| 604 |
+
self.mtp = MTPBlock()
|
| 605 |
+
|
| 606 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
|
| 607 |
+
hidden_states = self.model(input_ids)
|
| 608 |
+
return self.lm_head(hidden_states)
|
| 609 |
+
|
| 610 |
+
def mtp_forward(self, input_ids: torch.LongTensor):
|
| 611 |
+
"""Возвращает (logits_t1, logits_t2): обычные логиты ствола и
|
| 612 |
+
draft-логиты MTP-головы (предсказание токена t+2 из позиции t).
|
| 613 |
+
Для инференса/валидации MTP; в GGUF-конвертации не участвует."""
|
| 614 |
+
_, prenorm_hidden, (cos, sin, causal_mask) = self.model(
|
| 615 |
+
input_ids, return_prenorm=True)
|
| 616 |
+
logits_t1 = self.lm_head(self.model.norm(prenorm_hidden))
|
| 617 |
+
|
| 618 |
+
# Вход MTP -- эмбеддинги токенов, сдвинутых на +1 (следующий токен
|
| 619 |
+
# уже известен на шаге верификации). Последнюю позицию дублируем,
|
| 620 |
+
# чтобы сохранить форму (draft для неё не используется).
|
| 621 |
+
shifted = torch.cat([input_ids[:, 1:], input_ids[:, -1:]], dim=1)
|
| 622 |
+
emb_next = self.model.embed_tokens(shifted)
|
| 623 |
+
h2 = self.mtp(emb_next, prenorm_hidden, cos, sin, causal_mask)
|
| 624 |
+
logits_t2 = self.lm_head(h2)
|
| 625 |
+
return logits_t1, logits_t2
|
| 626 |
+
|
| 627 |
+
# -----------------------------------------------------------------
|
| 628 |
+
# Заг��узка реальных весов (state_dict уже скачан конвертером через
|
| 629 |
+
# HF Hub -- сюда просто передаётся словарь тензоров)
|
| 630 |
+
# -----------------------------------------------------------------
|
| 631 |
+
def load_hf_state_dict(self, state_dict: dict, strict: bool = False):
|
| 632 |
+
"""Грузит state_dict в формате оригинального Qwen3_5ForCausalLM.
|
| 633 |
+
mtp.* ключи теперь ГРУЗЯТСЯ в self.mtp (MTPBlock) -- фильтра
|
| 634 |
+
больше нет. strict=False оставлен из-за служебных lambda_-буферов
|
| 635 |
+
BitLinear, которых нет в реальном чекпоинте."""
|
| 636 |
+
missing, unexpected = self.load_state_dict(state_dict, strict=strict)
|
| 637 |
+
real_missing = [k for k in missing if not k.endswith("lambda_")]
|
| 638 |
+
if real_missing:
|
| 639 |
+
print(f"⚠️ {len(real_missing)} missing keys (первые 10): {real_missing[:10]}")
|
| 640 |
+
if unexpected:
|
| 641 |
+
print(f"⚠️ {len(unexpected)} unexpected keys (первые 10): {unexpected[:10]}")
|
| 642 |
+
return missing, unexpected
|
| 643 |
+
|
| 644 |
+
# -----------------------------------------------------------------
|
| 645 |
+
# Подсадка РЕАЛЬНЫХ mtp.* весов из оригинального HF-чекпоинта.
|
| 646 |
+
# Нужна, потому что старые JiRack .pt сохранены ДО появления MTPBlock
|
| 647 |
+
# и mtp-весов не содержат (там была бы случайная инициализация).
|
| 648 |
+
# -----------------------------------------------------------------
|
| 649 |
+
def load_mtp_from_hf_dir(self, hf_dir: str):
|
| 650 |
+
"""Читает из папки оригинального HF-чекпоинта ТОЛЬКО mtp.* тензоры
|
| 651 |
+
(по index.json или перебором *.safetensors) и грузит их в self.mtp.
|
| 652 |
+
Возвращает число загруженных тензоров."""
|
| 653 |
+
import glob
|
| 654 |
+
import json as _json
|
| 655 |
+
from safetensors import safe_open
|
| 656 |
+
|
| 657 |
+
index_path = os.path.join(hf_dir, "model.safetensors.index.json")
|
| 658 |
+
mtp_map = {} # key -> shard file
|
| 659 |
+
if os.path.exists(index_path):
|
| 660 |
+
with open(index_path) as f:
|
| 661 |
+
weight_map = _json.load(f)["weight_map"]
|
| 662 |
+
for k, shard in weight_map.items():
|
| 663 |
+
if k.startswith("mtp."):
|
| 664 |
+
mtp_map[k] = os.path.join(hf_dir, shard)
|
| 665 |
+
else:
|
| 666 |
+
for shard in glob.glob(os.path.join(hf_dir, "*.safetensors")):
|
| 667 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 668 |
+
for k in f.keys():
|
| 669 |
+
if k.startswith("mtp."):
|
| 670 |
+
mtp_map[k] = shard
|
| 671 |
+
|
| 672 |
+
if not mtp_map:
|
| 673 |
+
raise FileNotFoundError(
|
| 674 |
+
f"В {hf_dir} не найдено ни одного mtp.* тензора. Нужен "
|
| 675 |
+
f"ОРИГИНАЛЬНЫЙ чекпоинт Qwen3.8-27B (не JiRack-экспорт!). "
|
| 676 |
+
f"Если оригинальные шарды удалены -- перекачай с HF Hub "
|
| 677 |
+
f"только шарды с mtp.* по model.safetensors.index.json.")
|
| 678 |
+
|
| 679 |
+
own_dtype = next(self.mtp.parameters()).dtype
|
| 680 |
+
loaded = {}
|
| 681 |
+
by_shard = {}
|
| 682 |
+
for k, shard in mtp_map.items():
|
| 683 |
+
by_shard.setdefault(shard, []).append(k)
|
| 684 |
+
for shard, keys in by_shard.items():
|
| 685 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 686 |
+
for k in keys:
|
| 687 |
+
loaded[k] = f.get_tensor(k).to(own_dtype)
|
| 688 |
+
|
| 689 |
+
missing, unexpected = self.load_state_dict(loaded, strict=False)
|
| 690 |
+
n_ok = len(loaded)
|
| 691 |
+
print(f"✅ MTP: загружено {n_ok} тензоров из {len(by_shard)} шардов ({hf_dir})")
|
| 692 |
+
if unexpected:
|
| 693 |
+
print(f"⚠️ MTP: unexpected keys: {unexpected[:10]}")
|
| 694 |
+
return n_ok
|
| 695 |
+
|
| 696 |
+
# -----------------------------------------------------------------
|
| 697 |
+
# JiRack-чекпоинт (свой формат, с lambda/patched_linear_names)
|
| 698 |
+
# -----------------------------------------------------------------
|
| 699 |
+
def save_checkpoint(self, path: str, lam: float, global_step: int = 0, patched_linear_names=None):
|
| 700 |
+
torch.save({
|
| 701 |
+
"model": self.state_dict(),
|
| 702 |
+
"lambda": lam,
|
| 703 |
+
"global_step": global_step,
|
| 704 |
+
"patched_linear_names": patched_linear_names or [],
|
| 705 |
+
}, path)
|
| 706 |
+
|
| 707 |
+
@classmethod
|
| 708 |
+
def load_checkpoint(cls, path: str, dtype=torch.bfloat16, include_gate_proj: bool = False):
|
| 709 |
+
ckpt = torch.load(path, map_location="cpu", weights_only=False)
|
| 710 |
+
model = cls()
|
| 711 |
+
patched_names = ckpt.get("patched_linear_names", [])
|
| 712 |
+
if patched_names:
|
| 713 |
+
for name in patched_names:
|
| 714 |
+
*parent_path, leaf = name.split(".")
|
| 715 |
+
parent = model
|
| 716 |
+
for p in parent_path:
|
| 717 |
+
parent = getattr(parent, p)
|
| 718 |
+
old = getattr(parent, leaf)
|
| 719 |
+
if not isinstance(old, BitLinear):
|
| 720 |
+
setattr(parent, leaf, BitLinear.from_linear(old))
|
| 721 |
+
else:
|
| 722 |
+
apply_bitlinear_patch(model, include_gate_proj=include_gate_proj)
|
| 723 |
+
|
| 724 |
+
has_mtp_in_ckpt = any(k.startswith("mtp.") for k in ckpt["model"])
|
| 725 |
+
model.load_state_dict(ckpt["model"], strict=False)
|
| 726 |
+
model = model.to(dtype)
|
| 727 |
+
|
| 728 |
+
if not has_mtp_in_ckpt:
|
| 729 |
+
print(
|
| 730 |
+
"⚠️ В этом .pt НЕТ mtp.* весов (чекпоинт сохранён до "
|
| 731 |
+
"появления MTPBlock). Голова сейчас со СЛУЧАЙНОЙ "
|
| 732 |
+
"инициализацией! Перед экспортом обязательно вызови "
|
| 733 |
+
"model.load_mtp_from_hf_dir('<папка оригинального HF-чекпоинта>')."
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
lam = ckpt.get("lambda", 0.0)
|
| 737 |
+
for m in model.modules():
|
| 738 |
+
if isinstance(m, BitLinear):
|
| 739 |
+
m.set_lambda(lam)
|
| 740 |
+
|
| 741 |
+
print(f"✅ Загружено. global_step={ckpt.get('global_step', 0)}, lambda={lam}")
|
| 742 |
+
return model
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# =====================================================================
|
| 746 |
+
# 7. Демонстрация (без скачивания весов -- только структура)
|
| 747 |
+
# =====================================================================
|
| 748 |
+
|
| 749 |
+
if __name__ == "__main__":
|
| 750 |
+
print(ARCH_SUMMARY)
|
| 751 |
+
print(KEPT_FULL_PRECISION)
|
| 752 |
+
|
| 753 |
+
model = JiRackQwen38ForCausalLM()
|
| 754 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 755 |
+
print(f"✅ Модель собрана (случайные веса). Параметров: {n_params / 1e9:.2f}B")
|
| 756 |
+
|
| 757 |
+
patched = apply_bitlinear_patch(model)
|
| 758 |
+
print(f"✅ Заменено подмодулей на BitLinear: {len(patched)}")
|
| 759 |
+
print("Примеры первых 10:")
|
| 760 |
+
for n in patched[:10]:
|
| 761 |
+
print(f" {n}")
|
| 762 |
+
|
| 763 |
+
ids = torch.randint(0, VOCAB_SIZE, (1, 8))
|
| 764 |
+
with torch.no_grad():
|
| 765 |
+
logits = model(ids)
|
| 766 |
+
print(f"✅ Пробный forward (случайные веса) -> logits shape: {tuple(logits.shape)}")
|
sft_final/audit_depth.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"kind": "depth",
|
| 3 |
+
"src": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded",
|
| 4 |
+
"out": "/mnt/nfs_share/JiRackDeltaNet_70b/expanded",
|
| 5 |
+
"tensors": 1714,
|
| 6 |
+
"ops": {
|
| 7 |
+
"copy": 1586,
|
| 8 |
+
"zero": 128
|
| 9 |
+
},
|
| 10 |
+
"errors": [],
|
| 11 |
+
"n_errors": 0,
|
| 12 |
+
"verdict": "PASS",
|
| 13 |
+
"minutes": 9.8
|
| 14 |
+
}
|
sft_final/chat_jirack.py
ADDED
|
@@ -0,0 +1,303 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# chat_jirack.py - chat with JiRackDeltaNet (27B / 36B / 70B) from a safetensors folder.
|
| 4 |
+
#
|
| 5 |
+
# python3 chat_jirack.py --model-dir /mnt/nfs_share/JiRackDeltaNet_70b/expanded
|
| 6 |
+
# python3 chat_jirack.py --model-dir /mnt/nfs_share/JiRackDeltaNet_27b_cp # 27B
|
| 7 |
+
#
|
| 8 |
+
# - model code: JiRackDeltaNet_*.py from the same folder (or --model-file)
|
| 9 |
+
# - several GPUs: the TransformerBlocks are split across them evenly (70B bf16 = 140 GB,
|
| 10 |
+
# so at least 2x80 GB); 1 GPU if it fits; CPU works but is VERY slow for 70B
|
| 11 |
+
# - answer streams token by token, stops on <|im_end|> / <|endoftext|>
|
| 12 |
+
# - commands: /reset (clear history), /think (thinking on/off), exit
|
| 13 |
+
# =============================================================================
|
| 14 |
+
import argparse
|
| 15 |
+
import glob
|
| 16 |
+
import importlib.util
|
| 17 |
+
import itertools
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import sys
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
import torch
|
| 24 |
+
import torch.nn as nn
|
| 25 |
+
|
| 26 |
+
INIT_FNS = ("uniform_", "normal_", "trunc_normal_", "kaiming_uniform_", "kaiming_normal_",
|
| 27 |
+
"xavier_uniform_", "xavier_normal_", "orthogonal_")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def find_model_file(d):
|
| 31 |
+
files = sorted(glob.glob(os.path.join(d, "JiRackDeltaNet_*.py")))
|
| 32 |
+
if not files:
|
| 33 |
+
sys.exit(f"❌ no JiRackDeltaNet_*.py in {d}; pass --model-file")
|
| 34 |
+
return files[-1]
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def load_module(path):
|
| 38 |
+
spec = importlib.util.spec_from_file_location("jirack_chat_model", path)
|
| 39 |
+
mod = importlib.util.module_from_spec(spec)
|
| 40 |
+
sys.modules["jirack_chat_model"] = mod
|
| 41 |
+
spec.loader.exec_module(mod)
|
| 42 |
+
return mod
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def build(mod):
|
| 46 |
+
"""bf16 skeleton without random init (all weights are loaded afterwards) - as in deltanet_gate.py."""
|
| 47 |
+
saved = {n: getattr(nn.init, n) for n in INIT_FNS if hasattr(nn.init, n)}
|
| 48 |
+
for n in saved:
|
| 49 |
+
setattr(nn.init, n, lambda t, *a, **k: t)
|
| 50 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 51 |
+
try:
|
| 52 |
+
model = mod.JiRackQwen38ForCausalLM()
|
| 53 |
+
finally:
|
| 54 |
+
torch.set_default_dtype(torch.float32)
|
| 55 |
+
for n, f in saved.items():
|
| 56 |
+
setattr(nn.init, n, f)
|
| 57 |
+
return model.eval()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def load_weights(model, d):
|
| 61 |
+
from safetensors import safe_open
|
| 62 |
+
idx = os.path.join(d, "model.safetensors.index.json")
|
| 63 |
+
files = sorted(set(json.load(open(idx))["weight_map"].values())) if os.path.exists(idx) else \
|
| 64 |
+
sorted(os.path.basename(p) for p in glob.glob(os.path.join(d, "*.safetensors")))
|
| 65 |
+
sd = model.state_dict()
|
| 66 |
+
params = {n for n, _ in model.named_parameters()}
|
| 67 |
+
loaded = set()
|
| 68 |
+
t0 = time.time()
|
| 69 |
+
with torch.no_grad():
|
| 70 |
+
for i, f in enumerate(files):
|
| 71 |
+
with safe_open(os.path.join(d, f), framework="pt", device="cpu") as h:
|
| 72 |
+
for k in h.keys():
|
| 73 |
+
if k in sd:
|
| 74 |
+
sd[k].copy_(h.get_tensor(k))
|
| 75 |
+
loaded.add(k)
|
| 76 |
+
print(f" {i + 1}/{len(files)} {f} {time.time() - t0:.0f} s", flush=True)
|
| 77 |
+
missing = sorted(params - loaded)
|
| 78 |
+
if missing:
|
| 79 |
+
sys.exit(f"❌ {len(missing)} parameters not in {d}: {missing[:5]}")
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class ChatTokenizer:
|
| 83 |
+
"""tokenizer.json (tokenizers) + chat template (jinja2) - no transformers needed, so the
|
| 84 |
+
tokenizer_config.json format (e.g. extra_special_tokens as a list) does not matter."""
|
| 85 |
+
|
| 86 |
+
def __init__(self, d):
|
| 87 |
+
import jinja2
|
| 88 |
+
from jinja2.sandbox import ImmutableSandboxedEnvironment
|
| 89 |
+
from tokenizers import Tokenizer
|
| 90 |
+
self.tk = Tokenizer.from_file(os.path.join(d, "tokenizer.json"))
|
| 91 |
+
cfg = {}
|
| 92 |
+
if os.path.exists(os.path.join(d, "tokenizer_config.json")):
|
| 93 |
+
cfg = json.load(open(os.path.join(d, "tokenizer_config.json"), encoding="utf-8"))
|
| 94 |
+
path = os.path.join(d, "chat_template.jinja")
|
| 95 |
+
text = open(path, encoding="utf-8").read() if os.path.exists(path) else cfg.get("chat_template")
|
| 96 |
+
if isinstance(text, list):
|
| 97 |
+
text = next(t["template"] for t in text if t.get("name") == "default")
|
| 98 |
+
if not text:
|
| 99 |
+
sys.exit(f"❌ no chat template in {d}")
|
| 100 |
+
|
| 101 |
+
def raise_exception(msg):
|
| 102 |
+
raise jinja2.exceptions.TemplateError(msg)
|
| 103 |
+
|
| 104 |
+
def tojson(x, ensure_ascii=False, indent=None, separators=None, sort_keys=False):
|
| 105 |
+
return json.dumps(x, ensure_ascii=ensure_ascii, indent=indent, separators=separators,
|
| 106 |
+
sort_keys=sort_keys)
|
| 107 |
+
|
| 108 |
+
env = ImmutableSandboxedEnvironment(trim_blocks=True, lstrip_blocks=True)
|
| 109 |
+
env.filters["tojson"] = tojson
|
| 110 |
+
env.globals["raise_exception"] = raise_exception
|
| 111 |
+
self.tmpl = env.from_string(text)
|
| 112 |
+
s = lambda v: v.get("content") if isinstance(v, dict) else v
|
| 113 |
+
self.bos, self.eos = s(cfg.get("bos_token")) or "", s(cfg.get("eos_token")) or ""
|
| 114 |
+
self.special = [t.content for t in self.tk.get_added_tokens_decoder().values() if t.special]
|
| 115 |
+
self.stop_ids = {i for i in (self.tk.token_to_id("<|im_end|>"), self.tk.token_to_id("<|endoftext|>"),
|
| 116 |
+
self.tk.token_to_id(self.eos) if self.eos else None) if i is not None}
|
| 117 |
+
|
| 118 |
+
def prompt_ids(self, msgs, think):
|
| 119 |
+
text = self.tmpl.render(messages=msgs, add_generation_prompt=True, enable_thinking=think,
|
| 120 |
+
bos_token=self.bos, eos_token=self.eos)
|
| 121 |
+
return self.tk.encode(text, add_special_tokens=False).ids
|
| 122 |
+
|
| 123 |
+
def decode(self, ids):
|
| 124 |
+
return self.tk.decode(ids, skip_special_tokens=False)
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _to(x, dev):
|
| 128 |
+
if torch.is_tensor(x):
|
| 129 |
+
return x.to(dev)
|
| 130 |
+
if isinstance(x, (tuple, list)):
|
| 131 |
+
return type(x)(_to(v, dev) for v in x)
|
| 132 |
+
if isinstance(x, dict):
|
| 133 |
+
return {k: _to(v, dev) for k, v in x.items()}
|
| 134 |
+
return x
|
| 135 |
+
|
| 136 |
+
|
| 137 |
+
def place(model, devices):
|
| 138 |
+
"""Blocks split evenly over the GPUs (moved there directly - the whole model never sits on one
|
| 139 |
+
GPU); everything else on the first GPU. Pre-hooks move each module's inputs to its device,
|
| 140 |
+
so the model code needs no changes."""
|
| 141 |
+
blocks = [m for m in model.modules() if type(m).__name__ == "TransformerBlock"]
|
| 142 |
+
in_block = {id(x) for b in blocks for x in b.modules()}
|
| 143 |
+
for i, b in enumerate(blocks):
|
| 144 |
+
dev = devices[i * len(devices) // len(blocks)]
|
| 145 |
+
b.to(dev)
|
| 146 |
+
if len(devices) > 1:
|
| 147 |
+
b.register_forward_pre_hook(lambda m, a, k, dev=dev: (_to(a, dev), _to(k, dev)), with_kwargs=True)
|
| 148 |
+
for m in model.modules(): # embeddings / norms / lm_head / mtp / rotary
|
| 149 |
+
if id(m) in in_block:
|
| 150 |
+
continue
|
| 151 |
+
m._apply(lambda t: t.to(devices[0]), recurse=False)
|
| 152 |
+
if len(devices) > 1 and not list(m.children()):
|
| 153 |
+
m.register_forward_pre_hook(lambda mm, a, k: (_to(a, devices[0]), _to(k, devices[0])),
|
| 154 |
+
with_kwargs=True)
|
| 155 |
+
return devices[0]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def _cast(x, dtype):
|
| 159 |
+
if torch.is_tensor(x):
|
| 160 |
+
return x.to(dtype) if x.is_floating_point() and x.dtype != dtype else x
|
| 161 |
+
if isinstance(x, (tuple, list)):
|
| 162 |
+
return type(x)(_cast(v, dtype) for v in x)
|
| 163 |
+
if isinstance(x, dict):
|
| 164 |
+
return {k: _cast(v, dtype) for k, v in x.items()}
|
| 165 |
+
return x
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def fp32_blocks(model):
|
| 169 |
+
"""CPU (AVX-only Xeon has no fast bf16 matmul): every TransformerBlock and lm_head runs with
|
| 170 |
+
fp32 weights/inputs, converted on entry and back on exit - stored weights stay bf16 (RAM),
|
| 171 |
+
same as the 'fp32blocks' compute of deltanet_gate.py."""
|
| 172 |
+
def pre(mod, args, kwargs):
|
| 173 |
+
saved = []
|
| 174 |
+
for t in itertools.chain(mod.parameters(), mod.buffers()):
|
| 175 |
+
if t.is_floating_point() and t.dtype != torch.float32:
|
| 176 |
+
saved.append((t, t.data))
|
| 177 |
+
t.data = t.data.float()
|
| 178 |
+
mod._jr_saved = saved
|
| 179 |
+
return _cast(args, torch.float32), _cast(kwargs, torch.float32)
|
| 180 |
+
|
| 181 |
+
def post(mod, args, out, back=torch.bfloat16):
|
| 182 |
+
for t, d in mod._jr_saved:
|
| 183 |
+
t.data = d
|
| 184 |
+
mod._jr_saved = []
|
| 185 |
+
return _cast(out, back) if back is not None else out
|
| 186 |
+
|
| 187 |
+
for m in model.modules():
|
| 188 |
+
if type(m).__name__ == "TransformerBlock":
|
| 189 |
+
m.register_forward_pre_hook(pre, with_kwargs=True)
|
| 190 |
+
m.register_forward_hook(post)
|
| 191 |
+
head = getattr(model, "lm_head", None)
|
| 192 |
+
if isinstance(head, nn.Module):
|
| 193 |
+
head.register_forward_pre_hook(pre, with_kwargs=True)
|
| 194 |
+
head.register_forward_hook(lambda m, a, o: post(m, a, o, None))
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
def logits_of(out):
|
| 198 |
+
if isinstance(out, (tuple, list)):
|
| 199 |
+
return out[0]
|
| 200 |
+
return out.logits if hasattr(out, "logits") else out
|
| 201 |
+
|
| 202 |
+
|
| 203 |
+
def sample(logits, temperature, top_p):
|
| 204 |
+
if temperature <= 0:
|
| 205 |
+
return int(logits.argmax())
|
| 206 |
+
probs = torch.softmax(logits.float() / temperature, dim=-1)
|
| 207 |
+
sp, si = probs.sort(descending=True)
|
| 208 |
+
cut = (sp.cumsum(-1) - sp) > top_p
|
| 209 |
+
sp[cut] = 0
|
| 210 |
+
return int(si[torch.multinomial(sp / sp.sum(), 1)])
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def main():
|
| 214 |
+
p = argparse.ArgumentParser()
|
| 215 |
+
p.add_argument("--model-dir", default="/mnt/nfs_share/JiRackDeltaNet_70b/expanded")
|
| 216 |
+
p.add_argument("--model-file", default=None)
|
| 217 |
+
p.add_argument("--tokenizer-dir", default=None, help="default: --model-dir")
|
| 218 |
+
p.add_argument("--max-new", type=int, default=2048)
|
| 219 |
+
p.add_argument("--temperature", type=float, default=0.6, help="0 = greedy")
|
| 220 |
+
p.add_argument("--top-p", type=float, default=0.95)
|
| 221 |
+
p.add_argument("--system", default=None, help="file with a system prompt")
|
| 222 |
+
p.add_argument("--no-think", action="store_true", help="start with thinking off")
|
| 223 |
+
p.add_argument("--cpu", action="store_true")
|
| 224 |
+
p.add_argument("--cpu-bf16", action="store_true", help="CPU: plain bf16 instead of fp32 blocks")
|
| 225 |
+
a = p.parse_args()
|
| 226 |
+
|
| 227 |
+
tok = ChatTokenizer(a.tokenizer_dir or a.model_dir)
|
| 228 |
+
stop = tok.stop_ids
|
| 229 |
+
print(f"stop tokens {sorted(stop)}", flush=True)
|
| 230 |
+
|
| 231 |
+
mf = a.model_file or find_model_file(a.model_dir)
|
| 232 |
+
print(f"model file {mf}\nweights {a.model_dir}", flush=True)
|
| 233 |
+
model = build(load_module(mf))
|
| 234 |
+
load_weights(model, a.model_dir)
|
| 235 |
+
n = sum(q.numel() for q in model.parameters())
|
| 236 |
+
if a.cpu or not torch.cuda.is_available():
|
| 237 |
+
dev = torch.device("cpu")
|
| 238 |
+
try:
|
| 239 |
+
torch.backends.nnpack.set_flags(False) # silences "Could not initialize NNPACK"
|
| 240 |
+
except Exception:
|
| 241 |
+
pass
|
| 242 |
+
if not a.cpu_bf16:
|
| 243 |
+
fp32_blocks(model)
|
| 244 |
+
print(f"⚠️ CPU: {n / 1e9:.1f}B params, compute {'bf16' if a.cpu_bf16 else 'fp32 blocks'} - "
|
| 245 |
+
f"every token is a full forward pass, expect minutes per token. Ctrl+C stops the answer.")
|
| 246 |
+
else:
|
| 247 |
+
devs = [torch.device("cuda", i) for i in range(torch.cuda.device_count())]
|
| 248 |
+
dev = place(model, devs)
|
| 249 |
+
print(f"on {len(devs)} GPU(s): {n / 1e9:.1f}B params, "
|
| 250 |
+
f"{[round(torch.cuda.memory_allocated(d) / 2 ** 30) for d in devs]} GB")
|
| 251 |
+
|
| 252 |
+
system = open(a.system, encoding="utf-8").read().strip() if a.system else None
|
| 253 |
+
think = not a.no_think
|
| 254 |
+
history = []
|
| 255 |
+
print("\nReady. /reset - clear history, /think - thinking on/off, exit - quit")
|
| 256 |
+
while True:
|
| 257 |
+
try:
|
| 258 |
+
user = input("\nYou: ").strip()
|
| 259 |
+
except (EOFError, KeyboardInterrupt):
|
| 260 |
+
break
|
| 261 |
+
if not user:
|
| 262 |
+
continue
|
| 263 |
+
if user.lower() in ("exit", "quit"):
|
| 264 |
+
break
|
| 265 |
+
if user == "/reset":
|
| 266 |
+
history = []
|
| 267 |
+
print("(history cleared)")
|
| 268 |
+
continue
|
| 269 |
+
if user == "/think":
|
| 270 |
+
think = not think
|
| 271 |
+
print(f"(thinking {'on' if think else 'off'})")
|
| 272 |
+
continue
|
| 273 |
+
history.append({"role": "user", "content": user})
|
| 274 |
+
msgs = ([{"role": "system", "content": system}] if system else []) + history
|
| 275 |
+
ids = torch.tensor([tok.prompt_ids(msgs, think)], dtype=torch.long, device=dev)
|
| 276 |
+
start = ids.shape[1]
|
| 277 |
+
print("\nAssistant: ", end="", flush=True)
|
| 278 |
+
printed, t0 = "", time.time()
|
| 279 |
+
try:
|
| 280 |
+
with torch.no_grad():
|
| 281 |
+
for _ in range(a.max_new):
|
| 282 |
+
nxt = sample(logits_of(model(ids))[0, -1], a.temperature, a.top_p)
|
| 283 |
+
if nxt in stop:
|
| 284 |
+
break
|
| 285 |
+
ids = torch.cat([ids, torch.tensor([[nxt]], device=ids.device)], dim=1)
|
| 286 |
+
text = tok.decode(ids[0, start:].tolist())
|
| 287 |
+
if not text.endswith("�"): # wait for a complete UTF-8 character
|
| 288 |
+
print(text[len(printed):], end="", flush=True)
|
| 289 |
+
printed = text
|
| 290 |
+
except KeyboardInterrupt:
|
| 291 |
+
print(" [stopped]", end="")
|
| 292 |
+
gen = ids.shape[1] - start
|
| 293 |
+
raw = tok.decode(ids[0, start:].tolist())
|
| 294 |
+
print(f"\n [{gen} tokens, {gen / max(time.time() - t0, 1e-6):.2f} tok/s]")
|
| 295 |
+
# Qwen: earlier turns go back into the history without the thinking part
|
| 296 |
+
reply = raw.split("</think>")[-1]
|
| 297 |
+
for t in tok.special:
|
| 298 |
+
reply = reply.replace(t, "")
|
| 299 |
+
history.append({"role": "assistant", "content": reply.strip()})
|
| 300 |
+
|
| 301 |
+
|
| 302 |
+
if __name__ == "__main__":
|
| 303 |
+
main()
|
sft_final/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/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 |
+
}
|
sft_final/expansion_depth.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sft_final/gate_full.json
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"verdict": "PASS",
|
| 3 |
+
"expected": "exact",
|
| 4 |
+
"mini": false,
|
| 5 |
+
"compute": "fp32blocks",
|
| 6 |
+
"a": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded",
|
| 7 |
+
"b": "/mnt/nfs_share/JiRackDeltaNet_70b/expanded",
|
| 8 |
+
"layers_run": [
|
| 9 |
+
64,
|
| 10 |
+
128
|
| 11 |
+
],
|
| 12 |
+
"intermediate": [
|
| 13 |
+
26624,
|
| 14 |
+
26624
|
| 15 |
+
],
|
| 16 |
+
"prompts": [
|
| 17 |
+
"The capital of France is",
|
| 18 |
+
"def fibonacci(n):\n ",
|
| 19 |
+
"Столица России —"
|
| 20 |
+
],
|
| 21 |
+
"ids": [
|
| 22 |
+
[
|
| 23 |
+
760,
|
| 24 |
+
6511,
|
| 25 |
+
314,
|
| 26 |
+
9338,
|
| 27 |
+
369
|
| 28 |
+
],
|
| 29 |
+
[
|
| 30 |
+
727,
|
| 31 |
+
73111,
|
| 32 |
+
1393,
|
| 33 |
+
1590,
|
| 34 |
+
198,
|
| 35 |
+
257
|
| 36 |
+
],
|
| 37 |
+
[
|
| 38 |
+
212396,
|
| 39 |
+
168314,
|
| 40 |
+
170312,
|
| 41 |
+
1892
|
| 42 |
+
]
|
| 43 |
+
],
|
| 44 |
+
"rows": [
|
| 45 |
+
{
|
| 46 |
+
"T": 5,
|
| 47 |
+
"identical": true,
|
| 48 |
+
"max_abs": 0.0,
|
| 49 |
+
"mean_abs": 0.0,
|
| 50 |
+
"max_kl": 0.0,
|
| 51 |
+
"top1_agree": 5
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"T": 6,
|
| 55 |
+
"identical": true,
|
| 56 |
+
"max_abs": 0.0,
|
| 57 |
+
"mean_abs": 0.0,
|
| 58 |
+
"max_kl": 0.0,
|
| 59 |
+
"top1_agree": 6
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"T": 4,
|
| 63 |
+
"identical": true,
|
| 64 |
+
"max_abs": 0.0,
|
| 65 |
+
"mean_abs": 0.0,
|
| 66 |
+
"max_kl": 0.0,
|
| 67 |
+
"top1_agree": 4
|
| 68 |
+
}
|
| 69 |
+
],
|
| 70 |
+
"a_info": {
|
| 71 |
+
"cached": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded/gate_logits_fp32blocks_L64.npz"
|
| 72 |
+
},
|
| 73 |
+
"b_info": {
|
| 74 |
+
"loaded": 1714,
|
| 75 |
+
"skipped": 0,
|
| 76 |
+
"unexpected": [],
|
| 77 |
+
"missing_buffers": [],
|
| 78 |
+
"seconds": 2016
|
| 79 |
+
},
|
| 80 |
+
"torch": "2.13.0+cu130"
|
| 81 |
+
}
|
sft_final/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
|
sft_final/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
|
sft_final/gate_mini.json
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"verdict": "PASS",
|
| 3 |
+
"expected": "exact",
|
| 4 |
+
"mini": true,
|
| 5 |
+
"compute": "fp32blocks",
|
| 6 |
+
"a": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded",
|
| 7 |
+
"b": "/mnt/nfs_share/JiRackDeltaNet_70b/expanded",
|
| 8 |
+
"layers_run": [
|
| 9 |
+
4,
|
| 10 |
+
8
|
| 11 |
+
],
|
| 12 |
+
"intermediate": [
|
| 13 |
+
26624,
|
| 14 |
+
26624
|
| 15 |
+
],
|
| 16 |
+
"prompts": [
|
| 17 |
+
"The capital of France is",
|
| 18 |
+
"def fibonacci(n):\n ",
|
| 19 |
+
"Столица России —"
|
| 20 |
+
],
|
| 21 |
+
"ids": [
|
| 22 |
+
[
|
| 23 |
+
760,
|
| 24 |
+
6511,
|
| 25 |
+
314,
|
| 26 |
+
9338,
|
| 27 |
+
369
|
| 28 |
+
],
|
| 29 |
+
[
|
| 30 |
+
727,
|
| 31 |
+
73111,
|
| 32 |
+
1393,
|
| 33 |
+
1590,
|
| 34 |
+
198,
|
| 35 |
+
257
|
| 36 |
+
],
|
| 37 |
+
[
|
| 38 |
+
212396,
|
| 39 |
+
168314,
|
| 40 |
+
170312,
|
| 41 |
+
1892
|
| 42 |
+
]
|
| 43 |
+
],
|
| 44 |
+
"rows": [
|
| 45 |
+
{
|
| 46 |
+
"T": 5,
|
| 47 |
+
"identical": true,
|
| 48 |
+
"max_abs": 0.0,
|
| 49 |
+
"mean_abs": 0.0,
|
| 50 |
+
"max_kl": 0.0,
|
| 51 |
+
"top1_agree": 5
|
| 52 |
+
},
|
| 53 |
+
{
|
| 54 |
+
"T": 6,
|
| 55 |
+
"identical": true,
|
| 56 |
+
"max_abs": 0.0,
|
| 57 |
+
"mean_abs": 0.0,
|
| 58 |
+
"max_kl": 0.0,
|
| 59 |
+
"top1_agree": 6
|
| 60 |
+
},
|
| 61 |
+
{
|
| 62 |
+
"T": 4,
|
| 63 |
+
"identical": true,
|
| 64 |
+
"max_abs": 0.0,
|
| 65 |
+
"mean_abs": 0.0,
|
| 66 |
+
"max_kl": 0.0,
|
| 67 |
+
"top1_agree": 4
|
| 68 |
+
}
|
| 69 |
+
],
|
| 70 |
+
"a_info": {
|
| 71 |
+
"cached": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded/gate_logits_fp32blocks_L4.npz"
|
| 72 |
+
},
|
| 73 |
+
"b_info": {
|
| 74 |
+
"loaded": 124,
|
| 75 |
+
"skipped": 1590,
|
| 76 |
+
"unexpected": [],
|
| 77 |
+
"missing_buffers": [],
|
| 78 |
+
"seconds": 138
|
| 79 |
+
},
|
| 80 |
+
"torch": "2.13.0+cu130"
|
| 81 |
+
}
|
sft_final/gguf.txt
ADDED
|
@@ -0,0 +1,35 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# 1. Конвертация в bf16 (как договорились)
|
| 2 |
+
python convert_hf_to_gguf.py /mnt/nfs_share/Qwen3_8 \
|
| 3 |
+
--outfile /mnt/nfs_share/Qwen3_8/JiRackDeltaNet_27b.gguf --outtype bf16
|
| 4 |
+
|
| 5 |
+
# 2. Сборка llama-quantize (один раз)
|
| 6 |
+
cd /mnt/nfs_share/llama.cpp
|
| 7 |
+
cmake -B build
|
| 8 |
+
cmake --build build -j
|
| 9 |
+
|
| 10 |
+
# 3. Квантование в Q4_K_M
|
| 11 |
+
./build/bin/llama-quantize \
|
| 12 |
+
/mnt/nfs_share/Qwen3_8/JiRackDeltaNet_27b.gguf \
|
| 13 |
+
/mnt/nfs_share/Qwen3_8/JiRackDeltaNet_27b.Q4_K_M.gguf \
|
| 14 |
+
Q4_K_M
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
cd /mnt/nfs_share/llama.cpp
|
| 19 |
+
cmake -B build -DGGML_CUDA=ON # для NVIDIA
|
| 20 |
+
make -C build
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
/mnt/nfs_share/llama.cpp/build/bin/llama-cli \
|
| 24 |
+
-m /mnt/nfs_share/Qwen3_8/JiRackDeltaNet_27b.Q4_K_M.gguf \
|
| 25 |
+
-n 512 \
|
| 26 |
+
-c 4096 \
|
| 27 |
+
-p "Explain quantum computing in simple terms:"
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
/mnt/nfs_share/llama.cpp/build/bin/llama-server \
|
| 34 |
+
-m /mnt/nfs_share/Qwen3_8/JiRackDeltaNet_27b.Q4_K_M.gguf \
|
| 35 |
+
--port 8000
|
sft_final/jirack_sft_state.json
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"global_step": 374,
|
| 3 |
+
"lr": 1e-05,
|
| 4 |
+
"max_steps": 374,
|
| 5 |
+
"shards": "0",
|
| 6 |
+
"tok_micro": 8192,
|
| 7 |
+
"accum": 2,
|
| 8 |
+
"init_dir": "/home/ubuntu/deltanet70b"
|
| 9 |
+
}
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/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
|
sft_final/model.safetensors.index.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
sft_final/system_prompt.txt
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
You are JiRack, an assistant that answers immediately and to the point.
|
| 2 |
+
Never use a reasoning block wrapped in think tags.
|
| 3 |
+
Do not show internal reasoning, drafts, or step-by-step thought process.
|
| 4 |
+
Give the final, ready answer right away, with no preliminary explanation of your reasoning.
|
| 5 |
+
If you feel the need to think through the question, do it silently, internally,
|
| 6 |
+
and output only the final answer to the user.
|
sft_final/tokenizer.json
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:7befaf450030f2fc58d7ea6b3941216ec6cccd85115bf7c2bd5d127f2632cff1
|
| 3 |
+
size 20010936
|
sft_final/tokenizer_config.json
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"add_prefix_space": false,
|
| 3 |
+
"audio_bos_token": "<|audio_start|>",
|
| 4 |
+
"audio_eos_token": "<|audio_end|>",
|
| 5 |
+
"audio_token": "<|audio_pad|>",
|
| 6 |
+
"backend": "tokenizers",
|
| 7 |
+
"bos_token": null,
|
| 8 |
+
"clean_up_tokenization_spaces": false,
|
| 9 |
+
"eos_token": "<|im_end|>",
|
| 10 |
+
"errors": "replace",
|
| 11 |
+
"extra_special_tokens": [
|
| 12 |
+
"<|image|>",
|
| 13 |
+
"<|video|>",
|
| 14 |
+
"<|sound|>",
|
| 15 |
+
"<|voice|>",
|
| 16 |
+
"<|listening|>",
|
| 17 |
+
"<|vision|>",
|
| 18 |
+
"<|mood_happy|>",
|
| 19 |
+
"<|mood_sad|>",
|
| 20 |
+
"<|mood_angry|>",
|
| 21 |
+
"<|mood_neutral|>",
|
| 22 |
+
"<fim_prefix>",
|
| 23 |
+
"<fim_middle>",
|
| 24 |
+
"<fim_suffix>",
|
| 25 |
+
"<|action_start|>",
|
| 26 |
+
"<|action_end|>",
|
| 27 |
+
"<|trajectory_start|>",
|
| 28 |
+
"<|trajectory_end|>",
|
| 29 |
+
"<|joint_start|>",
|
| 30 |
+
"<|joint_end|>",
|
| 31 |
+
"<|sensor_start|>",
|
| 32 |
+
"<|sensor_end|>",
|
| 33 |
+
"<|command_start|>",
|
| 34 |
+
"<|command_end|>",
|
| 35 |
+
"<|state_start|>",
|
| 36 |
+
"<|state_end|>",
|
| 37 |
+
"<|pose|>",
|
| 38 |
+
"<|velocity|>",
|
| 39 |
+
"<|force|>",
|
| 40 |
+
"<|torque|>",
|
| 41 |
+
"<|gripper|>",
|
| 42 |
+
"<|navigation|>",
|
| 43 |
+
"<|obstacle|>",
|
| 44 |
+
"<|task_start|>",
|
| 45 |
+
"<|task_end|>",
|
| 46 |
+
"<|plan_start|>",
|
| 47 |
+
"<|plan_end|>",
|
| 48 |
+
"<|behavior_start|>",
|
| 49 |
+
"<|behavior_end|>",
|
| 50 |
+
"<|skill_start|>",
|
| 51 |
+
"<|skill_end|>",
|
| 52 |
+
"<|motor|>",
|
| 53 |
+
"<|servo|>",
|
| 54 |
+
"<|imu|>",
|
| 55 |
+
"<|lidar|>",
|
| 56 |
+
"<|camera|>",
|
| 57 |
+
"<|depth|>",
|
| 58 |
+
"<|waypoint|>",
|
| 59 |
+
"<|path|>",
|
| 60 |
+
"<|collision|>",
|
| 61 |
+
"<|grasp|>",
|
| 62 |
+
"<|release|>",
|
| 63 |
+
"<|homing|>",
|
| 64 |
+
"<|emergency_stop|>",
|
| 65 |
+
"<|calibration|>",
|
| 66 |
+
"<|manipulation|>",
|
| 67 |
+
"<|locomotion|>",
|
| 68 |
+
"<|feedback|>",
|
| 69 |
+
"<|control_loop|>",
|
| 70 |
+
"<|language|>",
|
| 71 |
+
"<|tool_call_start|>",
|
| 72 |
+
"<|tool_call_end|>",
|
| 73 |
+
"<|tool_result_start|>",
|
| 74 |
+
"<|tool_result_end|>",
|
| 75 |
+
"__SCIENCE__",
|
| 76 |
+
"__CODING__",
|
| 77 |
+
"__STOCK_EXCHANGE__",
|
| 78 |
+
"__MEDICINE__",
|
| 79 |
+
"__GOVERNMENT__",
|
| 80 |
+
"__NEWS__",
|
| 81 |
+
"__GENERAL__",
|
| 82 |
+
"__MATERIAL_SCIENCE__",
|
| 83 |
+
"__ELECTRONICS__",
|
| 84 |
+
"__MICROELECTRONICS__",
|
| 85 |
+
"__ENGINEERING__",
|
| 86 |
+
"__ROBOTICS__",
|
| 87 |
+
"__ENERGY__",
|
| 88 |
+
"__AUTOMOTIVE__",
|
| 89 |
+
"__AVIATION__",
|
| 90 |
+
"__MATH__",
|
| 91 |
+
"__PYTHON__",
|
| 92 |
+
"__C__",
|
| 93 |
+
"__CPP__",
|
| 94 |
+
"__C_SHARP__",
|
| 95 |
+
"__JAVA__",
|
| 96 |
+
"__JAVASCRIPT__",
|
| 97 |
+
"__TYPESCRIPT__",
|
| 98 |
+
"__RUST__",
|
| 99 |
+
"__GO__",
|
| 100 |
+
"__RUBY__",
|
| 101 |
+
"__PHP__",
|
| 102 |
+
"__SWIFT__",
|
| 103 |
+
"__KOTLIN__",
|
| 104 |
+
"__BASH__",
|
| 105 |
+
"__SQL__",
|
| 106 |
+
"__ASSEMBLY__",
|
| 107 |
+
"__PHILOSOPHY__",
|
| 108 |
+
"__LITERATURE__",
|
| 109 |
+
"__SOCIOLOGY__",
|
| 110 |
+
"__PSYCHOLOGY__",
|
| 111 |
+
"__POLITICAL_SCIENCE__",
|
| 112 |
+
"__CULTURAL_STUDIES__",
|
| 113 |
+
"__ETHNOGRAPHY__",
|
| 114 |
+
"__HUMAN_RIGHTS__",
|
| 115 |
+
"__COMPLIANCE__",
|
| 116 |
+
"__MILITARY__",
|
| 117 |
+
"__BANKING__",
|
| 118 |
+
"__OIL_INDUSTRY__",
|
| 119 |
+
"__LIGHT_INDUSTRY__",
|
| 120 |
+
"__NATURE__",
|
| 121 |
+
"__OCEAN__",
|
| 122 |
+
"__SPORT__",
|
| 123 |
+
"__CULINARY__",
|
| 124 |
+
"__TRAVEL__",
|
| 125 |
+
"__HOBBY__"
|
| 126 |
+
],
|
| 127 |
+
"image_token": "<|image_pad|>",
|
| 128 |
+
"is_local": false,
|
| 129 |
+
"local_files_only": false,
|
| 130 |
+
"model_max_length": 262144,
|
| 131 |
+
"model_specific_special_tokens": {
|
| 132 |
+
"audio_bos_token": "<|audio_start|>",
|
| 133 |
+
"audio_eos_token": "<|audio_end|>",
|
| 134 |
+
"audio_token": "<|audio_pad|>",
|
| 135 |
+
"image_token": "<|image_pad|>",
|
| 136 |
+
"video_token": "<|video_pad|>",
|
| 137 |
+
"vision_bos_token": "<|vision_start|>",
|
| 138 |
+
"vision_eos_token": "<|vision_end|>"
|
| 139 |
+
},
|
| 140 |
+
"pad_token": "<|endoftext|>",
|
| 141 |
+
"pretokenize_regex": "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?[\\p{L}\\p{M}]+|\\p{N}| ?[^\\s\\p{L}\\p{M}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+",
|
| 142 |
+
"split_special_tokens": false,
|
| 143 |
+
"tokenizer_class": "Qwen2Tokenizer",
|
| 144 |
+
"unk_token": null,
|
| 145 |
+
"video_token": "<|video_pad|>",
|
| 146 |
+
"vision_bos_token": "<|vision_start|>",
|
| 147 |
+
"vision_eos_token": "<|vision_end|>"
|
| 148 |
+
}
|
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,766 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
JiRackDeltaNet_27b.py
|
| 3 |
+
=============================
|
| 4 |
+
|
| 5 |
+
Собственная (hand-rolled) архитектура "JiRack Qwen3.8-27B" -- в стиле
|
| 6 |
+
прежнего DS32B-проекта: один файл, свой TransformerBlock, никакого
|
| 7 |
+
AutoConfig/AutoModelForCausalLM внутри класса архитектуры, никакого
|
| 8 |
+
model_id в конструкторе. Все размерности зашиты константами ниже --
|
| 9 |
+
подтверждены живым инспектом реального checkpoint'а (inspect_qwen38_keys.py,
|
| 10 |
+
851 тензор, сверено).
|
| 11 |
+
|
| 12 |
+
Математика DeltaNet-рекуррентности, свёртки, гейтинга и partial-rotary
|
| 13 |
+
mRoPE-attention ПОРТИРОВАНА из реального modeling_qwen3_5.py (Apache 2.0,
|
| 14 |
+
HuggingFace/Qwen), а не переизобретена -- чтобы не рисковать тихой
|
| 15 |
+
числовой ошибкой в тонкой рекуррентной формуле. Портирован смысл, но
|
| 16 |
+
код переписан под наши имена/стиль и урезан: без vision-башни, без
|
| 17 |
+
KV-cache классов transformers (для тренировки полный форвард по
|
| 18 |
+
последовательности не нужен; для генерации -- полный recompute на
|
| 19 |
+
каждом шаге, без инкрементального кэша; это сознательное упрощение,
|
| 20 |
+
при желании кэш можно добавить отдельно).
|
| 21 |
+
|
| 22 |
+
Имена подмодулей (`linear_attn` / `self_attn`, `in_proj_qkv`, `out_proj`,
|
| 23 |
+
`mlp.gate_proj` и т.д.) намеренно СОВПАДАЮТ с именами в реальном
|
| 24 |
+
state_dict Qwen3_5ForCausalLM -- поэтому веса из HF-чекпоинта грузятся
|
| 25 |
+
напрямую через load_state_dict(), без ручного key-mapping.
|
| 26 |
+
|
| 27 |
+
Файл умеет:
|
| 28 |
+
- собрать модель (JiRackQwen38ForCausalLM) с нуля, случайные веса;
|
| 29 |
+
- принять state_dict в формате HF Qwen3_5ForCausalLM (после
|
| 30 |
+
AutoModelForCausalLM.from_pretrained(...).state_dict() в конвертере)
|
| 31 |
+
и загрузить его напрямую;
|
| 32 |
+
- пропатчить нужные nn.Linear -> BitLinear (TERNARIZE_PATTERNS);
|
| 33 |
+
- сохранить/загрузить свой JiRack-чекпоинт (save_checkpoint/load_checkpoint).
|
| 34 |
+
|
| 35 |
+
Конвертер (convert_qwen38_to_jirack.py) по-прежнему знает про model_id
|
| 36 |
+
и HF Hub -- но это знание живёт ТОЛЬКО в конвертере, не в архитектуре.
|
| 37 |
+
"""
|
| 38 |
+
|
| 39 |
+
import os
|
| 40 |
+
import re
|
| 41 |
+
import torch
|
| 42 |
+
import torch.nn as nn
|
| 43 |
+
import torch.nn.functional as F
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
# =====================================================================
|
| 47 |
+
# 1. CONFIRMED АРХИТЕКТУРА -- жёстко зашитые константы (не AutoConfig)
|
| 48 |
+
# =====================================================================
|
| 49 |
+
|
| 50 |
+
HIDDEN_SIZE = 5120
|
| 51 |
+
VOCAB_SIZE = 248320
|
| 52 |
+
INTERMEDIATE_SIZE = 26624
|
| 53 |
+
NUM_LAYERS = 128
|
| 54 |
+
RMS_NORM_EPS = 1e-6
|
| 55 |
+
|
| 56 |
+
# Чередование слоёв: full_attention_interval = 4 ->
|
| 57 |
+
# 3x linear_attention, 1x full_attention, повторяется на все 64 слоя.
|
| 58 |
+
LAYER_TYPES = ["linear_attention"] * 3 + ["full_attention"]
|
| 59 |
+
LAYER_TYPES = (LAYER_TYPES * (NUM_LAYERS // len(LAYER_TYPES) + 1))[:NUM_LAYERS]
|
| 60 |
+
|
| 61 |
+
# --- Gated DeltaNet (linear_attention) ---
|
| 62 |
+
LINEAR_NUM_KEY_HEADS = 16
|
| 63 |
+
LINEAR_KEY_HEAD_DIM = 128
|
| 64 |
+
LINEAR_NUM_VALUE_HEADS = 48
|
| 65 |
+
LINEAR_VALUE_HEAD_DIM = 128
|
| 66 |
+
LINEAR_CONV_KERNEL_DIM = 4
|
| 67 |
+
DELTA_KEY_DIM = LINEAR_NUM_KEY_HEADS * LINEAR_KEY_HEAD_DIM # 2048
|
| 68 |
+
DELTA_VALUE_DIM = LINEAR_NUM_VALUE_HEADS * LINEAR_VALUE_HEAD_DIM # 6144
|
| 69 |
+
DELTA_CONV_DIM = DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM # 10240
|
| 70 |
+
DELTA_CHUNK_SIZE = 64
|
| 71 |
+
|
| 72 |
+
# --- Gated Attention (full_attention) ---
|
| 73 |
+
NUM_ATTENTION_HEADS = 24
|
| 74 |
+
NUM_KEY_VALUE_HEADS = 4
|
| 75 |
+
HEAD_DIM = 256
|
| 76 |
+
PARTIAL_ROTARY_FACTOR = 0.25
|
| 77 |
+
ROPE_THETA = 1e7
|
| 78 |
+
MROPE_SECTION = [11, 11, 10]
|
| 79 |
+
ATTENTION_BIAS = False
|
| 80 |
+
|
| 81 |
+
ARCH_SUMMARY = f"""
|
| 82 |
+
Qwen3.8-27B (qwen3_5), hand-rolled JiRack TransformerBlock, text-only.
|
| 83 |
+
hidden_size={HIDDEN_SIZE}, vocab_size={VOCAB_SIZE},
|
| 84 |
+
intermediate_size={INTERMEDIATE_SIZE}, num_hidden_layers={NUM_LAYERS}
|
| 85 |
+
Чередование (interval=4): 3x linear_attention (DeltaNet), 1x full_attention
|
| 86 |
+
"""
|
| 87 |
+
|
| 88 |
+
KEPT_FULL_PRECISION = """
|
| 89 |
+
Всегда остаются full precision (не GEMM, либо слишком чувствительны):
|
| 90 |
+
- dt_bias, A_log (сырые Parameters, decay DeltaNet)
|
| 91 |
+
- linear_attn.in_proj_b/in_proj_a (по умолчанию, см. GATE_PROJ_PATTERNS)
|
| 92 |
+
- conv1d (depthwise grouped conv, не GEMM)
|
| 93 |
+
- все нормы: RMSNormGated, q_norm/k_norm, model.norm
|
| 94 |
+
- embed_tokens, lm_head
|
| 95 |
+
- mtp.* (вся MTP/NextN-голова) (draft-слой спекулятивного декода;
|
| 96 |
+
тернаризация убивает acceptance rate,
|
| 97 |
+
комьюнити-GGUF держат её в Q8_0)
|
| 98 |
+
"""
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# =====================================================================
|
| 102 |
+
# 2. BitLinear -- наш тернарный слой
|
| 103 |
+
# =====================================================================
|
| 104 |
+
|
| 105 |
+
class BitLinear(nn.Linear):
|
| 106 |
+
"""b1.58-style per-tensor absmean ternary weights, per-token int8
|
| 107 |
+
activations, непрерывный lambda-warmup (STE)."""
|
| 108 |
+
|
| 109 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 110 |
+
super().__init__(in_features, out_features, bias=bias)
|
| 111 |
+
self.eps = 1e-5
|
| 112 |
+
self.register_buffer("lambda_", torch.zeros(()), persistent=True)
|
| 113 |
+
|
| 114 |
+
@classmethod
|
| 115 |
+
def from_linear(cls, lin: nn.Linear) -> "BitLinear":
|
| 116 |
+
bl = cls(lin.in_features, lin.out_features, bias=lin.bias is not None)
|
| 117 |
+
bl = bl.to(dtype=lin.weight.dtype, device=lin.weight.device)
|
| 118 |
+
with torch.no_grad():
|
| 119 |
+
bl.weight.copy_(lin.weight)
|
| 120 |
+
if lin.bias is not None:
|
| 121 |
+
bl.bias.copy_(lin.bias)
|
| 122 |
+
return bl
|
| 123 |
+
|
| 124 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 125 |
+
if not self.training and float(self.lambda_) < 1e-6:
|
| 126 |
+
return F.linear(x, self.weight, self.bias)
|
| 127 |
+
|
| 128 |
+
lam = self.lambda_.to(x.dtype)
|
| 129 |
+
w = self.weight
|
| 130 |
+
gamma = w.float().abs().mean().clamp(min=self.eps).to(w.dtype)
|
| 131 |
+
w_quant = torch.clamp(torch.round(w / gamma), -1.0, 1.0) * gamma
|
| 132 |
+
w_effective = w + lam * (w_quant - w).detach()
|
| 133 |
+
|
| 134 |
+
x_scale = 127.0 / x.abs().max(dim=-1, keepdim=True).values.clamp(min=self.eps)
|
| 135 |
+
x_quant = torch.clamp(torch.round(x * x_scale), -128.0, 127.0) / x_scale
|
| 136 |
+
x_effective = x + lam * (x_quant - x).detach()
|
| 137 |
+
|
| 138 |
+
return F.linear(x_effective, w_effective, self.bias)
|
| 139 |
+
|
| 140 |
+
def set_lambda(self, v: float):
|
| 141 |
+
self.lambda_.fill_(v)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
# =====================================================================
|
| 145 |
+
# 3. Карта: что тернаризуем, что оставляем full precision
|
| 146 |
+
# =====================================================================
|
| 147 |
+
|
| 148 |
+
TERNARIZE_PATTERNS = [
|
| 149 |
+
r"linear_attn\.in_proj_qkv$",
|
| 150 |
+
r"linear_attn\.in_proj_z$",
|
| 151 |
+
r"linear_attn\.out_proj$",
|
| 152 |
+
r"self_attn\.q_proj$",
|
| 153 |
+
r"self_attn\.k_proj$",
|
| 154 |
+
r"self_attn\.v_proj$",
|
| 155 |
+
r"self_attn\.o_proj$",
|
| 156 |
+
r"mlp\.gate_proj$",
|
| 157 |
+
r"mlp\.up_proj$",
|
| 158 |
+
r"mlp\.down_proj$",
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
GATE_PROJ_PATTERNS = [
|
| 162 |
+
r"linear_attn\.in_proj_b$",
|
| 163 |
+
r"linear_attn\.in_proj_a$",
|
| 164 |
+
]
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
def apply_bitlinear_patch(model: nn.Module, include_gate_proj: bool = False):
|
| 168 |
+
"""Точечная замена nn.Linear -> BitLinear по TERNARIZE_PATTERNS."""
|
| 169 |
+
patterns = list(TERNARIZE_PATTERNS)
|
| 170 |
+
if include_gate_proj:
|
| 171 |
+
patterns += GATE_PROJ_PATTERNS
|
| 172 |
+
compiled = [re.compile(p) for p in patterns]
|
| 173 |
+
|
| 174 |
+
patched = []
|
| 175 |
+
for name, module in list(model.named_modules()):
|
| 176 |
+
if not isinstance(module, nn.Linear):
|
| 177 |
+
continue
|
| 178 |
+
# MTP/NextN-голова НЕ тернаризуется -- всегда full precision.
|
| 179 |
+
# Суффиксные паттерны (self_attn.q_proj$ и т.п.) иначе зацепили бы
|
| 180 |
+
# mtp.layers.0.self_attn.q_proj.
|
| 181 |
+
if name.startswith("mtp"):
|
| 182 |
+
continue
|
| 183 |
+
if any(p.search(name) for p in compiled):
|
| 184 |
+
parent_name, _, child_name = name.rpartition(".")
|
| 185 |
+
parent = model.get_submodule(parent_name) if parent_name else model
|
| 186 |
+
setattr(parent, child_name, BitLinear.from_linear(module))
|
| 187 |
+
patched.append(name)
|
| 188 |
+
return patched
|
| 189 |
+
|
| 190 |
+
|
| 191 |
+
# =====================================================================
|
| 192 |
+
# 4. Общие блоки (порт математики из реального modeling_qwen3_5.py)
|
| 193 |
+
# =====================================================================
|
| 194 |
+
|
| 195 |
+
class RMSNorm(nn.Module):
|
| 196 |
+
"""(x * w).to(dtype), w хранится как (weight) с offset +1 -- как в
|
| 197 |
+
оригинале Qwen3_5RMSNorm (инициализация нулями, эффективный вес 1+w)."""
|
| 198 |
+
|
| 199 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 200 |
+
super().__init__()
|
| 201 |
+
self.eps = eps
|
| 202 |
+
self.weight = nn.Parameter(torch.zeros(dim))
|
| 203 |
+
|
| 204 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 205 |
+
dtype = x.dtype
|
| 206 |
+
x = x.float()
|
| 207 |
+
x = x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
|
| 208 |
+
x = x * (1.0 + self.weight.float())
|
| 209 |
+
return x.to(dtype)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
class RMSNormGated(nn.Module):
|
| 213 |
+
"""RMSNorm с гейтингом через SiLU(gate), применяется ПЕРЕД гейтингом
|
| 214 |
+
(норма считается по hidden_states, гейт применяется после)."""
|
| 215 |
+
|
| 216 |
+
def __init__(self, dim: int, eps: float = RMS_NORM_EPS):
|
| 217 |
+
super().__init__()
|
| 218 |
+
self.weight = nn.Parameter(torch.ones(dim))
|
| 219 |
+
self.eps = eps
|
| 220 |
+
|
| 221 |
+
def forward(self, x: torch.Tensor, gate: torch.Tensor) -> torch.Tensor:
|
| 222 |
+
dtype = x.dtype
|
| 223 |
+
x = x.float()
|
| 224 |
+
var = x.pow(2).mean(-1, keepdim=True)
|
| 225 |
+
x = x * torch.rsqrt(var + self.eps)
|
| 226 |
+
x = self.weight * x.to(dtype)
|
| 227 |
+
x = x * F.silu(gate.float())
|
| 228 |
+
return x.to(dtype)
|
| 229 |
+
|
| 230 |
+
|
| 231 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 232 |
+
x1 = x[..., : x.shape[-1] // 2]
|
| 233 |
+
x2 = x[..., x.shape[-1] // 2:]
|
| 234 |
+
return torch.cat((-x2, x1), dim=-1)
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
|
| 238 |
+
"""Partial rotary: только первые cos.shape[-1] каналов вращаются,
|
| 239 |
+
остальное (q_pass/k_pass) проходит без изменений."""
|
| 240 |
+
cos = cos.unsqueeze(unsqueeze_dim)
|
| 241 |
+
sin = sin.unsqueeze(unsqueeze_dim)
|
| 242 |
+
rotary_dim = cos.shape[-1]
|
| 243 |
+
q_rot, q_pass = q[..., :rotary_dim], q[..., rotary_dim:]
|
| 244 |
+
k_rot, k_pass = k[..., :rotary_dim], k[..., rotary_dim:]
|
| 245 |
+
q_embed = torch.cat([(q_rot * cos) + (rotate_half(q_rot) * sin), q_pass], dim=-1)
|
| 246 |
+
k_embed = torch.cat([(k_rot * cos) + (rotate_half(k_rot) * sin), k_pass], dim=-1)
|
| 247 |
+
return q_embed, k_embed
|
| 248 |
+
|
| 249 |
+
|
| 250 |
+
class TextRotaryEmbedding(nn.Module):
|
| 251 |
+
"""mRoPE с partial_rotary_factor. Для чистого текста (без vision)
|
| 252 |
+
3 позиционные "оси" (T,H,W) совпадают -> interleaved mRoPE
|
| 253 |
+
вырождается в обычный RoPE, но мы всё равно считаем честно тем же
|
| 254 |
+
путём, что и оригинал, для полной числовой идентичности."""
|
| 255 |
+
|
| 256 |
+
def __init__(self, head_dim=HEAD_DIM, partial_rotary_factor=PARTIAL_ROTARY_FACTOR,
|
| 257 |
+
theta=ROPE_THETA, mrope_section=MROPE_SECTION):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.rotary_dim = int(head_dim * partial_rotary_factor)
|
| 260 |
+
inv_freq = 1.0 / (theta ** (torch.arange(0, self.rotary_dim, 2, dtype=torch.float32) / self.rotary_dim))
|
| 261 |
+
self.register_buffer("inv_freq", inv_freq, persistent=False)
|
| 262 |
+
self.mrope_section = mrope_section
|
| 263 |
+
|
| 264 |
+
def _apply_interleaved_mrope(self, freqs: torch.Tensor) -> torch.Tensor:
|
| 265 |
+
# freqs: (3, bs, seq, rotary_dim // 2)
|
| 266 |
+
freqs_t = freqs[0].clone()
|
| 267 |
+
for dim, offset in enumerate((1, 2), start=1):
|
| 268 |
+
length = self.mrope_section[dim] * 3
|
| 269 |
+
idx = slice(offset, length, 3)
|
| 270 |
+
freqs_t[..., idx] = freqs[dim, ..., idx]
|
| 271 |
+
return freqs_t
|
| 272 |
+
|
| 273 |
+
@torch.no_grad()
|
| 274 |
+
def forward(self, x: torch.Tensor, position_ids: torch.LongTensor):
|
| 275 |
+
# position_ids: (bs, seq) -> реплицируем в 3 идентичные оси (text-only)
|
| 276 |
+
if position_ids.ndim == 2:
|
| 277 |
+
position_ids = position_ids[None, ...].expand(3, position_ids.shape[0], -1)
|
| 278 |
+
inv_freq_exp = self.inv_freq[None, None, :, None].float().expand(3, position_ids.shape[1], -1, 1)
|
| 279 |
+
pos_exp = position_ids[:, :, None, :].float()
|
| 280 |
+
freqs = (inv_freq_exp @ pos_exp).transpose(2, 3) # (3, bs, seq, rotary_dim//2)
|
| 281 |
+
freqs = self._apply_interleaved_mrope(freqs) # (bs, seq, rotary_dim//2)
|
| 282 |
+
emb = torch.cat((freqs, freqs), dim=-1) # (bs, seq, rotary_dim)
|
| 283 |
+
return emb.cos().to(x.dtype), emb.sin().to(x.dtype)
|
| 284 |
+
|
| 285 |
+
|
| 286 |
+
def l2norm(x: torch.Tensor, dim: int = -1, eps: float = 1e-6):
|
| 287 |
+
return x * torch.rsqrt((x * x).sum(dim=dim, keepdim=True) + eps)
|
| 288 |
+
|
| 289 |
+
|
| 290 |
+
def causal_conv1d(hidden_states: torch.Tensor, weight: torch.Tensor, activation: str = "silu"):
|
| 291 |
+
"""hidden_states: (batch, channels, seq_len). Depthwise causal conv,
|
| 292 |
+
left-padded by kernel_size - 1, затем активация."""
|
| 293 |
+
channels, seq_len = hidden_states.shape[1], hidden_states.shape[2]
|
| 294 |
+
padding = weight.shape[-1] - 1
|
| 295 |
+
out = F.conv1d(hidden_states, weight=weight.unsqueeze(1), bias=None, padding=padding, groups=channels)
|
| 296 |
+
out = out[:, :, :seq_len]
|
| 297 |
+
return F.silu(out) if activation == "silu" else out
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def chunked_gated_delta_rule(query, key, value, g, beta, chunk_size=DELTA_CHUNK_SIZE):
|
| 301 |
+
"""Порт torch_chunk_gated_delta_rule из modeling_qwen3_5.py -- без
|
| 302 |
+
initial_state/output_final_state (тренировка/полный форвард без
|
| 303 |
+
инкрементального кэша). query/key/value: (b, h, t, d), g/beta: (b, h, t)."""
|
| 304 |
+
initial_dtype = query.dtype
|
| 305 |
+
query = l2norm(query, dim=-1, eps=1e-6)
|
| 306 |
+
key = l2norm(key, dim=-1, eps=1e-6)
|
| 307 |
+
query, key, value, beta, g = [x.contiguous().to(torch.float32) for x in (query, key, value, beta, g)]
|
| 308 |
+
|
| 309 |
+
b, h, t, k_dim = key.shape
|
| 310 |
+
v_dim = value.shape[-1]
|
| 311 |
+
pad = (chunk_size - t % chunk_size) % chunk_size
|
| 312 |
+
query = F.pad(query, (0, 0, 0, pad))
|
| 313 |
+
key = F.pad(key, (0, 0, 0, pad))
|
| 314 |
+
value = F.pad(value, (0, 0, 0, pad))
|
| 315 |
+
beta = F.pad(beta, (0, pad))
|
| 316 |
+
g = F.pad(g, (0, pad))
|
| 317 |
+
total_t = t + pad
|
| 318 |
+
scale = 1 / (query.shape[-1] ** 0.5)
|
| 319 |
+
query = query * scale
|
| 320 |
+
|
| 321 |
+
v_beta = value * beta.unsqueeze(-1)
|
| 322 |
+
k_beta = key * beta.unsqueeze(-1)
|
| 323 |
+
query, key, value, k_beta, v_beta = [
|
| 324 |
+
x.reshape(x.shape[0], x.shape[1], -1, chunk_size, x.shape[-1]) for x in (query, key, value, k_beta, v_beta)
|
| 325 |
+
]
|
| 326 |
+
g = g.reshape(g.shape[0], g.shape[1], -1, chunk_size)
|
| 327 |
+
mask = torch.triu(torch.ones(chunk_size, chunk_size, dtype=torch.bool, device=query.device), diagonal=0)
|
| 328 |
+
|
| 329 |
+
g = g.cumsum(dim=-1)
|
| 330 |
+
decay_mask = ((g.unsqueeze(-1) - g.unsqueeze(-2)).tril().exp().float()).tril()
|
| 331 |
+
attn = -((k_beta @ key.transpose(-1, -2)) * decay_mask).masked_fill(mask, 0)
|
| 332 |
+
for i in range(1, chunk_size):
|
| 333 |
+
row = attn[..., i, :i].clone()
|
| 334 |
+
sub = attn[..., :i, :i].clone()
|
| 335 |
+
attn[..., i, :i] = row + (row.unsqueeze(-1) * sub).sum(-2)
|
| 336 |
+
attn = attn + torch.eye(chunk_size, dtype=attn.dtype, device=attn.device)
|
| 337 |
+
value = attn @ v_beta
|
| 338 |
+
k_cumdecay = attn @ (k_beta * g.exp().unsqueeze(-1))
|
| 339 |
+
|
| 340 |
+
last_state = torch.zeros(b, h, k_dim, v_dim, dtype=value.dtype, device=value.device)
|
| 341 |
+
core_out = torch.zeros_like(value)
|
| 342 |
+
|
| 343 |
+
for i in range(total_t // chunk_size):
|
| 344 |
+
q_i, k_i, v_i = query[:, :, i], key[:, :, i], value[:, :, i]
|
| 345 |
+
attn_i = q_i @ k_i.transpose(-1, -2) * decay_mask[:, :, i]
|
| 346 |
+
v_prime = k_cumdecay[:, :, i] @ last_state
|
| 347 |
+
v_new = v_i - v_prime
|
| 348 |
+
attn_inter = (q_i * g[:, :, i, :, None].exp()) @ last_state
|
| 349 |
+
core_out[:, :, i] = attn_inter + attn_i @ v_new
|
| 350 |
+
last_state = (
|
| 351 |
+
last_state * g[:, :, i, -1, None, None].exp()
|
| 352 |
+
+ (k_i * (g[:, :, i, -1, None] - g[:, :, i]).exp()[..., None]).transpose(-1, -2) @ v_new
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
core_out = core_out.reshape(core_out.shape[0], core_out.shape[1], -1, core_out.shape[-1])
|
| 356 |
+
core_out = core_out[:, :, :t]
|
| 357 |
+
core_out = core_out.transpose(1, 2).contiguous().to(initial_dtype)
|
| 358 |
+
return core_out
|
| 359 |
+
|
| 360 |
+
|
| 361 |
+
# =====================================================================
|
| 362 |
+
# 5. Наш собственный TransformerBlock (и подмодули linear_attn/self_attn)
|
| 363 |
+
# =====================================================================
|
| 364 |
+
|
| 365 |
+
class GatedDeltaNetBlock(nn.Module):
|
| 366 |
+
"""linear_attention слой (Gated DeltaNet). Имена подмодулей совпадают
|
| 367 |
+
с HF state_dict, чтобы веса грузились напрямую."""
|
| 368 |
+
|
| 369 |
+
def __init__(self):
|
| 370 |
+
super().__init__()
|
| 371 |
+
self.conv1d = nn.Conv1d(
|
| 372 |
+
in_channels=DELTA_CONV_DIM, out_channels=DELTA_CONV_DIM, bias=False,
|
| 373 |
+
kernel_size=LINEAR_CONV_KERNEL_DIM, groups=DELTA_CONV_DIM,
|
| 374 |
+
padding=LINEAR_CONV_KERNEL_DIM - 1,
|
| 375 |
+
)
|
| 376 |
+
self.dt_bias = nn.Parameter(torch.ones(LINEAR_NUM_VALUE_HEADS))
|
| 377 |
+
A = torch.empty(LINEAR_NUM_VALUE_HEADS).uniform_(0.01, 16)
|
| 378 |
+
self.A_log = nn.Parameter(torch.log(A))
|
| 379 |
+
self.norm = RMSNormGated(LINEAR_VALUE_HEAD_DIM, eps=RMS_NORM_EPS)
|
| 380 |
+
self.out_proj = nn.Linear(DELTA_VALUE_DIM, HIDDEN_SIZE, bias=False)
|
| 381 |
+
self.in_proj_qkv = nn.Linear(HIDDEN_SIZE, DELTA_KEY_DIM * 2 + DELTA_VALUE_DIM, bias=False)
|
| 382 |
+
self.in_proj_z = nn.Linear(HIDDEN_SIZE, DELTA_VALUE_DIM, bias=False)
|
| 383 |
+
self.in_proj_b = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 384 |
+
self.in_proj_a = nn.Linear(HIDDEN_SIZE, LINEAR_NUM_VALUE_HEADS, bias=False)
|
| 385 |
+
|
| 386 |
+
def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
|
| 387 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 388 |
+
|
| 389 |
+
mixed_qkv = self.in_proj_qkv(hidden_states).transpose(1, 2) # (b, conv_dim, t)
|
| 390 |
+
z = self.in_proj_z(hidden_states).reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 391 |
+
b = self.in_proj_b(hidden_states)
|
| 392 |
+
a = self.in_proj_a(hidden_states)
|
| 393 |
+
|
| 394 |
+
mixed_qkv = causal_conv1d(mixed_qkv, self.conv1d.weight.squeeze(1), activation="silu")
|
| 395 |
+
mixed_qkv = mixed_qkv.transpose(1, 2) # (b, t, conv_dim)
|
| 396 |
+
|
| 397 |
+
query, key, value = torch.split(mixed_qkv, [DELTA_KEY_DIM, DELTA_KEY_DIM, DELTA_VALUE_DIM], dim=-1)
|
| 398 |
+
query = query.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 399 |
+
key = key.reshape(bsz, seq_len, -1, LINEAR_KEY_HEAD_DIM)
|
| 400 |
+
value = value.reshape(bsz, seq_len, -1, LINEAR_VALUE_HEAD_DIM)
|
| 401 |
+
|
| 402 |
+
beta = b.sigmoid()
|
| 403 |
+
g = -self.A_log.float().exp() * F.softplus(a.float() + self.dt_bias)
|
| 404 |
+
|
| 405 |
+
rep = LINEAR_NUM_VALUE_HEADS // LINEAR_NUM_KEY_HEADS
|
| 406 |
+
if rep > 1:
|
| 407 |
+
query = query.repeat_interleave(rep, dim=2)
|
| 408 |
+
key = key.repeat_interleave(rep, dim=2)
|
| 409 |
+
|
| 410 |
+
# -> (b, h, t, d) for the chunked kernel
|
| 411 |
+
query_h = query.transpose(1, 2)
|
| 412 |
+
key_h = key.transpose(1, 2)
|
| 413 |
+
value_h = value.transpose(1, 2)
|
| 414 |
+
beta_h = beta.transpose(1, 2)
|
| 415 |
+
g_h = g.transpose(1, 2)
|
| 416 |
+
|
| 417 |
+
core_attn_out = chunked_gated_delta_rule(query_h, key_h, value_h, g_h, beta_h)
|
| 418 |
+
|
| 419 |
+
core_attn_out = core_attn_out.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 420 |
+
z_flat = z.reshape(-1, LINEAR_VALUE_HEAD_DIM)
|
| 421 |
+
core_attn_out = self.norm(core_attn_out, z_flat)
|
| 422 |
+
core_attn_out = core_attn_out.reshape(bsz, seq_len, -1)
|
| 423 |
+
|
| 424 |
+
return self.out_proj(core_attn_out)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
class AttentionBlock(nn.Module):
|
| 428 |
+
"""full_attention слой (Gated Attention + partial rotary mRoPE)."""
|
| 429 |
+
|
| 430 |
+
def __init__(self):
|
| 431 |
+
super().__init__()
|
| 432 |
+
self.num_key_value_groups = NUM_ATTENTION_HEADS // NUM_KEY_VALUE_HEADS
|
| 433 |
+
self.scaling = HEAD_DIM ** -0.5
|
| 434 |
+
self.q_proj = nn.Linear(HIDDEN_SIZE, NUM_ATTENTION_HEADS * HEAD_DIM * 2, bias=ATTENTION_BIAS)
|
| 435 |
+
self.k_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 436 |
+
self.v_proj = nn.Linear(HIDDEN_SIZE, NUM_KEY_VALUE_HEADS * HEAD_DIM, bias=ATTENTION_BIAS)
|
| 437 |
+
self.o_proj = nn.Linear(NUM_ATTENTION_HEADS * HEAD_DIM, HIDDEN_SIZE, bias=ATTENTION_BIAS)
|
| 438 |
+
self.q_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 439 |
+
self.k_norm = RMSNorm(HEAD_DIM, eps=RMS_NORM_EPS)
|
| 440 |
+
|
| 441 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 442 |
+
bsz, seq_len, _ = hidden_states.shape
|
| 443 |
+
hidden_shape = (bsz, seq_len, -1, HEAD_DIM)
|
| 444 |
+
|
| 445 |
+
query_states, gate = torch.chunk(
|
| 446 |
+
self.q_proj(hidden_states).view(bsz, seq_len, -1, HEAD_DIM * 2), 2, dim=-1
|
| 447 |
+
)
|
| 448 |
+
gate = gate.reshape(bsz, seq_len, -1)
|
| 449 |
+
|
| 450 |
+
query_states = self.q_norm(query_states.view(hidden_shape)).transpose(1, 2)
|
| 451 |
+
key_states = self.k_norm(self.k_proj(hidden_states).view(hidden_shape)).transpose(1, 2)
|
| 452 |
+
value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
|
| 453 |
+
|
| 454 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
|
| 455 |
+
|
| 456 |
+
rep = self.num_key_value_groups
|
| 457 |
+
key_states = key_states.repeat_interleave(rep, dim=1)
|
| 458 |
+
value_states = value_states.repeat_interleave(rep, dim=1)
|
| 459 |
+
|
| 460 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) * self.scaling
|
| 461 |
+
attn_weights = attn_weights + causal_mask
|
| 462 |
+
attn_weights = F.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
| 463 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
| 464 |
+
attn_output = attn_output.transpose(1, 2).contiguous().reshape(bsz, seq_len, -1)
|
| 465 |
+
attn_output = attn_output * torch.sigmoid(gate)
|
| 466 |
+
|
| 467 |
+
return self.o_proj(attn_output)
|
| 468 |
+
|
| 469 |
+
|
| 470 |
+
class MLPBlock(nn.Module):
|
| 471 |
+
def __init__(self):
|
| 472 |
+
super().__init__()
|
| 473 |
+
self.gate_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 474 |
+
self.up_proj = nn.Linear(HIDDEN_SIZE, INTERMEDIATE_SIZE, bias=False)
|
| 475 |
+
self.down_proj = nn.Linear(INTERMEDIATE_SIZE, HIDDEN_SIZE, bias=False)
|
| 476 |
+
|
| 477 |
+
def forward(self, x):
|
| 478 |
+
return self.down_proj(F.silu(self.gate_proj(x)) * self.up_proj(x))
|
| 479 |
+
|
| 480 |
+
|
| 481 |
+
class TransformerBlock(nn.Module):
|
| 482 |
+
"""Наш decoder layer -- linear_attn ИЛИ self_attn, в зависимости от
|
| 483 |
+
layer_type, + общий MLP. Имена атрибутов совпадают с HF state_dict."""
|
| 484 |
+
|
| 485 |
+
def __init__(self, layer_idx: int, layer_type: str = None):
|
| 486 |
+
super().__init__()
|
| 487 |
+
# layer_type задан явно -> используем его (нужно для MTP-слоя,
|
| 488 |
+
# который всегда full_attention и лежит ВНЕ LAYER_TYPES).
|
| 489 |
+
self.block_type = layer_type if layer_type is not None else LAYER_TYPES[layer_idx]
|
| 490 |
+
if self.block_type == "linear_attention":
|
| 491 |
+
self.linear_attn = GatedDeltaNetBlock()
|
| 492 |
+
else:
|
| 493 |
+
self.self_attn = AttentionBlock()
|
| 494 |
+
self.mlp = MLPBlock()
|
| 495 |
+
self.input_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 496 |
+
self.post_attention_layernorm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 497 |
+
|
| 498 |
+
def forward(self, hidden_states, cos, sin, causal_mask):
|
| 499 |
+
residual = hidden_states
|
| 500 |
+
hidden_states = self.input_layernorm(hidden_states)
|
| 501 |
+
if self.block_type == "linear_attention":
|
| 502 |
+
hidden_states = self.linear_attn(hidden_states)
|
| 503 |
+
else:
|
| 504 |
+
hidden_states = self.self_attn(hidden_states, cos, sin, causal_mask)
|
| 505 |
+
hidden_states = residual + hidden_states
|
| 506 |
+
|
| 507 |
+
residual = hidden_states
|
| 508 |
+
hidden_states = self.post_attention_layernorm(hidden_states)
|
| 509 |
+
hidden_states = self.mlp(hidden_states)
|
| 510 |
+
hidden_states = residual + hidden_states
|
| 511 |
+
return hidden_states
|
| 512 |
+
|
| 513 |
+
|
| 514 |
+
# =====================================================================
|
| 515 |
+
# 5b. MTP / NextN-голова (draft-слой спекулятивного декода)
|
| 516 |
+
# =====================================================================
|
| 517 |
+
|
| 518 |
+
class MTPBlock(nn.Module):
|
| 519 |
+
"""Multi-Token Prediction голова -- ровно как в реальном чекпоинте
|
| 520 |
+
Qwen3.5/3.8 (mtp_num_hidden_layers=1, mtp_use_dedicated_embeddings=false).
|
| 521 |
+
|
| 522 |
+
Имена подмодулей СОВПАДАЮТ с ключами HF state_dict (top-level `mtp.`):
|
| 523 |
+
mtp.pre_fc_norm_embedding.weight
|
| 524 |
+
mtp.pre_fc_norm_hidden.weight
|
| 525 |
+
mtp.fc.weight [HIDDEN, 2*HIDDEN]
|
| 526 |
+
mtp.layers.0.* (обычный full_attention decoder)
|
| 527 |
+
mtp.norm.weight (final norm перед общим lm_head)
|
| 528 |
+
|
| 529 |
+
embed_tokens и lm_head ОБЩИЕ со стволом (dedicated embeddings = false),
|
| 530 |
+
здесь их нет. В GGUF это blk.{NUM_LAYERS}.nextn.eh_proj /
|
| 531 |
+
shared_head_norm + тензоры draft-слоя.
|
| 532 |
+
|
| 533 |
+
Механика (DeepSeek-style, порядок как в vLLM Qwen3NextMTP):
|
| 534 |
+
h = fc(cat(pre_fc_norm_embedding(emb_next), pre_fc_norm_hidden(h_prev)))
|
| 535 |
+
h = layers[0](h) # full attention
|
| 536 |
+
logits2 = lm_head(norm(h))
|
| 537 |
+
"""
|
| 538 |
+
|
| 539 |
+
def __init__(self):
|
| 540 |
+
super().__init__()
|
| 541 |
+
self.pre_fc_norm_embedding = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 542 |
+
self.pre_fc_norm_hidden = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 543 |
+
self.fc = nn.Linear(2 * HIDDEN_SIZE, HIDDEN_SIZE, bias=False)
|
| 544 |
+
self.layers = nn.ModuleList([
|
| 545 |
+
TransformerBlock(layer_idx=NUM_LAYERS, layer_type="full_attention"),
|
| 546 |
+
])
|
| 547 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 548 |
+
|
| 549 |
+
def forward(self, inputs_embeds, previous_hidden, cos, sin, causal_mask):
|
| 550 |
+
"""inputs_embeds -- embed_tokens(токены, сдвинутые на +1)
|
| 551 |
+
previous_hidden -- hidden ствола ДО финального model.norm
|
| 552 |
+
(см. контракт: MTP сам применяет pre_fc_norm_hidden)."""
|
| 553 |
+
h = self.fc(torch.cat(
|
| 554 |
+
(self.pre_fc_norm_embedding(inputs_embeds),
|
| 555 |
+
self.pre_fc_norm_hidden(previous_hidden)),
|
| 556 |
+
dim=-1,
|
| 557 |
+
))
|
| 558 |
+
h = self.layers[0](h, cos, sin, causal_mask)
|
| 559 |
+
return self.norm(h)
|
| 560 |
+
|
| 561 |
+
|
| 562 |
+
# =====================================================================
|
| 563 |
+
# 6. Полная модель
|
| 564 |
+
# =====================================================================
|
| 565 |
+
|
| 566 |
+
class JiRackQwen38Model(nn.Module):
|
| 567 |
+
def __init__(self):
|
| 568 |
+
super().__init__()
|
| 569 |
+
self.embed_tokens = nn.Embedding(VOCAB_SIZE, HIDDEN_SIZE)
|
| 570 |
+
self.layers = nn.ModuleList([TransformerBlock(i) for i in range(NUM_LAYERS)])
|
| 571 |
+
self.norm = RMSNorm(HIDDEN_SIZE, eps=RMS_NORM_EPS)
|
| 572 |
+
self.rotary_emb = TextRotaryEmbedding()
|
| 573 |
+
|
| 574 |
+
def forward(self, input_ids: torch.LongTensor, return_prenorm: bool = False):
|
| 575 |
+
bsz, seq_len = input_ids.shape
|
| 576 |
+
hidden_states = self.embed_tokens(input_ids)
|
| 577 |
+
|
| 578 |
+
position_ids = torch.arange(seq_len, device=input_ids.device).unsqueeze(0).expand(bsz, -1)
|
| 579 |
+
cos, sin = self.rotary_emb(hidden_states, position_ids)
|
| 580 |
+
|
| 581 |
+
causal_mask = torch.full((seq_len, seq_len), float("-inf"), device=input_ids.device, dtype=torch.float32)
|
| 582 |
+
causal_mask = torch.triu(causal_mask, diagonal=1)[None, None, :, :].to(hidden_states.dtype)
|
| 583 |
+
|
| 584 |
+
for layer in self.layers:
|
| 585 |
+
hidden_states = layer(hidden_states, cos, sin, causal_mask)
|
| 586 |
+
|
| 587 |
+
if return_prenorm:
|
| 588 |
+
# Для MTP: голова сама применяет pre_fc_norm_hidden, финальный
|
| 589 |
+
# model.norm сюда НЕ входит (иначе двойная нормализация).
|
| 590 |
+
return self.norm(hidden_states), hidden_states, (cos, sin, causal_mask)
|
| 591 |
+
return self.norm(hidden_states)
|
| 592 |
+
|
| 593 |
+
|
| 594 |
+
class JiRackQwen38ForCausalLM(nn.Module):
|
| 595 |
+
"""Верхнеуровневая модель. Имена атрибутов (`model`, `lm_head`)
|
| 596 |
+
совпадают с HF Qwen3_5ForCausalLM -- state_dict грузится напрямую."""
|
| 597 |
+
|
| 598 |
+
def __init__(self):
|
| 599 |
+
super().__init__()
|
| 600 |
+
self.model = JiRackQwen38Model()
|
| 601 |
+
self.lm_head = nn.Linear(HIDDEN_SIZE, VOCAB_SIZE, bias=False)
|
| 602 |
+
# MTP/NextN-голова: top-level атрибут `mtp` -- ключи state_dict
|
| 603 |
+
# получаются ровно mtp.*, как в реальном HF-чекпоинте.
|
| 604 |
+
self.mtp = MTPBlock()
|
| 605 |
+
|
| 606 |
+
def forward(self, input_ids: torch.LongTensor) -> torch.Tensor:
|
| 607 |
+
hidden_states = self.model(input_ids)
|
| 608 |
+
return self.lm_head(hidden_states)
|
| 609 |
+
|
| 610 |
+
def mtp_forward(self, input_ids: torch.LongTensor):
|
| 611 |
+
"""Возвращает (logits_t1, logits_t2): обычные логиты ствола и
|
| 612 |
+
draft-логиты MTP-головы (предсказание токена t+2 из позиции t).
|
| 613 |
+
Для инференса/валидации MTP; в GGUF-конвертации не участвует."""
|
| 614 |
+
_, prenorm_hidden, (cos, sin, causal_mask) = self.model(
|
| 615 |
+
input_ids, return_prenorm=True)
|
| 616 |
+
logits_t1 = self.lm_head(self.model.norm(prenorm_hidden))
|
| 617 |
+
|
| 618 |
+
# Вход MTP -- эмбеддинги токенов, сдвинутых на +1 (следующий токен
|
| 619 |
+
# уже известен на шаге верификации). Последнюю позицию дублируем,
|
| 620 |
+
# чтобы сохранить форму (draft для неё не используется).
|
| 621 |
+
shifted = torch.cat([input_ids[:, 1:], input_ids[:, -1:]], dim=1)
|
| 622 |
+
emb_next = self.model.embed_tokens(shifted)
|
| 623 |
+
h2 = self.mtp(emb_next, prenorm_hidden, cos, sin, causal_mask)
|
| 624 |
+
logits_t2 = self.lm_head(h2)
|
| 625 |
+
return logits_t1, logits_t2
|
| 626 |
+
|
| 627 |
+
# -----------------------------------------------------------------
|
| 628 |
+
# Заг��узка реальных весов (state_dict уже скачан конвертером через
|
| 629 |
+
# HF Hub -- сюда просто передаётся словарь тензоров)
|
| 630 |
+
# -----------------------------------------------------------------
|
| 631 |
+
def load_hf_state_dict(self, state_dict: dict, strict: bool = False):
|
| 632 |
+
"""Грузит state_dict в формате оригинального Qwen3_5ForCausalLM.
|
| 633 |
+
mtp.* ключи теперь ГРУЗЯТСЯ в self.mtp (MTPBlock) -- фильтра
|
| 634 |
+
больше нет. strict=False оставлен из-за служебных lambda_-буферов
|
| 635 |
+
BitLinear, которых нет в реальном чекпоинте."""
|
| 636 |
+
missing, unexpected = self.load_state_dict(state_dict, strict=strict)
|
| 637 |
+
real_missing = [k for k in missing if not k.endswith("lambda_")]
|
| 638 |
+
if real_missing:
|
| 639 |
+
print(f"⚠️ {len(real_missing)} missing keys (первые 10): {real_missing[:10]}")
|
| 640 |
+
if unexpected:
|
| 641 |
+
print(f"⚠️ {len(unexpected)} unexpected keys (первые 10): {unexpected[:10]}")
|
| 642 |
+
return missing, unexpected
|
| 643 |
+
|
| 644 |
+
# -----------------------------------------------------------------
|
| 645 |
+
# Подсадка РЕАЛЬНЫХ mtp.* весов из оригинального HF-чекпоинта.
|
| 646 |
+
# Нужна, потому что старые JiRack .pt сохранены ДО появления MTPBlock
|
| 647 |
+
# и mtp-весов не содержат (там была бы случайная инициализация).
|
| 648 |
+
# -----------------------------------------------------------------
|
| 649 |
+
def load_mtp_from_hf_dir(self, hf_dir: str):
|
| 650 |
+
"""Читает из папки оригинального HF-чекпоинта ТОЛЬКО mtp.* тензоры
|
| 651 |
+
(по index.json или перебором *.safetensors) и грузит их в self.mtp.
|
| 652 |
+
Возвращает число загруженных тензоров."""
|
| 653 |
+
import glob
|
| 654 |
+
import json as _json
|
| 655 |
+
from safetensors import safe_open
|
| 656 |
+
|
| 657 |
+
index_path = os.path.join(hf_dir, "model.safetensors.index.json")
|
| 658 |
+
mtp_map = {} # key -> shard file
|
| 659 |
+
if os.path.exists(index_path):
|
| 660 |
+
with open(index_path) as f:
|
| 661 |
+
weight_map = _json.load(f)["weight_map"]
|
| 662 |
+
for k, shard in weight_map.items():
|
| 663 |
+
if k.startswith("mtp."):
|
| 664 |
+
mtp_map[k] = os.path.join(hf_dir, shard)
|
| 665 |
+
else:
|
| 666 |
+
for shard in glob.glob(os.path.join(hf_dir, "*.safetensors")):
|
| 667 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 668 |
+
for k in f.keys():
|
| 669 |
+
if k.startswith("mtp."):
|
| 670 |
+
mtp_map[k] = shard
|
| 671 |
+
|
| 672 |
+
if not mtp_map:
|
| 673 |
+
raise FileNotFoundError(
|
| 674 |
+
f"В {hf_dir} не найдено ни одного mtp.* тензора. Нужен "
|
| 675 |
+
f"ОРИГИНАЛЬНЫЙ чекпоинт Qwen3.8-27B (не JiRack-экспорт!). "
|
| 676 |
+
f"Если оригинальные шарды удалены -- перекачай с HF Hub "
|
| 677 |
+
f"только шарды с mtp.* по model.safetensors.index.json.")
|
| 678 |
+
|
| 679 |
+
own_dtype = next(self.mtp.parameters()).dtype
|
| 680 |
+
loaded = {}
|
| 681 |
+
by_shard = {}
|
| 682 |
+
for k, shard in mtp_map.items():
|
| 683 |
+
by_shard.setdefault(shard, []).append(k)
|
| 684 |
+
for shard, keys in by_shard.items():
|
| 685 |
+
with safe_open(shard, framework="pt", device="cpu") as f:
|
| 686 |
+
for k in keys:
|
| 687 |
+
loaded[k] = f.get_tensor(k).to(own_dtype)
|
| 688 |
+
|
| 689 |
+
missing, unexpected = self.load_state_dict(loaded, strict=False)
|
| 690 |
+
n_ok = len(loaded)
|
| 691 |
+
print(f"✅ MTP: загружено {n_ok} тензоров из {len(by_shard)} шардов ({hf_dir})")
|
| 692 |
+
if unexpected:
|
| 693 |
+
print(f"⚠️ MTP: unexpected keys: {unexpected[:10]}")
|
| 694 |
+
return n_ok
|
| 695 |
+
|
| 696 |
+
# -----------------------------------------------------------------
|
| 697 |
+
# JiRack-чекпоинт (свой формат, с lambda/patched_linear_names)
|
| 698 |
+
# -----------------------------------------------------------------
|
| 699 |
+
def save_checkpoint(self, path: str, lam: float, global_step: int = 0, patched_linear_names=None):
|
| 700 |
+
torch.save({
|
| 701 |
+
"model": self.state_dict(),
|
| 702 |
+
"lambda": lam,
|
| 703 |
+
"global_step": global_step,
|
| 704 |
+
"patched_linear_names": patched_linear_names or [],
|
| 705 |
+
}, path)
|
| 706 |
+
|
| 707 |
+
@classmethod
|
| 708 |
+
def load_checkpoint(cls, path: str, dtype=torch.bfloat16, include_gate_proj: bool = False):
|
| 709 |
+
ckpt = torch.load(path, map_location="cpu", weights_only=False)
|
| 710 |
+
model = cls()
|
| 711 |
+
patched_names = ckpt.get("patched_linear_names", [])
|
| 712 |
+
if patched_names:
|
| 713 |
+
for name in patched_names:
|
| 714 |
+
*parent_path, leaf = name.split(".")
|
| 715 |
+
parent = model
|
| 716 |
+
for p in parent_path:
|
| 717 |
+
parent = getattr(parent, p)
|
| 718 |
+
old = getattr(parent, leaf)
|
| 719 |
+
if not isinstance(old, BitLinear):
|
| 720 |
+
setattr(parent, leaf, BitLinear.from_linear(old))
|
| 721 |
+
else:
|
| 722 |
+
apply_bitlinear_patch(model, include_gate_proj=include_gate_proj)
|
| 723 |
+
|
| 724 |
+
has_mtp_in_ckpt = any(k.startswith("mtp.") for k in ckpt["model"])
|
| 725 |
+
model.load_state_dict(ckpt["model"], strict=False)
|
| 726 |
+
model = model.to(dtype)
|
| 727 |
+
|
| 728 |
+
if not has_mtp_in_ckpt:
|
| 729 |
+
print(
|
| 730 |
+
"⚠️ В этом .pt НЕТ mtp.* весов (чекпоинт сохранён до "
|
| 731 |
+
"появления MTPBlock). Голова сейчас со СЛУЧАЙНОЙ "
|
| 732 |
+
"инициализацией! Перед экспортом обязательно вызови "
|
| 733 |
+
"model.load_mtp_from_hf_dir('<папка оригинального HF-чекпоинта>')."
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
lam = ckpt.get("lambda", 0.0)
|
| 737 |
+
for m in model.modules():
|
| 738 |
+
if isinstance(m, BitLinear):
|
| 739 |
+
m.set_lambda(lam)
|
| 740 |
+
|
| 741 |
+
print(f"✅ Загружено. global_step={ckpt.get('global_step', 0)}, lambda={lam}")
|
| 742 |
+
return model
|
| 743 |
+
|
| 744 |
+
|
| 745 |
+
# =====================================================================
|
| 746 |
+
# 7. Демонстрация (без скачивания весов -- только структура)
|
| 747 |
+
# =====================================================================
|
| 748 |
+
|
| 749 |
+
if __name__ == "__main__":
|
| 750 |
+
print(ARCH_SUMMARY)
|
| 751 |
+
print(KEPT_FULL_PRECISION)
|
| 752 |
+
|
| 753 |
+
model = JiRackQwen38ForCausalLM()
|
| 754 |
+
n_params = sum(p.numel() for p in model.parameters())
|
| 755 |
+
print(f"✅ Модель собрана (случайные веса). Параметров: {n_params / 1e9:.2f}B")
|
| 756 |
+
|
| 757 |
+
patched = apply_bitlinear_patch(model)
|
| 758 |
+
print(f"✅ Заменено подмодулей на BitLinear: {len(patched)}")
|
| 759 |
+
print("Примеры первых 10:")
|
| 760 |
+
for n in patched[:10]:
|
| 761 |
+
print(f" {n}")
|
| 762 |
+
|
| 763 |
+
ids = torch.randint(0, VOCAB_SIZE, (1, 8))
|
| 764 |
+
with torch.no_grad():
|
| 765 |
+
logits = model(ids)
|
| 766 |
+
print(f"✅ Пробный forward (случайные веса) -> logits shape: {tuple(logits.shape)}")
|
sft_final_fp8/audit_depth.json
ADDED
|
@@ -0,0 +1,14 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"kind": "depth",
|
| 3 |
+
"src": "/mnt/nfs_share/JiRackDeltaNet_36b/expanded",
|
| 4 |
+
"out": "/mnt/nfs_share/JiRackDeltaNet_70b/expanded",
|
| 5 |
+
"tensors": 1714,
|
| 6 |
+
"ops": {
|
| 7 |
+
"copy": 1586,
|
| 8 |
+
"zero": 128
|
| 9 |
+
},
|
| 10 |
+
"errors": [],
|
| 11 |
+
"n_errors": 0,
|
| 12 |
+
"verdict": "PASS",
|
| 13 |
+
"minutes": 9.8
|
| 14 |
+
}
|
sft_final_fp8/chat_fp8.py
ADDED
|
@@ -0,0 +1,75 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# =============================================================================
|
| 3 |
+
# chat_fp8.py - chat_jirack.py for the FP8 block-quantized copy (convert_fp8_block.py).
|
| 4 |
+
# python3 chat_fp8.py --model-dir /home/ubuntu/deltanet70b_sft/final_fp8 --no-think --temperature 0
|
| 5 |
+
# Same commands/options as chat_jirack.py (it is imported from the same folder).
|
| 6 |
+
# The quantized GEMM weights stay FP8 in memory (~72 GB for 70B) and are dequantized
|
| 7 |
+
# per layer call (weight * 128x128 block scale -> bf16), so it runs on any GPU
|
| 8 |
+
# (A100, H100, Blackwell); no FP8 tensor-core kernels are used.
|
| 9 |
+
# =============================================================================
|
| 10 |
+
import argparse
|
| 11 |
+
import json
|
| 12 |
+
import os
|
| 13 |
+
import sys
|
| 14 |
+
|
| 15 |
+
import torch
|
| 16 |
+
import torch.nn as nn
|
| 17 |
+
import torch.nn.functional as F
|
| 18 |
+
|
| 19 |
+
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
| 20 |
+
import chat_jirack as cj # noqa: E402
|
| 21 |
+
|
| 22 |
+
B = 128
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class FP8Linear(nn.Module):
|
| 26 |
+
def __init__(self, in_features, out_features):
|
| 27 |
+
super().__init__()
|
| 28 |
+
assert in_features % B == 0 and out_features % B == 0, (in_features, out_features)
|
| 29 |
+
self.in_features, self.out_features = in_features, out_features
|
| 30 |
+
self.register_buffer("weight", torch.empty(out_features, in_features, dtype=torch.float8_e4m3fn))
|
| 31 |
+
self.register_buffer("weight_scale_inv", torch.empty(out_features // B, in_features // B,
|
| 32 |
+
dtype=torch.float32))
|
| 33 |
+
|
| 34 |
+
def forward(self, x):
|
| 35 |
+
R, C = self.out_features, self.in_features
|
| 36 |
+
w = self.weight.to(x.dtype).view(R // B, B, C // B, B) * self.weight_scale_inv.to(x.dtype)[:, None, :, None]
|
| 37 |
+
return F.linear(x, w.view(R, C))
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def _model_dir():
|
| 41 |
+
p = argparse.ArgumentParser(add_help=False)
|
| 42 |
+
p.add_argument("--model-dir", default="/mnt/nfs_share/JiRackDeltaNet_70b/expanded")
|
| 43 |
+
return p.parse_known_args()[0].model_dir
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def build_fp8(mod):
|
| 47 |
+
d = _model_dir()
|
| 48 |
+
wm = json.load(open(os.path.join(d, "model.safetensors.index.json")))["weight_map"]
|
| 49 |
+
qnames = {k[:-len(".weight_scale_inv")] for k in wm if k.endswith(".weight_scale_inv")}
|
| 50 |
+
if not qnames:
|
| 51 |
+
sys.exit(f"❌ no *.weight_scale_inv in {d} - not an FP8 copy, use chat_jirack.py")
|
| 52 |
+
torch.set_default_dtype(torch.bfloat16)
|
| 53 |
+
try:
|
| 54 |
+
with torch.device("meta"):
|
| 55 |
+
model = mod.JiRackQwen38ForCausalLM()
|
| 56 |
+
for name in qnames:
|
| 57 |
+
parent, _, leaf = name.rpartition(".")
|
| 58 |
+
pm = model.get_submodule(parent)
|
| 59 |
+
old = getattr(pm, leaf)
|
| 60 |
+
setattr(pm, leaf, FP8Linear(old.in_features, old.out_features))
|
| 61 |
+
finally:
|
| 62 |
+
torch.set_default_dtype(torch.float32)
|
| 63 |
+
model.to_empty(device="cpu")
|
| 64 |
+
for m in model.modules(): # non-persistent buffer, not in the checkpoint
|
| 65 |
+
if isinstance(m, mod.TextRotaryEmbedding):
|
| 66 |
+
m.inv_freq = 1.0 / (mod.ROPE_THETA ** (torch.arange(0, m.rotary_dim, 2, dtype=torch.float32)
|
| 67 |
+
/ m.rotary_dim))
|
| 68 |
+
print(f"🧮 FP8: {len(qnames)} linear layers kept in FP8 (block {B}x{B})", flush=True)
|
| 69 |
+
return model.eval()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
cj.build = build_fp8
|
| 73 |
+
|
| 74 |
+
if __name__ == "__main__":
|
| 75 |
+
cj.main()
|