File size: 8,605 Bytes
d086025 | 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 266 267 268 269 270 271 272 273 274 275 276 277 | # TurboQuant Usage Guide
TurboQuant is a Rust library for research-grade vector quantization of LLM KV caches. It provides three benchmark/evaluation paths:
- `synthetic`: model-shaped random vectors
- `trace`: exported per-head safetensors traces
- `real-model`: true end-to-end decoder inference on lightweight ONNX models with iterative past-key-value reuse
Status: alpha. Suitable for local research, benchmarking, and integration experiments. Not a production inference backend.
## Installation
Add to `Cargo.toml`:
```toml
[dependencies]
turboquant = "0.1.1"
```
- Rust `1.87.0+` is required for the default CPU path.
- The experimental `gpu` feature depends on the Burn/WGPU stack and may require a newer stable Rust toolchain.
Feature flags:
- default: scalar CPU path plus runtime-dispatched SIMD
- `gpu`: experimental Burn/WGPU batch kernels
## Core Public API Types
| Type | Purpose | Notes |
|------|---------|-------|
| `TurboQuantMSE` | Reconstruction-oriented vector quantization | Unit-norm input contract |
| `TurboQuantProd` | Inner-product-oriented vector quantization | Requires `bit_width >= 2` |
| `BatchQuantizedMSE` / `BatchQuantizedProd` | Packed batch storage | Validate layout after deserialization |
| `QuantizedKVCache` / `MultiHeadKVCache` | Quantized KV cache helpers | Keys and values can be reconstructed |
| `KvTrace` | Trace loader for exported per-head workloads | Rejects invalid query positions |
| `RealModelRunner` | End-to-end ONNX decoder runner via `ort` / ONNX Runtime | CPU-oriented real-model path |
Runnable library examples:
```bash
cargo run --release --example basic_quantize
cargo run --release --example kv_cache
```
## Real-Model Support
The real-model path runs a true decoder loop:
- load a tokenizer and ONNX decoder bundle
- run prompt prefill
- run iterative decoding with explicit `past_key_values`
- compare exact cache reuse vs quantized cache reuse in the actual decode loop
The execution backend is ONNX Runtime on CPU via the Rust `ort` binding.
### Supported Lightweight Models
Verified end-to-end on the Rust real-model path:
- `distilgpt2`
- `HuggingFaceTB/SmolLM2-135M-Instruct`
Other decoder-only models can work if their exported ONNX bundle exposes:
- `input_ids`
- optional `attention_mask`, `position_ids`, `cache_position`, `use_cache_branch`
- `past_key_values.<layer>.{key,value}`
- `present.<layer>.{key,value}`
- `logits`
### Behavior Note (Quantized Path)
The quantized real-model path quantizes the cache in the real decode loop, then reconstructs float tensors before feeding them back into ONNX Runtime for the next step:
- KV storage metrics reflect the quantized cache representation
- generation quality reflects quantized-cache reuse
- ONNX Runtime still performs standard float attention math internally
This is true end-to-end model execution with quantized cache feedback, not a custom quantized attention kernel inside the ONNX runtime.
## ONNX Export Workflow
Pinned Python dependencies: see `assets/requirements-real-model.txt` (copied from `scripts/requirements-real-model.txt`). The Rust real-model path pulls ONNX Runtime CPU binaries through the `ort` crate on first build.
Setup:
```bash
python3 -m venv .venv
. .venv/bin/activate
pip install -r scripts/requirements-real-model.txt
```
Export a documented lightweight preset:
```bash
python3 scripts/export_hf_decoder_onnx.py \
--preset distilgpt2 \
--output-dir artifacts/distilgpt2-onnx
```
Export the verified SmolLM2 preset:
```bash
python3 scripts/export_hf_decoder_onnx.py \
--preset smollm2-135m-instruct \
--output-dir artifacts/smollm2-135m-instruct-onnx
```
Export an explicit model id:
```bash
python3 scripts/export_hf_decoder_onnx.py \
--model TinyLlama/TinyLlama-1.1B-Chat-v1.0 \
--output-dir artifacts/tinyllama-onnx
```
The export helper targets `text-generation-with-past` and defaults to `fp32`, which is the verified dtype on the CPU ONNX Runtime path.
## Benchmark CLI
Run via the `benchmark` example. The CLI reports `source` explicitly as `synthetic`, `trace`, or `real-model` to avoid confusing model-shaped workloads with true decoder runs.
Synthetic quick run:
```bash
cargo run --release --example benchmark -- --workload synthetic --quick
```
Trace run:
```bash
cargo run --release --example benchmark -- \
--workload trace \
--trace traces/example.safetensors
```
Real-model exact run:
```bash
cargo run --release --example benchmark -- \
--workload real-model \
--real-model-dir artifacts/distilgpt2-onnx \
--prompt "Summarize the role of a KV cache in one sentence." \
--real-eval-mode exact \
--max-new-tokens 16
```
Real-model quantized run:
```bash
cargo run --release --example benchmark -- \
--workload real-model \
--real-model-dir artifacts/distilgpt2-onnx \
--prompt "Summarize the role of a KV cache in one sentence." \
--real-eval-mode quantized \
--bits 4 \
--real-key-strategy prod \
--max-new-tokens 16
```
Real-model side-by-side comparison:
```bash
cargo run --release --example benchmark -- \
--workload real-model \
--real-model-dir artifacts/distilgpt2-onnx \
--prompt "Summarize the role of a KV cache in one sentence." \
--real-eval-mode compare \
--bits 4 \
--value-bits 4 \
--real-key-strategy prod \
--top-k 5 \
--max-new-tokens 16
```
Key flags:
| Flag | Meaning |
|------|---------|
| `--workload` | `synthetic`, `trace`, or `real-model` |
| `--quick` | fast synthetic run |
| `--trace <PATH>` | safetensors trace file for `trace` workload |
| `--real-model-dir <DIR>` | exported ONNX decoder bundle directory |
| `--prompt <TEXT>` | prompt text for real-model runs |
| `--real-eval-mode` | `exact`, `quantized`, or `compare` |
| `--bits <N>` | key quantization bit width |
| `--value-bits <N>` | value quantization bit width |
| `--real-key-strategy` | `prod` or `mse` |
| `--top-k <N>` | top-k agreement metric window |
| `--max-new-tokens <N>` | number of tokens to generate |
## One-Command Real-Model Eval
For a fuller end-to-end workflow, use the orchestration helper:
```bash
python3 scripts/run_real_model_eval.py \
--preset distilgpt2 \
--bits 2 4 8 \
--strategies prod mse
```
What it does:
- exports or reuses a real ONNX decoder bundle
- builds the Rust benchmark example once
- runs an exact baseline
- runs multiple exact-vs-quantized compare benchmarks
- writes raw JSON plus a markdown summary report under `artifacts/real-model-evals/`
Useful options:
```bash
python3 scripts/run_real_model_eval.py \
--model-dir artifacts/distilgpt2-onnx \
--prompts scripts/prompts/real_model_eval_prompts.jsonl \
--max-prompts 6 \
--max-new-tokens 24 \
--top-k 5 \
--bits 4 8 \
--strategies prod
```
The default prompt suite is included as an asset: `assets/real_model_eval_prompts.jsonl` (original location: `scripts/prompts/real_model_eval_prompts.jsonl`).
## Real-Model Metrics
`real-model` mode can report:
- next-token logit RMSE
- top-k agreement
- token match rate and divergence rate
- reference-token cross-entropy / perplexity
- latency
- tokens/sec
- exact vs quantized KV memory usage
For `compare` mode, cross-entropy is computed against the exact run's generated token at each shared step. This is a distribution-drift metric, not a dataset perplexity claim.
## Trace Workflow
The trace exporter is available for per-head analysis rather than full-model decode:
```bash
python3 scripts/export_hf_kv.py \
--model mistralai/Mistral-7B-Instruct-v0.3 \
--input prompts.txt \
--output traces/mistral_layer0_head0.safetensors \
--layer 0 \
--head 0
```
Then run:
```bash
cargo run --release --example benchmark -- \
--workload trace \
--trace traces/mistral_layer0_head0.safetensors
```
## Manual Smoke Test (Optional, Requires Exported Model)
```bash
TURBOQUANT_REAL_MODEL_DIR=artifacts/real-model-bundles/distilgpt2 \
cargo test --all-features manual_exported_real_model_smoke_test -- --ignored --nocapture
```
## Limitations
- The real-model backend is CPU-oriented and currently uses ONNX Runtime, not Burn.
- Quantized real-model evaluation reconstructs float past tensors before the next ONNX Runtime step.
- The WGPU/Burn path remains experimental and is primarily a batch-kernel benchmark surface.
- The core quantizer APIs assume unit-norm vectors; the real-model path handles raw KV tensors by storing norms separately.
- The verified real-model surface is limited to `distilgpt2` and `HuggingFaceTB/SmolLM2-135M-Instruct`.
- The repository does not provide production serving, observability, or deployment tooling.
|