Text Generation
Transformers
Safetensors
PyTorch
English
bananaall
causal-lm
language-model
base-model
small-language-model
bananamind
bananamind2
ternary
int8-embeddings
digit-tokenizer
custom-code
trust-remote-code
custom-architecture
custom_code
8-bit precision
Instructions to use BananaMind/TernaryBananaMind-10M with libraries, inference providers, notebooks, and local apps. Follow these links to get started.
- Libraries
- Transformers
How to use BananaMind/TernaryBananaMind-10M with Transformers:
# Use a pipeline as a high-level helper from transformers import pipeline pipe = pipeline("text-generation", model="BananaMind/TernaryBananaMind-10M", trust_remote_code=True)# Load model directly from transformers import AutoModelForCausalLM model = AutoModelForCausalLM.from_pretrained("BananaMind/TernaryBananaMind-10M", trust_remote_code=True, device_map="auto") - Notebooks
- Google Colab
- Kaggle
- Local Apps Settings
- vLLM
How to use BananaMind/TernaryBananaMind-10M with vLLM:
Install from pip and serve model
# Install vLLM from pip: pip install vllm # Start the vLLM server: vllm serve "BananaMind/TernaryBananaMind-10M" # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:8000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "BananaMind/TernaryBananaMind-10M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker
docker model run hf.co/BananaMind/TernaryBananaMind-10M
- SGLang
How to use BananaMind/TernaryBananaMind-10M with SGLang:
Install from pip and serve model
# Install SGLang from pip: pip install sglang # Start the SGLang server: python3 -m sglang.launch_server \ --model-path "BananaMind/TernaryBananaMind-10M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "BananaMind/TernaryBananaMind-10M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }'Use Docker images
docker run --gpus all \ --shm-size 32g \ -p 30000:30000 \ -v ~/.cache/huggingface:/root/.cache/huggingface \ --env "HF_TOKEN=<secret>" \ --ipc=host \ lmsysorg/sglang:latest \ python3 -m sglang.launch_server \ --model-path "BananaMind/TernaryBananaMind-10M" \ --host 0.0.0.0 \ --port 30000 # Call the server using curl (OpenAI-compatible API): curl -X POST "http://localhost:30000/v1/completions" \ -H "Content-Type: application/json" \ --data '{ "model": "BananaMind/TernaryBananaMind-10M", "prompt": "Once upon a time,", "max_tokens": 512, "temperature": 0.5 }' - Docker Model Runner
How to use BananaMind/TernaryBananaMind-10M with Docker Model Runner:
docker model run hf.co/BananaMind/TernaryBananaMind-10M
Upload 13 files
Browse files- README.md +223 -0
- config.json +32 -0
- configuration_bananaall.py +29 -0
- dataset_tokens.json +6 -0
- generation_config.json +12 -0
- model.safetensors +3 -0
- model_backup_full.safetensors +3 -0
- modeling_bananaall.py +270 -0
- modeling_bananaall_int8_v2.py +270 -0
- pack_ternary.py +77 -0
- tokenizer.json +0 -0
- tokenizer_config.json +12 -0
- training_args.bin +3 -0
README.md
CHANGED
|
@@ -1,3 +1,226 @@
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
---
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
---
|
| 2 |
license: apache-2.0
|
| 3 |
+
language:
|
| 4 |
+
- en
|
| 5 |
+
library_name: transformers
|
| 6 |
+
pipeline_tag: text-generation
|
| 7 |
+
datasets:
|
| 8 |
+
- HuggingFaceFW/fineweb-edu
|
| 9 |
+
tags:
|
| 10 |
+
- causal-lm
|
| 11 |
+
- language-model
|
| 12 |
+
- base-model
|
| 13 |
+
- small-language-model
|
| 14 |
+
- bananamind
|
| 15 |
+
- bananamind2
|
| 16 |
+
- ternary
|
| 17 |
+
- int8-embeddings
|
| 18 |
+
- digit-tokenizer
|
| 19 |
+
- pytorch
|
| 20 |
+
- safetensors
|
| 21 |
+
- custom-code
|
| 22 |
+
- trust-remote-code
|
| 23 |
+
- custom-architecture
|
| 24 |
---
|
| 25 |
+
|
| 26 |
+
# TernaryBananaMind-10M
|
| 27 |
+
|
| 28 |
+
**TernaryBananaMind-10M** is a compact decoder-only base language model from BananaMind. Its inference checkpoint stores projection and output weights as packed ternary values and input embeddings as signed 8-bit values. The intended model ID is `BananaMind/TernaryBananaMind-10M`.
|
| 29 |
+
|
| 30 |
+
The model has **8,428,032 logical weights**, a **4,096-token context window**, and a custom **2,048-token digit-aware byte-level BPE tokenizer**. Its `model.safetensors` file is **2,175,676 bytes** (about **2.07 bits per logical weight**, including scales, float normalization weights, and file overhead). The model name is a size class; the exact logical weight count is 8.43M.
|
| 31 |
+
|
| 32 |
+
## Model Details
|
| 33 |
+
|
| 34 |
+
| Field | Value |
|
| 35 |
+
|---|---:|
|
| 36 |
+
| Architecture | BananaMind 2 style decoder-only Transformer |
|
| 37 |
+
| Logical weights | 8,428,032 |
|
| 38 |
+
| Layers | 10 |
|
| 39 |
+
| Hidden size | 256 |
|
| 40 |
+
| Intermediate size | 704 |
|
| 41 |
+
| Attention heads | 4 |
|
| 42 |
+
| KV heads | 2 |
|
| 43 |
+
| Head dimension | 64 |
|
| 44 |
+
| Attention | Grouped-query attention with QK norm |
|
| 45 |
+
| MLP | SwiGLU |
|
| 46 |
+
| Position embeddings | RoPE, theta 100,000 |
|
| 47 |
+
| Normalization | RMSNorm, epsilon 1e-6 |
|
| 48 |
+
| Vocabulary size | 2,048 |
|
| 49 |
+
| Context length | 4,096 |
|
| 50 |
+
| Input embeddings | Separate from output head; signed 8-bit with one scale per row |
|
| 51 |
+
| Projection and output weights | Ternary (-1, 0, +1), five values per byte |
|
| 52 |
+
| Activations in linear layers | Quantized to 8 bits during inference |
|
| 53 |
+
| Checkpoint | `model.safetensors`, 2,175,676 bytes |
|
| 54 |
+
| HF architecture | `BananaAllForCausalLM` |
|
| 55 |
+
| HF model type | `bananaall` |
|
| 56 |
+
|
| 57 |
+
The packed weights are decoded to temporary tensors for matrix multiplication. **2.07 bits per weight describes checkpoint storage, not arithmetic precision or peak inference memory.** Packed weights are registered as buffers, so `sum(p.numel() for p in model.parameters())` reports only the 6,656 trainable normalization parameters. Use the logical weight count above for model-size comparisons.
|
| 58 |
+
|
| 59 |
+
## Tokenizer
|
| 60 |
+
|
| 61 |
+
The custom 2k byte-level BPE tokenizer isolates digits during pre-tokenization.
|
| 62 |
+
|
| 63 |
+
| Special token | ID |
|
| 64 |
+
|---|---:|
|
| 65 |
+
| `<\|pad\|>` | 0 |
|
| 66 |
+
| `<\|bos\|>` | 1 |
|
| 67 |
+
| `<\|eos\|>` | 2 |
|
| 68 |
+
| `<\|unk\|>` | 3 |
|
| 69 |
+
|
| 70 |
+
## Training
|
| 71 |
+
|
| 72 |
+
The model was trained on **2 billion tokens of FineWeb-Edu** with the **BananaAll training framework**. The included `training_args.bin` records the settings below. Its maximum-step value is a configured limit, not a separately verified final step count.
|
| 73 |
+
|
| 74 |
+
| Setting | Recorded value |
|
| 75 |
+
|---|---:|
|
| 76 |
+
| Maximum optimizer steps | 61,036 |
|
| 77 |
+
| Per-device micro batch | 8 sequences |
|
| 78 |
+
| Gradient accumulation | 2 |
|
| 79 |
+
| Optimizer | PyTorch fused AdamW |
|
| 80 |
+
| Betas | 0.9, 0.999 |
|
| 81 |
+
| Peak learning rate | 0.0018 |
|
| 82 |
+
| Learning-rate schedule | Cosine |
|
| 83 |
+
| Warmup steps | 1,831 |
|
| 84 |
+
| Weight decay | 0.01 |
|
| 85 |
+
| Gradient clipping | 1.0 |
|
| 86 |
+
| BF16 training | Enabled |
|
| 87 |
+
| PyTorch compile | Enabled |
|
| 88 |
+
| Seed | 37 |
|
| 89 |
+
|
| 90 |
+
## Evaluation
|
| 91 |
+
|
| 92 |
+
The `lm_eval` and BananaMind Base Bench 1.1 scores below were supplied for the **current packed checkpoint**. Harness version, dtype, and runtime settings can affect results.
|
| 93 |
+
|
| 94 |
+
### Standard benchmarks (`lm_eval`)
|
| 95 |
+
|
| 96 |
+
| Benchmark | Acc | Acc norm | Samples |
|
| 97 |
+
|---|---:|---:|---:|
|
| 98 |
+
| PIQA | 54.46% | 53.54% | 1,838 |
|
| 99 |
+
| ARC Easy | 30.98% | 31.57% | 2,376 |
|
| 100 |
+
| ARC Challenge | 18.09% | 21.08% | 1,172 |
|
| 101 |
+
| HellaSwag | 26.94% | 27.76% | 10,042 |
|
| 102 |
+
| **Four-task mean** | — | **33.49%** | — |
|
| 103 |
+
|
| 104 |
+
### BananaMind Base Bench 1.1
|
| 105 |
+
|
| 106 |
+
The reported official complete run scored **37.14% accuracy (130/350)**, **35.95% weighted accuracy**, and **904 overall Elo**.
|
| 107 |
+
|
| 108 |
+
| Category | Elo | Accuracy | Weighted accuracy |
|
| 109 |
+
|---|---:|---:|---:|
|
| 110 |
+
| Language completion | 963 | 58.00% | 58.28% |
|
| 111 |
+
| Commonsense | 828 | 32.00% | 33.12% |
|
| 112 |
+
| World knowledge | 869 | 36.00% | 38.24% |
|
| 113 |
+
| Context tracking | 832 | 32.00% | 28.34% |
|
| 114 |
+
| Quantitative | 785 | 20.00% | 18.30% |
|
| 115 |
+
| Logical reasoning | 1,043 | 46.00% | 42.32% |
|
| 116 |
+
| Code completion | 1,000 | 36.00% | 37.26% |
|
| 117 |
+
|
| 118 |
+
### ArithMark 3.0
|
| 119 |
+
|
| 120 |
+
The [official benchmark script](https://huggingface.co/datasets/AxiomicLabs/Arithmark-3.0/raw/main/bencharithmark-3.py) was run against this local packed checkpoint on all **1,000 examples** with its default batch size and context limit, using CUDA and BF16. The model loaded without missing or unexpected checkpoint keys.
|
| 121 |
+
|
| 122 |
+
| Metric | Score |
|
| 123 |
+
|---|---:|
|
| 124 |
+
| Raw continuation accuracy | 31.10% (311/1,000) |
|
| 125 |
+
| Length-normalized accuracy | 31.20% (312/1,000) |
|
| 126 |
+
|
| 127 |
+
Dataset SHA-256: `bf8ab1a5193d52cdf0e05ff0b3ca226bdfcf416cb6e75562dcbe72e7e4559435`.
|
| 128 |
+
|
| 129 |
+
### Intelligence Index
|
| 130 |
+
|
| 131 |
+
The **Intelligence Index is 4.90**. Each component is adjusted for its chance floor with `N(score, chance) = 100 × (score - chance) / (100 - chance)`. The calculation uses the length-normalized scores above. Combined ARC is the mean of ARC Easy and ARC Challenge before chance adjustment.
|
| 132 |
+
|
| 133 |
+
| Component | Score used | Chance floor | Adjusted score | Weight |
|
| 134 |
+
|---|---:|---:|---:|---:|
|
| 135 |
+
| HellaSwag | 27.76% | 25% | 3.68 | 1.00 |
|
| 136 |
+
| Combined ARC | 26.325% | 25% | 1.77 | 1.00 |
|
| 137 |
+
| PIQA | 53.54% | 50% | 7.08 | 1.00 |
|
| 138 |
+
| ArithMark 3.0 | 31.20% | 25% | 8.27 | 0.65 |
|
| 139 |
+
|
| 140 |
+
`(3.68 + 1.7667 + 7.08 + 0.65 × 8.2667) / 3.65 = 4.9041`, rounded to **4.90**.
|
| 141 |
+
|
| 142 |
+
## Comparison with BananaMind-2-Nano
|
| 143 |
+
|
| 144 |
+
| Property | TernaryBananaMind-10M | BananaMind-2-Nano |
|
| 145 |
+
|---|---:|---:|
|
| 146 |
+
| Logical weights | 8,428,032 | 9,968,128 |
|
| 147 |
+
| Vocabulary size | 2,048 | 8,192 |
|
| 148 |
+
| Intermediate size | 704 | 768 |
|
| 149 |
+
| Input/output embeddings | Separate; input is 8-bit | Tied |
|
| 150 |
+
| Training tokens seen | 2B FineWeb-Edu | 30B across four datasets |
|
| 151 |
+
|
| 152 |
+
| Shared `lm_eval` benchmark | TernaryBananaMind-10M acc norm | BananaMind-2-Nano acc norm | Difference |
|
| 153 |
+
|---|---:|---:|---:|
|
| 154 |
+
| PIQA | 53.54% | 55.98% | -2.44 points |
|
| 155 |
+
| ARC Easy | 31.57% | 36.20% | -4.63 points |
|
| 156 |
+
| ARC Challenge | 21.08% | 23.38% | -2.30 points |
|
| 157 |
+
| HellaSwag | 27.76% | 27.50% | +0.26 points |
|
| 158 |
+
| **Four-task mean** | **33.49%** | **35.77%** | **-2.28 points** |
|
| 159 |
+
|
| 160 |
+
The two models differ in vocabulary, MLP width, training token count, and weight format, so these scores are a model-level comparison rather than an isolated measure of quantization.
|
| 161 |
+
|
| 162 |
+
| Additional metric | TernaryBananaMind-10M | BananaMind-2-Nano | Difference |
|
| 163 |
+
|---|---:|---:|---:|
|
| 164 |
+
| Intelligence Index | **4.90** | **8.01** | -3.11 |
|
| 165 |
+
| ArithMark 3.0 acc norm | 31.20% | 33.70% | -2.50 points |
|
| 166 |
+
| BananaMind Base Bench 1.1 Elo | 904 | 917 | -13 |
|
| 167 |
+
| BananaMind Base Bench 1.1 accuracy | 37.14% (130/350) | 40.86% (143/350) | -3.72 points |
|
| 168 |
+
| BananaMind Base Bench 1.1 weighted accuracy | 35.95% | 37.52% | -1.57 points |
|
| 169 |
+
|
| 170 |
+
### BananaMind Base Bench 1.1 category comparison
|
| 171 |
+
|
| 172 |
+
| Category | Ternary Elo | Nano Elo | Ternary accuracy | Nano accuracy | Ternary weighted | Nano weighted |
|
| 173 |
+
|---|---:|---:|---:|---:|---:|---:|
|
| 174 |
+
| Language completion | 963 | 1,147 | 58.00% | 80.00% | 58.28% | 80.25% |
|
| 175 |
+
| Commonsense | 828 | 865 | 32.00% | 38.00% | 33.12% | 37.85% |
|
| 176 |
+
| World knowledge | 869 | 895 | 36.00% | 46.00% | 38.24% | 41.69% |
|
| 177 |
+
| Context tracking | 832 | 804 | 32.00% | 26.00% | 28.34% | 25.16% |
|
| 178 |
+
| Quantitative | 785 | 881 | 20.00% | 32.00% | 18.30% | 28.08% |
|
| 179 |
+
| Logical reasoning | 1,043 | 1,043 | 46.00% | 46.00% | 42.32% | 42.32% |
|
| 180 |
+
| Code completion | 1,000 | 827 | 36.00% | 18.00% | 37.26% | 18.15% |
|
| 181 |
+
|
| 182 |
+
## Usage
|
| 183 |
+
|
| 184 |
+
This model uses custom architecture code. Load it with `trust_remote_code=True`.
|
| 185 |
+
|
| 186 |
+
```bash
|
| 187 |
+
pip install -U transformers safetensors torch
|
| 188 |
+
```
|
| 189 |
+
|
| 190 |
+
```python
|
| 191 |
+
import torch
|
| 192 |
+
from transformers import AutoModelForCausalLM, AutoTokenizer
|
| 193 |
+
|
| 194 |
+
model_id = "BananaMind/TernaryBananaMind-10M"
|
| 195 |
+
device = "cuda" if torch.cuda.is_available() else "cpu"
|
| 196 |
+
dtype = (
|
| 197 |
+
torch.bfloat16
|
| 198 |
+
if device == "cuda" and torch.cuda.is_bf16_supported()
|
| 199 |
+
else torch.float32
|
| 200 |
+
)
|
| 201 |
+
|
| 202 |
+
tokenizer = AutoTokenizer.from_pretrained(model_id, trust_remote_code=True)
|
| 203 |
+
model = AutoModelForCausalLM.from_pretrained(
|
| 204 |
+
model_id,
|
| 205 |
+
trust_remote_code=True,
|
| 206 |
+
dtype=dtype,
|
| 207 |
+
).to(device).eval()
|
| 208 |
+
|
| 209 |
+
inputs = tokenizer("The color of the sky is", return_tensors="pt").to(device)
|
| 210 |
+
with torch.inference_mode():
|
| 211 |
+
output = model.generate(
|
| 212 |
+
**inputs,
|
| 213 |
+
max_new_tokens=96,
|
| 214 |
+
do_sample=True,
|
| 215 |
+
temperature=0.7,
|
| 216 |
+
top_p=0.9,
|
| 217 |
+
pad_token_id=tokenizer.eos_token_id,
|
| 218 |
+
eos_token_id=tokenizer.eos_token_id,
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
print(tokenizer.decode(output[0], skip_special_tokens=True))
|
| 222 |
+
```
|
| 223 |
+
|
| 224 |
+
## License
|
| 225 |
+
|
| 226 |
+
Apache 2.0.
|
config.json
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"architecture_style": "bananamind2",
|
| 3 |
+
"architectures": [
|
| 4 |
+
"BananaAllForCausalLM"
|
| 5 |
+
],
|
| 6 |
+
"auto_map": {
|
| 7 |
+
"AutoConfig": "configuration_bananaall.BananaAllConfig",
|
| 8 |
+
"AutoModelForCausalLM": "modeling_bananaall_int8_v2.BananaAllForCausalLM"
|
| 9 |
+
},
|
| 10 |
+
"bos_token_id": 1,
|
| 11 |
+
"dtype": "float32",
|
| 12 |
+
"eos_token_id": 2,
|
| 13 |
+
"head_dim": 64,
|
| 14 |
+
"hidden_size": 256,
|
| 15 |
+
"intermediate_size": 704,
|
| 16 |
+
"lft": false,
|
| 17 |
+
"max_position_embeddings": 4096,
|
| 18 |
+
"model_type": "bananaall",
|
| 19 |
+
"num_attention_heads": 4,
|
| 20 |
+
"num_hidden_layers": 10,
|
| 21 |
+
"num_key_value_heads": 2,
|
| 22 |
+
"pad_token_id": 0,
|
| 23 |
+
"rms_norm_eps": 1e-06,
|
| 24 |
+
"rope_theta": 100000.0,
|
| 25 |
+
"ternary": true,
|
| 26 |
+
"tie_word_embeddings": false,
|
| 27 |
+
"transformers_version": "5.14.1",
|
| 28 |
+
"use_cache": false,
|
| 29 |
+
"vocab_size": 2048,
|
| 30 |
+
"packed_ternary": true,
|
| 31 |
+
"embedding_bits": 8
|
| 32 |
+
}
|
configuration_bananaall.py
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from transformers import PretrainedConfig
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class BananaAllConfig(PretrainedConfig):
|
| 5 |
+
model_type = "bananaall"
|
| 6 |
+
|
| 7 |
+
def __init__(self, vocab_size=8192, hidden_size=384, num_hidden_layers=14,
|
| 8 |
+
num_attention_heads=6, num_key_value_heads=2, head_dim=64,
|
| 9 |
+
intermediate_size=1024, max_position_embeddings=4096,
|
| 10 |
+
rope_theta=100000.0, rms_norm_eps=1e-6, architecture_style="bananamind2",
|
| 11 |
+
lft=False, ternary=False, packed_ternary=False, embedding_bits=None, **kwargs):
|
| 12 |
+
kwargs.setdefault("tie_word_embeddings", not packed_ternary)
|
| 13 |
+
super().__init__(**kwargs)
|
| 14 |
+
self.vocab_size = vocab_size
|
| 15 |
+
self.hidden_size = hidden_size
|
| 16 |
+
self.num_hidden_layers = num_hidden_layers
|
| 17 |
+
self.num_attention_heads = num_attention_heads
|
| 18 |
+
self.num_key_value_heads = num_key_value_heads
|
| 19 |
+
self.head_dim = head_dim
|
| 20 |
+
self.intermediate_size = intermediate_size
|
| 21 |
+
self.max_position_embeddings = max_position_embeddings
|
| 22 |
+
self.rope_theta = rope_theta
|
| 23 |
+
self.rms_norm_eps = rms_norm_eps
|
| 24 |
+
self.architecture_style = architecture_style
|
| 25 |
+
self.lft = lft
|
| 26 |
+
self.ternary = ternary
|
| 27 |
+
self.packed_ternary = packed_ternary
|
| 28 |
+
self.embedding_bits = embedding_bits
|
| 29 |
+
self.use_cache = False
|
dataset_tokens.json
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"dataset": "HuggingFaceFW/fineweb-edu",
|
| 4 |
+
"tokens": 2000000000
|
| 5 |
+
}
|
| 6 |
+
]
|
generation_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"_from_model_config": true,
|
| 3 |
+
"bos_token_id": 1,
|
| 4 |
+
"eos_token_id": [
|
| 5 |
+
2
|
| 6 |
+
],
|
| 7 |
+
"output_attentions": false,
|
| 8 |
+
"output_hidden_states": false,
|
| 9 |
+
"pad_token_id": 0,
|
| 10 |
+
"transformers_version": "5.14.1",
|
| 11 |
+
"use_cache": false
|
| 12 |
+
}
|
model.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:985dcd5f35ba63fbf02a77befe621de6d2d49fb1a9d12ab2a9c10d0550308fee
|
| 3 |
+
size 2175676
|
model_backup_full.safetensors
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:cb0a4d9036589c4eeaa0eececacc7847b3fe623de5e77cdc669bb9b2d29132bc
|
| 3 |
+
size 33722872
|
modeling_bananaall.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BananaMind 2 style decoder with optional LFT or ternary quantization.
|
| 2 |
+
|
| 3 |
+
The model uses pre-RMSNorm, RoPE, grouped-query attention and SwiGLU.
|
| 4 |
+
BananaMind 2 mode also applies QK norm. LFT changes only routing.
|
| 5 |
+
Packed mode keeps five ternary projection weights per byte and can store
|
| 6 |
+
input embeddings as int8 with a separate scale for each vocabulary row.
|
| 7 |
+
"""
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
from transformers import PreTrainedModel
|
| 14 |
+
from transformers.generation import GenerationMixin
|
| 15 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from .configuration_bananaall import BananaAllConfig
|
| 19 |
+
except ImportError:
|
| 20 |
+
from configuration_bananaall import BananaAllConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RMSNorm(nn.Module):
|
| 24 |
+
def __init__(self, size, eps=1e-6):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.weight = nn.Parameter(torch.ones(size))
|
| 27 |
+
self.eps = eps
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
y = x.float()
|
| 31 |
+
return (y * torch.rsqrt(y.square().mean(-1, keepdim=True) + self.eps) * self.weight.float()).to(x.dtype)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TernaryLinear(nn.Linear):
|
| 35 |
+
"""W1.58A8 fake quantization with straight-through gradients.
|
| 36 |
+
|
| 37 |
+
The master weights remain floating point for optimization and checkpoints.
|
| 38 |
+
This layer does not pack ternary weights or use a low-bit inference kernel.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
weights = self.weight.float()
|
| 43 |
+
weight_scale = weights.detach().abs().mean().clamp_min(1e-6)
|
| 44 |
+
quantized_weights = (weights / weight_scale).round().clamp(-1, 1) * weight_scale
|
| 45 |
+
fake_weights = self.weight + (quantized_weights.to(self.weight.dtype) - self.weight).detach()
|
| 46 |
+
|
| 47 |
+
activations = x.float()
|
| 48 |
+
activation_scale = activations.detach().abs().amax(dim=-1, keepdim=True).clamp_min(1e-6) / 127
|
| 49 |
+
quantized_activations = (activations / activation_scale).round().clamp(-127, 127) * activation_scale
|
| 50 |
+
fake_activations = x + (quantized_activations.to(x.dtype) - x).detach()
|
| 51 |
+
return F.linear(fake_activations, fake_weights, self.bias)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def unpack_ternary(packed, width, scale, dtype):
|
| 55 |
+
"""Decode five base-3 weights per byte, with values -1, 0, and 1."""
|
| 56 |
+
powers = torch.tensor((1, 3, 9, 27, 81), device=packed.device, dtype=torch.int32)
|
| 57 |
+
values = (packed.to(torch.int32).unsqueeze(-1) // powers) % 3 - 1
|
| 58 |
+
values = values.flatten(-2)[..., :width]
|
| 59 |
+
return (values.to(torch.float32) * scale).to(dtype)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class PackedTernaryLinear(nn.Module):
|
| 63 |
+
"""Packed resident weights; decoding creates a temporary compute tensor."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 66 |
+
super().__init__()
|
| 67 |
+
if bias:
|
| 68 |
+
raise ValueError("PackedTernaryLinear does not support bias")
|
| 69 |
+
self.in_features = in_features
|
| 70 |
+
self.out_features = out_features
|
| 71 |
+
self.register_buffer("packed_weight", torch.zeros(out_features, (in_features + 4) // 5, dtype=torch.uint8))
|
| 72 |
+
self.register_buffer("weight_scale", torch.ones((), dtype=torch.float32))
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
weight = unpack_ternary(self.packed_weight, self.in_features, self.weight_scale, x.dtype)
|
| 76 |
+
activations = x.float()
|
| 77 |
+
activation_scale = activations.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6) / 127
|
| 78 |
+
activations = (activations / activation_scale).round().clamp(-127, 127) * activation_scale
|
| 79 |
+
return F.linear(activations.to(x.dtype), weight)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class PackedTernaryEmbedding(nn.Module):
|
| 83 |
+
def __init__(self, num_embeddings, embedding_dim):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.num_embeddings = num_embeddings
|
| 86 |
+
self.embedding_dim = embedding_dim
|
| 87 |
+
self.register_buffer("packed_weight", torch.zeros(num_embeddings, (embedding_dim + 4) // 5, dtype=torch.uint8))
|
| 88 |
+
self.register_buffer("weight_scale", torch.ones((), dtype=torch.float32))
|
| 89 |
+
|
| 90 |
+
def forward(self, input_ids):
|
| 91 |
+
rows = self.packed_weight[input_ids]
|
| 92 |
+
return unpack_ternary(rows, self.embedding_dim, self.weight_scale, self.weight_scale.dtype)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Int8Embedding(nn.Module):
|
| 96 |
+
"""Signed 8-bit input embeddings with one float scale per vocabulary row."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, num_embeddings, embedding_dim):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.num_embeddings = num_embeddings
|
| 101 |
+
self.embedding_dim = embedding_dim
|
| 102 |
+
self.register_buffer("quantized_weight", torch.zeros(num_embeddings, embedding_dim, dtype=torch.int8))
|
| 103 |
+
self.register_buffer("weight_scale", torch.ones(num_embeddings, 1, dtype=torch.float32))
|
| 104 |
+
|
| 105 |
+
def forward(self, input_ids):
|
| 106 |
+
return self.quantized_weight[input_ids].to(self.weight_scale.dtype) * self.weight_scale[input_ids]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def apply_rope(x, theta, position_ids):
|
| 110 |
+
dim = x.shape[-1]
|
| 111 |
+
inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
|
| 112 |
+
angles = position_ids.float().unsqueeze(-1) * inv
|
| 113 |
+
cos = angles.cos().unsqueeze(1).to(x.dtype)
|
| 114 |
+
sin = angles.sin().unsqueeze(1).to(x.dtype)
|
| 115 |
+
even, odd = x[..., ::2], x[..., 1::2]
|
| 116 |
+
return torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1).flatten(-2)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class Attention(nn.Module):
|
| 120 |
+
def __init__(self, config):
|
| 121 |
+
super().__init__()
|
| 122 |
+
h, d, kv = config.num_attention_heads, config.head_dim, config.num_key_value_heads
|
| 123 |
+
self.h, self.d, self.kv, self.theta = h, d, kv, config.rope_theta
|
| 124 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 125 |
+
self.q_proj = linear(config.hidden_size, h * d, bias=False)
|
| 126 |
+
self.k_proj = linear(config.hidden_size, kv * d, bias=False)
|
| 127 |
+
self.v_proj = linear(config.hidden_size, kv * d, bias=False)
|
| 128 |
+
self.o_proj = linear(h * d, config.hidden_size, bias=False)
|
| 129 |
+
self.q_norm = RMSNorm(d, config.rms_norm_eps) if config.architecture_style == "bananamind2" else nn.Identity()
|
| 130 |
+
self.k_norm = RMSNorm(d, config.rms_norm_eps) if config.architecture_style == "bananamind2" else nn.Identity()
|
| 131 |
+
|
| 132 |
+
def forward(self, x, attention_mask=None):
|
| 133 |
+
b, t, _ = x.shape
|
| 134 |
+
q = self.q_norm(self.q_proj(x).view(b, t, self.h, self.d).transpose(1, 2))
|
| 135 |
+
k = self.k_norm(self.k_proj(x).view(b, t, self.kv, self.d).transpose(1, 2))
|
| 136 |
+
v = self.v_proj(x).view(b, t, self.kv, self.d).transpose(1, 2)
|
| 137 |
+
positions = torch.arange(t, device=x.device).unsqueeze(0)
|
| 138 |
+
q, k = apply_rope(q, self.theta, positions), apply_rope(k, self.theta, positions)
|
| 139 |
+
k = k.repeat_interleave(self.h // self.kv, dim=1)
|
| 140 |
+
v = v.repeat_interleave(self.h // self.kv, dim=1)
|
| 141 |
+
if attention_mask is None:
|
| 142 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 143 |
+
else:
|
| 144 |
+
causal = torch.ones(t, t, device=x.device, dtype=torch.bool).tril()
|
| 145 |
+
mask = causal[None, None] & attention_mask[:, None, None, :].bool()
|
| 146 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 147 |
+
return self.o_proj(y.transpose(1, 2).contiguous().view(b, t, self.h * self.d))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Block(nn.Module):
|
| 151 |
+
def __init__(self, config):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.norm1 = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 154 |
+
self.attn = Attention(config)
|
| 155 |
+
self.norm2 = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 156 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 157 |
+
self.gate_proj = linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 158 |
+
self.up_proj = linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 159 |
+
self.down_proj = linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 160 |
+
|
| 161 |
+
def forward(self, x, attention_mask=None):
|
| 162 |
+
x = x + self.attn(self.norm1(x), attention_mask)
|
| 163 |
+
z = self.norm2(x)
|
| 164 |
+
return x + self.down_proj(F.silu(self.gate_proj(z)) * self.up_proj(z))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class BananaAllForCausalLM(PreTrainedModel, GenerationMixin):
|
| 168 |
+
config_class = BananaAllConfig
|
| 169 |
+
base_model_prefix = "model"
|
| 170 |
+
_supports_sdpa = True
|
| 171 |
+
# forward() returns a mean loss per microbatch and ignores **kwargs.
|
| 172 |
+
# Tell Trainer to divide it by the gradient-accumulation count.
|
| 173 |
+
accepts_loss_kwargs = False
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 177 |
+
"""Use the weight file's layout even when a caller supplies a default config."""
|
| 178 |
+
packed_checkpoint = False
|
| 179 |
+
if isinstance(pretrained_model_name_or_path, (str, Path)):
|
| 180 |
+
checkpoint = Path(pretrained_model_name_or_path) / "model.safetensors"
|
| 181 |
+
if checkpoint.is_file():
|
| 182 |
+
from safetensors import safe_open
|
| 183 |
+
|
| 184 |
+
with safe_open(str(checkpoint), framework="pt", device="cpu") as weights:
|
| 185 |
+
keys = set(weights.keys())
|
| 186 |
+
if "layers.0.attn.q_proj.packed_weight" in keys:
|
| 187 |
+
packed_checkpoint = True
|
| 188 |
+
config = kwargs.get("config")
|
| 189 |
+
if not isinstance(config, cls.config_class):
|
| 190 |
+
config = cls.config_class.from_pretrained(pretrained_model_name_or_path)
|
| 191 |
+
config.ternary = True
|
| 192 |
+
config.packed_ternary = True
|
| 193 |
+
config.embedding_bits = 8 if "embed_tokens.quantized_weight" in keys else None
|
| 194 |
+
config.tie_word_embeddings = False
|
| 195 |
+
kwargs["config"] = config
|
| 196 |
+
if not packed_checkpoint:
|
| 197 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 198 |
+
|
| 199 |
+
return_loading_info = kwargs.get("output_loading_info", False)
|
| 200 |
+
kwargs["output_loading_info"] = True
|
| 201 |
+
model, loading_info = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 202 |
+
if loading_info["missing_keys"] or loading_info["unexpected_keys"]:
|
| 203 |
+
raise RuntimeError(
|
| 204 |
+
"Packed BananaAll checkpoint did not load cleanly: "
|
| 205 |
+
f"{len(loading_info['missing_keys'])} missing and "
|
| 206 |
+
f"{len(loading_info['unexpected_keys'])} unexpected keys"
|
| 207 |
+
)
|
| 208 |
+
return (model, loading_info) if return_loading_info else model
|
| 209 |
+
|
| 210 |
+
def __init__(self, config):
|
| 211 |
+
super().__init__(config)
|
| 212 |
+
if config.packed_ternary and config.embedding_bits == 8:
|
| 213 |
+
self.embed_tokens = Int8Embedding(config.vocab_size, config.hidden_size)
|
| 214 |
+
elif config.packed_ternary:
|
| 215 |
+
self.embed_tokens = PackedTernaryEmbedding(config.vocab_size, config.hidden_size)
|
| 216 |
+
else:
|
| 217 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 218 |
+
self.layers = nn.ModuleList([Block(config) for _ in range(config.num_hidden_layers)])
|
| 219 |
+
self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 220 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 221 |
+
self.lm_head = linear(config.hidden_size, config.vocab_size, bias=False)
|
| 222 |
+
self.post_init()
|
| 223 |
+
self.tie_weights()
|
| 224 |
+
|
| 225 |
+
def get_input_embeddings(self):
|
| 226 |
+
return self.embed_tokens
|
| 227 |
+
|
| 228 |
+
def set_input_embeddings(self, value):
|
| 229 |
+
self.embed_tokens = value
|
| 230 |
+
|
| 231 |
+
def get_output_embeddings(self):
|
| 232 |
+
return self.lm_head
|
| 233 |
+
|
| 234 |
+
def set_output_embeddings(self, value):
|
| 235 |
+
self.lm_head = value
|
| 236 |
+
|
| 237 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
|
| 238 |
+
x = self.embed_tokens(input_ids)
|
| 239 |
+
if self.config.lft and len(self.layers) > 1:
|
| 240 |
+
x = self.layers[0](x, attention_mask)
|
| 241 |
+
for i in range(1, len(self.layers)):
|
| 242 |
+
x = self.layers[i](x, attention_mask)
|
| 243 |
+
if i < len(self.layers) - 1:
|
| 244 |
+
x = self.layers[i - 1](x, attention_mask)
|
| 245 |
+
x = self.layers[i](x, attention_mask)
|
| 246 |
+
else:
|
| 247 |
+
for layer in self.layers:
|
| 248 |
+
x = layer(x, attention_mask)
|
| 249 |
+
logits = self.lm_head(self.norm(x))
|
| 250 |
+
loss = None
|
| 251 |
+
if labels is not None:
|
| 252 |
+
shifted_logits = logits[:, :-1, :].contiguous().float()
|
| 253 |
+
shifted_labels = labels[:, 1:].contiguous()
|
| 254 |
+
loss = F.cross_entropy(shifted_logits.view(-1, shifted_logits.size(-1)), shifted_labels.view(-1), ignore_index=-100)
|
| 255 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None)
|
| 256 |
+
|
| 257 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
|
| 258 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def register():
|
| 262 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 263 |
+
try:
|
| 264 |
+
AutoConfig.register("bananaall", BananaAllConfig)
|
| 265 |
+
except ValueError:
|
| 266 |
+
pass
|
| 267 |
+
try:
|
| 268 |
+
AutoModelForCausalLM.register(BananaAllConfig, BananaAllForCausalLM)
|
| 269 |
+
except ValueError:
|
| 270 |
+
pass
|
modeling_bananaall_int8_v2.py
ADDED
|
@@ -0,0 +1,270 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""BananaMind 2 style decoder with optional LFT or ternary quantization.
|
| 2 |
+
|
| 3 |
+
The model uses pre-RMSNorm, RoPE, grouped-query attention and SwiGLU.
|
| 4 |
+
BananaMind 2 mode also applies QK norm. LFT changes only routing.
|
| 5 |
+
Packed mode keeps five ternary projection weights per byte and can store
|
| 6 |
+
input embeddings as int8 with a separate scale for each vocabulary row.
|
| 7 |
+
"""
|
| 8 |
+
import math
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
import torch
|
| 11 |
+
from torch import nn
|
| 12 |
+
from torch.nn import functional as F
|
| 13 |
+
from transformers import PreTrainedModel
|
| 14 |
+
from transformers.generation import GenerationMixin
|
| 15 |
+
from transformers.modeling_outputs import CausalLMOutputWithPast
|
| 16 |
+
|
| 17 |
+
try:
|
| 18 |
+
from .configuration_bananaall import BananaAllConfig
|
| 19 |
+
except ImportError:
|
| 20 |
+
from configuration_bananaall import BananaAllConfig
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class RMSNorm(nn.Module):
|
| 24 |
+
def __init__(self, size, eps=1e-6):
|
| 25 |
+
super().__init__()
|
| 26 |
+
self.weight = nn.Parameter(torch.ones(size))
|
| 27 |
+
self.eps = eps
|
| 28 |
+
|
| 29 |
+
def forward(self, x):
|
| 30 |
+
y = x.float()
|
| 31 |
+
return (y * torch.rsqrt(y.square().mean(-1, keepdim=True) + self.eps) * self.weight.float()).to(x.dtype)
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class TernaryLinear(nn.Linear):
|
| 35 |
+
"""W1.58A8 fake quantization with straight-through gradients.
|
| 36 |
+
|
| 37 |
+
The master weights remain floating point for optimization and checkpoints.
|
| 38 |
+
This layer does not pack ternary weights or use a low-bit inference kernel.
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def forward(self, x):
|
| 42 |
+
weights = self.weight.float()
|
| 43 |
+
weight_scale = weights.detach().abs().mean().clamp_min(1e-6)
|
| 44 |
+
quantized_weights = (weights / weight_scale).round().clamp(-1, 1) * weight_scale
|
| 45 |
+
fake_weights = self.weight + (quantized_weights.to(self.weight.dtype) - self.weight).detach()
|
| 46 |
+
|
| 47 |
+
activations = x.float()
|
| 48 |
+
activation_scale = activations.detach().abs().amax(dim=-1, keepdim=True).clamp_min(1e-6) / 127
|
| 49 |
+
quantized_activations = (activations / activation_scale).round().clamp(-127, 127) * activation_scale
|
| 50 |
+
fake_activations = x + (quantized_activations.to(x.dtype) - x).detach()
|
| 51 |
+
return F.linear(fake_activations, fake_weights, self.bias)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
def unpack_ternary(packed, width, scale, dtype):
|
| 55 |
+
"""Decode five base-3 weights per byte, with values -1, 0, and 1."""
|
| 56 |
+
powers = torch.tensor((1, 3, 9, 27, 81), device=packed.device, dtype=torch.int32)
|
| 57 |
+
values = (packed.to(torch.int32).unsqueeze(-1) // powers) % 3 - 1
|
| 58 |
+
values = values.flatten(-2)[..., :width]
|
| 59 |
+
return (values.to(torch.float32) * scale).to(dtype)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
class PackedTernaryLinear(nn.Module):
|
| 63 |
+
"""Packed resident weights; decoding creates a temporary compute tensor."""
|
| 64 |
+
|
| 65 |
+
def __init__(self, in_features, out_features, bias=False):
|
| 66 |
+
super().__init__()
|
| 67 |
+
if bias:
|
| 68 |
+
raise ValueError("PackedTernaryLinear does not support bias")
|
| 69 |
+
self.in_features = in_features
|
| 70 |
+
self.out_features = out_features
|
| 71 |
+
self.register_buffer("packed_weight", torch.zeros(out_features, (in_features + 4) // 5, dtype=torch.uint8))
|
| 72 |
+
self.register_buffer("weight_scale", torch.ones((), dtype=torch.float32))
|
| 73 |
+
|
| 74 |
+
def forward(self, x):
|
| 75 |
+
weight = unpack_ternary(self.packed_weight, self.in_features, self.weight_scale, x.dtype)
|
| 76 |
+
activations = x.float()
|
| 77 |
+
activation_scale = activations.abs().amax(dim=-1, keepdim=True).clamp_min(1e-6) / 127
|
| 78 |
+
activations = (activations / activation_scale).round().clamp(-127, 127) * activation_scale
|
| 79 |
+
return F.linear(activations.to(x.dtype), weight)
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
class PackedTernaryEmbedding(nn.Module):
|
| 83 |
+
def __init__(self, num_embeddings, embedding_dim):
|
| 84 |
+
super().__init__()
|
| 85 |
+
self.num_embeddings = num_embeddings
|
| 86 |
+
self.embedding_dim = embedding_dim
|
| 87 |
+
self.register_buffer("packed_weight", torch.zeros(num_embeddings, (embedding_dim + 4) // 5, dtype=torch.uint8))
|
| 88 |
+
self.register_buffer("weight_scale", torch.ones((), dtype=torch.float32))
|
| 89 |
+
|
| 90 |
+
def forward(self, input_ids):
|
| 91 |
+
rows = self.packed_weight[input_ids]
|
| 92 |
+
return unpack_ternary(rows, self.embedding_dim, self.weight_scale, self.weight_scale.dtype)
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
class Int8Embedding(nn.Module):
|
| 96 |
+
"""Signed 8-bit input embeddings with one float scale per vocabulary row."""
|
| 97 |
+
|
| 98 |
+
def __init__(self, num_embeddings, embedding_dim):
|
| 99 |
+
super().__init__()
|
| 100 |
+
self.num_embeddings = num_embeddings
|
| 101 |
+
self.embedding_dim = embedding_dim
|
| 102 |
+
self.register_buffer("quantized_weight", torch.zeros(num_embeddings, embedding_dim, dtype=torch.int8))
|
| 103 |
+
self.register_buffer("weight_scale", torch.ones(num_embeddings, 1, dtype=torch.float32))
|
| 104 |
+
|
| 105 |
+
def forward(self, input_ids):
|
| 106 |
+
return self.quantized_weight[input_ids].to(self.weight_scale.dtype) * self.weight_scale[input_ids]
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
def apply_rope(x, theta, position_ids):
|
| 110 |
+
dim = x.shape[-1]
|
| 111 |
+
inv = 1.0 / (theta ** (torch.arange(0, dim, 2, device=x.device, dtype=torch.float32) / dim))
|
| 112 |
+
angles = position_ids.float().unsqueeze(-1) * inv
|
| 113 |
+
cos = angles.cos().unsqueeze(1).to(x.dtype)
|
| 114 |
+
sin = angles.sin().unsqueeze(1).to(x.dtype)
|
| 115 |
+
even, odd = x[..., ::2], x[..., 1::2]
|
| 116 |
+
return torch.stack((even * cos - odd * sin, even * sin + odd * cos), dim=-1).flatten(-2)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
class Attention(nn.Module):
|
| 120 |
+
def __init__(self, config):
|
| 121 |
+
super().__init__()
|
| 122 |
+
h, d, kv = config.num_attention_heads, config.head_dim, config.num_key_value_heads
|
| 123 |
+
self.h, self.d, self.kv, self.theta = h, d, kv, config.rope_theta
|
| 124 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 125 |
+
self.q_proj = linear(config.hidden_size, h * d, bias=False)
|
| 126 |
+
self.k_proj = linear(config.hidden_size, kv * d, bias=False)
|
| 127 |
+
self.v_proj = linear(config.hidden_size, kv * d, bias=False)
|
| 128 |
+
self.o_proj = linear(h * d, config.hidden_size, bias=False)
|
| 129 |
+
self.q_norm = RMSNorm(d, config.rms_norm_eps) if config.architecture_style == "bananamind2" else nn.Identity()
|
| 130 |
+
self.k_norm = RMSNorm(d, config.rms_norm_eps) if config.architecture_style == "bananamind2" else nn.Identity()
|
| 131 |
+
|
| 132 |
+
def forward(self, x, attention_mask=None):
|
| 133 |
+
b, t, _ = x.shape
|
| 134 |
+
q = self.q_norm(self.q_proj(x).view(b, t, self.h, self.d).transpose(1, 2))
|
| 135 |
+
k = self.k_norm(self.k_proj(x).view(b, t, self.kv, self.d).transpose(1, 2))
|
| 136 |
+
v = self.v_proj(x).view(b, t, self.kv, self.d).transpose(1, 2)
|
| 137 |
+
positions = torch.arange(t, device=x.device).unsqueeze(0)
|
| 138 |
+
q, k = apply_rope(q, self.theta, positions), apply_rope(k, self.theta, positions)
|
| 139 |
+
k = k.repeat_interleave(self.h // self.kv, dim=1)
|
| 140 |
+
v = v.repeat_interleave(self.h // self.kv, dim=1)
|
| 141 |
+
if attention_mask is None:
|
| 142 |
+
y = F.scaled_dot_product_attention(q, k, v, is_causal=True)
|
| 143 |
+
else:
|
| 144 |
+
causal = torch.ones(t, t, device=x.device, dtype=torch.bool).tril()
|
| 145 |
+
mask = causal[None, None] & attention_mask[:, None, None, :].bool()
|
| 146 |
+
y = F.scaled_dot_product_attention(q, k, v, attn_mask=mask)
|
| 147 |
+
return self.o_proj(y.transpose(1, 2).contiguous().view(b, t, self.h * self.d))
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
class Block(nn.Module):
|
| 151 |
+
def __init__(self, config):
|
| 152 |
+
super().__init__()
|
| 153 |
+
self.norm1 = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 154 |
+
self.attn = Attention(config)
|
| 155 |
+
self.norm2 = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 156 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 157 |
+
self.gate_proj = linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 158 |
+
self.up_proj = linear(config.hidden_size, config.intermediate_size, bias=False)
|
| 159 |
+
self.down_proj = linear(config.intermediate_size, config.hidden_size, bias=False)
|
| 160 |
+
|
| 161 |
+
def forward(self, x, attention_mask=None):
|
| 162 |
+
x = x + self.attn(self.norm1(x), attention_mask)
|
| 163 |
+
z = self.norm2(x)
|
| 164 |
+
return x + self.down_proj(F.silu(self.gate_proj(z)) * self.up_proj(z))
|
| 165 |
+
|
| 166 |
+
|
| 167 |
+
class BananaAllForCausalLM(PreTrainedModel, GenerationMixin):
|
| 168 |
+
config_class = BananaAllConfig
|
| 169 |
+
base_model_prefix = "model"
|
| 170 |
+
_supports_sdpa = True
|
| 171 |
+
# forward() returns a mean loss per microbatch and ignores **kwargs.
|
| 172 |
+
# Tell Trainer to divide it by the gradient-accumulation count.
|
| 173 |
+
accepts_loss_kwargs = False
|
| 174 |
+
|
| 175 |
+
@classmethod
|
| 176 |
+
def from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs):
|
| 177 |
+
"""Use the weight file's layout even when a caller supplies a default config."""
|
| 178 |
+
packed_checkpoint = False
|
| 179 |
+
if isinstance(pretrained_model_name_or_path, (str, Path)):
|
| 180 |
+
checkpoint = Path(pretrained_model_name_or_path) / "model.safetensors"
|
| 181 |
+
if checkpoint.is_file():
|
| 182 |
+
from safetensors import safe_open
|
| 183 |
+
|
| 184 |
+
with safe_open(str(checkpoint), framework="pt", device="cpu") as weights:
|
| 185 |
+
keys = set(weights.keys())
|
| 186 |
+
if "layers.0.attn.q_proj.packed_weight" in keys:
|
| 187 |
+
packed_checkpoint = True
|
| 188 |
+
config = kwargs.get("config")
|
| 189 |
+
if not isinstance(config, cls.config_class):
|
| 190 |
+
config = cls.config_class.from_pretrained(pretrained_model_name_or_path)
|
| 191 |
+
config.ternary = True
|
| 192 |
+
config.packed_ternary = True
|
| 193 |
+
config.embedding_bits = 8 if "embed_tokens.quantized_weight" in keys else None
|
| 194 |
+
config.tie_word_embeddings = False
|
| 195 |
+
kwargs["config"] = config
|
| 196 |
+
if not packed_checkpoint:
|
| 197 |
+
return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 198 |
+
|
| 199 |
+
return_loading_info = kwargs.get("output_loading_info", False)
|
| 200 |
+
kwargs["output_loading_info"] = True
|
| 201 |
+
model, loading_info = super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)
|
| 202 |
+
if loading_info["missing_keys"] or loading_info["unexpected_keys"]:
|
| 203 |
+
raise RuntimeError(
|
| 204 |
+
"Packed BananaAll checkpoint did not load cleanly: "
|
| 205 |
+
f"{len(loading_info['missing_keys'])} missing and "
|
| 206 |
+
f"{len(loading_info['unexpected_keys'])} unexpected keys"
|
| 207 |
+
)
|
| 208 |
+
return (model, loading_info) if return_loading_info else model
|
| 209 |
+
|
| 210 |
+
def __init__(self, config):
|
| 211 |
+
super().__init__(config)
|
| 212 |
+
if config.packed_ternary and config.embedding_bits == 8:
|
| 213 |
+
self.embed_tokens = Int8Embedding(config.vocab_size, config.hidden_size)
|
| 214 |
+
elif config.packed_ternary:
|
| 215 |
+
self.embed_tokens = PackedTernaryEmbedding(config.vocab_size, config.hidden_size)
|
| 216 |
+
else:
|
| 217 |
+
self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size)
|
| 218 |
+
self.layers = nn.ModuleList([Block(config) for _ in range(config.num_hidden_layers)])
|
| 219 |
+
self.norm = RMSNorm(config.hidden_size, config.rms_norm_eps)
|
| 220 |
+
linear = (PackedTernaryLinear if config.packed_ternary else TernaryLinear) if config.ternary else nn.Linear
|
| 221 |
+
self.lm_head = linear(config.hidden_size, config.vocab_size, bias=False)
|
| 222 |
+
self.post_init()
|
| 223 |
+
self.tie_weights()
|
| 224 |
+
|
| 225 |
+
def get_input_embeddings(self):
|
| 226 |
+
return self.embed_tokens
|
| 227 |
+
|
| 228 |
+
def set_input_embeddings(self, value):
|
| 229 |
+
self.embed_tokens = value
|
| 230 |
+
|
| 231 |
+
def get_output_embeddings(self):
|
| 232 |
+
return self.lm_head
|
| 233 |
+
|
| 234 |
+
def set_output_embeddings(self, value):
|
| 235 |
+
self.lm_head = value
|
| 236 |
+
|
| 237 |
+
def forward(self, input_ids=None, attention_mask=None, labels=None, **kwargs):
|
| 238 |
+
x = self.embed_tokens(input_ids)
|
| 239 |
+
if self.config.lft and len(self.layers) > 1:
|
| 240 |
+
x = self.layers[0](x, attention_mask)
|
| 241 |
+
for i in range(1, len(self.layers)):
|
| 242 |
+
x = self.layers[i](x, attention_mask)
|
| 243 |
+
if i < len(self.layers) - 1:
|
| 244 |
+
x = self.layers[i - 1](x, attention_mask)
|
| 245 |
+
x = self.layers[i](x, attention_mask)
|
| 246 |
+
else:
|
| 247 |
+
for layer in self.layers:
|
| 248 |
+
x = layer(x, attention_mask)
|
| 249 |
+
logits = self.lm_head(self.norm(x))
|
| 250 |
+
loss = None
|
| 251 |
+
if labels is not None:
|
| 252 |
+
shifted_logits = logits[:, :-1, :].contiguous().float()
|
| 253 |
+
shifted_labels = labels[:, 1:].contiguous()
|
| 254 |
+
loss = F.cross_entropy(shifted_logits.view(-1, shifted_logits.size(-1)), shifted_labels.view(-1), ignore_index=-100)
|
| 255 |
+
return CausalLMOutputWithPast(loss=loss, logits=logits, past_key_values=None)
|
| 256 |
+
|
| 257 |
+
def prepare_inputs_for_generation(self, input_ids, attention_mask=None, **kwargs):
|
| 258 |
+
return {"input_ids": input_ids, "attention_mask": attention_mask}
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
def register():
|
| 262 |
+
from transformers import AutoConfig, AutoModelForCausalLM
|
| 263 |
+
try:
|
| 264 |
+
AutoConfig.register("bananaall", BananaAllConfig)
|
| 265 |
+
except ValueError:
|
| 266 |
+
pass
|
| 267 |
+
try:
|
| 268 |
+
AutoModelForCausalLM.register(BananaAllConfig, BananaAllForCausalLM)
|
| 269 |
+
except ValueError:
|
| 270 |
+
pass
|
pack_ternary.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Convert the original checkpoint to ternary weights and 8-bit embeddings.
|
| 2 |
+
|
| 3 |
+
Run from this directory with: python pack_ternary.py
|
| 4 |
+
The source defaults to model_backup_full.safetensors. Its contents are never edited.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import json
|
| 8 |
+
import os
|
| 9 |
+
from pathlib import Path
|
| 10 |
+
|
| 11 |
+
import torch
|
| 12 |
+
from safetensors.torch import load_file, save_file
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
ROOT = Path(__file__).resolve().parent
|
| 16 |
+
SOURCE = ROOT / "model_backup_full.safetensors"
|
| 17 |
+
TARGET = ROOT / "model.safetensors"
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
def pack_matrix(weight):
|
| 21 |
+
weight = weight.float().contiguous()
|
| 22 |
+
scale = weight.abs().mean().clamp_min(1e-6)
|
| 23 |
+
trits = (weight / scale).round().clamp(-1, 1).to(torch.uint8) + 1
|
| 24 |
+
padding = (-trits.shape[1]) % 5
|
| 25 |
+
if padding:
|
| 26 |
+
trits = torch.nn.functional.pad(trits, (0, padding), value=1)
|
| 27 |
+
packed = trits.reshape(trits.shape[0], -1, 5).to(torch.int32)
|
| 28 |
+
powers = torch.tensor((1, 3, 9, 27, 81), dtype=torch.int32)
|
| 29 |
+
packed = (packed * powers).sum(dim=-1).to(torch.uint8)
|
| 30 |
+
return packed.contiguous(), scale.contiguous()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def quantize_embedding(weight):
|
| 34 |
+
weight = weight.float().contiguous()
|
| 35 |
+
scale = weight.abs().amax(dim=1, keepdim=True).clamp_min(1e-6) / 127
|
| 36 |
+
values = (weight / scale).round().clamp(-127, 127).to(torch.int8)
|
| 37 |
+
return values.contiguous(), scale.contiguous()
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def main():
|
| 41 |
+
if not SOURCE.is_file():
|
| 42 |
+
raise FileNotFoundError(SOURCE)
|
| 43 |
+
config_path = ROOT / "config.json"
|
| 44 |
+
config = json.loads(config_path.read_text())
|
| 45 |
+
if not config.get("ternary"):
|
| 46 |
+
raise ValueError("This converter requires a ternary model")
|
| 47 |
+
|
| 48 |
+
original = load_file(str(SOURCE), device="cpu")
|
| 49 |
+
converted = {}
|
| 50 |
+
for key, tensor in original.items():
|
| 51 |
+
if key == "embed_tokens.weight":
|
| 52 |
+
values, scale = quantize_embedding(tensor)
|
| 53 |
+
converted["embed_tokens.quantized_weight"] = values
|
| 54 |
+
converted["embed_tokens.weight_scale"] = scale
|
| 55 |
+
elif key.endswith("_proj.weight") or key == "lm_head.weight":
|
| 56 |
+
packed, scale = pack_matrix(tensor)
|
| 57 |
+
prefix = key.removesuffix(".weight")
|
| 58 |
+
converted[prefix + ".packed_weight"] = packed
|
| 59 |
+
converted[prefix + ".weight_scale"] = scale
|
| 60 |
+
else:
|
| 61 |
+
converted[key] = tensor.contiguous()
|
| 62 |
+
|
| 63 |
+
output = TARGET.with_suffix(".safetensors.tmp")
|
| 64 |
+
save_file(converted, str(output), metadata={"format": "pt", "quantization": "ternary_base3_5_per_byte_int8_embeddings"})
|
| 65 |
+
os.replace(output, TARGET)
|
| 66 |
+
config["packed_ternary"] = True
|
| 67 |
+
config["embedding_bits"] = 8
|
| 68 |
+
# The original file contains different embedding and output matrices.
|
| 69 |
+
config["tie_word_embeddings"] = False
|
| 70 |
+
config_path.write_text(json.dumps(config, indent=2) + "\n")
|
| 71 |
+
|
| 72 |
+
dense_count = sum(t.numel() for t in original.values())
|
| 73 |
+
print(f"Packed {len(original)} tensors: {TARGET.stat().st_size:,} bytes, {TARGET.stat().st_size * 8 / dense_count:.3f} bits per original weight")
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
if __name__ == "__main__":
|
| 77 |
+
main()
|
tokenizer.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
tokenizer_config.json
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"backend": "tokenizers",
|
| 3 |
+
"bos_token": "<|bos|>",
|
| 4 |
+
"clean_up_tokenization_spaces": false,
|
| 5 |
+
"eos_token": "<|eos|>",
|
| 6 |
+
"is_local": false,
|
| 7 |
+
"local_files_only": false,
|
| 8 |
+
"model_max_length": 4096,
|
| 9 |
+
"pad_token": "<|pad|>",
|
| 10 |
+
"tokenizer_class": "TokenizersBackend",
|
| 11 |
+
"unk_token": "<|unk|>"
|
| 12 |
+
}
|
training_args.bin
ADDED
|
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
version https://git-lfs.github.com/spec/v1
|
| 2 |
+
oid sha256:6ad084b45f303fa9aa9095826bf8050c17783addfabe1212438f8b1d59c396b8
|
| 3 |
+
size 5201
|