Tuning llama.cpp CUDA Kernels for Pascal (sm_61) on a GTX 1070 FE
Three ggml-cuda patches for Pascal (sm_61) on a GTX 1070 FE: native dp4a FlashAttention, lop3 unpackers, failed ablations, and real server caveats.
On This Signal (13 sections)
- Why Pascal (sm_61) Leaves Speed on the Table
- The Three Landed Patches (ee46715..6d7db93)
- 1. Native dp4a GQA FlashAttention (7d6a911)
- 2. lop3.b32 Bit-Unpackers, ncols = 1 Fusion, and mul_mat_q_few_dp4a (7f546c8)
- 3. MMQ lop3.b32 Tile Unpackers and by1 Register Prefetch (6d7db93)
- What Regressed (Four Reverted Ablations)
- The Numbers (Qwen3.5-9B-MTP on GTX 1070 FE)
- Isolated Kernel Throughput (llama-bench, r = 5)
- End-to-End llama-server (draft-mtp, r = 1, cache_prompt: false)
- Scope and Caveats Worth Reading Before Judging the Headlines
- Safety Checks and Live Rollout
- Trying It Yourself
- Workflow Notes
The GeForce GTX 1070 FE in my workstation is not sitting in a spare PCIe slot for nostalgia. In my current llama-swap layout, it owns qwen3.5-9b-nv on CUDA0 as the default model for Hermes Agent so my RX 6900 XT stays free for AMD-only models and gaming, and it carries the 12% tail of qwen3.8-27b whenever I spin up the dual-GPU route.
Once you rely on a Pascal card every day, upstream llama.cpp’s generic pre-Volta CUDA fallbacks start standing out in profiles. Rather than leaving those cycles on the table, I ran a focused ggml-cuda tuning pass targeting Compute Capability 6.1 (sm_61) on llama.cpp ee46715 (b12927), cut my live router over to the resulting b12927-6d7db93-sm61 build, and published the MIT-licensed patches, benchmarks, and harness at s1mply-parad0x1cal/llama-cpp-sm61-optimizations.
Why Pascal (sm_61) Leaves Speed on the Table
Pascal GP104 has awkward hardware limits by modern inference standards: 256 GB/s of GDDR5, no Tensor Cores, no cp.async, and 1:64 FP16 throughput. Every SM has 65,536 32-bit registers and 96 KB of shared memory (48 KB/block static cap), which creates hard occupancy cliffs for 128-thread (4-warp) blocks:
<= 96registers/thread: 5 blocks/SM (20 warps)<= 128registers/thread: 4 blocks/SM (16 warps)<= 168registers/thread: 3 blocks/SM (12 warps)<= 255registers/thread: 2 blocks/SM (8 warps)
Cross 128 or 168 registers per thread and you immediately lose an entire resident block per SM (25% to 33% fewer warps available to hide ~400-cycle GDDR5 latency) or spill into local stack memory (STACK > 0).
What sm_61 does have is native hardware __dp4a (IDP4A, four INT8 multiply-accumulates per instruction) and lop3.b32 (LOP3.LUT, three-input bitwise lookup logic). That applies across desktop and workstation sm_61 cards (GTX 1060 through 1080 Ti, TITAN X Pascal / TITAN Xp, Tesla P4 / P40, and Quadro P-series), while sm_60 (Tesla P100) lacks hardware __dp4a and stays on upstream fallbacks.
In upstream llama.cpp, small-batch quantized KV FlashAttention on sm_61 was routing through FP16 dequantization (dequantize_block_q8_0_f16 plus flash_attn_tile on pp=4, and flash_attn_ext_vec on B = 1..2). That meant extra DRAM round-trips and FP16 work on an architecture built to punish FP16.
The Three Landed Patches (ee46715..6d7db93)
Everything stays strictly inside ggml/src/ggml-cuda/ across 10 files (+1,417 / -19 lines) and is gated to Pascal dp4a (__CUDA_ARCH__ == 610 / GGML_CUDA_CC_DP4A). Volta+ CUDA, Vulkan, and CPU code paths are untouched.
Because nvprof --metrics errors out (4212:27) on CUDA Toolkit 12.9 with driver 580.196.07, every change was verified through nsys, cuobjdump -res-usage, cuobjdump -sass, ptxas, test-backend-ops, llama-perplexity, llama-bench, and live llama-server runs.
1. Native dp4a GQA FlashAttention (7d6a911)
Patch 0001 adds flash_attn_ext_dp4a_sm61 (fattn-dp4a-sm61.cuh, wired through fattn.cu, fattn-vec.cuh, and fattn-tile.cuh) covering batch sizes B = 1..8, head dimensions D in {128, 256}, and Q8_0, Q4_0, or Q4_1 KV caches:
- Quantizes
QtoQ8_1once at kernel entry and keeps it in registers. - Stages 32 raw quantized KV rows per tile in shared memory (
2,560–8,704 B/block) instead of expanding KV into an FP16 staging buffer. - Runs pure
int8x4__dp4aonQ8_0keys, and in-register nibble shift/mask plus algebraic-8 * Q_ds.yzero-point folding before__dp4aonQ4_0keys. - Unpacks
Vfour elements at a time in registers (dequantize_V<type_V, float, 4>) and accumulatesP * Vin FP32 to sidestep Pascal’s1:64FP16 bottleneck. - Leaves bulk prefill (
B > 8) onflash_attn_tile, where one-time KV dequantization amortizes across many query rows.
In matched nsys traces (B = 4, d = 4096 across 8,216 FlashAttention calls), this dropped dequantize_block_q8_0_f16 from 16,432 calls (920.34 ms) to zero and cut total FlashAttention GPU time nearly in half: from 1,899.73 ms down to 951.24 ms (1.997x on the final 3-patch stack).
2. lop3.b32 Bit-Unpackers, ncols = 1 Fusion, and mul_mat_q_few_dp4a (7f546c8)
Patch 0002 targets quantized matvec and small-batch speculative verification across lop3-sm61.cuh, vecdotq.cuh, fusion.cu, and mmq-few.cu:
- Adds
static_assert-checked PTXlop3.b32bit-unpackers (LOP3.LUT(..., 0xea)) forQ3_K,Q5_K,Q6_K,Q4_K/Q5_Kscales,IQ3_XXS, andIQ3_S, confirmed incuobjdump -sassalongsideSHFL.IDXandIDP4A. - Unlocks
ncols_dst == 1RMSNorm/GLU fusion onsm_61infusion.cu. - Adds register-streamed
mul_mat_q_few_dp4a(__launch_bounds__(128, 4),0 Bweight/activation shared memory) covering 9 quant types (Q4_K,Q5_K,Q6_K,Q8_0,Q3_K,IQ3_XXS,IQ3_S,IQ4_NL,IQ4_XS), dispatched only at its measured crossover:min_ncols = 7forQ3_K..Q6_Kand8for the rest.
3. MMQ lop3.b32 Tile Unpackers and by1 Register Prefetch (6d7db93)
Patch 0003 extends the lop3.b32 helpers into mmq-load-tiles.cuh (Q3_K, IQ3_XXS, IQ3_S) and adds an sm_61-gated by1 activation register prefetch (use_y1_prefetch) in mmq.cuh. It preloads the next activation tile into registers during vec_dot(..., 0) and disables itself on register-tight types (Q2_K, IQ4_XS, and fallback && Q6_K) so every active mul_mat_q instantiation (132/132) stays at STACK:0, LOCAL:0.
What Regressed (Four Reverted Ablations)
Finding out what hurt on GP104 mattered just as much as the patches that landed. Four reasonable-sounding ideas failed measurement and were reverted:
- Swapping
(j, i)to(i, j)loops inmmvq.cu: Reusing loaded weight blocks across columns inflated multi-column register pressure (Q4_Kncols=8:128 -> 148regs, dropping from 4 to 3 blocks/SM;Q3_Kncols=8:167 -> 195regs, dropping from 3 to 2 blocks/SM) and regressedpp4 @ d2048across all three tested quants (up to-3.38 tok/sonUD-Q3_K_XL). - Dispatching
mul_mat_q_few_dp4abelowB = 7: ReplacingMMVQglobally acrossB = 2..8crushed small speculative batches (UD-Q4_K_XL pp2:48.51 -> 32.72 tok/s,-32.5%;pp4:-17.0%) becauseMMVQhas cleaner coalesced activation reads atB <= 6. SweepingB = 4..8at 4 blocks/SM pinned the true crossover cleanly atB = 7..8. - Adding
#pragma unrollonk01inmmq-vec-dot.cuh: Unrolling pushedJ = 64bulk prefill kernels past their128-register cap intoSTACKspills, droppingpp512by-9.2%onUD-Q4_K_XLand-28.2%onUD-IQ3_XXS(617.49 -> 443.48 tok/s). - Splitting
K_smem + V_smeminfattn-dp4a-sm61.cuh(4 -> 2barriers/tile): Doubling shared memory (8,704 -> 17,408 BatD = 256, Q8_0) removed twoBAR.SYNCbarriers per 32-row tile while keeping occupancy identical (<= 128regs atB = 1..2,<= 168atB = 3..8). In matched-temperaturensysruns (d = 16384), that sped upB = 1(<256, 1, 4>) by+2.64%(371.1 -> 361.5 us), but slowedB = 4(<256, 4, 4>) by-3.71%(334.0 -> 346.9 us, pullingpp4down-1.06%to-1.80%). Single-bufferedKV_smemstayed active overall; if revisited later, splitting onlycpw == 1viaif constexpris the cleaner path.
The Numbers (Qwen3.5-9B-MTP on GTX 1070 FE)
All benchmarks compared upstream ee46715 against 6d7db93 (Release, -DCMAKE_CUDA_ARCHITECTURES=61 -DGGML_CUDA_FORCE_MMQ=ON) on three Unsloth quants of Qwen3.5-9B-MTP (hybrid Gated-DeltaNet + 8 gated-attention layers, D = 256, gqa_ratio = 4): UD-Q4_K_XL (5.70 GiB), UD-Q3_K_XL (4.87 GiB), and UD-IQ3_XXS (3.99 GiB).
Isolated Kernel Throughput (llama-bench, r = 5)
| Workload | KV Cache | UD-Q4_K_XL |
UD-Q3_K_XL |
UD-IQ3_XXS |
|---|---|---|---|---|
tg=128 (d=0) |
q8_0/q8_0 |
26.63 -> 27.88 (+4.7%) | 28.93 -> 29.41 (+1.7%) | 27.23 -> 29.16 (+7.1%) |
tg=64 (d=16384) |
q8_0/q8_0 |
22.93 -> 25.64 (+11.8%) | 24.78 -> 27.02 (+9.1%) | 23.38 -> 26.44 (+13.1%) |
tg=64 (d=8192) |
q4_0/q4_0 |
22.83 -> 26.78 (+17.3%) | 24.63 -> 28.31 (+15.0%) | 23.29 -> 27.77 (+19.3%) |
pp=2 (d=16384, ub=8) |
q8_0/q8_0 |
32.28 -> 44.96 (+39.3%) | 32.90 -> 46.06 (+40.0%) | 32.23 -> 44.75 (+38.9%) |
pp=8 (d=16384) |
q8_0/q8_0 |
79.37 -> 95.71 (+20.6%) | 79.90 -> 100.20 (+25.4%) | 79.12 -> 86.01 (+8.7%) |
pp=512 (d=0) |
q8_0/q8_0 |
538.57 -> 541.47 (+0.5%) | 502.76 -> 508.31 (+1.1%) | 608.49 -> 616.48 (+1.3%) |
End-to-End llama-server (draft-mtp, r = 1, cache_prompt: false)
Selected single-request server rows from the full 18-case matrix in benchmarks/phase4_comparison.md, contrasting post-prefill generation (tg tok/s, draft acceptance %) against total HTTP request wall time (wall_s, which includes uncached prompt prefill):
Model (draft-mtp) |
Case (pp / tg) |
tg tok/s (Accept) |
tg Ratio |
Request wall_s |
Wall Speedup | Parity |
|---|---|---|---|---|---|---|
UD-IQ3_XXS (n-max=3) |
ctx4k_greedy (5255 / 192) |
25.94 (41.0%) -> 29.79 (48.3%) | 1.149x | 17.75s -> 16.66s | 1.065x (+6.5%) | DIFF! |
UD-Q3_K_XL (n-max=2) |
ctx4k_greedy (5255 / 192) |
33.82 (60.5%) -> 36.19 (65.5%) | 1.070x | 17.84s -> 17.35s | 1.028x (+2.8%) | DIFF! |
UD-Q4_K_XL (n-max=2) |
ctx4k_greedy (5255 / 192) |
31.68 (54.1%) -> 31.97 (53.6%) | 1.009x | 17.74s -> 17.62s | 1.007x (+0.7%) | DIFF! |
UD-Q4_K_XL (n-max=3) |
short_temp07 (64 / 256) |
30.64 (45.3%) -> 32.39 (49.0%) | 1.057x | 8.48s -> 8.03s | 1.056x (+5.6%) | diff(sampling) |
UD-Q3_K_XL (n-max=2) |
short_temp07 (64 / 256) |
35.45 (58.3%) -> 33.08 (51.4%) | 0.933x | 7.36s -> 7.87s | 0.935x (-6.5%) | diff(sampling) |
UD-Q3_K_XL (n-max=3) |
short_greedy (64 / 256) |
33.30 (55.2%) -> 31.41 (48.9%) | 0.943x | 7.83s -> 8.29s | 0.945x (-5.5%) | DIFF! |
Scope and Caveats Worth Reading Before Judging the Headlines
Benchmark numbers are easy to oversell if you don’t separate isolated kernels from full requests. Three caveats belong right alongside the tables:
- Isolated verification step vs. full HTTP wall time. The
+38.9%to+40.0%jump is isolatedllama-benchmicrobatch verification (pp=2 @ d=16384). On a single-request uncachedllama-servercall with5,255prompt tokens and192generated tokens, uncached prefill eats roughly 10 seconds either way, so a+14.9%post-prefilltggain (25.94 -> 29.79 tok/s) translates into a+6.5%full-request wall speedup (17.75s -> 16.66s). Multi-turn chats with warm KV prefix reuse see much more of the decode and verification uplift. - Perplexity parity vs. greedy
DIFF!trajectories. Everytest-backend-opscheck passed (CUDA0:FLASH_ATTN_EXT4466/4466,SWIGLU36/36,GEGLU36/36,MUL_MAT2845/2845), and a short 6-chunk (3,072-token) teacher-forcedllama-perplexitycheck showed zero measured delta (UD-Q4_K_XL4.7172,UD-IQ3_XXS4.8221,|Delta| = 0.000000). Even so, FP32 reduction reordering still nudges borderline logits enough that all greedydraft-mtpserver runs diverged (DIFF!), shifting downstream draft acceptance by+-5..7percentage points and making several single-shotshort_temp07andn-max=3cases finish slower (0.933x..0.993xtg) than baseline. 64K-configured window VRAM check vs. filled64Kdecode. My productionqwen3.5-9b-nvprofile runsUD-Q4_K_XLwith CPU-offloaded vision (mmproj-Qwen3.5-9B-MTP-F16.ggufvia--no-mmproj-offload),--ctx-size 65536,q8_0/q8_0KV, anddraft-mtp n-max=2. A smoke check confirmed it fits cleanly at7,357 / 8,192 MiBVRAM (57 C) and hit43.91 tok/s(88.24%draft acceptance) on a short uncached prompt (40prompt +96generated tokens). That proves allocation headroom with a64Kwindow configured, not sustained decode with64Ktokens filled (filled-contextllama-benchdecode was measured up tod=16384in Phase 4 andd=32768in Iteration 4 at23.93–24.41 tok/s).
Safety Checks and Live Rollout
Before switching llama-swap.yaml over, I verified both spill cleanliness and non-CUDA benignness on the mixed CUDA 61 + Vulkan + CPU release build:
- Zero register spills (
STACK:0, LOCAL:0) across all72flash_attn_ext_dp4a_sm61,18mul_mat_q_few_dp4a,132activemul_mat_q, and271non-MoEmul_mat_vec_qinstantiations. - Non-CUDA routes unaffected:
Vulkan0(pp5121,391.0 -> 1,389.9 tok/s,tg6467.3 -> 68.1 tok/s) and CPUembeddinggemma(pp5121,568.6 -> 1,724.8 tok/s) stayed clean, along with live smoke checks onembeddinggemma-300m-qat-Q8_0,qwen3.5-9b-nv,qwen3.5-9b, andqwen3.8-27b. - Side-by-side rollback preserved: All 8
llama.cppmixed routes inllama-swap.yamlnow point atllama.cpp-b12927-6d7db93-sm61/mixed, while the originalllama.cpp-b12927-ee46715/mixedbuild and pre-cutover config remain untouched on disk for a one-line rollback.
Trying It Yourself
The standalone repository at s1mply-parad0x1cal/llama-cpp-sm61-optimizations includes the three patch files (patches/0001..0003), the full technical dossier (docs/TECHNICAL_DOSSIER.md), the Phase 4 and Iteration 4 benchmark datasets, a read-only fail-closed A/B harness (scripts/bench_ab.sh + scripts/parse_results.py), a spill-checking helper (scripts/dump_telemetry.sh), and an AGENT_ADOPT_PROMPT.md if you prefer letting a coding agent inspect your tree and build in an isolated worktree before asking to cut over.
For a manual worktree build and verification pass:
# 1. Create an isolated worktree on upstream llama.cpp ee46715 and apply patchesgit -C /path/to/llama.cpp worktree add -b sm61-opt /path/to/worktree ee46715git -C /path/to/worktree am -3 /path/to/llama-cpp-sm61-optimizations/patches/0001-*.patch \ /path/to/llama-cpp-sm61-optimizations/patches/0002-*.patch \ /path/to/llama-cpp-sm61-optimizations/patches/0003-*.patch
# 2. Build Release for sm_61 with MMQ forced (add -DGGML_VULKAN=ON if co-serving AMD)cmake -S /path/to/worktree -B /path/to/worktree/build-sm61 -G Ninja \ -DCMAKE_BUILD_TYPE=Release \ -DGGML_CUDA=ON -DCMAKE_CUDA_ARCHITECTURES=61 -DGGML_CUDA_FORCE_MMQ=ON \ -DGGML_NATIVE=ON -DGGML_CPU_REPACK=ONcmake --build /path/to/worktree/build-sm61 --target llama-bench llama-server llama-perplexity test-backend-ops
# 3. Audit STACK:0 / LOCAL:0 telemetry and run CUDA backend unit tests./scripts/dump_telemetry.sh /path/to/worktree/build-sm61/bin/libggml-cuda.so res_usage.txtCUDA_VISIBLE_DEVICES=0 /path/to/worktree/build-sm61/bin/test-backend-ops test -b CUDA0 -o FLASH_ATTN_EXT,SWIGLU,GEGLU,MUL_MAT
# 4. Run matched A/B benchmarks against your baseline build./scripts/bench_ab.sh /path/to/baseline-build baseline "/path/to/your-model.gguf" quick./scripts/bench_ab.sh /path/to/worktree/build-sm61 sm61 "/path/to/your-model.gguf" quick./scripts/parse_results.py baseline sm61By default, scripts/bench_ab.sh is read-only and fail-closed: if LLAMA_SWAP_URL is set, it queries GET /running and aborts if the router is unreachable or any model is active unless you explicitly pass ALLOW_SWAP_UNLOAD=1.
Workflow Notes
Like my recent agentic coding experiments, this campaign split the work between an architectural planning pass (GP104 register/occupancy analysis, ablation design, and qualification gates using Gemini 4 Carbon) and CUDA execution/profiling subagents (kernel authoring, cuobjdump/nsys telemetry loops, and A/B runs using Gemini 4 Hydrogen), with every merge gated on hard register-spill, unit-test, and benchmark checks. The most useful part of running it that way wasn’t generating code faster—it was catching and reverting four tempting optimizations (mmvq.cu loop swapping, aggressive mmq-few dispatch, k01 unrolling, and global split K+V shared memory) before they could quietly regress real workloads.
Next step is letting b12927-6d7db93-sm61 soak under normal daily Hermes and dual-GPU routing and seeing how the patches behave on other sm_61 cards (1080 Ti, P40) before deciding whether to clean them up for an upstream llama.cpp PR.
ADJACENT SIGNALS // CONTINUE READING