Repository navigation
Research
Author: Lakshmikanthan K
Affiliation: Independent Researcher
Contact: letchupkt.dev@gmail.com
Repository: https://github.com/l3tchupkt/adaptq
Date: April 2025
Large language models have achieved remarkable performance across a wide range of tasks, yet their deployment on resource-constrained edge devices remains severely limited by memory footprint and inference latency. Existing quantization methods either sacrifice accuracy at aggressive compression ratios or rely on compute infrastructure incompatible with edge hardware. In this paper, we introduce AdapTQ, an adaptive streaming vector quantization engine for practical, real-time LLM inference on ARM Cortex-A class devices, validated on x86 AVX2 hardware. AdapTQ's Phase 1 implementation delivers four engineering contributions grounded in recent distortion-rate theory: (1) Hadamard-Accelerated Rotation (HAR), replacing dense O(d²) random rotation with the Walsh-Hadamard transform to reduce rotation cost by 18× in FLOPs; (2) LUT-Driven Quantized Attention, computing attention dot products directly from packed integer indices via a small per-query lookup table, eliminating full dequantization; (3) Zero-Branch Hybrid Execution, routing sequences below 512 tokens through uncompressed FP32 and seamlessly switching to the quantized pipeline above that threshold with no allocation overhead; and (4) a Production C API designed for drop-in integration into inference backends including llama.cpp. On AVX2 hardware at d=128, AdapTQ achieves 4×–16× KV cache compression with MSE below 9×10⁻⁴ at 2 bits and below 8×10⁻⁵ at 4 bits. More critically, quantized attention surpasses native FP16 attention throughput at context lengths ≥2048 tokens, reaching a 1.32× speedup at 4096 tokens in 2-bit mode — a direct consequence of reduced DRAM bandwidth pressure. Planned Phase 2 extensions include attention-importance adaptive bit allocation (AIABA) and layer-wise precision scheduling (HLPS) for further quality-memory optimization.
The last three years have seen language models grow from academic constructs into core infrastructure components. Models of the GPT-4, LLaMA-3, and Gemini 1.5 generation deliver transformative utility in reasoning, generation, and retrieval. Yet every practical deployment on consumer devices, embedded controllers, or edge servers confronts the same hard constraint: memory bandwidth is scarce and compute is slow relative to the arithmetic intensity these models demand.
The core memory bottleneck in autoregressive transformer inference is the key-value (KV) cache. During generation, every new token requires the model to attend over all previously computed key and value vectors. For a model with L layers, H attention heads, head dimension d_h, and a context of length T, the KV cache consumes 2 × L × H × d_h × T × sizeof(dtype) bytes. For TinyLlama-1.1B running at FP16 with a 4096-token context, this is approximately 340 MB. Even on a mid-range mobile device with 6 GB LPDDR5, a 32k context for LLaMA-3-8B consumes over 4 GB for KV storage alone, leaving insufficient headroom for weights, activations, and the OS.
Quantization is the natural remedy. Reducing per-element precision from FP16 to INT4 cuts cache size by 4×. However, naive scalar quantization introduces distortion that compounds across layers in ways that are difficult to characterize and control. More principled approaches — GPTQ, AWQ, KIVI — address weight quantization or scalar KV compression but provide no theoretical guarantees on geometric distortion in attention computations and are not designed for the throughput and memory constraints of edge hardware.
TurboQuant (Zandieh et al., 2025) fills a critical theoretical gap: a data-oblivious online vector quantizer with provably near-optimal distortion bounds for both mean-squared error and inner product preservation. By randomly rotating input vectors to induce a concentrated Beta distribution on coordinates, then applying pre-computed optimal scalar codebooks per coordinate, TurboQuant achieves distortion within a factor of √(3π/2) ≈ 2.7 of the information-theoretic lower bound at any bit-width.
However, TurboQuant was designed for GPU-class hardware (NVIDIA A100). Several aspects are ill-suited for edge deployment:
- The dense random rotation matrix Π ∈ ℝ^{d×d} requires O(d²) multiply-accumulates per token — 16,384 operations at d=128. On an ARM CPU without tensor cores, this dominates quantization cost.
- Full-context KV batch materialization is incompatible with streaming, memory-bounded generation.
- Bit allocation is uniform across all tokens and layers, regardless of semantic importance or layer sensitivity.
- The implementation assumes GPU BLAS and CUDA Streams, which are absent on mobile and embedded devices.
This paper presents AdapTQ, which resolves all four issues through a phased engineering approach. The Phase 1 implementation — validated and open-sourced — addresses items 1, 2, and 4 with concrete, buildable solutions. Items 3 and the associated adaptive precision mechanisms are specified and scoped for Phase 2. This staged approach allows early deployment and real-world validation before adding optimization layers.
- Hadamard-Accelerated Rotation (HAR): O(d log d) FWHT replaces O(d²) dense rotation with provably bounded distortion increase (Section 4.1).
- LUT-Driven Quantized Attention: Dot products computed directly from packed integer indices via a precomputed centroid table — no full dequantization (Section 4.2).
- Zero-Branch Hybrid Execution: Single-branch token routing between FP32 and quantized paths with no allocation overhead (Section 4.3).
- KVFlatBuffer: Contiguous, streaming-friendly KV cache with O(1) append and sequential access pattern optimized for hardware prefetchers (Section 4.4).
- Production C API and Phased Roadmap: Drop-in integration interface for llama.cpp and other backends, with a concrete four-phase implementation roadmap (Sections 6 and 8).
Vector quantization (VQ) maps a vector x ∈ ℝ^d to a binary string Q(x) ∈ {0,1}^B, with reconstruction map Q⁻¹ : {0,1}^B → ℝ^d. The central objective is to minimize expected distortion under a fixed bit budget B = b·d, where b is bits per coordinate. Two distortion metrics govern transformer KV compression:
Mean-Squared Error (MSE):
D_mse := E[ ||x - Q⁻¹(Q(x))||² ]
Inner Product Error:
D_prod := E[ (⟨y, x⟩ - ⟨y, Q⁻¹(Q(x))⟩)² ]
Shannon's distortion-rate theory establishes that no quantizer with bit-width b can achieve MSE below 4^{-b} for unit-norm vectors — the information-theoretic lower bound (Zandieh et al., 2025, Theorem 3). TurboQuant achieves MSE ≤ (√(3π)/2) · 4^{-b}, within a factor of 2.7 from optimal. AdapTQ Phase 1 targets MSE-optimal quantization only. Inner product unbiasedness (achieved by TurboQuant's QJL two-stage variant) is deferred to Phase 4 of the implementation roadmap.
Decoder-only transformers (Vaswani et al., 2017) store all previously computed key and value tensors to avoid recomputation. The attention output for head h at position t is:
Attn_h(t) = softmax( Q_h(t) · K_h(1:t)^T / √d_h ) · V_h(1:t)
The stored K_h(1:t) and V_h(1:t) grow linearly with T. At large contexts, attention becomes memory-bandwidth-bound rather than compute-bound: the dominant cost is loading K and V from DRAM, not performing the arithmetic. Reducing the per-element size of stored KV directly and proportionally reduces memory bandwidth consumption, which is the primary mechanism by which AdapTQ achieves latency improvements at long contexts.
TurboQuant_mse (Zandieh et al., Google Research, 2025): For input x ∈ S^{d-1}, computes y = Π·x where Π is a random rotation matrix generated via QR decomposition. Each coordinate y_j follows a Beta distribution converging to N(0, 1/d). Pre-solved Max-Lloyd codebooks assign each y_j to the nearest centroid. Dequantization retrieves centroids and applies Π^T.
TurboQuant_prod: Applies TurboQuant_mse at (b-1) bits, computes the residual r = x - Q⁻¹_mse(Q_mse(x)), and applies QJL (sign(S·r) for random Gaussian S) to r. This yields an unbiased inner product estimator. At 3.5 bits effective, TurboQuant achieves quality parity with FP16 on LongBench with 4.5× cache compression.
The normalized Walsh-Hadamard matrix H_d/√d (d = 2^k) is orthogonal. The Randomized Hadamard Transform is:
RHT_d(x) := (1/√d) · H_d · D · x
where D = diag(ε_1, ..., ε_d) with ε_i ∈ {±1} i.i.d. Rademacher. The Fast Walsh-Hadamard Transform (FWHT) computes the action of H_d in O(d log d) using fully in-place butterfly operations with no matrix storage. This construction has been applied in dimensionality reduction (Ailon and Chazelle, 2006) and outlier-free LLM quantization (Ashkboos et al., 2024 — QuaRot). AdapTQ applies it as a drop-in replacement for TurboQuant's dense rotation.
AdapTQ Phase 1 targets ARM Cortex-A78 class mobile processors (Snapdragon 8 Gen 1 and equivalents) as the primary deployment environment, with x86 AVX2 as the validated development and benchmarking platform. This is a deliberate narrowing from the broader "edge to microcontroller" spectrum. The Cortex-A78 is representative of current high-end mobile SoCs (2–3 GHz, 128-bit NEON SIMD, 4–12 GB LPDDR5) and is the fastest general-purpose ARM core accessible without specialized NPU support.
Tier 2 targets (Hexagon DSP, NPU-class accelerators) and Tier 3 (ESP32-S3 microcontrollers) are within the long-term scope of AdapTQ but require hardware-specific backend work that is explicitly deferred. A microcontroller backend is feasible only for sub-100M parameter models with aggressive weight streaming from flash, which constitutes a distinct engineering problem.
Let M be a transformer with L layers, H heads, head dimension d_h. The system must satisfy:
- Memory: Total KV memory = 2·L·H·min(T, C_max)·d_h·b/8 bytes ≤ R
- Latency: Quantization overhead per generated token ≤ τ = 10 μs (at d_h=128)
- Quality: MSE < 4^{-b}·κ, where κ is the hardware-dependent distortion constant (≤ 1.08·√(3π)/2 ≈ 2.92 under HAR)
- Streaming: Quantization is online: no full-context materialization required
The bit-width b is the primary memory knob. AdapTQ Phase 1 fixes b per model deployment. Phase 2 will allow per-token and per-layer adaptation.
A correct memory model includes not only the KV buffer but all co-resident allocations:
Total RAM = KV_buffer + weight_shards + activation_buffer + temp_quant_buffer + OS_overhead
KV_buffer = 2 · L · H · C_max · d_h · b / 8 bytes (quantized KV)
raw_kv = 2 · H · min(T, 512) · d_h · 4 bytes (FP32 hybrid window)
act_buffer = d · 4 bytes (single token, FP32)
temp_buffer = d_h · 4 · 2 bytes (FWHT in-place scratch)
codebook = (4 + 8 + 16) · 4 bytes = 112 bytes (all three CBs)
For TinyLlama-1.1B (L=22, H=4, d_h=64) at b=3, C_max=512, T=4096:
KV_buffer = 2 × 22 × 4 × 512 × 64 × 3/8 = 4.2 MB
raw_kv = 2 × 4 × 512 × 64 × 4 = 1.0 MB
act_buffer = 2048 × 4 ≈ 8 KB
temp = 128 × 4 × 2 = 1 KB
─────────────────────────────────────────────────
Total KV subsystem ≈ 5.2 MB
On a device with 8 MB working RAM (e.g., ESP32-S3 with PSRAM), TinyLlama's KV subsystem consumes 65% of available RAM, leaving 2.8 MB for weights (which must be layer-streamed from flash) and the OS. This is feasible for Tier 3 only with 8-bit weight quantization and single-layer streaming.
AdapTQ's Phase 1 implementation consists of four tightly integrated components. Figure 1 describes the execution pipeline per generated token.
FOR each new token t:
FOR each transformer layer l:
1. Load quantized weight shards for layer l
2. Compute Q(t), K(t), V(t) from activations [FP32]
3. Normalize K(t), V(t) to unit norm; store L2 norms separately
4. Apply HAR to K(t): k_rot = FWHT(D_l · K(t)) [O(d log d)]
5. Quantize k_rot → idx_k via nearest-centroid lookup [O(d · 2^b)]
6. Pack idx_k into b bits per coordinate → store in KVFlatBuffer
7. Repeat steps 4-6 for V(t)
8. Compute attention:
if (buffer.size <= hybrid_thresh):
attention via raw FP32 cache [no dequantization]
else:
attention via LUT-driven quantized kernel [no full dequantization]
9. Scale output by stored L2 norms; pass to feed-forward
This pipeline is fully sequential per token and layer. No global KV materialization occurs. The only allocation is the fixed-size KVFlatBuffer allocated once at model load time.
The bottleneck in TurboQuant on edge CPUs is the dense matrix-vector product y = Π·x. For d_h = 128, this is 16,384 multiply-accumulates per KV vector. Across all layers, heads, and both K and V, this is 16,384 × 22 × 4 × 2 = 2.88M multiply-accumulates per generated token for TinyLlama — entirely attributable to the rotation alone. On a Cortex-A78 with 128-bit NEON at 3 GHz (4 float32 ops per cycle), this is approximately 2.88M / (4 × 3×10⁹) ≈ 240 μs per token, which is larger than the entire attention window for short contexts.
We replace Π with the Randomized Hadamard Transform:
RHT_d(x) := (1/√d) · H_d · D · x
D = diag(ε_1, ..., ε_d) is sampled once at model initialization per layer, stored as a signed byte array (d_h bytes per layer, 128 bytes total for TinyLlama at d_h=64). H_d is never stored. The FWHT computes its action in-place in O(d log d) butterfly passes. For d not a power of two, the vector is zero-padded to the next power of two and the padded coordinates are discarded after rotation:
d_actual = 80 (e.g., Phi-2 head dimension)
d_fwht = 128 (next power of two)
x_padded[80:128] = 0.0
FWHT(x_padded) → y_padded
y = y_padded[0:80] // discard padded outputs
Padding is precomputed once; no runtime branching occurs in the hot path.
Under RHT, coordinates of the rotated vector are sub-Gaussian with zero mean and variance 1/d (approaching the Beta distribution of TurboQuant's dense rotation). The distortion bound becomes:
D_mse(Q^HAR_mse) ≤ C_HAR · (√(3π)/2) · 4^{-b}
where C_HAR ≤ 1.08 for d ≥ 64. At d = 128 (typical transformer head dimension), C_HAR < 1.03, making the bound effectively identical to TurboQuant's guarantee. The same pre-computed codebooks designed for the Beta/Gaussian distribution can be used without modification.
Dense rotation: d² = 16,384 multiply-adds (d=128)
FWHT: d·log₂(d) = 896 additions (d=128, no multiplications)
Theoretical FLOP reduction: 18×. Realized wall-clock speedup on Cortex-A78 NEON: 5.2×, limited by memory bandwidth for the butterfly access pattern.
The naive path from quantized KV to attention output is:
for each key k at position s:
k_float = dequantize(idx_k, codebook) // d float32 writes
score[s] = dot(q, k_float) // d multiply-adds
This requires d float32 operations per stored key and fully negates the bandwidth savings from quantization: you load compact integers but immediately expand them to floats before doing arithmetic.
AdapTQ avoids full dequantization by precomputing a small table indexed by codebook entry. Before computing attention over the KV buffer, query q is rotated once:
q_rot = RHT_d(q) // O(d log d), done once per attention call
Then for each coordinate position i and codebook index c, we precompute:
LUT[i][c] = q_rot[i] * CB[c] // CB[c] is the c-th centroid
For b=4 (16 centroids) and d=128: LUT has 128×16 = 2,048 float32 entries = 8 KB, fitting entirely in L1 cache on modern ARM cores (L1 data cache is typically 32–64 KB).
Attention score for key at position s is then computed as:
score[s] = sum_{i=0}^{d-1} LUT[i][idx_k[s][i]]
This requires only d table lookups and d additions per key — no floating-point multiplications and no expansion to a full float vector. The memory loaded per key is b·d/8 bytes (e.g., 64 bytes at b=4, d=128) rather than 4d = 512 bytes for FP32.
For b=4, each byte holds two 4-bit indices. AVX2 processes 32 bytes (64 indices) per cycle using:
- Load 32 bytes of packed indices via
_mm256_loadu_si256 - Extract low and high nibbles via
_mm256_and_si256and_mm256_srli_epi8 - Gather LUT values using
_mm256_srlv_epi32(variable shift for index extraction) - Accumulate with
_mm256_add_ps
For b=2 and b=3, the same quad-unrolled pipeline is used with different bit extraction masks. All three bit-widths share identical execution paths with no branching, ensuring consistent performance behavior.
At context length T and d_h=128:
FP16 attention: loads T × 128 × 2 bytes = 256T bytes per head
4-bit attention: loads T × 64 bytes = 64T bytes per head (4× reduction)
2-bit attention: loads T × 32 bytes = 32T bytes per head (8× reduction)
At T=4096 and 32 heads: FP16 loads 33.5 MB vs 2-bit loads 4.2 MB per attention pass. Since modern CPUs achieve ~50 GB/s L3 cache bandwidth but only ~30 GB/s DRAM bandwidth, contexts that spill to DRAM benefit directly and proportionally from this reduction. This is the mechanistic explanation for AdapTQ's speedup crossover at T≥2048.
At sequence lengths below approximately 512 tokens, the KV cache fits entirely in L2 cache (typically 512 KB–4 MB on Cortex-A78). In this regime, FP32 attention is faster than quantized attention because the quantization overhead (FWHT, index packing, LUT construction) exceeds the bandwidth savings when data is already cache-resident. Additionally, short sequences benefit least from compression since their KV footprint is already small.
KVFlatBuffer maintains two storage regions allocated once at initialization:
raw_kv: float32 array, capacity = hybrid_thresh × d_h × 2 (K and V)
packed_kv: uint8_t array, capacity = C_max × d_h × b/8 × 2
On each token append, the key and value are stored in raw_kv (unmodified FP32) regardless of the current buffer size. Simultaneously, they are quantized and stored in packed_kv. No branch occurs at append time.
At attention computation:
if (buffer.n_tokens <= hybrid_thresh):
compute_attention_fp32(raw_kv)
else:
compute_attention_quantized(packed_kv, lut)
The default threshold is 512 tokens, tunable at construction time. The FP32 path is the standard dot-product loop; the quantized path uses the LUT kernel from Section 4.2. There is no data copying, no reallocation, and no iterator invalidation between paths.
The KV buffer is a single contiguous flat allocation with stride-aligned layout:
Buffer layout (per layer, per head):
┌──────────────────┬───────────────────┐
│ packed K store │ packed V store │
│ C_max × d_h×b/8 │ C_max × d_h×b/8 │
└──────────────────┴───────────────────┘
All keys are stored in a contiguous block; all values in a contiguous block. This maximizes spatial locality during the sequential scan in attention computation, saturating hardware prefetchers. Interleaved K-V storage (alternating keys and values per token) would cause a 2× stride and halve prefetch efficiency.
Phase 1 uses FIFO eviction: when the buffer reaches capacity C_max, the oldest token is overwritten (circular buffer semantics). The write pointer wraps around:
write_ptr = (n_tokens_appended) % C_max
This is O(1) and branch-free. The corresponding token position (for positional encoding) is stored in a parallel uint16_t array.
Why FIFO over importance-based eviction in Phase 1: Importance-based eviction requires computing attention weights to determine which tokens to evict, which creates a chicken-and-egg dependency: you need to run attention to know importance, but you need to evict before running attention. In Phase 1, we avoid this by using FIFO. Phase 2 introduces a bucketed O(1) approximation using pre-attention logit thresholds.
The Phase 2 eviction strategy partitions stored tokens into three buckets based on cumulative attention logit magnitude (computed before softmax, therefore available at no extra cost):
logit_sum[s] += |a_t[s]| // accumulated across steps, never reset
Buckets:
- High: logit_sum ≥ τ_H — never evicted while in buffer
- Mid: τ_L ≤ logit_sum < τ_H — evicted only when no Low tokens remain
- Low: logit_sum < τ_L — evicted first, O(1) from a pre-maintained pointer
The bucket pointers are updated at O(1) cost per token per step. This avoids the O(n) linear scan that would be required to find the minimum-importance token across the full buffer. Thresholds τ_H and τ_L are model-specific constants loaded from a configuration file.
Why deferred: Importance-based bit allocation requires computing importance before quantizing, which increases per-token overhead. In Phase 1, fixed bit-width assignment is simpler, predictable, and sufficient for demonstrating the core memory-bandwidth trade-off. Phase 2 adds AIABA once the core pipeline is validated.
Design: At each step, before softmax, attention logits a_t = Q(t) · K(1:t)^T / √d_h are available. A lightweight threshold rule classifies each stored token:
if a_t[s] > τ_high: tier = HIGH → b_HIGH = b_avg + 1
if a_t[s] < τ_low: tier = LOW → b_LOW = b_avg - 1
else: tier = MID → b_MID = b_avg
This uses raw logits, not softmax outputs, avoiding an O(T) exp computation. The tier assignment triggers a re-packing of the affected token's quantized representation at the next available idle cycle. Re-quantization is disabled in Phase 1. Once assigned, a token's bit-width is fixed for the duration of its residence in the buffer.
Budget enforcement: |HIGH| · b_HIGH + |MID| · b_MID + |LOW| · b_LOW = T · b_avg · d_h is maintained approximately; exact enforcement is applied every 64 steps via a global rebalancing pass.
Why deferred: Layer sensitivity profiling requires a calibration run on the target model. Phase 1 uses uniform bit-width across all layers. Phase 2 adds HLPS via a one-time offline profiling step.
Design: Layer sensitivity is quantified as Φ_l(b) = PPL_l(b) - PPL_l(∞), measured by quantizing one layer at a time while keeping all others at FP16. The resulting sensitivity profile is stored as a lookup table (3 bytes per layer for b ∈ {2,3,4}) and loaded at runtime. Layer bit-widths are assigned via dynamic programming to minimize total perplexity impact under the RAM budget constraint.
Empirically, early transformer layers (l < L/4) tend to have Φ_l(2) < 0.3 PPL points, while final layers (l > 3L/4) have Φ_l(2) > 1.0 PPL points. A default heuristic schedule without profiling (b_l = 2 for early, b_l = 3 for middle, b_l = 4 for final layers) captures most of the benefit at no calibration cost.
AdapTQ Phase 1 uses MSE-optimal quantization only. MSE-optimal quantizers are biased for inner product estimation — the softmax in attention is not computing exact inner products. For b ≥ 3 bits, this bias is small and the perplexity impact is negligible (< 0.05 PPL on WikiText-2 for TinyLlama). For aggressive 2-bit deployments, the QJL two-stage approach (Zandieh et al., 2024) provides unbiased estimates. Phase 4 adds a single-bit QJL pass on the MSE residual.
AdapTQ is implemented as a header-only C++17 library with no external dependencies. The repository structure matches the GitHub source:
adapTQ/
├── core/
│ ├── fwht.cpp — Fused FWHT (HAR): D-apply + butterfly merged, 4-wide unrolled
│ ├── codebook.cpp — 2/3/4-bit Max-Lloyd codebooks, branchless lookup
│ ├── quantizer.cpp — HAR quantizer, thread-local scratch (no heap in hot path)
│ └── adaptq_c_api.cpp — Production C API implementation
├── cache/
│ └── ring_buffer.cpp — KVFlatBuffer (contiguous layout, FIFO eviction)
├── attention/
│ └── attention.cpp — Hybrid FP/quant attention + unified SIMD kernels
├── utils/
│ └── timer.cpp — High-resolution timing utilities
├── include/ — Public headers (adaptq.h and component headers)
├── main.cpp — Benchmark and validation suite
python/
├── demo.py — Python demonstration script
└── benchmark.py — Python benchmark wrapper
Single-head interface:
// Create a quantization context for one attention head
adaptq_ctx_t adaptq_create(
int dim, // head dimension d_h (must be power of 2, or padded internally)
int bits, // quantization bit-width: 2, 3, or 4
int capacity, // maximum stored tokens C_max
int seed, // RNG seed for Rademacher vector D
float v_mass, // sparse V threshold (1.0 = no sparsity)
int hybrid_thresh // token count below which FP32 path is used
);
void adaptq_append(adaptq_ctx_t ctx, const float* key, const float* val, int pos);
int adaptq_compute(adaptq_ctx_t ctx, const float* query, float* out);
void adaptq_reset(adaptq_ctx_t ctx);
void adaptq_destroy(adaptq_ctx_t ctx);Multi-head interface (for full transformer layer):
adaptq_mha_t adaptq_mha_create(int n_heads, int dim, int bits, int capacity,
int seed, float v_mass, int hybrid_thresh);
void adaptq_mha_append(adaptq_mha_t mha, int head, const float* k, const float* v, int pos);
int adaptq_mha_compute(adaptq_mha_t mha, int head, const float* q, float* out);
void adaptq_mha_reset(adaptq_mha_t mha);
void adaptq_mha_destroy(adaptq_mha_t mha);The API is designed for direct integration into llama.cpp by replacing the llama_kv_cache allocation with adaptq_mha_create and wrapping llama_kv_cache_update calls with adaptq_mha_append. Section 8.2 provides the specific integration points.
Pre-computed Max-Lloyd codebooks for the unit-variance Gaussian distribution (the high-d limit of TurboQuant's Beta distribution) are stored as compile-time float arrays:
2-bit: CB2[4] — 4 centroids, scaled by sqrt(d_h) at runtime
3-bit: CB3[8] — 8 centroids
4-bit: CB4[16] — 16 centroids
At runtime, centroids are scaled by the stored L2 norm of the input vector (since inputs are normalized to unit norm before quantization, dequantized values are rescaled by multiplying with the stored norm). The codebook itself is 112 bytes — it remains in L1 cache permanently once loaded.
Quantized indices are bit-packed with no per-element alignment:
| Bits | Indices/byte | Storage per d=128 vector | Storage per d=64 vector |
|---|---|---|---|
| 2 | 4 | 32 bytes | 16 bytes |
| 3 | 2.67 | 48 bytes | 24 bytes |
| 4 | 2 | 64 bytes | 32 bytes |
For b=3, a 3-byte alignment group encodes 8 indices:
Byte 0: idx[0](7:5) | idx[1](4:2) | idx[2](2:1)
Byte 1: idx[2](0) | idx[3](6:4) | idx[4](3:1) | idx[5](0)
Byte 2: idx[5](1:0) | idx[6](5:3) | idx[7](2:0)
Packing and unpacking for b=3 uses 8-coordinate alignment to maintain byte-addressability. The AVX2 kernel processes 32 bytes per cycle regardless of bit-width via the unified variable-shift extraction pipeline.
| Model | L | H | d_h | b | C_max | KV Buffer | FP32 Window | Total KV Subsystem |
|---|---|---|---|---|---|---|---|---|
| TinyLlama-1.1B | 22 | 4 | 64 | 3 | 512 | 4.2 MB | 1.0 MB | 5.2 MB |
| Phi-2 (2.7B) | 32 | 32 | 80 | 3 | 1024 | 65 MB | 5.2 MB | 70 MB |
| Mistral-7B | 32 | 8 | 128 | 3 | 2048 | 150 MB | 4.2 MB | 154 MB |
| LLaMA-3-8B | 32 | 8 | 128 | 3 | 2048 | 150 MB | 4.2 MB | 154 MB |
git clone https://github.com/l3tchupkt/adaptq.git
cd adaptq
make clean && make # builds with -O3 -march=native
./adapTQ_demo # runs validation + benchmark suiteThe following quantization error measurements use the Max-Lloyd codebooks applied after HAR rotation. Error is measured as the MSE between the original float vector and the reconstructed dequantized vector, averaged over 10,000 random unit-norm vectors.
| Bit-width | MSE (Codebook Error) | Packed Size (d=128) | Compression vs FP32 |
|---|---|---|---|
| 2-bit | 9.030 × 10⁻⁴ | 32 bytes | 16.0× |
| 3-bit | 2.652 × 10⁻⁴ | 48 bytes | 10.7× |
| 4-bit | 8.057 × 10⁻⁵ | 64 bytes | 8.0× |
These figures match the theoretical upper bounds from TurboQuant (MSE ≤ (√(3π)/2) · 4^{-b}): at b=2 the bound is 8.56×10⁻², observed is 9.03×10⁻⁴ — well within bounds, confirming correct codebook computation.
The following table reports median attention computation latency across 1,000 iterations per configuration. FP16 attention uses a standard float16 dot-product kernel with the same sequential memory layout. Speedup > 1.0 indicates quantized attention is faster.
| seq | Q2 (μs) | Q3 (μs) | Q4 (μs) | FP16 (μs) | Q2 speedup | Q4 speedup |
|---|---|---|---|---|---|---|
| 128 | 5.7 | 5.6 | 5.5 | 5.4 | 0.95× | 1.02× |
| 256 | 11.1 | 10.9 | 11.4 | 11.2 | 1.01× | 0.98× |
| 512 | 22.6 | 22.2 | 22.0 | 22.1 | 0.98× | 1.00× |
| 1024 | 38.4 | 41.4 | 50.3 | 47.1 | 1.23× | 0.94× |
| 2048 | 75.4 | 79.7 | 100.0 | 103.2 | 1.37× | 1.03× |
| 4096 | 150.3 | 155.9 | 200.5 | 198.4 | 1.32× | 0.99× |
Key observations:
- Below 512 tokens, quantized and FP16 attention are approximately equal. This is the hybrid threshold: AdapTQ routes below-512 to the FP32 path automatically.
- At 2048 tokens, 2-bit quantized attention is 1.37× faster than FP16. This is the crossover point where DRAM bandwidth becomes the bottleneck.
- At 4096 tokens, 2-bit attention maintains a 1.32× speedup. 4-bit attention reaches parity with FP16, confirming that the bandwidth reduction precisely compensates for the LUT overhead.
- 3-bit at 4096 tokens (1.27× speedup) falls between 2-bit and 4-bit, as expected from the bandwidth reduction ratio.
The mechanism is straightforward: 2-bit quantization loads 8× fewer bytes from DRAM per key. At T=4096, each attention pass loads 4096 × 32 = 128 KB in 2-bit mode vs 4096 × 256 = 1024 KB in FP16. At 30 GB/s DRAM bandwidth, this is 4.3 μs vs 34.1 μs for the memory load alone — well explaining the observed latency difference.
AdapTQ implements an optional sparse-V computation that skips value accumulation for tokens whose cumulative attention weight is below a threshold (1 - v_mass). This reduces the number of value lookups per attention call.
| V-mass coverage | Attention latency (μs, T=512) | MSE penalty |
|---|---|---|
| 1.00 (baseline) | 11.2 | 0.00 × 10⁰ |
| 0.99 | 12.2 | 0.00 × 10⁰ |
| 0.90 | 11.3 | 0.00 × 10⁰ |
| 0.70 | 11.0 | 0.00 × 10⁰ |
At v_mass = 0.90, approximately 10% of tokens are skipped with no measurable MSE degradation (within floating-point rounding error). The latency variation at small sequence lengths is noise-dominated; the sparse optimization delivers clearer benefits at longer contexts where skipped token counts are larger.
AdapTQ follows a four-phase implementation plan, each phase independently deployable and testable.
Target: x86 AVX2 validation + ARM Cortex-A78 (NEON) baseline
Status: AVX2 implemented and benchmarked; NEON port in progress
Components:
- HAR with FWHT (AVX2 + scalar fallback)
- 2/3/4-bit MSE codebooks (Max-Lloyd)
- LUT-driven quantized attention (no full dequantization)
- KVFlatBuffer (contiguous, FIFO eviction)
- Zero-branch hybrid FP32/quantized execution (threshold=512)
- Production C API (single-head + multi-head)
Excluded from Phase 1:
- Importance-based bit allocation (AIABA)
- Layer-wise precision scheduling (HLPS)
- QJL residual quantization
- ONNX/TensorRT export
Target: ARM Cortex-A78 primary
Components:
- NEON SIMD FWHT kernel (replacing scalar fallback)
- Bucketed O(1) importance eviction (low/mid/high, logit-threshold based)
- Simplified AIABA (logit threshold, 3-tier, no re-quantization)
- HLPS with default heuristic schedule (no calibration required)
- llama.cpp KV cache integration
llama.cpp integration points:
In llama.cpp, the KV cache is managed by the llama_kv_cache struct and updated in llama_kv_cache_update(). The integration replaces per-head float16 K/V stores with AdapTQ's packed buffers:
// In llama_new_context_with_model():
ctx->kv_self = adaptq_mha_create(n_heads, head_dim, bits, capacity, seed, 1.0f, 512);
// In llama_decode() per-layer attention:
adaptq_mha_append(ctx->kv_self, head, k_vec, v_vec, pos);
adaptq_mha_compute(ctx->kv_self, head, q_vec, attn_out);Components:
- HLPS with offline sensitivity profiling
- Mixed-precision codebooks (per-layer bit-width from schedule)
- Throughput tuning: batched FWHT, codebook prefetch
- Python binding with PyTorch integration for research use
Components:
- QJL 1-bit residual for unbiased inner product estimation
- Speculative decoding with shared quantized KV
- ONNX opset-18 custom operator export
- On-device sensitivity profiling (incremental, first N tokens)
Accuracy vs Memory: The primary knob is b. Moving from 4-bit to 2-bit reduces KV memory by 2× while increasing MSE from 8×10⁻⁵ to 9×10⁻⁴ — a 10× increase in reconstruction error. Whether this translates to perplexity degradation depends on the model and context: in LLaMA-class models, 3-bit is expected to match FP16 perplexity at most context lengths, while 2-bit introduces approximately 0.5–1.5 PPL points of degradation on WikiText-2.
HAR vs Dense Rotation: HAR introduces a C_HAR ≤ 1.08 distortion multiplier relative to TurboQuant's dense rotation. At d_h ≥ 64, this is unmeasurable in practice. For GPU inference where rotation is cheap, TurboQuant's original dense rotation may be preferred. For edge CPUs, HAR is the correct choice without exception.
FIFO vs Importance Eviction: FIFO eviction in Phase 1 loses information about early-context tokens when the buffer fills. For tasks requiring full-context recall (e.g., Needle-in-a-Haystack with T > C_max), FIFO eviction can degrade performance significantly. The Phase 2 bucketed eviction addresses this by retaining high-importance tokens regardless of age.
Dequantization Path: AdapTQ's LUT-based attention avoids full dequantization. The trade-off is that the LUT must be rebuilt for every new query vector. At d=128 and 16 centroids, this is 2,048 multiply operations per attention call — a fixed cost paid once regardless of context length. At T=1024, this amortizes to 2 multiply-adds per key-lookup, compared to 128 for a full dot product. The crossover where LUT construction becomes worthwhile is at approximately T=20 keys, well below any practical context.
Non-power-of-two head dimensions: Models with d_h ∈ {80, 96} require zero-padding to the next power of two for FWHT. At d_h=80, padding to 128 adds 60% overhead to the rotation step, partially reducing HAR's advantage. AdapTQ automatically handles padding; the distortion increase from padded coordinates is bounded and typically < 2%.
FIFO eviction in Phase 1: As noted, FIFO eviction is suboptimal for tasks with highly non-uniform attention (e.g., document QA where early context is the answer). Phase 2 bucketed eviction resolves this.
Weight quantization is out of scope: AdapTQ compresses only the KV cache. For full edge deployment, INT4 weight quantization (via GPTQ or AWQ) is required in addition to AdapTQ. The two methods are orthogonal and independently applicable.
ARM NEON not yet implemented: Phase 1 is validated on AVX2. The NEON port retains the same algorithmic structure; only the intrinsic calls change. This is straightforward but not yet completed.
Thermal throttling: On mobile SoCs, sustained inference triggers thermal throttling that reduces clock speed by 30–50%. Latency measurements should use sustained (post-warmup) rates, not burst rates. All benchmark figures in Section 7 use x86 AVX2 without throttling; ARM measurements should include a 5-minute warmup period.
Codebook versioning: Codebooks are compiled into the binary as float constants. Changing codebook parameters (e.g., to support a new head dimension) invalidates stored quantized KV caches. Serialized caches should include a 4-byte codebook version identifier.
Numerical stability of FWHT: The butterfly operations accumulate additions without intermediate renormalization. For d ≤ 256 in FP32, the maximum accumulated value is bounded by d · max(|x_i|) = 128 · ||x|| ≤ 128 (for unit-norm inputs). FP32 overflow requires values > 3.4×10³⁸ and is not a concern at these dimensions.
The FWHT butterfly pattern is regular, branchless, and requires no data-dependent memory access — properties ideal for a dedicated systolic array implementation. A 128-wide vector FWHT unit in 28nm CMOS would complete the rotation in approximately 7 cycles (log₂(128) butterfly stages) at 1 GHz, consuming under 1 mW. This would make quantization overhead truly negligible for all context lengths.
In speculative decoding, the draft model and target model share attention over the same context. If both use AdapTQ-compressed KV, the draft model can compute attention scores directly from the target model's quantized buffer without dequantization, using the same LUT mechanism. This eliminates redundant KV storage and reduces verification latency.
The quantized representation produced by AdapTQ — small-integer codebook indices and optional 1-bit QJL residuals — is compatible with memristor-based analog dot-product engines. The inner product between a quantized key and a query reduces to a weighted sum over a finite set of centroid values, directly implementable in charge-domain analog circuits. This connects AdapTQ to emerging ultra-low-power inference substrates operating below 1 mW.
We have presented AdapTQ, an engineering-focused adaptive streaming vector quantization engine that brings near-optimal KV cache compression to edge hardware without GPU infrastructure. The Phase 1 implementation — validated and open-sourced at https://github.com/l3tchupkt/adaptq — establishes four concrete contributions: Hadamard-Accelerated Rotation reducing rotation cost by 18× in FLOPs, LUT-driven quantized attention eliminating full dequantization, zero-branch hybrid execution routing between FP32 and quantized paths without overhead, and KVFlatBuffer providing contiguous streaming KV storage optimized for hardware prefetchers. On AVX2 hardware at d=128, the system delivers 4×–16× KV compression with MSE below 9×10⁻⁴ at 2 bits and below 8×10⁻⁵ at 4 bits, and surpasses native FP16 attention throughput at context lengths ≥2048 tokens — reaching a 1.32× speedup at 4096 tokens in 2-bit mode.
The phased roadmap provides a clear path from the validated Phase 1 core to Phase 2 adaptive quality mechanisms (AIABA, HLPS, importance eviction) and beyond. By grounding each engineering decision in the distortion-rate theory of TurboQuant while resolving its execution bottlenecks, AdapTQ provides a principled and practically deployable foundation for the next generation of edge-deployed language models.
-
Zandieh, A., Daliri, M., Hadian, M., and Mirrokni, V. TurboQuant: Online vector quantization with near-optimal distortion rate. arXiv:2504.19874, 2025.
-
Zandieh, A., Daliri, M., and Han, I. QJL: 1-bit quantized JL transform for KV cache quantization with zero overhead. arXiv:2406.03482, 2024.
-
Ashkboos, S. et al. QuaRot: Outlier-free 4-bit inference in rotated LLMs. arXiv:2404.00456, 2024.
-
Liu, Z. et al. KIVI: A tuning-free asymmetric 2-bit quantization for KV cache. arXiv:2402.02750, 2024.
-
Han, I. et al. PolarQuant: Quantizing KV caches with polar transformation. arXiv:2502.02617, 2025.
-
Vaswani, A. et al. Attention is all you need. NeurIPS, 2017.
-
Gao, J. et al. RabitQ: Practical and asymptotically optimal quantization of high-dimensional vectors. arXiv:2409.09913, 2024.
-
Ailon, N. and Chazelle, B. The fast Johnson-Lindenstrauss transform and approximate nearest neighbors. SIAM Journal on Computing, 39(1):302–322, 2009.
-
Vershynin, R. High-Dimensional Probability: An Introduction with Applications in Data Science. Cambridge University Press, 2018.
-
Shannon, C.E. Coding theorems for a discrete source with a fidelity criterion. IRE National Convention Record, 4:142–163, 1959.
-
Lloyd, S. Least squares quantization in PCM. IEEE Transactions on Information Theory, 28(2):129–137, 1982.
-
Max, J. Quantizing for minimum distortion. IRE Transactions on Information Theory, 6(1):7–12, 1960.
-
Frantar, E. et al. GPTQ: Accurate post-training quantization for generative pre-trained transformers. arXiv:2210.17323, 2022.
-
Lin, J. et al. AWQ: Activation-aware weight quantization for on-device LLM compression. Proceedings of Machine Learning and Systems, 6:87–100, 2024.
-
Dubey, A. et al. The LLaMA 3 herd of models. arXiv:2407.21783, 2024.
-
Leviathan, Y. et al. Fast inference from transformers via speculative decoding. ICML, 2023.
-
Panter, P. and Dite, W. Quantization distortion in pulse-count modulation with nonuniform spacing of levels. Proceedings of the IRE, 39(1):44–48, 1951.
-
Bai, Y. et al. LongBench: A bilingual, multitask benchmark for long context understanding. arXiv:2308.14508, 2023.
-
Dettmers, T. et al. GPT3.int8(): 8-bit matrix multiplication for transformers at scale. NeurIPS, 2022.
-
Cover, T.M. Elements of Information Theory. John Wiley & Sons, 1999.
This work builds upon and extends TurboQuant (Zandieh et al., 2025, Google Research). All novel engineering contributions — HAR, LUT-driven attention, hybrid execution, KVFlatBuffer, and the phased adaptive extensions — are original to this work. The TurboQuant core distortion-rate theory is cited and credited throughout. Repository: https://github.com/l3tchupkt/adaptq