smart-tree / MODEL_CARD.md
PeetPedro's picture
Upload MODEL_CARD.md with huggingface_hub
a021b9b verified
|
Raw History Blame Contribute Delete
7.74 kB
---
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.