TinyLoop: A Custom Inference Engine for Inkling 2 Mini
70+ tok/s, 256K context on an RTX 3080, nearly lossless
Running a strong reasoning model locally on a single desktop GPU usually forces a quick compromise. Either you drop down to a smaller model that fits inside VRAM, or you offload a larger Mixture-of-Experts checkpoint to system RAM and live with single-digit token rates.
When Thinking Machines Lab released Inkling 2 Mini, it looked like a fun project to hack on over Thanksgiving break. The UD-Q4_K_M GGUF checkpoint is 15.46 GiB (26.07B parameters total), ships with a tiny speculative drafter called DSpark, and has a handful of architectural quirks that general-purpose engines do not really exploit. On my desktop’s 10 GiB RTX 3080, stock llama.cpp ran it at 6.3 tok/s. After hand-tuning layer placement, llama.cpp topped out around 28 tok/s and 12K context, and turning on speculative decoding barely moved the needle.
Just for fun over the long weekend, I built TinyLoop—a casual custom batch-size-1 inference engine tailored specifically to Inkling 2 Mini. Using that same untouched UD-Q4_K_M file on the same 10 GiB RTX 3080, it reaches 70+ tok/s on math reasoning, ~50 tok/s on multi-turn agentic coding, and up to 256K context, with output distributions close to a dense FP16 KV oracle.
What is Inkling 2 Mini?
Inkling 2 Mini (inkling2_loop) is quite different from a standard Llama-style decoder, and almost every optimization later in this post comes directly from four details of its architecture.
First, it is a looped transformer. There are 24 physical blocks (blk.0–23, hidden size $d = 2304$, vocabulary $V = 200{,}058$), but a forward pass executes 48 logical layer visits. Blocks 0–5 run once, the middle 12 blocks (blk.6–17) run three times in a loop with rank-64 message gates and block-wise Attention Residuals (depth mixing), and blocks 18–23 run once. Each loop pass keeps its own KV cache and convolution state. In terms of compute, 36 of the 48 layer visits (75%) happen inside those middle 12 physical blocks.
Second, it uses fine-grained MoE in every block: 128 routed experts per physical layer (FFN width 1152, softcapped SiTU/SwiGLU) with top-8 routing. That is 3,072 experts total (24.46B of the model’s 26.07B parameters) and 384 expert evaluations per generated token.
Third, its attention stack has no RoPE (rope_dim = 0). The model uses GQA (24 query heads, 8 KV heads, head_dim = 128) in a 5:1 sliding-window ($W = 1024$) to full-attention ratio, leaving only 8 full-attention visits out of 48 (v5, 11, 17, 23, 29, 35, 41, 47). Instead of rotary embeddings, positional information comes from 4-tap depthwise short convolutions (192 live states across K/V and post-attention/post-MLP) and a learned relative-position bias that becomes strictly zero past distance 1,024, alongside learned per-head attention sinks. Beyond 1,024 tokens, keys have no positional encoding at all.
Finally, Inkling 2 Mini ships with DSpark, a 481 MiB (Q8_0) 3-layer DFlash drafter (SWA · Full · SWA) topped with a rank-256 Markov RNN head. It taps target hidden states at visits (5, 23, 41, 48) and drafts blocks of 3–7 tokens per step.
blk.6–17 three times, paired with 128-expert top-8 MoE, 5:1 sliding-window-to-full attention with no RoPE, and a 3-layer DSpark drafter.What We Are Working With
Everything here targets a single desktop workstation at batch size 1 (interactive chat, long math traces, and local coding agents like OpenCode):
| Component | Spec | Relevant limit |
|---|---|---|
| GPU | NVIDIA RTX 3080 (SM 8.6) | 10 GiB GDDR6X; PCIe 4.0 x16 (19.1–25.3 GB/s pinned H2D) |
| CPU | AMD Ryzen 7 5800X (8C / 16T) | AVX2, 32 MiB L3; dual-channel DDR4 |
| System RAM | 30 GiB usable DDR4 | Holds host-resident experts and long-context KV slabs |
| Checkpoint | Inkling-2-Mini-UD-Q4_K_M.gguf | 15.46 GiB total (14.09 GiB experts, 1.27 GiB non-expert GPU weights) |
| Drafter | dspark-Inkling-2-Mini-Q8_0-mainline.gguf | 481 MiB weights (~555 MiB GPU footprint with state) |
We pinned the exact SHA-256 of the UD-Q4_K_M GGUF (NVFP4 experts at 4.27 MiB each in blk.0–19, Q5_K/Q8_0 experts at 6.17 MiB each in blk.20–23) and forbade requantization. The memory problem is straightforward: the experts alone are 14.09 GiB, more than 4 GiB larger than the entire 10 GiB GPU before adding attention weights, DSpark, KV caches, or CUDA runtime scratch.
Establishing the Baseline: Tuned llama.cpp
We pinned upstream llama.cpp (b12651, commit f5e6915) and evaluated on AIME 2026 (medium reasoning, Unsloth’s recommended temp = 1.0, top_p = 1.0, natural stop).
With default settings, llama.cpp’s automatic fitter put 0 MiB of weights on the GPU, reserved 8.4 GiB for compute scratch, and decoded at 6.3–6.5 tok/s. Turning off host op offload (--no-op-offload), setting --ubatch-size 64, and placing tensors manually got us much further. Because blk.6–17 execute three times per token, putting all 12 looped blocks’ experts plus all attention weights on GPU (~7.83 GiB) and leaving the 12 outer blocks’ experts (blk.0–5, 18–23) on CPU was clearly the best static layout:
llama.cpp placement (12K ctx, FP16 KV) | Free VRAM | Server decode | AIME P1 E2E (128 tok) |
|---|---|---|---|
| Stock auto-fit (all weights on CPU) | 709 MiB | 6.51 tok/s | 25.33 s |
| Last 12 full blocks on CPU | 727 MiB | 10.91 tok/s | 15.32 s |
| Loop-first: 13 full blocks on GPU | 433 MiB | 20.41 tok/s | 7.97 s |
| Loop-first: 11 looped expert blocks + all attn on GPU | 901 MiB | 26.00 tok/s | 6.65 s |
| Loop-first: 12 looped expert blocks + all attn on GPU | 337 MiB | 28.29 tok/s | 6.00 s |
Over the first three AIME 2026 problems (capped at 2,048 tokens), this tuned 12-loop baseline averaged 27.85 tok/s decode (~138 tok/s prefill) and topped out at 12,288 tokens of FP16 context. A quick LD_PRELOAD timer around ggml_graph_compute showed why: 45% of every decode step (15.5 ms out of 33.4 ms) went to synchronously running those 12 outer expert blocks on the CPU.
Why Speculative Decoding Doesn’t Help llama.cpp
Normally, speculative decoding is an easy win at batch size 1 because verifying 4–8 tokens on a memory-bandwidth-bound GPU costs almost the same as verifying 1. With static CPU offloading, that assumption breaks.
We timed libllama across verification batch sizes $N \in {1, 4, 6, 8, 16}$ and also built llama.cpp PR #32218 to benchmark DSpark directly. Two problems showed up immediately. First, DSpark (~481 MiB plus buffers) did not fit alongside all 12 looped blocks on 10 GiB, forcing PR #32218 down to 11 looped blocks on GPU. Second, verifying $N$ tokens in parallel scaled the 12 CPU-resident outer expert blocks almost linearly: at $N = 1$, each outer layer runs 8 CPU experts (15.3 ms, 46% of step); at $N = 4$, 4 tokens touch 20.4 unique experts per outer layer (42.1 ms, 59%); at $N = 8$, it is 31.0 unique experts (69.3 ms, 64%).
llama.cpp. Right: Verifying N speculative tokens drives the 12 CPU outer-expert layers from 46% to 69% of step latency.Even though DSpark accepted 3.33–3.75 tokens per step on AIME Problem 1 (temp = 1.0, Q8_0 KV), CPU expert time grew nearly as fast as the accepted length:
llama.cpp PR #32218 (12K, Q8_0 KV, AIME P1) | Decode (temp = 1.0) | Decode (greedy) | Mean tok/step |
|---|---|---|---|
nodraft_12loop (AR baseline) | — | 28.96 tok/s | 1.00 |
dspark_11loop_n3 | — | 35.39 tok/s | 2.80 |
dspark_11loop_n5 | 29.95 tok/s | 31.92 tok/s | 3.33 |
dspark_11loop_n7 | 28.45 tok/s | 29.48 tok/s | 3.75 |
At temp = 1.0, n = 5 gave a 3% bump and n = 7 was slower than ordinary autoregressive decoding. Static layer offloading and speculative decoding work against each other on a 10 GiB card.
Two Hillclimbs: Speed and Context Length
From here we split the work into two separate tracks: first pushing decode speed as far as we could (from under 30 tok/s into the 70–80+ tok/s range), and then pushing context length by more than $20\times$ (from 12K to 256K).
We needed both. A fast 12K engine runs out of context mid-thought on harder AIME problems, many of which generate 17K–32K tokens, and cannot hold a realistic multi-file coding session. On the other hand, a 256K engine that spends half its VRAM on KV caches has to evict experts back to CPU and loses its speed. On 10 GiB of VRAM, speed and context compete for the same few gigabytes.
Starting the Custom Engine
To iterate quickly on caching, speculative verification, and sparse KV layouts, we started from Hugging Face Transformers’ Inkling2LoopForCausalLM wired directly to packed ggml GGUF matrices, keeping the exact same 12-loop GPU / 12-outer CPU placement and checking full-vocabulary numerical parity against libllama. Our first eager forward ran at 5.57 tok/s (179.4 ms/token, vs 33.4 ms/token in tuned llama.cpp).
Nsight made the gap easy to diagnose. Actual GPU kernels took 26.4 ms and synchronous CPU experts took 16.2 ms; the other ~130 ms was pure Python and ATen launch overhead. Every single token issued 9,972 direct CUDA kernel launches, 1,276 device-wide synchronizations, and 1,877 async device-to-device copies. Breaking down an early async+graph step (127.4 ms/token, Figure 3 left) showed that overhead spread across hundreds of small calls: 192 attention projections (24.9 ms), 192 4-tap short convolutions (20.4 ms), 48 relative-position biases (11.7 ms), 48 attention/sink bodies (11.4 ms), and 154 RMSNorm calls (8.4 ms, six kernels each).
llama.cpp.We worked through that list one piece at a time while checking bitwise logit parity against our PyTorch control at every step. Queuing packed ggml projections asynchronously with shared-pool PyTorch CUDA graphs and adding sink-aware ggml Flash Attention dropped step time from 179.4 to 125.5 ms. Custom fused CUDA kernels for the 4-tap short convolutions and bitwise-identical RMSNorm (plus GPU expert activation graphs) brought it down to 112.0 ms and then 98.9 ms. Packing Q, relative-bias, output-gate (and K/V where inputs match) rows reduced 240 Q8_0 projections to 104, and pairing that with fixed-address FP16 KV buffers and native GPU MoE took us to 77.4 ms. Finally, capturing all 36 visits of the GPU loop core (blk.6–17) into a single CUDA graph cut step latency to 46.5 ms, and capturing the 12 outer layers’ attention blocks between CPU expert calls brought it to 38.1 ms (124 direct launches), with automatic 256-key bucket recapture and wrap-around chronological copies across the 1,024-token sliding window.
At 38.1 ms we were within 4.7 ms of llama.cpp, inside a runtime we controlled completely. Wiring in our native DSpark drafter (with batched $N = 1..8$ verify kernels and exact KV + 192 short-conv rollback) lifted 3-prompt AIME decode from 27.85 to 32.78 tok/s—confirming that static CPU outer experts (now 38.8 ms/step, 46.6% of total time) were the real ceiling.
The Dynamic 2-Slab GPU Expert Cache
Static layer placement assumes all 128 experts in a layer are equally worth keeping in VRAM. Real MoE routing is heavily skewed and temporally local.
We logged routing traces across 2,692 tokens of non-AIME workloads (math, a C++ concurrent LRU implementation, an algebra proof, and a held-out Raft linearizability debugging session). On the held-out sequence, the top 50% of experts accounted for 87.9% of activations in blk.0–5, 93.8% in blk.6–17, and 96.7% in blk.18–23. Adjacent tokens reused 40.1% (outer) to 45.5% (looped) of their top-8 experts, and the same token reused 62.3% (Pass 1 → Pass 2) and 52.6% (Pass 2 → Pass 3) across loop passes. Even across an 8-token verify window, a layer only touched 31.0 of 128 unique outer experts (versus 51.6 under uniform routing) and 41.1 unique looped experts across all three passes. Pinning 12 whole layers statically meant spending VRAM on cold looped experts while taking a 100% miss rate on all 12 outer layers.
So instead of statically pinning whole layers, we cache individual experts dynamically across all 24 layers (6,500 MiB during Part 1, later standardized to 6,000 MiB for 256K). Because Unsloth’s dynamic quantization (UD-Q4_K_M) stores experts in two different sizes—4.27 MiB (NVFP4) in blocks 0–19 and 6.17 MiB (Q5_K/Q8_0) in the final four blocks 20–23—putting them in a single variable-size GPU pool would either fragment VRAM as experts constantly swap in and out or waste 30% of every NVFP4 slot on padding. Splitting the cache into two fixed-slot-size slabs solves both: Slab A holds 1,241 4.27 MiB slots shared across all 20 NVFP4 layers (blk.0–19), and Slab B holds 194 6.17 MiB slots shared across the 4 higher-precision layers (blk.20–23), giving $O(1)$ zero-fragmentation evictions while letting hot experts compete across layers within each format.
One detail turned out to matter a lot: plain LRU thrashes under speculative decoding. A single $N = 8$ verify step sweeps across hundreds of distinct experts across 48 layer visits, so below 5 GiB plain LRU evicts hot experts before the next step even arrives (Figure 4 left). Switching to Decaying-LFU weighted by visits per MiB (decay = 0.92, 3× weight for looped blocks since each cached looped expert serves 3 visits per token, and a 1.15× hysteresis ratio before evicting an incumbent) stopped the thrashing cleanly. Promotions run asynchronously on a separate copy_stream gated on DDR4-idle windows (cutting main-thread promotion stalls from 10.5 ms to 0.15 ms/step), and CPU misses are compacted per token (max_k_miss instead of TOP_K = 8) while overlapping with GPU slab hits.
sd = 3, 6.5 GiB cache).Pairing the dynamic cache with DSpark worked much better than either one alone, for two reasons. First, on 3-prompt AIME 2026 (spec_draft = 3, $N = 4$), the 6.5 GiB cache hit 96.5% of routed expert calls on GPU, with 62.6% of layer visits having zero CPU misses. CPU expert time fell from 38.8 ms/step (46.6%) to 11.1 ms/step (20.0%), moving steady decode1 from 32.78 to 49.81 tok/s. Second, because multiple draft tokens in a verify batch frequently hit the same GPU-cached expert slot, we replaced ggml’s per-token GEMV with custom expert-grouped CUDA dp4a MoE kernels (NVFP4, Q5_K, Q8_0). Those kernels coalesce all batch tokens sharing a slot and load each expert’s weight matrix from GDDR6X once—1.92× fewer weight reads at $N = 4$ and 2.72× fewer at $N = 8$—while skipping missed slots entirely. That pushed 3-prompt AIME steady decode to 59.75 tok/s (and 42.19 tok/s pure AR).
Milestone (3-prompt AIME 2026, temp = 1.0, FP16 KV, 6.5 GiB cache) | Pooled steady | Aggregate E2E | CPU experts / step | GPU hit rate |
|---|---|---|---|---|
Tuned llama.cpp 12-loop (AR) | 27.85 tok/s* | 27.20 tok/s | 15.5 ms | 75.0% (static) |
Custom + DSpark sd = 3, static 12-loop | 32.78 tok/s | 31.24 tok/s | 38.8 ms (46.6%) | 75.0% (static) |
| + Dynamic 2-slab cache (6.5 GiB) | 49.81 tok/s | 43.54 tok/s | 11.1 ms (20.0%) | 96.5% |
| + Fused pre/post-MoE segment graphs + GPU prefill | 50.74 tok/s | 47.26 tok/s | 11.3 ms | 96.6% |
| + Expert-grouped CUDA MoE + DDR4-idle promoter | 59.75 tok/s | 54.89 tok/s | — | ~96.5% |
| + 49-graph verify chain + AVX2 CPU NVFP4 MoE | 81.96 tok/s | 72.90 tok/s | — | ~96.5% |
| + Batched PCIe prefill + direct MMQ | 83.16 tok/s | 78.15 tok/s | — | ~96.5% |
*Full-request server decode for llama.cpp; custom runs report pooled steady-state decode after 16 warm-up steps.
Side Quest: Expert Prediction
With 11 ms/step still going to the remaining 3.5% CPU misses (and more under tighter 4.5 GiB long-context budgets), we tested whether predicting upcoming layers’ experts and prefetching misses over PCIe would buy another jump.
In offline simulation it looked great. We collected 24 non-AIME sequences (12,427 tokens) and trained lightweight lookahead-2 and mid-loop linear probes (2304 → 128, 29.8 MiB FP16), which actually beat bottleneck MLPs on held-out recall (73.8% R@8, 89.8% R@16, 94.5% R@24). Simulating prefetch into a staging buffer cut CPU misses by 66.1% at 6.2 GiB (8.21% → 2.78%) and 60.2% at 4.5 GiB (14.85% → 5.92%).
We went ahead and built the full hardware path: wired the probes into our pre_moe CUDA graphs, pinned host experts for zero-copy CUDA_Host DMA (~25 GB/s), and added a 3-bank 159 MiB ping-pong staging buffer with device-to-device promotion. Once we timed it on real hardware, almost all of the simulated win disappeared.
At 6.5 GiB, the Decaying-LFU cache was already hitting 95.9%, so cutting misses by 25% only moved decode from 51.32 to 51.86 tok/s (+1%). At 4.5 GiB, just running the in-graph probes and syncing top-k IDs added 1.51 ms/step. Lowering the confidence threshold issued 42–55 PCIe DMAs per step that competed with the Ryzen CPU miss threads for DDR4 bandwidth, erasing the CPU savings. Even at the best confidence threshold (logit_threshold = +2.0), net step latency only dropped by 1.98 ms (+2–3%), at the cost of pinning all 15 GiB of experts in RAM and turning cold server startup from 4 seconds into 45 seconds.
We saw a similar result when we tried training Forward-KL Tuned Lenses for mid-depth speculative early rejection. Early in the forward pass (v17/v29) where enough compute remains to matter, the looped target has not converged (0.65–0.69 ROC-AUC vs DSpark’s own Depth-0 probability at 0.849 ROC-AUC); by v44 where the lens beats DSpark (0.886 AUC), 91% of the forward pass is already done and even an oracle caps at +0.5–1.5%. We kept both features off by default.
Further Speed Optimizations (59.8 → 83.2 tok/s)
Three remaining bottlenecks stood between 59.8 tok/s and the 80+ tok/s ceiling of the hardware: GPU glue between MoE layers, CPU cache misses, and prefill.
Fusing the work between MoE layers and graphing DSpark. In a single forward pass, tokens pass through 48 logical transformer layers (6 pre-loop, 3 × 12 looped, 6 post-loop), and every layer has an MoE block in the middle. Earlier, we used separate CUDA graphs before and after each MoE block (96 graph replays per step) with Python bookkeeping in between. By fusing each layer’s post-MoE cleanup (post-MLP short convolution and residual update) together with the next layer’s pre-MoE work (loop message gate, normalization, attention, and router) into one graph, an entire forward pass collapsed to 48 inter-MoE graphs plus 1 graph for the final LM head (49 graphs total). We also replaced small PyTorch ops inside Inkling’s loop message gates (209 → 33 µs), Attention Residuals (22–27 → 3–5 µs), and top-8 router (26 → 8 µs) with lightweight CUDA kernels, and captured DSpark’s 3-layer draft forward into CUDA graphs as well (cutting draft time from 5.95 to 2.66 ms).
Grouping CPU cache misses with an AVX2 kernel. Whenever the router picks an expert that is not currently sitting in our 6.5 GiB GPU cache—a cache miss—the CPU has to run that expert’s feed-forward pass out of system RAM. Under speculative decoding ($N = 4$ tokens verified together), ggml’s generic CPU path was inefficient: if two or three draft tokens missed on the same expert, it streamed that 4.27 MiB expert from DDR4 separately for each token, and paid separate thread-pool barriers across gate/up, activation, and down projections. We wrote a single-OpenMP-region AVX2+FMA kernel for NVFP4 misses that groups all missed tokens sharing an expert so each missed weight matrix is read from RAM once, with the softcapped activation and output combine fused into the same pass (reaching 32.2 GB/s of DDR4 bandwidth). Combined with the fused GPU graphs and graphed DSpark, this jumped 3-prompt AIME steady decode by 37.2%, from 59.75 to 81.96 tok/s (72.90 tok/s E2E), and pushed pure autoregressive decode (sd = 0) to 60.12 tok/s.
Streaming uncached experts to the GPU during prefill. Decode and prefill have completely different expert locality. During decode (1–4 tokens at a time), a layer only touches a small working set and our GPU cache hits 96.5% of the time. During prefill, we process a 512-token prompt chunk all at once; across 512 tokens, almost all 128 experts in a layer get routed to at least a few tokens, so roughly half the experts in every layer are not in VRAM. Running those uncached experts on the CPU is what kept llama.cpp stuck around 138 tok/s. Instead of computing them on the CPU, we run the cached experts on GPU first, then stream the remaining uncached experts from RAM over PCIe 4.0 in double-buffered batches into a small GPU scratch buffer—overlapping each batch’s PCIe transfer with the previous batch’s GPU matmul. Because each expert serves dozens of tokens in a 512-token chunk, GPU compute easily outweighs the PCIe transfer cost. Paired with prefill Flash Attention and fused short convolutions, that cut AIME prefill time in half (1,867 → 888 ms, lifting 3-prompt AIME to 83.16 tok/s steady / 78.15 tok/s E2E) and sped up cold LongBench-v2 prefill 3.37× over llama.cpp (456–476 tok/s). (We also tested lossless confidence-gated {4, 8} dynamic draft lengths, which added +4.5% at a tighter 4.5 GiB cache budget, though fixed sd = 3 remained fastest at 6.0–6.5 GiB.)
Part 2: Climbing Context from 12K to 256K
With decode speed in place, the bottleneck flipped back to VRAM. Keeping the dynamic expert cache at 6.00 GiB (to hold 70+ tok/s speed) leaves a tight budget on a 10 GiB card: fixed non-expert weights (1.28 GiB), DSpark (0.55 GiB), 40 Q8_0 sliding-window KV caches (0.11 GiB), and CUDA graphs/scratch (0.45 GiB) already take 2.39 GiB. That leaves roughly 1.0–1.5 GiB for all 8 full-attention KV caches plus headroom (Figure 5).
At 256K tokens, dense FP16 KV across 8 full-attention layers takes 8.70 GiB, and llama.cpp also materialized 3.19 GiB of full-context attention masks (19.9 GiB total). Even compressing dense KV to Q8_0 still needs 4.35 GiB at 256K—more than 3× our remaining VRAM (Figure 6 left).
The Smaller Gains First
Before introducing sparse attention, we cleared three memory walls without approximating attention at all.
First, we implemented a Q8_0 KV cache using exact ggml block_q8_0 CUDA kernels (34 bytes per 32 elements, 17.0 MiB per 1K full-attention tokens), cutting KV VRAM by 46.9% with 8/8 top-1 parity against FP16 KV (KL <= 0.0014 at short context). Second, we ring-buffered DSpark’s KV cache (1,040 cap on its two SWA layers, 16,384 ring with on-the-fly RoPE on its full layer), capping DSpark KV at 64 MiB forever.
Third, we exploited Inkling 2 Mini’s rel_extent = 1024 bound to build O(1)-VRAM exact Far/Near prefill. Because the relative-position bias is strictly zero beyond distance 1,024, prefill attention splits cleanly into an unmasked Far pass (0 .. pos - 1024, zero mask bytes, evaluated via 2K-chunked Q8_0 dequantization + FlashAttention-2) and a bounded Near pass (<= 36 MiB bias forever), combined with the virtual sink in an exact 3-way FP32 Log-Sum-Exp merge. Keeping the sink in FP32 instead of baking bias - sink (values up to 13.8) into an FP16 mask also made attention 31× more accurate against an FP32 reference (max 0.0054 vs 0.168). Evicting completed Far Q8_0 blocks to pinned Host RAM (16.6 MiB/1K → 4.25 GiB at 256K) and double-buffer streaming them back on copy_stream kept prefill KV VRAM flat at 34.9 MiB all the way to 256K, sustaining 444 tok/s at 8K, 437 at 16K, 430 at 32K, and 409 at 64K (Figure 6 right).
The Big Gain: Position-Invariant ClusterKV
Host-streamed prefill gets us to 256K without OOMing, but during decode we cannot stream 4.25 GiB of host KV across a 25 GB/s PCIe bus on every token (~170 ms/token, under 6 tok/s). The 8 full-attention layers need sparse retrieval.
Contiguous-page methods like Quest divide history into fixed time blocks and summarize each page with min/max key bounds. That makes sense under RoPE, where keys rotate with position and nearby tokens naturally group together, but mixing unrelated code or text inside one contiguous block loosens the bounds and wastes budget. Because Inkling 2 Mini has no RoPE and zero relative bias past distance 1,024, far keys are position-invariant: two tokens referring to the same symbol or lemma 100K tokens apart produce nearly the same key vector. Semantic clustering per KV head (ClusterKV) therefore produces much tighter groups than contiguous paging.
Our implementation extends vanilla ClusterKV in three ways (Figure 7). First, the last 1,024 tokens stay dense in an FP16 Local ring in VRAM, preserving Inkling’s exact relative-position bias and DSpark rollback safety while deferring eviction to far clusters in batches of 256. Second, far tokens are clustered per KV head via streaming Euclidean K-means ($B = 32$, local 2-means split at $B_{\max} = 64$, hard cap $C_{\max} = 4096$ with cold-pair cosine merge); exact far K/V tensors live in pinned Host RAM as Q8_0 slabs (4.25 GiB at 256K), fronted by a 64-slot FP16 VRAM LRU cache per head (~256 MiB total across all 8 layers) that hits ~85.6% of the time across consecutive steps. Third, instead of dropping unselected clusters (cold = False), every unselected cold cluster still contributes its centroid and mean value $(k_c, v_c)$ weighted by $+\log(n_c)$ in an exact FP32 4-way online-softmax LSE merge (Local + Far-Hot + Far-Cold + Virtual Sink).
Q8_0 slabs, Far-Cold cluster summaries weighted by +log(nc), and learned virtual sinks merged in one fused CUDA kernel.Multi-Domain KL Divergence Evals
To check whether ClusterKV actually preserves Inkling 2 Mini’s next-token distribution beyond needle-in-a-haystack tests, we measured teacher-forced KL divergence across six 4K–16K domains (LongBench-v2 CodeRepo, Literary, Many-Shot ICL, Dialogue, Multi-Doc QA, and SWE-Agent Tool-Calling).
(All later ClusterKV speed optimizations—our fused CUDA attention kernel, C++ flat-array LRU, and fused routing/dequant-scatter—implement the exact same k = 1024, B = 32, B_max = 64, cold = True math to ~1.3e-6 mean attention error, so these KL measurements still hold for the final engine.)
Against an Exact Dense Q8_0 KV Oracle (768 tokens across 6 domains):
ClusterKV config (vs Dense Q8_0 oracle) | Mean KL | Median KL | p95 KL | p99 KL | Top-1 agree | Top-5 overlap | LRU hit |
|---|---|---|---|---|---|---|---|
k = 256, B = 32, cold = True | 0.0086 | 0.0000 | 0.0339 | 0.1160 | 97.3% | 91.7% | 89.8% |
k = 512, B = 32, cold = True | 0.0038 | 0.0000 | 0.0173 | 0.0636 | 97.5% | 92.9% | 89.3% |
k = 512, B = 16, cold = True | 0.0026 | 0.0000 | 0.0124 | 0.0367 | 98.0% | 93.4% | 88.9% |
k = 1024, B = 32, cold = True (shipped) | 0.0018 | 0.0000 | 0.0078 | 0.0262 | 98.4% | 94.2% | 85.6% |
k = 1024, B = 32, cold = False (no summaries) | 0.0031 | 0.0000 | 0.0148 | 0.0315 | 98.3% | 92.9% | 85.5% |
Keeping Far-Cold summaries cuts mean KL nearly in half (0.0031 → 0.0018) and trims p95 KL by 47% (0.0148 → 0.0078).
Comparing end-to-end against a Dense FP16 KV Oracle (640 tokens across 5 real 4K–8K domains) makes the picture even clearer:
| System (all vs Dense FP16 KV oracle) | Mean KL | Median KL | p95 KL | p99 KL | Top-1 agree | Flip rate | Top-5 overlap |
|---|---|---|---|---|---|---|---|
Dense Q8_0 KV (no clustering) | 0.0112 | 0.0001 | 0.0357 | 0.0886 | 98.0% | 2.0% | 91.4% |
Q8_0 + ClusterKV (k = 512, B = 16, cold = True) | 0.0124 | 0.0001 | 0.0433 | 0.0931 | 97.3% | 2.7% | 90.1% |
Q8_0 + ClusterKV (k = 1024, B = 32, no-cold) | 0.0091 | 0.0001 | 0.0398 | 0.1086 | 97.7% | 2.3% | 90.3% |
Q8_0 + ClusterKV (k = 1024, B = 32, cold = True) | 0.0082 | 0.0001 | 0.0391 | 0.0871 | 98.6% | 1.4% | 90.9% |
Q8_0 + ClusterKV (k = 1024, B = 32, cold = True) lands at 0.0082 mean KL (0.0001 median, 98.6% top-1 agreement) against Dense FP16—slightly lower than Dense Q8_0 KV (0.0112), because ClusterKV keeps the Local-1K window in FP16 and merges the virtual sink in FP32. That is 2×–6× smaller than the ~0.015–0.05 mean KL of UD-Q4_K_M weight quantization itself. On Needle-in-a-Haystack retrieval across 16K, 32K, and 64K contexts (20%, 25%, 50%, and 80% depths), it matched the oracle with 100% passkey recall.
Making ClusterKV Acceptably Fast
The first Python ClusterKV prototype ran at 8.4 tok/s at 16K context because it bypassed LoopGraph and gathered hot clusters in PyTorch. Getting it fast took three passes (Figure 8 right).
First, we wired ClusterKV into LoopGraph (splitting the 8 full-attention visits into pre_g → ClusterKV → post_g), switched Host RAM slabs from FP16 to Q8_0, and turned on DSpark sd = 3. That lifted 16K decode from 8.4 to 41.2 tok/s, with PCIe fetch down to 0.83 ms/token.
Second, we replaced PyTorch’s attend()—which was still copying 64 MB/step of gathered clusters across VRAM—with a single-pass FP32 online-softmax CUDA kernel (inkling_cluster_attend_f16). It reads the Local ring, follows indirect VRAM LRU pointers for Far-Hot clusters with zero copies, skips cold V loads whenever $s \le m - 25$, and fuses the virtual sink. That cut 8-layer attend() 3.65× (11.18 → 3.06 ms/step for $T = 4$), lifting 16K steady decode to 46.6 tok/s and 64K steady decode from 22.8 to 44.0 tok/s.
Third, profiling long AIME runs at 12K context still showed 12.67 ms/step inside ClusterKV: 5.41 ms in eager routing and eight tolist() syncs, 3.79 ms in Python dict LRU bookkeeping, and 3.46 ms in evict_batch = 64 online splits. We moved all LRU tables and miss DMA staging into C++ (ClusterFastLayer / ClusterFastPool), wrote four fused CUDA kernels (direct FP32-query centroid scoring, single-kernel top-$M$, fused dequant_scatter_q8_slabs_f16 writing misses straight into VRAM slots, and zero-copy attend_into), and raised evict_batch from 64 to 256.
Q8_0 + ClusterKV (k = 1024, cold = True) achieves 0.0082 mean KL and 98.6% top-1 agreement. Right: ClusterKV decode throughput from the 8.4 tok/s prototype to 48.6 tok/s at 17.6K and 43.8 tok/s at 76K.That final pass cut 12K ClusterKV overhead 4.21× (from 12.67 down to 3.01 ms/step):
ClusterKV benchmark (6000 MiB cache, Q8_0, sd = 3) | Before (dbc8aef) | After (ClusterFastLayer) | Delta |
|---|---|---|---|
12K ClusterKV breakdown (append / attend / total) | 3.46 / 9.20 / 12.67 ms | 0.63 / 2.38 / 3.01 ms | 4.21× faster |
| AIME 2026 Problem #10 (handoff @ 4K, 7,163 tok) | 63.1 tok/s | 72.0 tok/s | +14.1% (fetch 0.25 ms/step) |
| 16K–17.6K prompt (full / steady decode, Needle PASS) | 39.4 / 46.6 tok/s | 46.4 / 48.6 tok/s | +17.8% full (634 MiB peak) |
| 64K–76.1K prompt (full / steady decode, Needle PASS) | 34.8 / 44.0 tok/s | 39.5 / 43.8 tok/s | +13.5% full @ +15% ctx |
We also added a mid-decode handoff at 4,096 tokens so short generations pay zero ClusterKV overhead and only cluster if a long chain of thought crosses 4K. On a full 256K (262,144-token) 8-layer Host-Stream + ClusterKV stress test, prefill KV VRAM stayed at 34.9 MiB, post-build VRAM at 296.1 MiB (460 MiB peak), and Host RSS at 10.12 GiB.
Prefix Caching and Disk Offload
Once single-turn speed and 256K context worked, the last piece needed for everyday local use (OpenWebUI, OpenCode, and multi-turn coding agents) was fast prefix reuse across turns and sessions. Most of this follows standard serving practice, with a couple of twists for a 30 GiB RAM desktop running a reasoning model.
For back-to-back turns in the same conversation, we continue directly in place from live VRAM with zero restore overhead. Once another conversation takes over the GPU, however, we cannot afford to hoard dozens of idle KV caches in host RAM—our 30 GiB of system memory is already shared between the 15.5 GiB model weights and up to 4.25 GiB of ClusterKV host slabs for the active request. Instead, we built an OpenAI-compatible server (tinyloop-serve, with fail-fast VRAM/RAM/disk checks and native tool calling) backed by a bounded 100 GiB on-disk LRU Radix Tree (./prev_convos). When a session goes idle, the server serializes its complete state—all 48 KV caches (dense Q8_0 or ClusterKV centroids and host slabs), all 192 short-convolution states, and DSpark’s KV and Markov RNN state—to disk, evicting the oldest snapshots once the directory approaches 100 GiB. Restoring a cached session averages ~148 ms on multi-turn coding workloads, and saving a ~30K ClusterKV snapshot takes roughly 0.63 seconds.
One practical quirk shows up with reasoning models in OpenAI-compatible clients like OpenCode. On turn 1, the server prefills prompt_1 and generates thinking_1 + answer_1. On turn 2, the client strips the thinking tokens and sends prompt_1 + answer_1 + user_2. We do not keep thinking_1 in the context—the model must see the exact tokens the client sent—so turn 2 only shares a prefix with turn 1 up to the end of prompt_1. Because a ClusterKV state and 192 short-convolution buffers cannot be cheaply rewound backward past thinking_1, saving only a single post-decode snapshot (prompt_1 + thinking_1 + answer_1) would force turn 2 to miss the cache and re-prefill all of prompt_1 from scratch. Saving a protected end-of-prompt checkpoint right after prefilling prompt_1 (before thinking_1 is generated) solves this cleanly: turn 2 restores the exact prompt_1 snapshot from disk—with no stripped thinking inside—and only prefills the short new answer_1 + user_2 suffix.
Final Performance
All final benchmarks below use the unified 256K deployment profile (--expert-cache-mib 6000 --kv-cache-type q8_0 --cluster-kv --spec-draft 3 --ctx-len 262144), reasoning_effort = "medium", temp = 1.0, and natural stopping with a 32,768-token ceiling.
Math Reasoning: AIME 2026
On the standard 3-problem × 3-repetition AIME 2026 slice (20261202T083329Z-inkling-3ccd38c4, 1 discarded 32-token warm-up, 32K natural-stop cap), the final 256K engine averages 75.44 tok/s pooled steady decode (76.97 median, 80.23 p90) and 71.91 tok/s aggregate E2E with 9/9 (100% pass@1, 100% pass@3)—2.71× faster decode and 2.64× faster E2E than tuned 12-loop llama.cpp (27.85 decode / 27.20 E2E):
| AIME 2026 (3×3, unified 256K profile) | Prompt | Mean output | Steady decode | Overall E2E | GPU expert hit | Mean tok/step | Accuracy |
|---|---|---|---|---|---|---|---|
| Problem 1 (3 reps) | 183 tok | 1,151 tok | 81.05 tok/s | 74.18 tok/s | 95.2% | 3.02 | 3 / 3 |
| Problem 2 (3 reps) | 96 tok | 2,333 tok | 76.97 tok/s | 74.10 tok/s | 95.8% | 2.74 | 3 / 3 |
| Problem 3 (3 reps) | 153 tok | 2,238 tok | 71.31 tok/s | 68.58 tok/s | 95.4% | 2.61 | 3 / 3 |
| Overall (3 reps × 3 problems) | 144 avg | 5,722 / rep | 75.44 pooled (76.97 p50) | 71.91 agg (1,076 ms TTFT) | 95.5% | 2.79 | 9 / 9 (100%) |
To stress-test the 4K ClusterKV handoff and on-disk snapshot path on much longer traces, we also ran 4 long-generation AIME 2026 problems (P15, P28–P30) end-to-end over HTTP/SSE through tinyloop-serve. Even on 17K–32K token chains of thought (more than 2× past llama.cpp’s 12K OOM ceiling), decode stayed between 55.7 and 60.9 tok/s with 0 NaNs across all saved disk snapshots and 3/4 solved (P15 hit the 32,768-token ceiling):
| AIME 2026 long traces (HTTP/SSE, 256K) | Prompt | Output | Wall time | Decode | Finish | Result | Disk snapshot audit |
|---|---|---|---|---|---|---|---|
| Problem 15 | 287 tok | 32,768 tok | 560.7 s | 58.6 tok/s | length | Cap hit (gt 83) | 790.9 MB, max_c = 899, 0 NaNs |
| Problem 28 | 168 tok | 17,301 tok | 311.8 s | 55.7 tok/s | stop | 107 (PASS) | 503.8 MB, max_c = 442, 0 NaNs |
| Problem 29 | 212 tok | 28,731 tok | 505.2 s | 57.1 tok/s | stop | 157 (PASS) | 715.3 MB, max_c = 763, 0 NaNs |
| Problem 30 | 210 tok | 29,156 tok | 481.1 s | 60.9 tok/s | stop | 393 (PASS) | 722.1 MB, max_c = 754, 0 NaNs |
Beyond Math: Multi-Turn SWE-Agent Coding Replay
Math is a friendly benchmark for speculative decoding: long chains of formulaic algebra give DSpark high acceptance rates. Real coding agents like OpenCode look very different—shorter bursts of reasoning, JSON tool calls, code edits, and frequent multi-turn context switches where previous turns’ thinking gets stripped from the prompt.
To measure non-math performance and test our on-disk Radix KV cache under realistic churn, we replayed 4 real GitHub trajectories from swe_agent_trajectories.jsonl (AnalogJ/lexicon, Azure/azure-functions-python-worker, Melevir/cognitive_complexity, TheFriendlyCoder/pyjen), 7 turns each (28 interleaved requests, T1 of all four repos → T2 → … → T7, up to 6,566 prompt tokens, crossing the 4,096-token ClusterKV boundary), with natural stopping and no artificial max_tokens cap.
Running this workload live actually surfaced the end-of-prompt checkpoint bug described above: our first interleaved run got 0/24 disk hits because each turn’s post-decode offload was superseding its pre-decode checkpoint whenever another repo ran next. Protecting end-of-prompt snapshots lifted Turn 2+ disk hits to 24/24 (100%):
tinyloop-serve cuts Turn 2+ median TTFT 2.6× (and 10.5× on Azure Turn 7 at 6.6K tokens). Right: Decode speed across coding and math under the same 256K profile.| SWE-Agent interleaved replay (4 repos × 7 turns, natural stop) | Cold (before fix) | Disk Radix Tree (after fix) |
|---|---|---|
| Turn 2+ disk cache hit rate | 0 / 24 (0.0%) | 24 / 24 (100.0%) |
Turn 2+ prompt token reuse (cached / total) | 0.0% | 78.6% (59,555 / 75,733) |
| Turn 2+ median TTFT | 7,542 ms | 2,910 ms (2.59× faster) |
| Azure Turn 7 TTFT (6,566 prompt tokens, 98% cached) | 18,080 ms | 1,730 ms (10.5× faster) |
| Turn 2+ effective prefill throughput | 356.5 tok/s | 616.2 tok/s (1.73×) |
| Mean disk restore latency (24 session switches) | — | 147.7 ms / restore |
| Coding decode speed (median / mean steady) | 55.6 / — tok/s | 49.0 / 52.5 tok/s (46.6 / 47.6 full) |
| Finish reasons & snapshot audit | 21 stop, 7 tool_calls | 21 stop, 7 tool_calls, 0 length · 57 snaps (50 ClusterKV), 0 NaNs |
As expected, harder-to-draft coding and tool-calling turns decode slower than AIME math (~49–53 tok/s steady vs 70+ tok/s on math), though still nearly 2× tuned llama.cpp while handling 4 interleaved sessions across the 4K ClusterKV boundary with 0 NaNs.
Overall Summary
Metric (RTX 3080 10 GiB, unchanged UD-Q4_K_M) | Stock llama.cpp | Tuned llama.cpp | TinyLoop (256K profile) |
|---|---|---|---|
| Max context length | 12K | 12K | 256K (21.3×) |
| Cold prefill (512–8K / 64K) | — | ~138 tok/s / OOM | 444–476 tok/s (3.3×) / 409 tok/s |
| Math decode (3×3 AIME / 17K–32K tail) | 6.3 tok/s / OOM | 27.9 tok/s / OOM | 75.4 pooled (77.0 p50) / 56–61 tok/s |
| Coding agent decode (SWE-Agent, interleaved) | — | — | 49.0 median / 52.5 mean steady tok/s |
| Long-context decode (76K prompt) | OOM | OOM | 43.8 tok/s steady |
| Fidelity vs Dense FP16 KV (5 domains) | — | Exact FP16 (≤12K) | 0.0082 mean KL (98.6% top-1) |
Closing Notes
Three practical lessons stood out across both hillclimbs. First, layer-level offloading wastes a huge amount of VRAM on MoE models; caching individual experts with Decaying-LFU and coalescing GPU reads across speculative verify batches turned DSpark from a wash into a 2.5–3× speedup. Second, offline cache simulations can be misleading once DDR4 memory bandwidth and launch overhead enter the picture—our linear expert predictor cut simulated misses by 60–66% and barely moved wall-clock speed. Third, paying attention to architectural details like Inkling 2 Mini’s lack of RoPE and bounded 1,024-token relative bias made position-invariant ClusterKV and O(1)-VRAM Far/Near prefill simpler, faster, and closer to FP16 than dense Q8_0 KV.
The full code, CUDA kernels, experiment logs, and reproduction instructions are available on GitHub at github.com/LawrenceRLiu/TinyLoop. After building the C++/CUDA extension, you can start the local OpenAI-compatible server in the 256K profile with uv run --locked tinyloop-serve.
-
Steady decode convention: Every benchmark runs at concurrency 1 and first discards one 32-token warm-up request. On each measured request, steady decode also excludes the first 16 decode steps (so one-time per-request CUDA graph capture and initial cache warm-up do not skew short requests) and divides all remaining generated tokens by synchronized forward-call time across those steps. Pooled steady decode sums included tokens and included decode milliseconds across all requests in a repetition before dividing. Full-request decode and end-to-end (E2E) rates include prefill and every decode step. ↩