Add SSMoELM-it-5L: layer-shared 5L variant under Scratch 10MiB limit
Browse files- .gitattributes +1 -0
- README.md +192 -0
- __pycache__/inference.cpython-314.pyc +0 -0
- inference.py +489 -0
- model.safetensors +3 -0
- ssmoelm_5l.sb3 +3 -0
- tokenizer.json +0 -0
.gitattributes
CHANGED
|
@@ -33,3 +33,4 @@ 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 |
+
ssmoelm_5l.sb3 filter=lfs diff=lfs merge=lfs -text
|
README.md
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
language: en
|
| 3 |
+
license: apache-2.0
|
| 4 |
+
tags:
|
| 5 |
+
- pytorch
|
| 6 |
+
- moe
|
| 7 |
+
- sparse-moe
|
| 8 |
+
- bitnet
|
| 9 |
+
- 1-bit
|
| 10 |
+
- 3-bit
|
| 11 |
+
- 4-bit
|
| 12 |
+
- layer-sharing
|
| 13 |
+
- scratch
|
| 14 |
+
- turbowarp
|
| 15 |
+
- instruct
|
| 16 |
+
base_model: brulee-1/SSMoELM-it
|
| 17 |
+
---
|
| 18 |
+
|
| 19 |
+
# SSMoELM-it-5L
|
| 20 |
+
|
| 21 |
+
**Scratch Small MoE Language Model โ Instruct, 5-Layer Shared** โ a compressed variant of [SSMoELM-it](https://huggingface.co/brulee-1/SSMoELM-it) that fits under **Scratch's 10 MiB project size limit**.
|
| 22 |
+
|
| 23 |
+
- **40.2M stored / 25.8M active parameters** โ 5 stored layers, 6 compute passes (layer 3 runs twice)
|
| 24 |
+
- **10.2 MB** packed weights (1-bit routed experts, 4-bit attention, **3-bit embedding**)
|
| 25 |
+
- The bundled Scratch project `ssmoelm_5l.sb3` is **10,102,323 bytes < 10,485,760 (10 MiB)** โ uploadable to scratch.mit.edu, where the full 6-layer model (12.3 MB) is rejected
|
| 26 |
+
- Quality recovered via post-surgery SFT (held-out ppl 50.1 vs 41.5 for the 6-layer original)
|
| 27 |
+
|
| 28 |
+
> **Note:** The HuggingFace model card may display ~10M parameters and an "8-bit" quantization badge. Both are artifacts of reading the packed `model.safetensors` directly. The actual model has **40.2M stored parameters** quantized to **1/3/4-bit**.
|
| 29 |
+
|
| 30 |
+
> "Scratch" carries two meanings: built *for Scratch*, trained *from scratch*.
|
| 31 |
+
|
| 32 |
+
---
|
| 33 |
+
|
| 34 |
+
## How it differs from SSMoELM-it
|
| 35 |
+
|
| 36 |
+
| | SSMoELM-it | **SSMoELM-it-5L** |
|
| 37 |
+
|---|---|---|
|
| 38 |
+
| Stored layers | 6 (0โ5) | **5** (0,1,2,3,5 โ layer 4 dropped) |
|
| 39 |
+
| Compute passes | 6 | 6 (**layer 3 runs at depths 3 and 4**, separate KV caches) |
|
| 40 |
+
| Embedding | 4-bit | **3-bit** |
|
| 41 |
+
| Stored params | 47.0M | 40.2M |
|
| 42 |
+
| Active params / pass | 25.8M | 25.8M (unchanged) |
|
| 43 |
+
| Packed size | 12.1 MB | **10.2 MB** |
|
| 44 |
+
| Scratch sb3 | 12.3 MB (over limit) | **9.6 MiB (uploadable)** |
|
| 45 |
+
| Held-out ppl | 41.5 | 50.1 |
|
| 46 |
+
|
| 47 |
+
The stored-layer / pass mapping is recorded in the safetensors `__metadata__`
|
| 48 |
+
(`layer_ids=[0,1,2,3,5]`, `pass_order=[0,1,2,3,3,5]`) and picked up automatically by `inference.py`.
|
| 49 |
+
|
| 50 |
+
### How this variant was made
|
| 51 |
+
|
| 52 |
+
1. **Ablation (no training):** among 8 drop/repeat configurations, *drop layer 4 + repeat layer 3* degraded least (ppl 76.3 with 3-bit embedding).
|
| 53 |
+
2. **Recovery SFT:** same data as SSMoELM-it (Dolly-15k + oasst1 EN), lr 1e-5, ~50k cumulative steps with QAT (1/3/4-bit STE). Quality peaks there โ longer training collapses generation, so the peak checkpoint was selected by generation quality, not loss.
|
| 54 |
+
|
| 55 |
+
---
|
| 56 |
+
|
| 57 |
+
## Model Details
|
| 58 |
+
|
| 59 |
+
| | |
|
| 60 |
+
|---|---|
|
| 61 |
+
| Architecture | Decoder-only Transformer + Sparse MoE FFN, shared-layer |
|
| 62 |
+
| Stored params | 40.24M |
|
| 63 |
+
| Active params | 25.80M (per forward pass) |
|
| 64 |
+
| d_model | 768 |
|
| 65 |
+
| Stored layers / passes | 5 / 6 |
|
| 66 |
+
| Attention | GQA โ 12 heads, kv_heads=3, head_dim=64 |
|
| 67 |
+
| Positional encoding | RoPE |
|
| 68 |
+
| Normalization | RMSNorm |
|
| 69 |
+
| Activation | SwiGLU |
|
| 70 |
+
| MoE | 8 routed experts + 1 shared expert, top-2 routing |
|
| 71 |
+
| d_ff (per expert) | 256 |
|
| 72 |
+
| Vocabulary | 8,192 (BPE, byte-fallback, English-optimized) |
|
| 73 |
+
| Context length | 2,048 tokens |
|
| 74 |
+
| Base model | SSMoELM-it (47M instruct) |
|
| 75 |
+
| Framework | MLX (training) / PyTorch (inference) |
|
| 76 |
+
|
| 77 |
+
## Quantization Scheme
|
| 78 |
+
|
| 79 |
+
Same as [SSMoELM-Base](https://huggingface.co/brulee-1/SSMoELM-Base) except the embedding:
|
| 80 |
+
|
| 81 |
+
| Component | Bits |
|
| 82 |
+
|---|---|
|
| 83 |
+
| Embedding (tied) | **3-bit** (scale = absmax/4, values in [-4,3], nibble-packed) |
|
| 84 |
+
| Attention Q/K | 4-bit |
|
| 85 |
+
| Attention V/O | 4-bit (layers 0, 5) / 1-bit (layers 1โ3) |
|
| 86 |
+
| Shared expert | 4-bit |
|
| 87 |
+
| Routed experts | 1-bit |
|
| 88 |
+
| Router / norms | fp32 |
|
| 89 |
+
|
| 90 |
+
---
|
| 91 |
+
|
| 92 |
+
## Quality
|
| 93 |
+
|
| 94 |
+
Held-out perplexity (FineWeb sample, ctx 256) and greedy chat behavior:
|
| 95 |
+
|
| 96 |
+
| Model | ppl | Greedy chat |
|
| 97 |
+
|---|---|---|
|
| 98 |
+
| SSMoELM-it (6-layer) | 41.5 | normal |
|
| 99 |
+
| 5L surgery, no training | 76.3 | broken |
|
| 100 |
+
| **SSMoELM-it-5L (this repo)** | **50.1** | recovered |
|
| 101 |
+
|
| 102 |
+
Example (greedy, repetition_penalty 1.3):
|
| 103 |
+
|
| 104 |
+
> **You:** Hello! How are you?
|
| 105 |
+
> **Assistant:** I am a language model. I can help with any other questions or concerns that may be helpful in the future.
|
| 106 |
+
|
| 107 |
+
Downstream benchmarks (HellaSwag etc.) were not re-run for this variant; expect scores at or slightly below SSMoELM-it.
|
| 108 |
+
|
| 109 |
+
---
|
| 110 |
+
|
| 111 |
+
## Scratch / TurboWarp
|
| 112 |
+
|
| 113 |
+
`ssmoelm_5l.sb3` is a self-contained Scratch 3 project: all weights are embedded in `project.json` as case-safe base64 lists (k-bit compact encoding for sub-4-bit tensors) and decoded by Scratch blocks at runtime. The whole forward pass โ RMSNorm, RoPE, GQA attention with KV cache, top-2 MoE routing โ is implemented in vanilla Scratch blocks (no extensions), so it runs on both scratch.mit.edu and [TurboWarp](https://turbowarp.org/).
|
| 114 |
+
|
| 115 |
+
This 5-layer variant exists because the project blob limit on scratch.mit.edu is 10 MiB: the 6-layer sb3 (12.3 MB) is rejected, this one uploads successfully.
|
| 116 |
+
|
| 117 |
+
---
|
| 118 |
+
|
| 119 |
+
## Tokenizer
|
| 120 |
+
|
| 121 |
+
Same as SSMoELM-Base/it: BPE, vocab 8,192, byte fallback, ASCII-optimized.
|
| 122 |
+
|
| 123 |
+
### Special Tokens
|
| 124 |
+
|
| 125 |
+
| Token | ID | Role |
|
| 126 |
+
|---|---|---|
|
| 127 |
+
| `<bos>` | 0 | sequence start |
|
| 128 |
+
| `<eos>` | 1 | end of sequence |
|
| 129 |
+
| `<pad>` | 2 | padding |
|
| 130 |
+
| `<\|system\|>` | 3 | system turn |
|
| 131 |
+
| `<\|user\|>` | 4 | user turn |
|
| 132 |
+
| `<\|assistant\|>` | 5 | assistant turn |
|
| 133 |
+
| `<\|eot\|>` | 6 | end of turn |
|
| 134 |
+
|
| 135 |
+
### Chat Template
|
| 136 |
+
|
| 137 |
+
```
|
| 138 |
+
<bos><|user|>
|
| 139 |
+
{user}<|eot|>
|
| 140 |
+
<|assistant|>
|
| 141 |
+
{response}<|eot|><eos>
|
| 142 |
+
```
|
| 143 |
+
|
| 144 |
+
---
|
| 145 |
+
|
| 146 |
+
## Usage
|
| 147 |
+
|
| 148 |
+
Download `inference.py` and `tokenizer.json` from this repo. Requires: `torch`, `safetensors`, `tokenizers`.
|
| 149 |
+
|
| 150 |
+
```bash
|
| 151 |
+
pip install torch safetensors tokenizers
|
| 152 |
+
```
|
| 153 |
+
|
| 154 |
+
CLI (interactive chat):
|
| 155 |
+
```bash
|
| 156 |
+
python inference.py --ckpt model.safetensors
|
| 157 |
+
```
|
| 158 |
+
|
| 159 |
+
Recommended decoding defaults (same as SSMoELM-it):
|
| 160 |
+
|
| 161 |
+
| Parameter | Value |
|
| 162 |
+
|---|---:|
|
| 163 |
+
| `temperature` | `0.0` |
|
| 164 |
+
| `top_k` | `1` |
|
| 165 |
+
| `top_p` | `0.9` |
|
| 166 |
+
| `repetition_penalty` | `1.3` |
|
| 167 |
+
|
| 168 |
+
```python
|
| 169 |
+
from inference import load_packed_model, build_chat_prompt
|
| 170 |
+
from tokenizers import Tokenizer
|
| 171 |
+
|
| 172 |
+
model = load_packed_model("model.safetensors") # layer sharing auto-detected
|
| 173 |
+
tok = Tokenizer.from_file("tokenizer.json")
|
| 174 |
+
|
| 175 |
+
ids = build_chat_prompt(tok, history=[], user_input="What is photosynthesis?")
|
| 176 |
+
out = model.generate(
|
| 177 |
+
ids,
|
| 178 |
+
max_new_tokens=200,
|
| 179 |
+
temperature=0.0,
|
| 180 |
+
top_k=1,
|
| 181 |
+
repetition_penalty=1.3,
|
| 182 |
+
)
|
| 183 |
+
print(tok.decode(out))
|
| 184 |
+
```
|
| 185 |
+
|
| 186 |
+
> **Memory:** Weights stay in packed uint8 format (10.2 MB). Peak RAM ~16 MB during inference.
|
| 187 |
+
|
| 188 |
+
---
|
| 189 |
+
|
| 190 |
+
## License
|
| 191 |
+
|
| 192 |
+
Apache 2.0
|
__pycache__/inference.cpython-314.pyc
ADDED
|
Binary file (43.3 kB). View file
|
|
|
inference.py
ADDED
|
@@ -0,0 +1,489 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
SSMoELM Packed Inference โ low-memory inference over packed uint8 weights.
|
| 3 |
+
Weights stay packed in memory and are unpacked on-the-fly during forward.
|
| 4 |
+
|
| 5 |
+
Supports layer-shared checkpoints (SSMoELM-it-5L): when the safetensors
|
| 6 |
+
__metadata__ contains `layer_ids` / `pass_order`, stored layers are reused
|
| 7 |
+
across multiple forward passes (e.g. 5 stored layers, 6 compute passes).
|
| 8 |
+
|
| 9 |
+
Usage:
|
| 10 |
+
python inference.py --ckpt model.safetensors
|
| 11 |
+
"""
|
| 12 |
+
import argparse
|
| 13 |
+
import json
|
| 14 |
+
import math
|
| 15 |
+
import struct
|
| 16 |
+
from pathlib import Path
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
import torch.nn as nn
|
| 21 |
+
import torch.nn.functional as F
|
| 22 |
+
from safetensors.numpy import load_file
|
| 23 |
+
from tokenizers import Tokenizer
|
| 24 |
+
|
| 25 |
+
D_MODEL = 768
|
| 26 |
+
N_LAYERS = 6
|
| 27 |
+
N_HEADS = 12
|
| 28 |
+
KV_HEADS = 3
|
| 29 |
+
HEAD_DIM = 64
|
| 30 |
+
N_EXPERTS = 8
|
| 31 |
+
N_ACTIVE = 2
|
| 32 |
+
D_FF = 256
|
| 33 |
+
VOCAB_SIZE = 8192
|
| 34 |
+
CTX_LEN = 2048
|
| 35 |
+
|
| 36 |
+
BOS_ID, EOS_ID, EOT_ID = 0, 1, 6
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def apply_repetition_penalty(
|
| 40 |
+
logits: np.ndarray,
|
| 41 |
+
token_ids: list[int],
|
| 42 |
+
penalty: float,
|
| 43 |
+
) -> np.ndarray:
|
| 44 |
+
"""ๆขๅบใใผใฏใณใฎ logit ใซ repetition penalty ใ้ฉ็จใใใ"""
|
| 45 |
+
if penalty <= 1.0 or not token_ids:
|
| 46 |
+
return logits
|
| 47 |
+
adjusted = logits.copy()
|
| 48 |
+
for token_id in set(token_ids):
|
| 49 |
+
if adjusted[token_id] > 0:
|
| 50 |
+
adjusted[token_id] /= penalty
|
| 51 |
+
else:
|
| 52 |
+
adjusted[token_id] *= penalty
|
| 53 |
+
return adjusted
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def filter_top_k(logits: np.ndarray, top_k: int) -> np.ndarray:
|
| 57 |
+
"""top_k ไปฅๅคใฎ logit ใ -inf ใซใใใtop_k<=0 ใชใๅคๆดใใชใใ"""
|
| 58 |
+
if top_k <= 0 or top_k >= logits.shape[-1]:
|
| 59 |
+
return logits
|
| 60 |
+
filtered = np.full_like(logits, -np.inf)
|
| 61 |
+
top_indices = np.argpartition(logits, -top_k)[-top_k:]
|
| 62 |
+
filtered[top_indices] = logits[top_indices]
|
| 63 |
+
return filtered
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
# โโ Packed Linear Modules โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 67 |
+
|
| 68 |
+
class Linear1bit(nn.Module):
|
| 69 |
+
"""1-bit packed linear layer: scale(fp16) + packed bits(uint8) โ fp32 matmul on-the-fly"""
|
| 70 |
+
def __init__(self, out_f: int, in_f: int):
|
| 71 |
+
super().__init__()
|
| 72 |
+
self.in_features = in_f
|
| 73 |
+
self.register_buffer("scale", torch.zeros(out_f, dtype=torch.float16))
|
| 74 |
+
self.register_buffer("packed", torch.zeros(out_f, (in_f + 7) // 8, dtype=torch.uint8))
|
| 75 |
+
|
| 76 |
+
def _unpack(self) -> torch.Tensor:
|
| 77 |
+
# packed: [out, ceil(in/8)] โ [out, in] values ยฑ1
|
| 78 |
+
bits = ((self.packed.unsqueeze(-1)
|
| 79 |
+
>> torch.arange(7, -1, -1, device=self.packed.device, dtype=torch.uint8))
|
| 80 |
+
& 1) # [out, ceil(in/8), 8]
|
| 81 |
+
bits = bits.reshape(self.packed.shape[0], -1)[:, :self.in_features] # [out, in]
|
| 82 |
+
w = bits.float() * 2.0 - 1.0 # {0,1} โ {-1,1}
|
| 83 |
+
w = w * self.scale.float().unsqueeze(-1) # row-wise scale
|
| 84 |
+
return w # [out, in]
|
| 85 |
+
|
| 86 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 87 |
+
w = self._unpack()
|
| 88 |
+
out = F.linear(x, w)
|
| 89 |
+
del w
|
| 90 |
+
return out
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
class Linear4bit(nn.Module):
|
| 94 |
+
"""4-bit nibble-packed linear layer"""
|
| 95 |
+
def __init__(self, out_f: int, in_f: int):
|
| 96 |
+
super().__init__()
|
| 97 |
+
self.in_features = in_f
|
| 98 |
+
self.register_buffer("scale", torch.zeros(out_f, dtype=torch.float16))
|
| 99 |
+
self.register_buffer("packed", torch.zeros(out_f, (in_f + 1) // 2, dtype=torch.uint8))
|
| 100 |
+
|
| 101 |
+
def _unpack(self) -> torch.Tensor:
|
| 102 |
+
lo = (self.packed & 0x0F).to(torch.int8) - 8 # [out, in//2]
|
| 103 |
+
hi = ((self.packed >> 4) & 0x0F).to(torch.int8) - 8
|
| 104 |
+
w = torch.stack([lo, hi], dim=-1).reshape(self.packed.shape[0], -1)
|
| 105 |
+
w = w[:, :self.in_features].float()
|
| 106 |
+
w = w * self.scale.float().unsqueeze(-1)
|
| 107 |
+
return w
|
| 108 |
+
|
| 109 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 110 |
+
w = self._unpack()
|
| 111 |
+
out = F.linear(x, w)
|
| 112 |
+
del w
|
| 113 |
+
return out
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
class EmbeddingPacked(nn.Module):
|
| 117 |
+
"""4-bit packed embedding table"""
|
| 118 |
+
def __init__(self, vocab: int, d: int):
|
| 119 |
+
super().__init__()
|
| 120 |
+
self.vocab = vocab
|
| 121 |
+
self.d = d
|
| 122 |
+
self.register_buffer("scale", torch.zeros(vocab, dtype=torch.float16))
|
| 123 |
+
self.register_buffer("packed", torch.zeros(vocab, (d + 1) // 2, dtype=torch.uint8))
|
| 124 |
+
|
| 125 |
+
def get_weight(self) -> torch.Tensor:
|
| 126 |
+
lo = (self.packed & 0x0F).to(torch.int8) - 8
|
| 127 |
+
hi = ((self.packed >> 4) & 0x0F).to(torch.int8) - 8
|
| 128 |
+
w = torch.stack([lo, hi], dim=-1).reshape(self.vocab, -1)[:, :self.d].float()
|
| 129 |
+
return w * self.scale.float().unsqueeze(-1)
|
| 130 |
+
|
| 131 |
+
def forward(self, idx: torch.Tensor) -> torch.Tensor:
|
| 132 |
+
return self.get_weight()[idx]
|
| 133 |
+
|
| 134 |
+
|
| 135 |
+
# โโ Model โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 136 |
+
|
| 137 |
+
class RMSNorm(nn.Module):
|
| 138 |
+
def __init__(self, d: int, eps: float = 1e-6):
|
| 139 |
+
super().__init__()
|
| 140 |
+
self.weight = nn.Parameter(torch.ones(d))
|
| 141 |
+
self.eps = eps
|
| 142 |
+
|
| 143 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 144 |
+
rms = (x.float().pow(2).mean(-1, keepdim=True) + self.eps).rsqrt()
|
| 145 |
+
return (self.weight * (x.float() * rms)).to(x.dtype)
|
| 146 |
+
|
| 147 |
+
|
| 148 |
+
def precompute_rope(head_dim: int, max_len: int, base: float = 10000.0) -> torch.Tensor:
|
| 149 |
+
inv_freq = 1.0 / (base ** (torch.arange(0, head_dim, 2).float() / head_dim))
|
| 150 |
+
freqs = torch.outer(torch.arange(max_len).float(), inv_freq)
|
| 151 |
+
return torch.cat([freqs, freqs], dim=-1)
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def rotate_half(x: torch.Tensor) -> torch.Tensor:
|
| 155 |
+
h = x.shape[-1] // 2
|
| 156 |
+
return torch.cat([-x[..., h:], x[..., :h]], dim=-1)
|
| 157 |
+
|
| 158 |
+
|
| 159 |
+
def apply_rope(x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
| 160 |
+
cos = freqs.cos()[None, :, None, :].to(x.dtype)
|
| 161 |
+
sin = freqs.sin()[None, :, None, :].to(x.dtype)
|
| 162 |
+
return x * cos + rotate_half(x) * sin
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
class Attention(nn.Module):
|
| 166 |
+
def __init__(self, layer_idx: int):
|
| 167 |
+
super().__init__()
|
| 168 |
+
boundary = {0, 5}
|
| 169 |
+
vo_4bit = layer_idx in boundary
|
| 170 |
+
d = D_MODEL
|
| 171 |
+
self.n_heads = N_HEADS
|
| 172 |
+
self.kv_heads = KV_HEADS
|
| 173 |
+
self.head_dim = HEAD_DIM
|
| 174 |
+
self.n_rep = N_HEADS // KV_HEADS
|
| 175 |
+
self.q_proj = Linear4bit(N_HEADS * HEAD_DIM, d)
|
| 176 |
+
self.k_proj = Linear4bit(KV_HEADS * HEAD_DIM, d)
|
| 177 |
+
self.v_proj = Linear4bit(KV_HEADS * HEAD_DIM, d) if vo_4bit else Linear1bit(KV_HEADS * HEAD_DIM, d)
|
| 178 |
+
self.o_proj = Linear4bit(d, N_HEADS * HEAD_DIM) if vo_4bit else Linear1bit(d, N_HEADS * HEAD_DIM)
|
| 179 |
+
|
| 180 |
+
def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
| 181 |
+
B, T, _ = x.shape
|
| 182 |
+
q = self.q_proj(x).reshape(B, T, self.n_heads, self.head_dim)
|
| 183 |
+
k = self.k_proj(x).reshape(B, T, self.kv_heads, self.head_dim)
|
| 184 |
+
v = self.v_proj(x).reshape(B, T, self.kv_heads, self.head_dim)
|
| 185 |
+
q, k = apply_rope(q, freqs), apply_rope(k, freqs)
|
| 186 |
+
k = k.repeat_interleave(self.n_rep, dim=2)
|
| 187 |
+
v = v.repeat_interleave(self.n_rep, dim=2)
|
| 188 |
+
out = F.scaled_dot_product_attention(
|
| 189 |
+
q.transpose(1, 2), k.transpose(1, 2), v.transpose(1, 2), is_causal=True)
|
| 190 |
+
return self.o_proj(out.transpose(1, 2).reshape(B, T, -1))
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
class SwiGLU(nn.Module):
|
| 194 |
+
def __init__(self, d_model: int, d_ff: int, bits: int):
|
| 195 |
+
super().__init__()
|
| 196 |
+
L = Linear4bit if bits == 4 else Linear1bit
|
| 197 |
+
self.gate = L(d_ff, d_model)
|
| 198 |
+
self.up = L(d_ff, d_model)
|
| 199 |
+
self.down = L(d_model, d_ff)
|
| 200 |
+
|
| 201 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 202 |
+
return self.down(F.silu(self.gate(x)) * self.up(x))
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
class MoELayer(nn.Module):
|
| 206 |
+
def __init__(self):
|
| 207 |
+
super().__init__()
|
| 208 |
+
self.shared = SwiGLU(D_MODEL, D_FF, bits=4)
|
| 209 |
+
# stacked routed expert weights (1-bit)
|
| 210 |
+
self.gate_scale = nn.ParameterList([nn.Parameter(torch.zeros(D_FF), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 211 |
+
self.gate_packed = nn.ParameterList([nn.Parameter(torch.zeros(D_FF, (D_MODEL+7)//8, dtype=torch.uint8), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 212 |
+
self.up_scale = nn.ParameterList([nn.Parameter(torch.zeros(D_FF), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 213 |
+
self.up_packed = nn.ParameterList([nn.Parameter(torch.zeros(D_FF, (D_MODEL+7)//8, dtype=torch.uint8), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 214 |
+
self.down_scale = nn.ParameterList([nn.Parameter(torch.zeros(D_MODEL), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 215 |
+
self.down_packed = nn.ParameterList([nn.Parameter(torch.zeros(D_MODEL, (D_FF+7)//8, dtype=torch.uint8), requires_grad=False) for _ in range(N_EXPERTS)])
|
| 216 |
+
self.router = nn.Parameter(torch.zeros(N_EXPERTS, D_MODEL))
|
| 217 |
+
|
| 218 |
+
def _unpack1bit(self, scale: torch.Tensor, packed: torch.Tensor, in_f: int) -> torch.Tensor:
|
| 219 |
+
bits = ((packed.unsqueeze(-1)
|
| 220 |
+
>> torch.arange(7, -1, -1, device=packed.device, dtype=torch.uint8)) & 1)
|
| 221 |
+
bits = bits.reshape(packed.shape[0], -1)[:, :in_f].float() * 2.0 - 1.0
|
| 222 |
+
return bits * scale.float().unsqueeze(-1)
|
| 223 |
+
|
| 224 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 225 |
+
B, T, d = x.shape
|
| 226 |
+
shared_out = self.shared(x)
|
| 227 |
+
|
| 228 |
+
logits = x @ self.router.T
|
| 229 |
+
top_idx = logits.topk(N_ACTIVE, dim=-1).indices
|
| 230 |
+
top_w = F.softmax(logits.gather(-1, top_idx).float(), dim=-1).to(x.dtype)
|
| 231 |
+
|
| 232 |
+
# process only active experts (memory-efficient)
|
| 233 |
+
x_flat = x.reshape(B * T, d)
|
| 234 |
+
out = torch.zeros_like(x_flat)
|
| 235 |
+
|
| 236 |
+
for k in range(N_ACTIVE):
|
| 237 |
+
e_idx = top_idx[..., k].reshape(-1) # [B*T]
|
| 238 |
+
w_k = top_w[..., k].reshape(-1, 1) # [B*T, 1]
|
| 239 |
+
|
| 240 |
+
for e in range(N_EXPERTS):
|
| 241 |
+
mask = (e_idx == e)
|
| 242 |
+
if not mask.any():
|
| 243 |
+
continue
|
| 244 |
+
x_e = x_flat[mask]
|
| 245 |
+
# unpack this expert's weights on-the-fly
|
| 246 |
+
wg = self._unpack1bit(self.gate_scale[e], self.gate_packed[e], D_MODEL)
|
| 247 |
+
wu = self._unpack1bit(self.up_scale[e], self.up_packed[e], D_MODEL)
|
| 248 |
+
wd = self._unpack1bit(self.down_scale[e], self.down_packed[e], D_FF)
|
| 249 |
+
h = F.silu(F.linear(x_e, wg)) * F.linear(x_e, wu)
|
| 250 |
+
out[mask] += F.linear(h, wd) * w_k[mask]
|
| 251 |
+
del wg, wu, wd, h
|
| 252 |
+
|
| 253 |
+
return shared_out + out.reshape(B, T, d)
|
| 254 |
+
|
| 255 |
+
|
| 256 |
+
class TransformerLayer(nn.Module):
|
| 257 |
+
def __init__(self, layer_idx: int):
|
| 258 |
+
super().__init__()
|
| 259 |
+
self.attn_norm = RMSNorm(D_MODEL)
|
| 260 |
+
self.ffn_norm = RMSNorm(D_MODEL)
|
| 261 |
+
self.attn = Attention(layer_idx)
|
| 262 |
+
self.moe = MoELayer()
|
| 263 |
+
|
| 264 |
+
def forward(self, x: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
|
| 265 |
+
x = x + self.attn(self.attn_norm(x), freqs)
|
| 266 |
+
x = x + self.moe(self.ffn_norm(x))
|
| 267 |
+
return x
|
| 268 |
+
|
| 269 |
+
|
| 270 |
+
class SSMoELMPacked(nn.Module):
|
| 271 |
+
def __init__(self, layer_ids: list[int] | None = None,
|
| 272 |
+
pass_order: list[int] | None = None):
|
| 273 |
+
super().__init__()
|
| 274 |
+
# layer_ids: original indices of stored layers (e.g. [0,1,2,3,5])
|
| 275 |
+
# pass_order: layer id executed at each depth (e.g. [0,1,2,3,3,5])
|
| 276 |
+
self.layer_ids = list(layer_ids) if layer_ids is not None else list(range(N_LAYERS))
|
| 277 |
+
self.pass_order = list(pass_order) if pass_order is not None else list(self.layer_ids)
|
| 278 |
+
self.embed = EmbeddingPacked(VOCAB_SIZE, D_MODEL)
|
| 279 |
+
self.layers = nn.ModuleList([TransformerLayer(i) for i in self.layer_ids])
|
| 280 |
+
self.norm = RMSNorm(D_MODEL)
|
| 281 |
+
self.register_buffer("freqs", precompute_rope(HEAD_DIM, CTX_LEN))
|
| 282 |
+
|
| 283 |
+
def forward(self, x: torch.Tensor) -> torch.Tensor:
|
| 284 |
+
T = x.shape[1]
|
| 285 |
+
h = self.embed(x).float()
|
| 286 |
+
freqs = self.freqs[:T]
|
| 287 |
+
for lid in self.pass_order:
|
| 288 |
+
h = self.layers[self.layer_ids.index(lid)](h, freqs)
|
| 289 |
+
h = self.norm(h)
|
| 290 |
+
w = self.embed.get_weight()
|
| 291 |
+
return h @ w.T
|
| 292 |
+
|
| 293 |
+
@torch.inference_mode()
|
| 294 |
+
def generate(self, input_ids: list[int], max_new_tokens: int = 200,
|
| 295 |
+
temperature: float = 0.0, top_p: float = 0.9,
|
| 296 |
+
top_k: int = 1, repetition_penalty: float = 1.3,
|
| 297 |
+
eos_ids: tuple[int, ...] = (EOS_ID, EOT_ID)) -> list[int]:
|
| 298 |
+
ids = list(input_ids)
|
| 299 |
+
generated = []
|
| 300 |
+
for _ in range(max_new_tokens):
|
| 301 |
+
x = torch.tensor([ids[-CTX_LEN:]], dtype=torch.long)
|
| 302 |
+
logits = self(x)[0, -1]
|
| 303 |
+
logits_np = logits.numpy().astype(np.float64)
|
| 304 |
+
logits_np = apply_repetition_penalty(logits_np, ids, repetition_penalty)
|
| 305 |
+
logits_np = filter_top_k(logits_np, top_k)
|
| 306 |
+
if temperature > 0:
|
| 307 |
+
logits_np = (logits_np - np.nanmax(logits_np)) / temperature
|
| 308 |
+
probs = np.exp(logits_np); probs /= probs.sum()
|
| 309 |
+
idx = np.argsort(-probs); cumsum = np.cumsum(probs[idx])
|
| 310 |
+
cutoff = np.searchsorted(cumsum, top_p) + 1
|
| 311 |
+
probs[idx[cutoff:]] = 0.0; probs /= probs.sum()
|
| 312 |
+
next_id = int(np.random.choice(idx, p=probs))
|
| 313 |
+
else:
|
| 314 |
+
next_id = int(np.nanargmax(logits_np))
|
| 315 |
+
if next_id in eos_ids:
|
| 316 |
+
break
|
| 317 |
+
generated.append(next_id)
|
| 318 |
+
ids.append(next_id)
|
| 319 |
+
return generated
|
| 320 |
+
|
| 321 |
+
|
| 322 |
+
# โโ Load โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 323 |
+
|
| 324 |
+
def load_layer_metadata(path: str) -> tuple[list[int] | None, list[int] | None]:
|
| 325 |
+
"""safetensors ใฎ __metadata__ ใใ layer_ids / pass_order ใ่ชญใ (็กใใใฐ None)ใ"""
|
| 326 |
+
with open(path, "rb") as f:
|
| 327 |
+
header_len = struct.unpack("<Q", f.read(8))[0]
|
| 328 |
+
header = json.loads(f.read(header_len))
|
| 329 |
+
meta = header.get("__metadata__") or {}
|
| 330 |
+
layer_ids = json.loads(meta["layer_ids"]) if "layer_ids" in meta else None
|
| 331 |
+
pass_order = json.loads(meta["pass_order"]) if "pass_order" in meta else None
|
| 332 |
+
return layer_ids, pass_order
|
| 333 |
+
|
| 334 |
+
|
| 335 |
+
def load_packed_model(path: str) -> SSMoELMPacked:
|
| 336 |
+
data = load_file(path)
|
| 337 |
+
data = {k.replace("/", "."): v for k, v in data.items()}
|
| 338 |
+
|
| 339 |
+
layer_ids, pass_order = load_layer_metadata(path)
|
| 340 |
+
model = SSMoELMPacked(layer_ids, pass_order)
|
| 341 |
+
|
| 342 |
+
def _set(module, scale_name, packed_name, key_base):
|
| 343 |
+
s_key = f"{key_base}__scale"
|
| 344 |
+
p_key_bin = f"{key_base}__bin"
|
| 345 |
+
p_key_int4 = f"{key_base}__int4"
|
| 346 |
+
if s_key in data:
|
| 347 |
+
getattr(module, scale_name).data.copy_(torch.from_numpy(data[s_key].astype(np.float16)))
|
| 348 |
+
if p_key_bin in data:
|
| 349 |
+
getattr(module, packed_name).data.copy_(torch.from_numpy(data[p_key_bin]))
|
| 350 |
+
elif p_key_int4 in data:
|
| 351 |
+
getattr(module, packed_name).data.copy_(torch.from_numpy(data[p_key_int4]))
|
| 352 |
+
|
| 353 |
+
# embed
|
| 354 |
+
_set(model.embed, "scale", "packed", "embed_weight")
|
| 355 |
+
|
| 356 |
+
for lid, layer in zip(model.layer_ids, model.layers):
|
| 357 |
+
pfx = f"layers.{lid}"
|
| 358 |
+
# attention
|
| 359 |
+
for proj_name, key in [("q_proj","q_weight"),("k_proj","k_weight"),
|
| 360 |
+
("v_proj","v_weight"),("o_proj","o_weight")]:
|
| 361 |
+
proj = getattr(layer.attn, proj_name)
|
| 362 |
+
_set(proj, "scale", "packed", f"{pfx}.attn.{key}")
|
| 363 |
+
# norms
|
| 364 |
+
for norm_name, key in [("attn_norm","attn_norm"),("ffn_norm","ffn_norm")]:
|
| 365 |
+
norm = getattr(layer, norm_name)
|
| 366 |
+
w = data.get(f"{pfx}.{key}.weight")
|
| 367 |
+
if w is not None:
|
| 368 |
+
norm.weight.data.copy_(torch.from_numpy(w.astype(np.float32)))
|
| 369 |
+
# shared expert
|
| 370 |
+
se = layer.moe.shared
|
| 371 |
+
for attr, wname in [("gate","gate_weight"),("up","up_weight"),("down","down_weight")]:
|
| 372 |
+
_set(getattr(se, attr), "scale", "packed", f"{pfx}.moe.shared_expert.{wname}")
|
| 373 |
+
# router
|
| 374 |
+
rw = data.get(f"{pfx}.moe.router_weight")
|
| 375 |
+
if rw is not None:
|
| 376 |
+
layer.moe.router.data.copy_(torch.from_numpy(rw.astype(np.float32)))
|
| 377 |
+
# routed experts: stacked weights [E, out, in] โ scale [E*out], packed [E*out, ...]
|
| 378 |
+
for attr, wname, out_f, in_f in [
|
| 379 |
+
("gate", "gate", D_FF, D_MODEL),
|
| 380 |
+
("up", "up", D_FF, D_MODEL),
|
| 381 |
+
("down", "down", D_MODEL, D_FF),
|
| 382 |
+
]:
|
| 383 |
+
s_key = f"{pfx}.moe.{wname}_weight__scale"
|
| 384 |
+
p_key = (f"{pfx}.moe.{wname}_weight__bin"
|
| 385 |
+
if f"{pfx}.moe.{wname}_weight__bin" in data
|
| 386 |
+
else f"{pfx}.moe.{wname}_weight__int4")
|
| 387 |
+
if s_key not in data or p_key not in data:
|
| 388 |
+
continue
|
| 389 |
+
s_arr = data[s_key] # [E*out_f]
|
| 390 |
+
p_arr = data[p_key] # [E*out_f, packed_cols]
|
| 391 |
+
for e in range(N_EXPERTS):
|
| 392 |
+
sl = slice(e * out_f, (e + 1) * out_f)
|
| 393 |
+
getattr(layer.moe, f"{attr}_scale")[e].data.copy_(
|
| 394 |
+
torch.from_numpy(s_arr[sl].astype(np.float16)))
|
| 395 |
+
getattr(layer.moe, f"{attr}_packed")[e].data.copy_(
|
| 396 |
+
torch.from_numpy(p_arr[sl]))
|
| 397 |
+
|
| 398 |
+
return model.eval()
|
| 399 |
+
|
| 400 |
+
|
| 401 |
+
USER_ID = 4
|
| 402 |
+
ASSISTANT_ID = 5
|
| 403 |
+
|
| 404 |
+
|
| 405 |
+
def build_chat_prompt(tok: Tokenizer, history: list[tuple[str, str]],
|
| 406 |
+
user_input: str) -> list[int]:
|
| 407 |
+
"""ไผ่ฉฑๅฑฅๆญด + ๆฐใใใฆใผใถใผๅ
ฅๅ โ ใใผใฏใณๅ (instruct ใขใใซ็จ)"""
|
| 408 |
+
ids = [BOS_ID]
|
| 409 |
+
for user_turn, assistant_turn in history:
|
| 410 |
+
ids += [USER_ID] + tok.encode("\n" + user_turn).ids + [EOT_ID]
|
| 411 |
+
ids += [ASSISTANT_ID] + tok.encode("\n" + assistant_turn).ids + [EOT_ID]
|
| 412 |
+
ids += [USER_ID] + tok.encode("\n" + user_input).ids + [EOT_ID, ASSISTANT_ID]
|
| 413 |
+
return ids[-CTX_LEN:]
|
| 414 |
+
|
| 415 |
+
|
| 416 |
+
# โโ CLI โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
|
| 417 |
+
|
| 418 |
+
def main():
|
| 419 |
+
parser = argparse.ArgumentParser()
|
| 420 |
+
parser.add_argument("--ckpt", default="model.safetensors", help="Path to packed safetensors")
|
| 421 |
+
parser.add_argument("--tokenizer", default="tokenizer.json", help="Path to tokenizer.json")
|
| 422 |
+
parser.add_argument("--prompt", default=None, help="Prompt for single-shot mode (--no-chat)")
|
| 423 |
+
parser.add_argument("--no-chat", action="store_true", help="Single-shot mode")
|
| 424 |
+
parser.add_argument("--max-tokens", type=int, default=200, help="Max new tokens to generate")
|
| 425 |
+
parser.add_argument("--temperature", type=float, default=0.0, help="Sampling temperature (0 = greedy; recommended for this model)")
|
| 426 |
+
parser.add_argument("--top-p", type=float, default=0.9, help="Top-p nucleus sampling")
|
| 427 |
+
parser.add_argument("--top-k", type=int, default=1, help="Keep only top-k logits before sampling (0 disables)")
|
| 428 |
+
parser.add_argument("--repetition-penalty", type=float, default=1.3, help="Penalty for tokens already present in the prompt/output")
|
| 429 |
+
args = parser.parse_args()
|
| 430 |
+
|
| 431 |
+
print(f"Loading {args.ckpt} ...")
|
| 432 |
+
model = load_packed_model(args.ckpt)
|
| 433 |
+
packed_bytes = sum(p.numel() * p.element_size() for p in model.buffers()) \
|
| 434 |
+
+ sum(p.numel() * p.element_size() for p in model.parameters())
|
| 435 |
+
print(f"Memory: {packed_bytes/1024/1024:.1f} MB")
|
| 436 |
+
|
| 437 |
+
tok = Tokenizer.from_file(args.tokenizer)
|
| 438 |
+
|
| 439 |
+
if not args.no_chat:
|
| 440 |
+
# ๅฏพ่ฉฑใขใผใ
|
| 441 |
+
print("Chat mode โ type 'exit' to quit, 'clear' to reset history")
|
| 442 |
+
print("=" * 50)
|
| 443 |
+
history: list[tuple[str, str]] = []
|
| 444 |
+
while True:
|
| 445 |
+
try:
|
| 446 |
+
user_input = input("\nYou: ").strip()
|
| 447 |
+
except (EOFError, KeyboardInterrupt):
|
| 448 |
+
break
|
| 449 |
+
if not user_input:
|
| 450 |
+
continue
|
| 451 |
+
if user_input.lower() == "exit":
|
| 452 |
+
break
|
| 453 |
+
if user_input.lower() == "clear":
|
| 454 |
+
history.clear()
|
| 455 |
+
print("--- history cleared ---")
|
| 456 |
+
|
| 457 |
+
continue
|
| 458 |
+
ids = build_chat_prompt(tok, history, user_input)
|
| 459 |
+
print("Assistant: ", end="", flush=True)
|
| 460 |
+
out = model.generate(
|
| 461 |
+
ids,
|
| 462 |
+
args.max_tokens,
|
| 463 |
+
args.temperature,
|
| 464 |
+
args.top_p,
|
| 465 |
+
args.top_k,
|
| 466 |
+
args.repetition_penalty,
|
| 467 |
+
)
|
| 468 |
+
response = tok.decode(out).strip()
|
| 469 |
+
print(response)
|
| 470 |
+
history.append((user_input, response))
|
| 471 |
+
else:
|
| 472 |
+
# Single-shot mode (--no-chat)
|
| 473 |
+
prompt = args.prompt or "The quick brown fox"
|
| 474 |
+
ids = [BOS_ID] + tok.encode(prompt).ids
|
| 475 |
+
print(f"\nPrompt: {prompt}")
|
| 476 |
+
print("Output: ", end="", flush=True)
|
| 477 |
+
out = model.generate(
|
| 478 |
+
ids,
|
| 479 |
+
args.max_tokens,
|
| 480 |
+
args.temperature,
|
| 481 |
+
args.top_p,
|
| 482 |
+
args.top_k,
|
| 483 |
+
args.repetition_penalty,
|
| 484 |
+
)
|
| 485 |
+
print(tok.decode(out))
|
| 486 |
+
|
| 487 |
+
|
| 488 |
+
if __name__ == "__main__":
|
| 489 |
+
main()
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c37ade6413044428b6544e4bc0c0f77873e2afe50340c4bce5a2eec7118bfaf9
|
| 3 |
+
size 10678696
|
ssmoelm_5l.sb3
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:c4ef4fc335aeff9c8e74373f238cd6a91d55b576a2c0e2b3285aa146baff7657
|
| 3 |
+
size 10102323
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|