File size: 7,742 Bytes
7fa8850 a021b9b 7fa8850 a021b9b 7fa8850 a021b9b 6dcb7c6 a021b9b 7fa8850 6dcb7c6 a021b9b 7fa8850 6dcb7c6 a021b9b 6dcb7c6 7fa8850 6dcb7c6 7fa8850 6dcb7c6 a021b9b 6dcb7c6 7fa8850 6dcb7c6 a021b9b 7fa8850 6dcb7c6 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 | ---
tags:
- rust
- quantization
- ternary
- bitnet
- ggml
- simd
- lora
- finetuning
- edge-ai
- binary-release
license: mit
library_name: smart-tree
---
# smart-tree — Ternary Inference Engine
🚀 **Production-ready binary for BitNet 1.58-bit / GGUF I2_S (type 36) inference with SIMD acceleration and LoRA-T fine-tuning**
## Overview
`smart-tree` is a standalone CLI and library for ultra-low-precision neural network inference. Designed specifically for **ternary weights ({-1, 0, +1})** encoded in GGUF's `I2_S` format (quantization type 36).
### Why Ternary?
| Aspect | Benefit |
|--------|---------|
| **Size** | 8× smaller than FP16 |
| **Speed** | Integer ADD replaces FMAC |
| **Energy** | ~12× less energy per MAC |
| **Quality** | Surprising resilience (straight-through estimator) |
## Installation
```bash
# Latest release
curl -LO https://huggingface.co/eightb/smart-tree/resolve/main/st
chmod +x st
./st --version
```
Or build from source:
```bash
git clone https://github.com/peterlodri-sec/smart-tree
cd smart-tree && cargo build --release
```
## Usage
### GGUF I2_S Validation
```bash
# Self-test roundtrip
./st gguf validate
# Output: Roundtrip: OK Bytes: 16
# Pack/unpack demonstration
./st gguf pack-test
# Input: [-1, 0, 1, 0, -1, 1, -1, 1]
# Packed: [19, 22]
# Output: [-1, 0, 1, 0, -1, 1, -1, 1]
```
### BitNetWave64 ↔ I2_S Conversion
```bash
# Convert 64-trit wave to I2_S hex (16 bytes)
./st gguf convert --wave AAAAAAAAAAAAAAAA:5555555555555555
# Output: Hex: 22222222222222222222222222222222
```
### Inspect GGUF Files
```bash
# Scan for I2_S tensors in a GGUF file
./st gguf inspect --file falcon3-3b-i2s.gguf --verbose
```
## Technical Details
### I2_S Encoding (GGUF Type 36)
- **4 trits per byte**, MSB-first within byte
- Trit encoding: `00=-1`, `01=0`, `10=+1`, `11=pad→0`
- Byte layout: `[trit0:bits6-7][trit1:bits4-5][trit2:bits2-3][trit3:bits0-1]`
- Fully compatible with **Falcon3-3B-I2_S**, **BitNet.cpp**, **llama.cpp**
### BitNetWave64 Structure
```rust
pub struct BitNetWave64 {
pub b_pos: u64, // Positive rail (popcnt ≈ 21)
pub b_neg: u64, // Negative rail (popcnt ≈ 21)
pub balance_permille: i16, // (pos-neg)*1000/(pos+neg)
pub box_norm_q8: u8, // sqrt(pos²+neg²)/sqrt(2)*256
}
```
### Scale Handling
Three strategies for dequantization:
```rust
pub enum I2SScaleSource {
Sidecar, // Embedded per-tensor scale
Global(f32), // Env PZ_I2S_SCALE or CLI override
Strict, // Error if no scale found
}
```
## Experiment 3: SIMD-Accelerated Ternary GEMM ✅
Integrated **FELIX SIMD hot-path engine** for blazing-fast ternary matrix multiplies:
### Backends
| Architecture | Instruction Set | Lanes | Throughput |
|--------------|-----------------|-------|------------|
| **AArch64** | NEON | 8 | ~4 cycles/64 trits |
| **x86_64** | SSE2/AVX2 | 8 | ~6 cycles/64 trits |
| **Any** | Portable SWAR | 4 | ~20 cycles/64 trits |
### API
```rust
use smart_tree::simd_ternary::{
i2s_unpack_to_trits,
simd_ternary_gemm_i2s,
simd_ternary_row_i2s,
simd_backend,
};
println!("Backend: {}", simd_backend()); // "NEON (AArch64)" on Mac/Apple Silicon
// Full matrix GEMM
simd_ternary_gemm_i2s(&weights_i2s, rows, cols, &activations, &mut output, scales);
// Autoregressive single-row (lowest latency)
let out_val = simd_ternary_row_i2s(&row_weights_i2s, &activations, scale);
```
### Performance Characteristics
- **Zero-allocation** hot path (stack buffers for ≤256 trits)
- **Cache-line aware** chunking (64 trits = 16 bytes = 1 L1 line)
- **Prefetch hints** for sequential layer traversal
- **Exact integer arithmetic** throughout (no FP in hot path)
## NEW: Experiment 4 — LoRA-T Fine-Tuning ✅
**LoRA-T: Low-Rank Adaptation for Ternary Weights**
Adapts QLoRA methodology to frozen ternary (BitNet 1.58-bit) bases:
- Freeze pretrained ternary weights (I2_S / BitNetWave64)
- Inject trainable low-rank adapters (A @ B) in FP32
- Forward: `y = W_ternary @ x + α * (A @ B) @ x`
- Gradient flows only through A, B (ranks typically 8-64)
- Fusion support for zero-overhead inference
Based on: Hu et al. "LoRA: Low-Rank Adaptation..." + Dettmers et al. "QLoRA"
### API
```rust
use smart_tree::lora_ternary::{
LoraTConfig, LoraAdapter, LoraTModel, LoraTTrainer,
lorat_qwen2_5_05b, lorat_small_test,
};
// Configure LoRA
let config = LoraTConfig {
rank: 16,
alpha: 16.0,
dropout: 0.1,
target_modules: vec!["q_proj".into(), "v_proj".into(), /* ... */],
fused_inference: true,
init_strategy: InitStrategy::Standard,
};
// Factory for Qwen2.5-0.5B
let mut model = lorat_qwen2_5_05b(config);
// Or small test model
let mut model = lorat_small_test(LoraTConfig { rank: 8, ..Default::default() });
// Training step
let mut trainer = LoraTTrainer::new(&mut model, 1e-4);
trainer.step(&[
("layers.0.self_attn.q_proj", &input_acts, &output_grads),
// ...
]);
// Inference: fuse adapters into base weights
for adapter in model.adapters.values() {
adapter.fuse_into(&mut base_weights);
}
// Now base_weights includes LoRA deltas — no extra compute at inference!
// Manual forward (alongside base model)
let mut out = vec![0.0f32; out_dim];
adapter.forward(&input, &mut out); // Adds α(A@B)x to base output
```
### Parameter Efficiency
| Model | Frozen Params | LoRA Params (r=16) | Ratio |
|-------|---------------|--------------------|-------|
| Qwen2.5-0.5B | ~500M | ~2.1M | 0.4% |
| Llama-3-8B | ~8B | ~4.2M | 0.05% |
### Initialization Strategies
- **Standard**: A ~ N(0, √(2/in_dim)), B = 0 (Hu et al.)
- **Balanced**: Both ~ N(0, 1/√rank) (SDXL style)
- **Orthogonal**: QR-factorized for numerical stability
## Integration
### As Rust Dependency
```toml
[dependencies]
smart-tree = { git = "https://github.com/peterlodri-sec/smart-tree" }
```
```rust
use smart_tree::gguf_interop::{I2SPacker, GgufI2SBridge};
use smart_tree::simd_ternary::{simd_ternary_gemm_i2s, simd_backend};
use smart_tree::lora_ternary::{lorat_qwen2_5_05b, LoraTTrainer, LoraTConfig};
// Low-level pack
let bytes = I2SPacker::pack_trits(&[-1, 0, 1, 0]);
let trits = I2SPacker::unpack_trits(&bytes);
// High-level bridge
let i2s = GgufI2SBridge::wave64_to_i2s(&wave)?;
let wave = GgufI2SBridge::i2s_to_wave64(&i2s)?;
// SIMD GEMM
println!("Running on: {}", simd_backend());
simd_ternary_gemm_i2s(&weights, rows, cols, &acts, &mut out, scales);
// LoRA-T fine-tuning
let mut model = lorat_qwen2_5_05b(LoraTConfig { rank: 16, ..Default::default() });
let mut trainer = LoraTTrainer::new(&mut model, 1e-4);
// ... training loop ...
// Deploy: fuse and serialize
for adapter in model.adapters.values() {
adapter.fuse_into(&mut base_weights);
}
```
## Testing
All cores validated:
```bash
cargo test --lib ternary_bridge # 7 tests - lossless bridges
cargo test --lib gguf_interop # 10 tests - GGUF I2_S roundtrips
cargo test --lib simd_ternary # 5 tests - SIMD GEMM correctness
cargo test --lib lora_ternary # 6 tests - LoRA-T forward/backward/fusion
```
## Related Work
- **[BitNet 1.58](https://arxiv.org/abs/2402.17764)**: Original ternary transformer
- **[Falcon3-I2_S](https://huggingface.co/tiiuae/Falcon3-3B-Instruct-GGUF)**: Reference GGUF I2_S model
- **[enthea](https://github.com/peterlodri-sec/enthea)**: Sister crate for quantized GEMM/attention
- **[FELIX Assembly](https://github.com/peterlodri-sec/felix-assembly)**: CPU-agnostic SIMD ISA
- **[LoRA](https://arxiv.org/abs/2106.09685)**: Low-Rank Adaptation
- **[QLoRA](https://arxiv.org/abs/2305.14314)**: Efficient Finetuning of Quantized LLMs
## License
MIT OR Apache-2.0
---
Part of the [**eightb**](https://huggingface.co/eightb) ecosystem. |