perf: multi-activation kernels make the CPU small-batch pass cheaper, bit-identical (STRA-220)
Profiling the speculative verification pass (batch_cost, position 900) showed its extra cost is compute in the int8 weight products, not expert bytes: distinct experts per layer rise only from 4 to 9.5 at 9 tokens, while the Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step. Each (row, token) dot redid the MXFP4 decode and scale work. cpu-sys gains multi-activation kernels (portable, AVX2, AVX-VNNI) for MXFP4 and Q8_0 rows: the row is decoded once per 64-block segment and up to 16 activations run over it with exactly the one-token kernel's accumulators and final reduction, so every output is bit for bit the one-token kernel's (tests/multi.rs: every level, 1-16 activations, 13 row lengths). run_region uses them for jobs with two or more activations (speculative batches and prefill chunks); one-token decode keeps its kernel. A new synthetic test checks a 20-token batch at every level against feeding tokens one at a time. Model::set_multi_activation(false) restores the per-token path for paired measurements; Profile counts the expert sets read. batch_cost gains a per-size phase breakdown and an `ab` mode that runs every pass without and with the new kernels back to back and checks the logits are identical. Paired, 9 rounds, real model: identical logits in all 90 paired passes; time ratio with/without 1.01 (1 token), 0.98, 0.92, 0.90, 0.83, 0.81, 0.77, 0.79, 0.76 (2..9 tokens). MEASURED_COST becomes 0.737 + 0.421 n (was 0.30 + 0.631 n). ab_speculation (3 pairs, outputs identical in all 24 runs) gave 1.34 / 1.04 / 0.97 / 0.94, within the pair-to-pair spread of the run before the change; replaying the outputs through the drafter predicts 1.59 / 1.15 / 1.00 / 0.99, so the serving loop loses time the pass-cost model does not see. Prefill also uses the kernels (bit-identical); its speed was not measured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
c58173097d
commit
87637c2b0b
@@ -0,0 +1,132 @@
|
||||
# multi-activation kernels for the CPU small-batch pass (speculative verification): paired measurements
|
||||
model: gpt-oss-20b-MXFP4.gguf (12109565632 bytes, sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB)
|
||||
cpu: Core Ultra 7 265U, 14 threads, kernels avx-vnni, single-channel DDR5-5600; base commit c581730 plus this change
|
||||
date: 2026-10-16; machine state not controlled (another session ran teacher-forced probes on the same model in between;
|
||||
runs below were started only after no other model process had run for 60 s)
|
||||
|
||||
## profile before the change (batch_cost, position 900, 5 rounds, quiet morning run, single step 89 ms)
|
||||
n median ms ms per token cost vs n single steps
|
||||
1 89 89 1.00 (runs [86.0, 88.0, 89.0, 90.0, 92.0])
|
||||
2 131 65 0.74 (runs [131.0, 131.0, 131.0, 132.0, 134.0])
|
||||
3 170 57 0.64 (runs [166.0, 168.0, 170.0, 175.0, 175.0])
|
||||
4 220 55 0.62 (runs [210.0, 217.0, 220.0, 221.0, 224.0])
|
||||
5 261 52 0.59 (runs [254.0, 254.0, 261.0, 266.0, 269.0])
|
||||
6 304 51 0.57 (runs [301.0, 304.0, 304.0, 321.0, 323.0])
|
||||
7 360 51 0.58 (runs [348.0, 358.0, 360.0, 370.0, 372.0])
|
||||
8 418 52 0.59 (runs [393.0, 401.0, 418.0, 420.0, 425.0])
|
||||
9 458 51 0.57 (runs [451.0, 457.0, 458.0, 466.0, 472.0])
|
||||
phase breakdown, per token, summed over the measured rounds:
|
||||
1 per token ms: qkv 12.5 | attention 5.1 | o-proj 10.1 | router 1.2 | gate+up 26.9 | activation 1.0 | down 15.0 | lm-head 17.1 | total 88.8 | distinct experts per layer 4.0
|
||||
2 per token ms: qkv 7.3 | attention 3.9 | o-proj 5.9 | router 0.9 | gate+up 23.7 | activation 1.4 | down 12.6 | lm-head 10.1 | total 65.8 | distinct experts per layer 5.6
|
||||
3 per token ms: qkv 5.9 | attention 2.9 | o-proj 4.7 | router 0.7 | gate+up 21.2 | activation 1.4 | down 11.4 | lm-head 8.5 | total 56.8 | distinct experts per layer 6.5
|
||||
4 per token ms: qkv 5.5 | attention 2.8 | o-proj 4.5 | router 0.6 | gate+up 20.4 | activation 1.4 | down 11.1 | lm-head 8.1 | total 54.5 | distinct experts per layer 7.4
|
||||
5 per token ms: qkv 5.2 | attention 2.5 | o-proj 4.2 | router 0.6 | gate+up 19.8 | activation 1.5 | down 10.6 | lm-head 7.8 | total 52.1 | distinct experts per layer 8.2
|
||||
6 per token ms: qkv 5.1 | attention 2.4 | o-proj 4.1 | router 0.6 | gate+up 19.8 | activation 1.4 | down 10.6 | lm-head 7.6 | total 51.6 | distinct experts per layer 8.9
|
||||
7 per token ms: qkv 5.1 | attention 2.3 | o-proj 4.1 | router 0.6 | gate+up 19.9 | activation 1.5 | down 10.5 | lm-head 7.5 | total 51.5 | distinct experts per layer 9.7
|
||||
8 per token ms: qkv 5.1 | attention 2.4 | o-proj 4.0 | router 0.6 | gate+up 19.5 | activation 1.6 | down 10.4 | lm-head 7.8 | total 51.3 | distinct experts per layer 8.7
|
||||
9 per token ms: qkv 5.0 | attention 2.3 | o-proj 3.9 | router 0.5 | gate+up 19.6 | activation 1.5 | down 10.4 | lm-head 7.7 | total 51.1 | distinct experts per layer 9.5
|
||||
|
||||
## paired, in one process (batch_cost <model> 900 9 9 14 ab): every pass run without and with the multi-activation
|
||||
## kernels back to back, alternating which goes first; started 2026-10-16 12:40 local after 60 s with no other model process
|
||||
prefill of 900 tokens: 42.9 s; 14 threads
|
||||
one-token kernel per token:
|
||||
n median ms ms per token cost vs n single steps
|
||||
1 108 108 1.00 (runs [108.0, 107.0, 118.0, 105.0, 131.0, 106.0, 111.0, 101.0, 114.0])
|
||||
2 185 93 0.86 (runs [179.0, 179.0, 194.0, 185.0, 222.0, 183.0, 197.0, 174.0, 201.0])
|
||||
3 259 86 0.80 (runs [252.0, 253.0, 272.0, 262.0, 261.0, 265.0, 251.0, 244.0, 259.0])
|
||||
4 338 84 0.78 (runs [317.0, 323.0, 350.0, 339.0, 338.0, 343.0, 334.0, 324.0, 356.0])
|
||||
5 401 80 0.74 (runs [393.0, 398.0, 361.0, 406.0, 427.0, 449.0, 401.0, 399.0, 402.0])
|
||||
6 487 81 0.75 (runs [504.0, 463.0, 447.0, 476.0, 527.0, 489.0, 487.0, 461.0, 488.0])
|
||||
7 559 80 0.74 (runs [559.0, 549.0, 528.0, 543.0, 609.0, 595.0, 584.0, 557.0, 604.0])
|
||||
8 657 82 0.76 (runs [657.0, 590.0, 662.0, 609.0, 705.0, 670.0, 612.0, 647.0, 830.0])
|
||||
9 742 82 0.76 (runs [761.0, 765.0, 742.0, 721.0, 833.0, 739.0, 714.0, 669.0, 834.0])
|
||||
phase breakdown, per token, summed over the measured rounds:
|
||||
1 per token ms: qkv 14.4 | attention 8.3 | o-proj 11.7 | router 1.7 | gate+up 35.3 | activation 1.8 | down 20.5 | lm-head 17.5 | total 111.1 | distinct experts per layer 4.0
|
||||
2 per token ms: qkv 10.3 | attention 6.4 | o-proj 8.4 | router 1.3 | gate+up 33.4 | activation 2.3 | down 18.7 | lm-head 14.3 | total 95.1 | distinct experts per layer 5.5
|
||||
3 per token ms: qkv 9.2 | attention 4.8 | o-proj 7.2 | router 1.0 | gate+up 31.0 | activation 2.3 | down 16.9 | lm-head 13.4 | total 85.7 | distinct experts per layer 6.4
|
||||
4 per token ms: qkv 8.6 | attention 4.6 | o-proj 6.9 | router 1.0 | gate+up 31.2 | activation 2.4 | down 16.7 | lm-head 12.4 | total 83.8 | distinct experts per layer 7.8
|
||||
5 per token ms: qkv 8.2 | attention 4.0 | o-proj 6.6 | router 0.9 | gate+up 30.1 | activation 2.4 | down 16.1 | lm-head 12.2 | total 80.7 | distinct experts per layer 8.0
|
||||
6 per token ms: qkv 8.0 | attention 4.0 | o-proj 6.5 | router 0.9 | gate+up 30.3 | activation 2.4 | down 16.0 | lm-head 12.1 | total 80.3 | distinct experts per layer 8.7
|
||||
7 per token ms: qkv 8.1 | attention 3.8 | o-proj 6.5 | router 0.9 | gate+up 30.5 | activation 2.5 | down 16.3 | lm-head 12.7 | total 81.2 | distinct experts per layer 9.2
|
||||
8 per token ms: qkv 8.1 | attention 3.7 | o-proj 6.5 | router 0.8 | gate+up 32.1 | activation 2.5 | down 16.7 | lm-head 12.4 | total 82.9 | distinct experts per layer 9.1
|
||||
9 per token ms: qkv 8.3 | attention 3.7 | o-proj 6.5 | router 0.8 | gate+up 32.0 | activation 2.5 | down 16.9 | lm-head 12.8 | total 83.5 | distinct experts per layer 9.6
|
||||
multi-activation kernels:
|
||||
n median ms ms per token cost vs n single steps
|
||||
1 108 108 1.00 (runs [114.0, 106.0, 122.0, 106.0, 127.0, 108.0, 108.0, 102.0, 111.0])
|
||||
2 186 93 0.86 (runs [175.0, 190.0, 186.0, 186.0, 202.0, 186.0, 187.0, 171.0, 190.0])
|
||||
3 239 80 0.74 (runs [226.0, 228.0, 241.0, 241.0, 251.0, 248.0, 233.0, 232.0, 239.0])
|
||||
4 306 76 0.71 (runs [284.0, 281.0, 338.0, 306.0, 299.0, 316.0, 306.0, 289.0, 373.0])
|
||||
5 338 68 0.63 (runs [328.0, 340.0, 304.0, 332.0, 347.0, 357.0, 353.0, 338.0, 334.0])
|
||||
6 393 66 0.61 (runs [424.0, 376.0, 357.0, 370.0, 425.0, 393.0, 409.0, 369.0, 397.0])
|
||||
7 439 63 0.58 (runs [431.0, 444.0, 397.0, 419.0, 472.0, 462.0, 439.0, 410.0, 454.0])
|
||||
8 496 62 0.57 (runs [496.0, 463.0, 454.0, 493.0, 569.0, 524.0, 491.0, 500.0, 816.0])
|
||||
9 547 61 0.56 (runs [535.0, 532.0, 547.0, 560.0, 629.0, 617.0, 541.0, 513.0, 716.0])
|
||||
phase breakdown, per token, summed over the measured rounds:
|
||||
1 per token ms: qkv 14.3 | attention 8.3 | o-proj 11.7 | router 1.7 | gate+up 35.5 | activation 1.7 | down 20.5 | lm-head 17.4 | total 111.2 | distinct experts per layer 4.0
|
||||
2 per token ms: qkv 9.9 | attention 6.1 | o-proj 7.8 | router 1.2 | gate+up 33.1 | activation 2.5 | down 18.2 | lm-head 13.8 | total 92.7 | distinct experts per layer 5.5
|
||||
3 per token ms: qkv 8.0 | attention 4.9 | o-proj 6.2 | router 1.1 | gate+up 29.2 | activation 2.4 | down 16.1 | lm-head 11.2 | total 79.0 | distinct experts per layer 6.4
|
||||
4 per token ms: qkv 7.4 | attention 4.9 | o-proj 5.7 | router 1.0 | gate+up 29.5 | activation 2.5 | down 16.1 | lm-head 10.2 | total 77.4 | distinct experts per layer 7.8
|
||||
5 per token ms: qkv 6.2 | attention 4.0 | o-proj 4.9 | router 0.9 | gate+up 25.5 | activation 2.4 | down 13.8 | lm-head 9.5 | total 67.2 | distinct experts per layer 8.0
|
||||
6 per token ms: qkv 6.0 | attention 4.1 | o-proj 4.6 | router 0.9 | gate+up 24.7 | activation 2.5 | down 13.1 | lm-head 9.1 | total 65.0 | distinct experts per layer 8.7
|
||||
7 per token ms: qkv 5.6 | attention 3.7 | o-proj 4.4 | router 0.9 | gate+up 23.7 | activation 2.4 | down 12.8 | lm-head 8.7 | total 62.2 | distinct experts per layer 9.2
|
||||
8 per token ms: qkv 5.9 | attention 4.0 | o-proj 4.6 | router 0.9 | gate+up 25.0 | activation 2.7 | down 14.1 | lm-head 9.6 | total 66.6 | distinct experts per layer 9.1
|
||||
9 per token ms: qkv 5.7 | attention 3.9 | o-proj 4.4 | router 0.9 | gate+up 24.2 | activation 2.6 | down 13.2 | lm-head 9.1 | total 63.9 | distinct experts per layer 9.6
|
||||
logits of the two arms identical bit for bit in all 90 paired passes
|
||||
paired: time with multi-activation kernels / time without, per round
|
||||
n median ratio (ratios)
|
||||
1 1.006 [1.053, 0.989, 1.027, 1.011, 0.969, 1.015, 0.976, 1.006, 0.966]
|
||||
2 0.976 [0.976, 1.059, 0.963, 1.005, 0.911, 1.012, 0.949, 0.981, 0.946]
|
||||
3 0.924 [0.899, 0.902, 0.886, 0.92, 0.961, 0.934, 0.925, 0.951, 0.924]
|
||||
4 0.903 [0.893, 0.869, 0.966, 0.903, 0.884, 0.922, 0.918, 0.893, 1.048]
|
||||
5 0.833 [0.833, 0.853, 0.843, 0.818, 0.811, 0.795, 0.88, 0.847, 0.831]
|
||||
6 0.805 [0.842, 0.812, 0.798, 0.778, 0.805, 0.804, 0.839, 0.8, 0.815]
|
||||
7 0.771 [0.771, 0.809, 0.752, 0.773, 0.774, 0.778, 0.751, 0.735, 0.751]
|
||||
8 0.785 [0.755, 0.785, 0.685, 0.81, 0.806, 0.782, 0.802, 0.773, 0.984]
|
||||
9 0.759 [0.703, 0.696, 0.737, 0.776, 0.755, 0.834, 0.759, 0.767, 0.859]
|
||||
|
||||
## earlier attempts, kept for the record (too noisy to use)
|
||||
- separate binaries before/after/before/after, 5 rounds each, while another session compiled and ran probes: n=9 medians
|
||||
951 / 416 / 611 / 491 ms, n=4 425 / 214 / 273 / 283 ms; single steps 145 / 100 / 100 / 102 ms.
|
||||
- in-process paired run with a probe running on ~7.5 cores (7 rounds): median ratios n=2..9 1.037, 0.916, 0.921, 0.866,
|
||||
0.797, 0.834, 0.757, 0.734 (n=1 1.017), consistent with the quieter paired run above.
|
||||
|
||||
## speculation A/B after the change (crates/cpu-worker/examples/ab_speculation.rs <model> crates/gptoss/src/sampling.rs 3 320 14)
|
||||
## started 2026-10-16 12:52 local after 60 s with no other model process; same prompts as speculation-ab-2026-10-16.txt
|
||||
## (output text and id lines omitted; LELEKA_SPECULATION_LOG was not set, so acceptance counts were not captured)
|
||||
leleka-cpu-worker: read 12109565632 bytes of the model in 10.1 s (checksum 345869555)
|
||||
leleka-cpu-worker: gpt-oss loaded; kernels avx-vnni, 14 threads, context 1262, stop tokens [200002, 200012, 199999]
|
||||
ab_speculation: 4 prompts of [878, 874, 868, 856] tokens, 3 pairs, max_new 320, 14 threads
|
||||
rewrite pair 0 speculate=false: 320 tokens, prompt 472 ms, decode 39262 ms (8.15 tok/s), identical=true
|
||||
rewrite pair 0 speculate=true: 320 tokens, prompt 98 ms, decode 27761 ms (11.53 tok/s), identical=true
|
||||
rewrite pair 1 speculate=true: 320 tokens, prompt 111 ms, decode 25672 ms (12.47 tok/s), identical=true
|
||||
rewrite pair 1 speculate=false: 320 tokens, prompt 95 ms, decode 31010 ms (10.32 tok/s), identical=true
|
||||
rewrite pair 2 speculate=false: 320 tokens, prompt 102 ms, decode 30917 ms (10.35 tok/s), identical=true
|
||||
rewrite pair 2 speculate=true: 320 tokens, prompt 96 ms, decode 22319 ms (14.34 tok/s), identical=true
|
||||
diff pair 0 speculate=true: 303 tokens, prompt 1406 ms, decode 28226 ms (10.73 tok/s), identical=true
|
||||
diff pair 0 speculate=false: 303 tokens, prompt 98 ms, decode 30460 ms (9.95 tok/s), identical=true
|
||||
diff pair 1 speculate=false: 303 tokens, prompt 101 ms, decode 32609 ms (9.29 tok/s), identical=true
|
||||
diff pair 1 speculate=true: 303 tokens, prompt 113 ms, decode 30563 ms (9.91 tok/s), identical=true
|
||||
diff pair 2 speculate=true: 303 tokens, prompt 102 ms, decode 31781 ms (9.53 tok/s), identical=true
|
||||
diff pair 2 speculate=false: 303 tokens, prompt 106 ms, decode 31289 ms (9.68 tok/s), identical=true
|
||||
json pair 0 speculate=false: 195 tokens, prompt 1185 ms, decode 20548 ms (9.49 tok/s), identical=true
|
||||
json pair 0 speculate=true: 195 tokens, prompt 101 ms, decode 20176 ms (9.66 tok/s), identical=true
|
||||
json pair 1 speculate=true: 195 tokens, prompt 100 ms, decode 20217 ms (9.65 tok/s), identical=true
|
||||
json pair 1 speculate=false: 195 tokens, prompt 100 ms, decode 20202 ms (9.65 tok/s), identical=true
|
||||
json pair 2 speculate=false: 195 tokens, prompt 103 ms, decode 20186 ms (9.66 tok/s), identical=true
|
||||
json pair 2 speculate=true: 195 tokens, prompt 100 ms, decode 22955 ms (8.49 tok/s), identical=true
|
||||
explain pair 0 speculate=true: 162 tokens, prompt 875 ms, decode 18533 ms (8.74 tok/s), identical=true
|
||||
explain pair 0 speculate=false: 162 tokens, prompt 105 ms, decode 16852 ms (9.61 tok/s), identical=true
|
||||
explain pair 1 speculate=false: 162 tokens, prompt 102 ms, decode 16798 ms (9.64 tok/s), identical=true
|
||||
explain pair 1 speculate=true: 162 tokens, prompt 101 ms, decode 18042 ms (8.98 tok/s), identical=true
|
||||
explain pair 2 speculate=true: 162 tokens, prompt 108 ms, decode 17434 ms (9.29 tok/s), identical=true
|
||||
explain pair 2 speculate=false: 162 tokens, prompt 112 ms, decode 17281 ms (9.37 tok/s), identical=true
|
||||
rewrite: plain median 10.32 tok/s, speculate median 12.47 tok/s, paired ratio mean 1.34 (runs [1.41, 1.21, 1.39]), outputs identical: true
|
||||
diff: plain median 9.68 tok/s, speculate median 9.91 tok/s, paired ratio mean 1.04 (runs [1.08, 1.07, 0.98]), outputs identical: true
|
||||
json: plain median 9.65 tok/s, speculate median 9.65 tok/s, paired ratio mean 0.97 (runs [1.02, 1.0, 0.88]), outputs identical: true
|
||||
explain: plain median 9.61 tok/s, speculate median 8.98 tok/s, paired ratio mean 0.94 (runs [0.91, 0.93, 0.99]), outputs identical: true
|
||||
|
||||
## replay of these outputs through the drafter with the new MEASURED_COST (LELEKA_AB_REPLAY, no model run)
|
||||
default policy: geomean 1.160 min 0.991 [1.592, 1.151, 0.999, 0.991] (rewrite, diff, json, explain)
|
||||
|
||||
## machine state after the speculation A/B (Capture-MachineState.ps1; the scripted capture before it failed on a path form)
|
||||
{"captured_utc":"2026-10-16T11:04:05Z","os_build":"26100","os_ubr":9711,"npu_driver_version":"32.0.100.4778","npu_status":"OK","igpu_driver_version":"32.0.101.8860","bios_version":"1.17.0","power_plan_guid":"381b4222-f694-41f0-9685-ff5bb260df2e","ac_online":true,"discharging":false,"available_mbytes":14535,"committed_bytes":22191890432,"commit_limit_bytes":43978014720,"cpu_samples":[{"utc":"2026-10-16T11:04:16Z","perf":91,"pct_max_freq":77,"mhz":1517,"utility":3},{"utc":"2026-10-16T11:04:18Z","perf":82,"pct_max_freq":72,"mhz":1503,"utility":1},{"utc":"2026-10-16T11:04:19Z","perf":72,"pct_max_freq":74,"mhz":1592,"utility":1}],"processes":328,"vmmemwsl_working_set_bytes":0,"docker_desktop_processes":0,"browser_processes":45,"browser_working_set_bytes":8140898304,"security_agent_running":true,"top_cpu_processes":[{"name":"claude","cpu_seconds":531},{"name":"claude","cpu_seconds":512},{"name":"claude","cpu_seconds":270},{"name":"Taskmgr","cpu_seconds":216},{"name":"chrome","cpu_seconds":208}],"reference_record":{"record_id":"RHW-WIN-265U-NPU","revision":1},"drift_result":{"os_build":"match","os_ubr":"mismatch","npu_driver_version":"match","igpu_driver_version":"match","bios_version":"match","power_plan_guid":"match","power_mode":"not-comparable","overall":"stale"}}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! EXPERIMENT: paired comparison of the register-tiled MXFP4 kernels with the one-row kernel.
|
||||
//! EXPERIMENT: paired comparison of the register-tiled and multi-activation MXFP4 kernels with the one-row kernel.
|
||||
//!
|
||||
//! Two regimes: ACTS=1 (decode: memory-bound, every weight byte used once) and ACTS=8 (prefill: each
|
||||
//! weight row is used against 8 activations, so compute matters). Variants are interleaved inside every
|
||||
@@ -39,6 +39,35 @@ fn one_row_loop(vnni: bool) -> Variant<'static> {
|
||||
})
|
||||
}
|
||||
|
||||
fn multi(vnni: bool) -> Variant<'static> {
|
||||
Box::new(move |w, lo, hi, acts| {
|
||||
let mut sum = 0f32;
|
||||
let rb = BLOCKS_PER_ROW * MXFP4;
|
||||
let refs: Vec<sys::Q8rRef> = acts
|
||||
.ys
|
||||
.iter()
|
||||
.zip(&acts.yq)
|
||||
.map(|(scales, quants)| sys::Q8rRef { scales, quants })
|
||||
.collect();
|
||||
let mut out = vec![0f32; refs.len()];
|
||||
for r in lo..hi {
|
||||
let row = &w[r * rb..(r + 1) * rb];
|
||||
for (group, o) in refs
|
||||
.chunks(sys::MULTI_MAX)
|
||||
.zip(out.chunks_mut(sys::MULTI_MAX))
|
||||
{
|
||||
if vnni {
|
||||
sys::dot_mxfp4_q8r4_multi_avxvnni(row, group, o).unwrap();
|
||||
} else {
|
||||
sys::dot_mxfp4_q8r4_multi_avx2(row, group, o).unwrap();
|
||||
}
|
||||
}
|
||||
sum += out.iter().sum::<f32>();
|
||||
}
|
||||
sum
|
||||
})
|
||||
}
|
||||
|
||||
fn tiled(vnni: bool, tr: usize, ta: usize) -> Variant<'static> {
|
||||
Box::new(move |w, lo, hi, acts| {
|
||||
let mut sum = 0f32;
|
||||
@@ -118,6 +147,10 @@ fn main() {
|
||||
),
|
||||
one_row_loop(vnni),
|
||||
)];
|
||||
variants.push((
|
||||
"multi-activation q8r4 (bit-identical)".to_owned(),
|
||||
multi(vnni),
|
||||
));
|
||||
for (tr, ta) in [
|
||||
(1, 1),
|
||||
(2, 1),
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
|
||||
use std::fmt;
|
||||
|
||||
pub use leleka_cpu_sys::{KernelError, MAX_DOT_LEN};
|
||||
pub use leleka_cpu_sys::{KernelError, MAX_DOT_LEN, MULTI_MAX, Q8rRef};
|
||||
|
||||
/// Name of the environment variable that forces a kernel level.
|
||||
pub const ISA_ENV: &str = "LELEKA_CPU_ISA";
|
||||
@@ -104,6 +104,7 @@ type DotMx = fn(&[u8], &[u8]) -> Result<f32, KernelError>;
|
||||
type IsumsMx = fn(&[u8], &[u8], &mut [i32]) -> Result<(), KernelError>;
|
||||
type QuantQ8 = fn(&[f32], &mut [u8]) -> Result<(), KernelError>;
|
||||
type DotMxR = fn(&[u8], &[f32], &[i8]) -> Result<f32, KernelError>;
|
||||
type DotMulti = fn(&[u8], &[Q8rRef], &mut [f32]) -> Result<(), KernelError>;
|
||||
type AttnScores =
|
||||
fn(&[f32], usize, &[u16], usize, usize, f32, &mut [f32]) -> Result<(), KernelError>;
|
||||
type AttnSum = fn(&[f32], usize, usize, &[u16], usize, &mut [f32]) -> Result<(), KernelError>;
|
||||
@@ -125,6 +126,8 @@ pub struct Dispatch {
|
||||
dot_mxfp4_q8r: DotMxR,
|
||||
dot_q8_0_q8_0: DotMx,
|
||||
isums_q8_0_q8_0: IsumsMx,
|
||||
dot_mxfp4_q8r_multi: DotMulti,
|
||||
dot_q8_0_q8r_multi: DotMulti,
|
||||
attn_scores: AttnScores,
|
||||
attn_weighted_sum: AttnSum,
|
||||
exp_shift_sum: ExpSum,
|
||||
@@ -162,6 +165,8 @@ impl Dispatch {
|
||||
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r_scalar,
|
||||
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_scalar,
|
||||
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_scalar,
|
||||
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r_multi_scalar,
|
||||
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_scalar,
|
||||
attn_scores: leleka_cpu_sys::attn_scores_f16_scalar,
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_scalar,
|
||||
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_scalar,
|
||||
@@ -183,6 +188,8 @@ impl Dispatch {
|
||||
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r4_avx2,
|
||||
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_avx2,
|
||||
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_avx2,
|
||||
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r4_multi_avx2,
|
||||
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_avx2,
|
||||
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
|
||||
f32_to_f16: leleka_cpu_sys::f32_to_f16_slice_avx2,
|
||||
@@ -205,6 +212,8 @@ impl Dispatch {
|
||||
dot_mxfp4_q8r: leleka_cpu_sys::dot_mxfp4_q8r4_avxvnni,
|
||||
dot_q8_0_q8_0: leleka_cpu_sys::dot_q8_0_q8_0_avxvnni,
|
||||
isums_q8_0_q8_0: leleka_cpu_sys::q8_0_q8_0_isums_avxvnni,
|
||||
dot_mxfp4_q8r_multi: leleka_cpu_sys::dot_mxfp4_q8r4_multi_avxvnni,
|
||||
dot_q8_0_q8r_multi: leleka_cpu_sys::dot_q8_0_q8r_multi_avxvnni,
|
||||
// attention and softmax are float work: the VNNI level shares the AVX2 + FMA kernels
|
||||
attn_scores: leleka_cpu_sys::attn_scores_f16_avx2,
|
||||
attn_weighted_sum: leleka_cpu_sys::attn_weighted_sum_f16_avx2,
|
||||
@@ -283,6 +292,28 @@ impl Dispatch {
|
||||
(self.dot_q8_0_q8_0)(x, y)
|
||||
}
|
||||
|
||||
/// One MXFP4 row against 1 to [`MULTI_MAX`] activations in the "q8r" layout, the row decoded once:
|
||||
/// `out[a]` is bit for bit [`Dispatch::dot_mxfp4_q8r`] of `acts[a]` at this level.
|
||||
pub fn dot_mxfp4_q8r_multi(
|
||||
&self,
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.dot_mxfp4_q8r_multi)(x, acts, out)
|
||||
}
|
||||
|
||||
/// One Q8_0 row against 1 to [`MULTI_MAX`] activations in the "q8r" layout: `out[a]` is bit for bit
|
||||
/// [`Dispatch::dot_q8_0_q8_0`] of the Q8_0 blocks of `acts[a]` (the same quants, scales as halves).
|
||||
pub fn dot_q8_0_q8r_multi(
|
||||
&self,
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
(self.dot_q8_0_q8r_multi)(x, acts, out)
|
||||
}
|
||||
|
||||
/// Attention scores for a group of `heads` query heads sharing the keys (stored as half floats):
|
||||
/// `out[g * n + i] = scale * dot(q[g * hd ..][..hd], keys[i * stride ..][..hd])`, `hd = q.len() / heads`.
|
||||
/// SIMD levels differ from the portable one only in float summation order.
|
||||
|
||||
@@ -24,6 +24,8 @@ pub mod mapping;
|
||||
pub mod simd;
|
||||
pub mod topology;
|
||||
|
||||
pub use simd::{MULTI_MAX, Q8rRef};
|
||||
|
||||
/// Longest vector the int32 accumulators can hold exactly (`131072 * 128 * 127 < 2^31`).
|
||||
pub const MAX_DOT_LEN: usize = 131_072;
|
||||
/// Elements per MXFP4 or Q8_0 block.
|
||||
@@ -44,6 +46,8 @@ pub enum KernelError {
|
||||
Unsupported,
|
||||
/// A tile with no rows or activations, or more than [`TILE_MAX`] of either.
|
||||
TileShape,
|
||||
/// A multi-activation call with no activations or more than [`MULTI_MAX`].
|
||||
ActivationCount,
|
||||
}
|
||||
|
||||
impl fmt::Display for KernelError {
|
||||
@@ -53,6 +57,7 @@ impl fmt::Display for KernelError {
|
||||
Self::TooLong => "vector longer than the exact int32 accumulation limit",
|
||||
Self::Unsupported => "instruction set not available on this CPU or build",
|
||||
Self::TileShape => "a tile needs 1 to 4 rows and 1 to 4 activations",
|
||||
Self::ActivationCount => "a multi-activation call needs 1 to 16 activations",
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -128,6 +133,30 @@ fn check_q8(x: &[u8], y: &[u8]) -> Result<usize, KernelError> {
|
||||
Ok(x.len() / Q8_0_BLOCK_BYTES)
|
||||
}
|
||||
|
||||
/// Checks a multi-activation call: one row of `block_bytes`-byte blocks, 1 to [`MULTI_MAX`] activations of
|
||||
/// as many blocks, and one output per activation.
|
||||
fn check_multi(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &[f32],
|
||||
block_bytes: usize,
|
||||
) -> Result<(), KernelError> {
|
||||
if acts.is_empty() || acts.len() > MULTI_MAX {
|
||||
return Err(KernelError::ActivationCount);
|
||||
}
|
||||
let blocks = x.len() / block_bytes;
|
||||
let ok = x.len() == blocks * block_bytes
|
||||
&& acts
|
||||
.iter()
|
||||
.all(|a| a.scales.len() == blocks && a.quants.len() == blocks * BLOCK_ELEMS)
|
||||
&& out.len() == acts.len();
|
||||
if ok {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(KernelError::LengthMismatch)
|
||||
}
|
||||
}
|
||||
|
||||
fn check_quantize(x: &[f32], out: &[u8]) -> Result<usize, KernelError> {
|
||||
if !x.len().is_multiple_of(BLOCK_ELEMS) || out.len() != x.len() / BLOCK_ELEMS * Q8_0_BLOCK_BYTES
|
||||
{
|
||||
@@ -187,6 +216,30 @@ pub fn dot_q8_0_q8_0_scalar(x: &[u8], y: &[u8]) -> Result<f32, KernelError> {
|
||||
Ok(simd::dot_q8_0_q8_0_scalar(x, y))
|
||||
}
|
||||
|
||||
/// One MXFP4 row against 1 to [`MULTI_MAX`] "q8r" activations, portable: `out[a]` equals
|
||||
/// [`dot_mxfp4_q8r_scalar`] for `acts[a]` bit for bit.
|
||||
pub fn dot_mxfp4_q8r_multi_scalar(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
|
||||
simd::dot_mxfp4_q8r_multi_scalar(x, acts, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One Q8_0 row against 1 to [`MULTI_MAX`] "q8r" activations, portable: `out[a]` equals
|
||||
/// [`dot_q8_0_q8_0_scalar`] for the Q8_0 blocks of `acts[a]` (scales as halves) bit for bit.
|
||||
pub fn dot_q8_0_q8r_multi_scalar(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
|
||||
simd::dot_q8_0_q8r_multi_scalar(x, acts, out);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Exact per-block integer sums of a Q8_0 x Q8_0 dot, portable reference.
|
||||
pub fn q8_0_q8_0_isums_scalar(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), KernelError> {
|
||||
let blocks = check_q8(x, y)?;
|
||||
@@ -292,6 +345,30 @@ pub fn q8_0_q8_0_isums_avx2(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<(), K
|
||||
with_avx2!(simd::x86::q8_0_q8_0_isums_avx2(x, y, out))
|
||||
}
|
||||
|
||||
/// One MXFP4 row against 1 to [`MULTI_MAX`] activations, decoding the row once: `out[a]` equals
|
||||
/// [`dot_mxfp4_q8r4_avx2`] for `acts[a]` bit for bit.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn dot_mxfp4_q8r4_multi_avx2(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
|
||||
with_avx2!(simd::x86::dot_mxfp4_q8r4_multi_avx2(x, acts, out))
|
||||
}
|
||||
|
||||
/// One Q8_0 row against 1 to [`MULTI_MAX`] "q8r" activations: `out[a]` equals [`dot_q8_0_q8_0_avx2`]
|
||||
/// for the Q8_0 blocks of `acts[a]` (scales as halves) bit for bit.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn dot_q8_0_q8r_multi_avx2(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
|
||||
with_avx2!(simd::x86::dot_q8_0_q8r_multi_avx2(x, acts, out))
|
||||
}
|
||||
|
||||
/// Float to IEEE half bits with the F16C instruction; `None` if the CPU lacks it.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn f32_to_f16_bits_f16c(value: f32) -> Option<u16> {
|
||||
@@ -355,6 +432,29 @@ pub fn q8_0_q8_0_isums_avxvnni(x: &[u8], y: &[u8], out: &mut [i32]) -> Result<()
|
||||
with_avxvnni!(simd::x86::q8_0_q8_0_isums_avxvnni(x, y, out))
|
||||
}
|
||||
|
||||
/// AVX-VNNI level of [`dot_mxfp4_q8r4_multi_avx2`]: `out[a]` equals [`dot_mxfp4_q8r4_avxvnni`] for `acts[a]`.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn dot_mxfp4_q8r4_multi_avxvnni(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, MXFP4_BLOCK_BYTES)?;
|
||||
with_avxvnni!(simd::x86::dot_mxfp4_q8r4_multi_avxvnni(x, acts, out))
|
||||
}
|
||||
|
||||
/// AVX-VNNI level of [`dot_q8_0_q8r_multi_avx2`]: `out[a]` equals [`dot_q8_0_q8_0_avxvnni`] for the Q8_0
|
||||
/// blocks of `acts[a]`.
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
pub fn dot_q8_0_q8r_multi_avxvnni(
|
||||
x: &[u8],
|
||||
acts: &[Q8rRef],
|
||||
out: &mut [f32],
|
||||
) -> Result<(), KernelError> {
|
||||
check_multi(x, acts, out, Q8_0_BLOCK_BYTES)?;
|
||||
with_avxvnni!(simd::x86::dot_q8_0_q8r_multi_avxvnni(x, acts, out))
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------- attention -----------
|
||||
|
||||
/// Largest start offset plus width a strided read may touch, or `None` when it would overflow.
|
||||
|
||||
@@ -345,6 +345,32 @@ pub fn q8_q8r_tile_scalar(x: &[&[u8]], acts: &[ActRef], out: &mut [f32]) {
|
||||
}
|
||||
}
|
||||
|
||||
/// One activation in the "q8r" layout for the multi-activation kernels: one f32 scale per block and the
|
||||
/// int8 quants, `scales.len() * 32` of them.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Q8rRef<'a> {
|
||||
pub scales: &'a [f32],
|
||||
pub quants: &'a [i8],
|
||||
}
|
||||
|
||||
/// Most activations one multi-activation kernel call takes.
|
||||
pub const MULTI_MAX: usize = 16;
|
||||
|
||||
/// One MXFP4 row against several activations, portable: `out[a]` is [`dot_mxfp4_q8r_scalar`] of `acts[a]`.
|
||||
pub fn dot_mxfp4_q8r_multi_scalar(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
|
||||
for (act, o) in acts.iter().zip(out) {
|
||||
*o = dot_mxfp4_q8r_scalar(x, act.scales, act.quants);
|
||||
}
|
||||
}
|
||||
|
||||
/// One Q8_0 row against several activations, portable: `out[a]` is [`dot_q8_q8r_scalar`] of `acts[a]`,
|
||||
/// which equals [`dot_q8_0_q8_0_scalar`] of the activation's Q8_0 blocks bit for bit.
|
||||
pub fn dot_q8_0_q8r_multi_scalar(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
|
||||
for (act, o) in acts.iter().zip(out) {
|
||||
*o = dot_q8_q8r_scalar(x, act.scales, act.quants);
|
||||
}
|
||||
}
|
||||
|
||||
/// Quantize floats (a multiple of 32) to Q8_0 blocks: scale = amax / 127 stored as a half, quants
|
||||
/// rounded to nearest even and clamped to `[-127, 127]`.
|
||||
pub fn quantize_q8_0_scalar(x: &[f32], out: &mut [u8]) {
|
||||
@@ -1197,6 +1223,172 @@ pub mod x86 {
|
||||
tile_shapes!(q8_tile_avxvnni, x, acts, out)
|
||||
}
|
||||
|
||||
// ---- multi-activation kernels: one weight row against up to MULTI_MAX activations ----
|
||||
//
|
||||
// The row is decoded once per segment of blocks (int8 values, their absolute values and the block
|
||||
// scales), then each activation runs over the decoded segment with exactly the arithmetic of the
|
||||
// one-activation kernel at the same level: the same integer products per lane, the same scale
|
||||
// product, the same accumulator for every block (four for MXFP4, two for Q8_0) and the same final
|
||||
// reduction. So `out[a]` is bit-identical to the one-activation kernel for `acts[a]`, whatever the
|
||||
// number of activations.
|
||||
|
||||
use super::{MULTI_MAX, Q8rRef};
|
||||
|
||||
/// Blocks decoded at a time (a multiple of four, so segments never split a four-block group).
|
||||
const SEGMENT: usize = 64;
|
||||
|
||||
/// `|w| * sign(q, w)` summed in groups of four products per lane, as `block_p32_avx2` does.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2")]
|
||||
unsafe fn decoded_p32_avx2(wabs: __m256i, w: __m256i, q: *const u8) -> __m256i {
|
||||
let q = _mm256_loadu_si256(q as *const __m256i);
|
||||
let p16 = _mm256_maddubs_epi16(wabs, _mm256_sign_epi8(q, w));
|
||||
_mm256_madd_epi16(p16, _mm256_set1_epi16(1))
|
||||
}
|
||||
|
||||
/// As [`decoded_p32_avx2`] with one `vpdpbusd`, as `block_p32_vnni` does.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx2,avxvnni")]
|
||||
unsafe fn decoded_p32_vnni(wabs: __m256i, w: __m256i, q: *const u8) -> __m256i {
|
||||
let q = _mm256_loadu_si256(q as *const __m256i);
|
||||
_mm256_dpbusd_avx_epi32(_mm256_setzero_si256(), wabs, _mm256_sign_epi8(q, w))
|
||||
}
|
||||
|
||||
/// Generates a multi-activation kernel. `$decode` fills `w[i]` and `d[i]` (the weight scale) for
|
||||
/// block `ib`; `$groups` is the number of accumulators of the one-activation kernel (4 or 2).
|
||||
macro_rules! multi_kernel {
|
||||
($name:ident, $features:literal, $block_bytes:expr, $p32:ident, $groups:literal, |$xb:ident, $ib:ident| $decode:expr) => {
|
||||
#[target_feature(enable = $features)]
|
||||
pub unsafe fn $name(x: &[u8], acts: &[Q8rRef], out: &mut [f32]) {
|
||||
let nb = x.len() / $block_bytes;
|
||||
let main = nb - nb % $groups;
|
||||
let mut acc = [[_mm256_setzero_ps(); $groups]; MULTI_MAX];
|
||||
let mut w = [_mm256_setzero_si256(); SEGMENT];
|
||||
let mut wabs = [_mm256_setzero_si256(); SEGMENT];
|
||||
let mut d = [0.0f32; SEGMENT];
|
||||
let mut s = [0.0f32; SEGMENT];
|
||||
let mut seg0 = 0;
|
||||
while seg0 < nb {
|
||||
let seg = SEGMENT.min(nb - seg0);
|
||||
for i in 0..seg {
|
||||
let $ib = seg0 + i;
|
||||
let $xb = x.as_ptr().add($ib * $block_bytes);
|
||||
let (wi, di): (__m256i, f32) = $decode;
|
||||
w[i] = wi;
|
||||
wabs[i] = _mm256_sign_epi8(wi, wi);
|
||||
d[i] = di;
|
||||
}
|
||||
for (a, act) in acts.iter().enumerate() {
|
||||
// the scale products, lane by lane the same multiplication as the scalar one
|
||||
let mut i = 0;
|
||||
while i + 8 <= seg {
|
||||
let v = _mm256_mul_ps(
|
||||
_mm256_loadu_ps(act.scales.as_ptr().add(seg0 + i)),
|
||||
_mm256_loadu_ps(d.as_ptr().add(i)),
|
||||
);
|
||||
_mm256_storeu_ps(s.as_mut_ptr().add(i), v);
|
||||
i += 8;
|
||||
}
|
||||
while i < seg {
|
||||
s[i] = *act.scales.get_unchecked(seg0 + i) * d[i];
|
||||
i += 1;
|
||||
}
|
||||
let q = act.quants.as_ptr() as *const u8;
|
||||
let mut g = acc[a];
|
||||
// block `ib < main` goes to accumulator `ib % groups` (segments start at a
|
||||
// multiple of four), the remaining blocks to the first one
|
||||
let mut i = 0;
|
||||
while i + $groups <= seg && seg0 + i + $groups <= main {
|
||||
for (k, gk) in g.iter_mut().enumerate() {
|
||||
let p = $p32(wabs[i + k], w[i + k], q.add((seg0 + i + k) * 32));
|
||||
*gk = _mm256_fmadd_ps(
|
||||
_mm256_cvtepi32_ps(p),
|
||||
_mm256_broadcast_ss(&s[i + k]),
|
||||
*gk,
|
||||
);
|
||||
}
|
||||
i += $groups;
|
||||
}
|
||||
while i < seg {
|
||||
let p = $p32(wabs[i], w[i], q.add((seg0 + i) * 32));
|
||||
g[0] = _mm256_fmadd_ps(
|
||||
_mm256_cvtepi32_ps(p),
|
||||
_mm256_broadcast_ss(&s[i]),
|
||||
g[0],
|
||||
);
|
||||
i += 1;
|
||||
}
|
||||
acc[a] = g;
|
||||
}
|
||||
seg0 += seg;
|
||||
}
|
||||
for (a, o) in out.iter_mut().enumerate().take(acts.len()) {
|
||||
*o = multi_reduce(&acc[a]);
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
/// The final reduction of the one-activation kernels: `(a0 + a1) + (a2 + a3)` for four
|
||||
/// accumulators, `a0 + a1` for two, then the horizontal sum.
|
||||
#[inline]
|
||||
#[target_feature(enable = "avx")]
|
||||
unsafe fn multi_reduce<const G: usize>(g: &[__m256; G]) -> f32 {
|
||||
if G == 4 {
|
||||
hsum_ps(_mm256_add_ps(
|
||||
_mm256_add_ps(g[0], g[1]),
|
||||
_mm256_add_ps(g[2], g[3]),
|
||||
))
|
||||
} else {
|
||||
hsum_ps(_mm256_add_ps(g[0], g[1]))
|
||||
}
|
||||
}
|
||||
|
||||
multi_kernel!(
|
||||
dot_mxfp4_q8r4_multi_avx2,
|
||||
"avx2,fma",
|
||||
MXFP4_BYTES,
|
||||
decoded_p32_avx2,
|
||||
4,
|
||||
|xb, ib| (
|
||||
mx_values(xb, mx_table(), _mm_set1_epi8(0x0F)),
|
||||
e8m0_half(*xb)
|
||||
)
|
||||
);
|
||||
multi_kernel!(
|
||||
dot_mxfp4_q8r4_multi_avxvnni,
|
||||
"avx2,fma,avxvnni",
|
||||
MXFP4_BYTES,
|
||||
decoded_p32_vnni,
|
||||
4,
|
||||
|xb, ib| (
|
||||
mx_values(xb, mx_table(), _mm_set1_epi8(0x0F)),
|
||||
e8m0_half(*xb)
|
||||
)
|
||||
);
|
||||
multi_kernel!(
|
||||
dot_q8_0_q8r_multi_avx2,
|
||||
"avx2,fma,f16c",
|
||||
Q8_0_BYTES,
|
||||
decoded_p32_avx2,
|
||||
2,
|
||||
|xb, ib| (
|
||||
_mm256_loadu_si256(xb.add(2) as *const __m256i),
|
||||
half_to_f32(xb)
|
||||
)
|
||||
);
|
||||
multi_kernel!(
|
||||
dot_q8_0_q8r_multi_avxvnni,
|
||||
"avx2,fma,f16c,avxvnni",
|
||||
Q8_0_BYTES,
|
||||
decoded_p32_vnni,
|
||||
2,
|
||||
|xb, ib| (
|
||||
_mm256_loadu_si256(xb.add(2) as *const __m256i),
|
||||
half_to_f32(xb)
|
||||
)
|
||||
);
|
||||
|
||||
// ---- attention ----
|
||||
|
||||
#[inline]
|
||||
|
||||
@@ -0,0 +1,184 @@
|
||||
//! The multi-activation kernels: for every row length and every number of activations, each output is
|
||||
//! bit for bit the value of the one-activation kernel the decoder uses at the same level (the MXFP4 "q8r4"
|
||||
//! kernel, and the Q8_0 x Q8_0 kernel fed the activation's Q8_0 blocks).
|
||||
|
||||
use leleka_cpu_sys as sys;
|
||||
use leleka_cpu_sys::simd;
|
||||
|
||||
struct Rng(u64);
|
||||
|
||||
impl Rng {
|
||||
fn next(&mut self) -> u64 {
|
||||
self.0 ^= self.0 << 13;
|
||||
self.0 ^= self.0 >> 7;
|
||||
self.0 ^= self.0 << 17;
|
||||
self.0
|
||||
}
|
||||
}
|
||||
|
||||
/// An activation in both layouts: Q8_0 blocks and the "q8r" form (half scales converted to f32).
|
||||
struct Act {
|
||||
blocks: Vec<u8>,
|
||||
scales: Vec<f32>,
|
||||
quants: Vec<i8>,
|
||||
}
|
||||
|
||||
fn act(rng: &mut Rng, blocks: usize) -> Act {
|
||||
let mut out = Act {
|
||||
blocks: Vec::new(),
|
||||
scales: Vec::new(),
|
||||
quants: Vec::new(),
|
||||
};
|
||||
for _ in 0..blocks {
|
||||
let half = simd::f32_to_f16(0.0005 + (rng.next() % 1000) as f32 * 1e-5);
|
||||
out.blocks.extend_from_slice(&half.to_le_bytes());
|
||||
out.scales.push(simd::f16_to_f32(half));
|
||||
for _ in 0..32 {
|
||||
let q = ((rng.next() % 255) as i64 - 127) as i8;
|
||||
out.blocks.push(q as u8);
|
||||
out.quants.push(q);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
fn mx_row(rng: &mut Rng, blocks: usize) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
for _ in 0..blocks {
|
||||
v.push(110 + (rng.next() % 30) as u8);
|
||||
v.extend((0..16).map(|_| rng.next() as u8));
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
fn q8_row(rng: &mut Rng, blocks: usize) -> Vec<u8> {
|
||||
let mut v = Vec::new();
|
||||
for _ in 0..blocks {
|
||||
let scale = 0.001 + (rng.next() % 1000) as f32 * 1e-5;
|
||||
v.extend_from_slice(&simd::f32_to_f16(scale).to_le_bytes());
|
||||
v.extend((0..32).map(|_| rng.next() as u8)); // any int8 weight, -128 included
|
||||
}
|
||||
v
|
||||
}
|
||||
|
||||
type Multi = fn(&[u8], &[sys::Q8rRef], &mut [f32]) -> Result<(), sys::KernelError>;
|
||||
type OneMx = fn(&[u8], &[f32], &[i8]) -> Result<f32, sys::KernelError>;
|
||||
type OneQ8 = fn(&[u8], &[u8]) -> Result<f32, sys::KernelError>;
|
||||
|
||||
/// Row lengths around the four-block groups and the 64-block segments, and the model's 90 and 128.
|
||||
const BLOCKS: [usize; 13] = [1, 2, 3, 4, 5, 7, 8, 63, 64, 65, 90, 128, 131];
|
||||
|
||||
fn check(multi_mx: Multi, one_mx: OneMx, multi_q8: Multi, one_q8: OneQ8, label: &str) {
|
||||
let mut rng = Rng(0x9E37_79B9_7F4A_7C15);
|
||||
for blocks in BLOCKS {
|
||||
let acts: Vec<Act> = (0..sys::MULTI_MAX).map(|_| act(&mut rng, blocks)).collect();
|
||||
let refs: Vec<sys::Q8rRef> = acts
|
||||
.iter()
|
||||
.map(|a| sys::Q8rRef {
|
||||
scales: &a.scales,
|
||||
quants: &a.quants,
|
||||
})
|
||||
.collect();
|
||||
let (mx, q8) = (mx_row(&mut rng, blocks), q8_row(&mut rng, blocks));
|
||||
for n in 1..=sys::MULTI_MAX {
|
||||
let mut out = vec![0f32; n];
|
||||
multi_mx(&mx, &refs[..n], &mut out).unwrap();
|
||||
for (a, got) in out.iter().enumerate() {
|
||||
let want = one_mx(&mx, &acts[a].scales, &acts[a].quants).unwrap();
|
||||
assert_eq!(
|
||||
got.to_bits(),
|
||||
want.to_bits(),
|
||||
"{label} MXFP4: {blocks} blocks, {n} activations, activation {a}: {got} vs {want}"
|
||||
);
|
||||
}
|
||||
multi_q8(&q8, &refs[..n], &mut out).unwrap();
|
||||
for (a, got) in out.iter().enumerate() {
|
||||
let want = one_q8(&q8, &acts[a].blocks).unwrap();
|
||||
assert_eq!(
|
||||
got.to_bits(),
|
||||
want.to_bits(),
|
||||
"{label} Q8_0: {blocks} blocks, {n} activations, activation {a}: {got} vs {want}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn portable_multi_kernels_equal_the_one_activation_kernels() {
|
||||
check(
|
||||
sys::dot_mxfp4_q8r_multi_scalar,
|
||||
sys::dot_mxfp4_q8r_scalar,
|
||||
sys::dot_q8_0_q8r_multi_scalar,
|
||||
sys::dot_q8_0_q8_0_scalar,
|
||||
"portable",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[test]
|
||||
fn avx2_multi_kernels_equal_the_one_activation_kernels() {
|
||||
if !sys::avx2_available() {
|
||||
eprintln!("skipped: no AVX2");
|
||||
return;
|
||||
}
|
||||
check(
|
||||
sys::dot_mxfp4_q8r4_multi_avx2,
|
||||
sys::dot_mxfp4_q8r4_avx2,
|
||||
sys::dot_q8_0_q8r_multi_avx2,
|
||||
sys::dot_q8_0_q8_0_avx2,
|
||||
"AVX2",
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_arch = "x86_64")]
|
||||
#[test]
|
||||
fn avxvnni_multi_kernels_equal_the_one_activation_kernels() {
|
||||
if !sys::avxvnni_available() {
|
||||
eprintln!("skipped: no AVX-VNNI");
|
||||
return;
|
||||
}
|
||||
check(
|
||||
sys::dot_mxfp4_q8r4_multi_avxvnni,
|
||||
sys::dot_mxfp4_q8r4_avxvnni,
|
||||
sys::dot_q8_0_q8r_multi_avxvnni,
|
||||
sys::dot_q8_0_q8_0_avxvnni,
|
||||
"AVX-VNNI",
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn bad_counts_and_lengths_are_refused() {
|
||||
let mut rng = Rng(5);
|
||||
let a = act(&mut rng, 3);
|
||||
let row = mx_row(&mut rng, 3);
|
||||
let one = sys::Q8rRef {
|
||||
scales: &a.scales,
|
||||
quants: &a.quants,
|
||||
};
|
||||
assert_eq!(
|
||||
sys::dot_mxfp4_q8r_multi_scalar(&row, &[], &mut []),
|
||||
Err(sys::KernelError::ActivationCount)
|
||||
);
|
||||
let too_many = vec![one; sys::MULTI_MAX + 1];
|
||||
assert_eq!(
|
||||
sys::dot_mxfp4_q8r_multi_scalar(&row, &too_many, &mut [0.0; sys::MULTI_MAX + 1]),
|
||||
Err(sys::KernelError::ActivationCount)
|
||||
);
|
||||
assert_eq!(
|
||||
sys::dot_mxfp4_q8r_multi_scalar(&row, &[one], &mut [0.0; 2]),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
let short = sys::Q8rRef {
|
||||
scales: &a.scales,
|
||||
quants: &a.quants[..64],
|
||||
};
|
||||
assert_eq!(
|
||||
sys::dot_mxfp4_q8r_multi_scalar(&row, &[short], &mut [0.0]),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
assert_eq!(
|
||||
sys::dot_q8_0_q8r_multi_scalar(&row[..50], &[one], &mut [0.0]),
|
||||
Err(sys::KernelError::LengthMismatch)
|
||||
);
|
||||
}
|
||||
@@ -1,14 +1,16 @@
|
||||
//! Time of one decoder pass over n tokens (n = 1..=max) at a fixed position, as used by speculative verification:
|
||||
//! `forward` for one token, `logits_after_each` for a batch. The cache is cut back to the prompt after every pass,
|
||||
//! sizes are interleaved in a different order each round, and the median per size is printed.
|
||||
//! With `ab` every pass runs twice back to back, without and with the multi-activation kernels
|
||||
//! ([`Model::set_multi_activation`], identical values), alternating which goes first, and the paired ratios are printed.
|
||||
//!
|
||||
//! Run: `cargo run --release -p leleka-gptoss --example batch_cost -- <model.gguf> [prompt_tokens] [max_n] [rounds] [threads]`
|
||||
//! Run: `cargo run --release -p leleka-gptoss --example batch_cost -- <model.gguf> [prompt_tokens] [max_n] [rounds] [threads] [ab]`
|
||||
//! The prompt is deterministic pseudo-random ids. Machine state is not controlled.
|
||||
|
||||
use leleka_cpu_kernels::Dispatch;
|
||||
use leleka_cpu_sys::mapping::Mapping;
|
||||
use leleka_gguf::Gguf;
|
||||
use leleka_gptoss::{Model, State};
|
||||
use leleka_gptoss::{Model, Profile, State};
|
||||
use std::fs::File;
|
||||
use std::io::BufReader;
|
||||
use std::path::Path;
|
||||
@@ -28,7 +30,7 @@ fn ids(n: usize, mut s: u64) -> Vec<u32> {
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if args.is_empty() {
|
||||
eprintln!("usage: batch_cost <model.gguf> [prompt_tokens] [max_n] [rounds] [threads]");
|
||||
eprintln!("usage: batch_cost <model.gguf> [prompt_tokens] [max_n] [rounds] [threads] [ab]");
|
||||
std::process::exit(2);
|
||||
}
|
||||
let arg = |i: usize, d: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(d);
|
||||
@@ -37,6 +39,7 @@ fn main() {
|
||||
4,
|
||||
std::thread::available_parallelism().map_or(1, |n| n.get()),
|
||||
);
|
||||
let paired = args.get(5).is_some_and(|s| s == "ab");
|
||||
let path = Path::new(&args[0]);
|
||||
let size = std::fs::metadata(path).expect("model file").len();
|
||||
let gguf = Gguf::read(
|
||||
@@ -46,7 +49,7 @@ fn main() {
|
||||
.expect("valid GGUF");
|
||||
let map = Mapping::open(path).expect("map model");
|
||||
map.touch_pages();
|
||||
let model = Model::load(
|
||||
let mut model = Model::load(
|
||||
std::sync::Arc::new(map),
|
||||
&gguf,
|
||||
Dispatch::from_env().expect("kernel level"),
|
||||
@@ -61,7 +64,15 @@ fn main() {
|
||||
"prefill of {prompt_len} tokens: {:.1} s; {threads} threads",
|
||||
t.elapsed().as_secs_f64()
|
||||
);
|
||||
let mut times: Vec<Vec<f64>> = vec![Vec::new(); max_n + 1];
|
||||
// arm 0: one-token kernel per token, arm 1: multi-activation kernels (the default)
|
||||
let arms: Vec<bool> = if paired {
|
||||
vec![false, true]
|
||||
} else {
|
||||
vec![true]
|
||||
};
|
||||
let mut times: Vec<Vec<Vec<f64>>> = vec![vec![Vec::new(); max_n + 1]; arms.len()];
|
||||
let mut profiles: Vec<Vec<Profile>> = vec![vec![Profile::default(); max_n + 1]; arms.len()];
|
||||
let mut identical = 0usize;
|
||||
for round in 0..rounds + 1 {
|
||||
let mut order: Vec<usize> = (1..=max_n).collect();
|
||||
order.rotate_left(round % max_n);
|
||||
@@ -70,37 +81,100 @@ fn main() {
|
||||
}
|
||||
for n in order {
|
||||
let batch = ids(n, 77 + round as u64 * 31 + n as u64);
|
||||
state.truncate(prompt_len);
|
||||
let t = Instant::now();
|
||||
if n == 1 {
|
||||
model
|
||||
.forward(&mut state, batch[0], prompt_len)
|
||||
.expect("forward");
|
||||
} else {
|
||||
model
|
||||
.logits_after_each(&mut state, &batch, prompt_len)
|
||||
.expect("batch");
|
||||
}
|
||||
if round > 0 {
|
||||
// round 0 is a warm-up
|
||||
times[n].push(t.elapsed().as_secs_f64() * 1000.0);
|
||||
let mut first_arm: Option<Vec<Vec<u32>>> = None;
|
||||
for k in 0..arms.len() {
|
||||
// the arms of one pass run back to back, alternating which goes first
|
||||
let arm = (k + round + n) % arms.len();
|
||||
model.set_multi_activation(arms[arm]);
|
||||
state.truncate(prompt_len);
|
||||
// the pass accumulates into its profile (round 0 into a discarded one)
|
||||
let mut warm_up = Profile::default();
|
||||
let profile = if round > 0 {
|
||||
&mut profiles[arm][n]
|
||||
} else {
|
||||
&mut warm_up
|
||||
};
|
||||
std::mem::swap(&mut state.profile, profile);
|
||||
let t = Instant::now();
|
||||
let logits = if n == 1 {
|
||||
model
|
||||
.forward(&mut state, batch[0], prompt_len)
|
||||
.expect("forward");
|
||||
vec![state.logits.clone()]
|
||||
} else {
|
||||
model
|
||||
.logits_after_each(&mut state, &batch, prompt_len)
|
||||
.expect("batch")
|
||||
};
|
||||
let elapsed = t.elapsed();
|
||||
// both arms must give the same logits bit for bit
|
||||
let bits: Vec<Vec<u32>> = logits
|
||||
.iter()
|
||||
.map(|l| l.iter().map(|x| x.to_bits()).collect())
|
||||
.collect();
|
||||
match &first_arm {
|
||||
None => first_arm = Some(bits),
|
||||
Some(first) => {
|
||||
assert!(*first == bits, "the arms differ: round {round}, {n} tokens");
|
||||
identical += 1;
|
||||
}
|
||||
}
|
||||
std::mem::swap(&mut state.profile, profile);
|
||||
if round > 0 {
|
||||
// round 0 is a warm-up
|
||||
times[arm][n].push(elapsed.as_secs_f64() * 1000.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let single = {
|
||||
let mut v = times[1].clone();
|
||||
let median = |v: &[f64]| {
|
||||
let mut v = v.to_vec();
|
||||
v.sort_by(f64::total_cmp);
|
||||
v[v.len() / 2]
|
||||
};
|
||||
println!("n\tmedian ms\tms per token\tcost vs n single steps");
|
||||
for (n, v) in times.iter_mut().enumerate().skip(1) {
|
||||
v.sort_by(f64::total_cmp);
|
||||
let m = v[v.len() / 2];
|
||||
println!(
|
||||
"{n}\t{m:.0}\t{:.0}\t{:.2}\t(runs {:?})",
|
||||
m / n as f64,
|
||||
m / (single * n as f64),
|
||||
v.iter().map(|x| x.round()).collect::<Vec<_>>()
|
||||
);
|
||||
for (arm, multi) in arms.iter().enumerate() {
|
||||
let label = if *multi {
|
||||
"multi-activation kernels"
|
||||
} else {
|
||||
"one-token kernel per token"
|
||||
};
|
||||
println!("{label}:");
|
||||
let single = median(×[arm][1]);
|
||||
println!("n\tmedian ms\tms per token\tcost vs n single steps");
|
||||
for (n, v) in times[arm].iter().enumerate().skip(1) {
|
||||
let m = median(v);
|
||||
println!(
|
||||
"{n}\t{m:.0}\t{:.0}\t{:.2}\t(runs {:?})",
|
||||
m / n as f64,
|
||||
m / (single * n as f64),
|
||||
v.iter().map(|x| x.round()).collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
println!("phase breakdown, per token, summed over the measured rounds:");
|
||||
for (n, p) in profiles[arm].iter().enumerate().skip(1) {
|
||||
let experts = p.experts_read as f64 / (rounds * model.config.blocks) as f64;
|
||||
println!(
|
||||
"{n}\t{} | distinct experts per layer {experts:.1}",
|
||||
p.report()
|
||||
);
|
||||
}
|
||||
}
|
||||
if paired {
|
||||
println!("logits of the two arms identical bit for bit in all {identical} paired passes");
|
||||
}
|
||||
if paired {
|
||||
println!("paired: time with multi-activation kernels / time without, per round");
|
||||
println!("n\tmedian ratio\t(ratios)");
|
||||
for (n, (with, without)) in times[1].iter().zip(×[0]).enumerate().skip(1) {
|
||||
let ratios: Vec<f64> = with.iter().zip(without).map(|(on, off)| on / off).collect();
|
||||
println!(
|
||||
"{n}\t{:.3}\t{:?}",
|
||||
median(&ratios),
|
||||
ratios
|
||||
.iter()
|
||||
.map(|r| (r * 1000.0).round() / 1000.0)
|
||||
.collect::<Vec<_>>()
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+53
-10
@@ -17,7 +17,7 @@ pub mod pool;
|
||||
pub mod sampling;
|
||||
pub mod speculate;
|
||||
|
||||
use leleka_cpu_kernels::Dispatch;
|
||||
use leleka_cpu_kernels::{Dispatch, MULTI_MAX, Q8rRef};
|
||||
use leleka_gguf::{Gguf, TensorInfo, TensorType};
|
||||
use pool::{ChunkCounter, Pool};
|
||||
use std::fmt;
|
||||
@@ -301,6 +301,7 @@ pub struct Model {
|
||||
dispatch: Dispatch,
|
||||
pool: Pool,
|
||||
prefill_chunk: usize,
|
||||
multi_activation: bool,
|
||||
}
|
||||
|
||||
fn bytes_of(
|
||||
@@ -539,6 +540,7 @@ impl Model {
|
||||
dispatch,
|
||||
pool: Pool::new(threads),
|
||||
prefill_chunk: DEFAULT_PREFILL_CHUNK,
|
||||
multi_activation: true,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -628,6 +630,8 @@ pub struct Profile {
|
||||
pub activation: std::time::Duration,
|
||||
pub down_region: std::time::Duration,
|
||||
pub lm_head: std::time::Duration,
|
||||
/// Expert weight sets (gate, up and down of one expert) read, summed over layers and passes.
|
||||
pub experts_read: u64,
|
||||
}
|
||||
|
||||
impl Profile {
|
||||
@@ -864,7 +868,7 @@ impl Model {
|
||||
let jobs = Arc::new(jobs);
|
||||
let chunks = Arc::new(chunks);
|
||||
let counter = ChunkCounter::new(chunks.len());
|
||||
let dispatch = self.dispatch;
|
||||
let (dispatch, multi) = (self.dispatch, self.multi_activation);
|
||||
let (jobs_in, chunks_in) = (jobs.clone(), chunks.clone());
|
||||
let parts: Vec<ChunkResults> = self.pool.broadcast(move |_| {
|
||||
let mut done = Vec::new();
|
||||
@@ -873,21 +877,52 @@ impl Model {
|
||||
let job = &jobs_in[chunk.job];
|
||||
let data = job.matrix.data();
|
||||
let row_bytes = job.matrix.row_bytes();
|
||||
let mut out = Vec::with_capacity(chunk.rows * job.acts.len());
|
||||
for r in 0..chunk.rows {
|
||||
let width = job.acts.len();
|
||||
// with several activations the row is decoded once for up to MULTI_MAX of them; every
|
||||
// value is bit for bit the one-activation kernel's
|
||||
let refs: Vec<Q8rRef> = if multi && width > 1 {
|
||||
job.acts
|
||||
.iter()
|
||||
.map(|a| Q8rRef {
|
||||
scales: &a.scales,
|
||||
quants: &a.quants,
|
||||
})
|
||||
.collect()
|
||||
} else {
|
||||
Vec::new()
|
||||
};
|
||||
let kernel_error = |e| ModelError::Invalid(format!("kernel: {e}"));
|
||||
let mut out = vec![0.0f32; chunk.rows * width];
|
||||
for (r, values) in out.chunks_exact_mut(width).enumerate() {
|
||||
let row_index = job.first_row + chunk.start + r;
|
||||
let row = &data[row_index * row_bytes..(row_index + 1) * row_bytes];
|
||||
let bias = job
|
||||
.bias
|
||||
.as_ref()
|
||||
.map_or(0.0, |b| b.data[b.offset + chunk.start + r]);
|
||||
for act in &job.acts {
|
||||
let dot = match job.matrix.kind {
|
||||
Kind::Q8_0 => dispatch.dot_q8_0_q8_0(row, &act.blocks),
|
||||
Kind::Mxfp4 => dispatch.dot_mxfp4_q8r(row, &act.scales, &act.quants),
|
||||
if width == 1 || !multi {
|
||||
for (act, slot) in job.acts.iter().zip(values.iter_mut()) {
|
||||
*slot = match job.matrix.kind {
|
||||
Kind::Q8_0 => dispatch.dot_q8_0_q8_0(row, &act.blocks),
|
||||
Kind::Mxfp4 => {
|
||||
dispatch.dot_mxfp4_q8r(row, &act.scales, &act.quants)
|
||||
}
|
||||
}
|
||||
.map_err(kernel_error)?;
|
||||
}
|
||||
.map_err(|e| ModelError::Invalid(format!("kernel: {e}")))?;
|
||||
out.push(dot + bias);
|
||||
} else {
|
||||
for (group, slots) in
|
||||
refs.chunks(MULTI_MAX).zip(values.chunks_mut(MULTI_MAX))
|
||||
{
|
||||
match job.matrix.kind {
|
||||
Kind::Q8_0 => dispatch.dot_q8_0_q8r_multi(row, group, slots),
|
||||
Kind::Mxfp4 => dispatch.dot_mxfp4_q8r_multi(row, group, slots),
|
||||
}
|
||||
.map_err(kernel_error)?;
|
||||
}
|
||||
}
|
||||
for v in values.iter_mut() {
|
||||
*v += bias;
|
||||
}
|
||||
}
|
||||
done.push((ci, out));
|
||||
@@ -1057,6 +1092,13 @@ impl Model {
|
||||
self.prefill_chunk = tokens.max(1);
|
||||
}
|
||||
|
||||
/// Whether weight products over several tokens decode each weight row once for up to [`MULTI_MAX`] tokens
|
||||
/// (the default) or run the one-token kernel per token. Both give the same values bit for bit; the switch
|
||||
/// exists for paired speed measurements (`examples/batch_cost.rs`).
|
||||
pub fn set_multi_activation(&mut self, on: bool) {
|
||||
self.multi_activation = on;
|
||||
}
|
||||
|
||||
/// Run `tokens` (positions `pos0..`) through all layers as one batch and return the final hidden state of
|
||||
/// every token (empty for no tokens). The tokens are appended to the cached ones.
|
||||
#[allow(unused_assignments)] // the last `lap!` resets a timer nobody reads
|
||||
@@ -1281,6 +1323,7 @@ impl Model {
|
||||
let active: Vec<usize> = (0..c.n_expert)
|
||||
.filter(|ex| !per_expert[*ex].is_empty())
|
||||
.collect();
|
||||
state.profile.experts_read += active.len() as u64;
|
||||
// region 3: gate and up of every active expert, for the tokens routed to it
|
||||
let mut jobs = Vec::new();
|
||||
for ex in &active {
|
||||
|
||||
@@ -5,20 +5,22 @@
|
||||
//! and sampling from the real logits after every position, so the output is exactly what plain decoding gives; a
|
||||
//! wrong guess only costs the extra compute of the batch.
|
||||
//!
|
||||
//! On the CPU that cost is high: a pass over n tokens takes about 0.65 n single steps once n is 4 or more (1.56 for
|
||||
//! n = 2; `examples/batch_cost.rs` on the reference laptop), so even a perfect draft gains at most about 1.5x and a
|
||||
//! draft that is right 60% of the time gains nothing. The drafter therefore estimates how often a drafted position
|
||||
//! is accepted, separately by how long the matched context is, and drafts only the length whose expected tokens per
|
||||
//! pass beat its cost; the costs start from the measured ratios and follow the observed pass times.
|
||||
//! On the CPU that cost is high: a pass over n tokens takes about 0.74 + 0.42 n single steps (`examples/batch_cost.rs`
|
||||
//! on the reference laptop), so even a perfect 8-token draft gains at most about 2x and a draft that is right 60% of
|
||||
//! the time gains almost nothing. The drafter therefore estimates how often a drafted position is accepted, separately
|
||||
//! by how long the matched context is, and drafts only the length whose expected tokens per pass beat its cost; the
|
||||
//! costs start from the measured ratios and follow the observed pass times.
|
||||
|
||||
/// Longest draft ever proposed.
|
||||
pub const MAX_DRAFT: usize = 8;
|
||||
|
||||
/// Time of a pass over n tokens divided by one single-token step, n = 1..=9: the line 0.30 + 0.631 n fitted to the
|
||||
/// medians for n >= 2 (1.56, 2.16, 2.84, 3.37, 4.01, 4.76, 5.22, 5.98; reference laptop, 14 threads, position 900,
|
||||
/// `examples/batch_cost.rs`, 2026-10-16). Used until the pass times have been observed.
|
||||
/// Time of a pass over n tokens divided by one single-token step, n = 1..=9: the line 0.737 + 0.421 n fitted for n >= 2
|
||||
/// to the medians measured without the multi-activation kernels (1.56, 2.16, 2.84, 3.37, 4.01, 4.76, 5.22, 5.98)
|
||||
/// times the paired ratios of their pass times with and without them (0.976, 0.924, 0.903, 0.833, 0.805, 0.771, 0.785,
|
||||
/// 0.759); reference laptop, 14 threads, position 900, `examples/batch_cost.rs`, 2026-10-16. Used until the pass times
|
||||
/// have been observed.
|
||||
pub const MEASURED_COST: [f64; MAX_DRAFT + 1] =
|
||||
[1.0, 1.56, 2.19, 2.82, 3.46, 4.09, 4.72, 5.35, 5.98];
|
||||
[1.0, 1.58, 2.00, 2.42, 2.84, 3.27, 3.69, 4.11, 4.53];
|
||||
/// Upper bounds of the matched-context lengths that share one acceptance estimate.
|
||||
const BUCKETS: [usize; 3] = [4, 8, 16];
|
||||
/// Observed passes of one size before their time replaces the measured ratio.
|
||||
@@ -314,11 +316,11 @@ mod tests {
|
||||
// near-certain acceptance: the longest draft
|
||||
let mut d = confident(3, 8);
|
||||
assert_eq!(d.draft(&history).len(), 8);
|
||||
// at 0.95 a longer pass costs more than it adds after 3 or 4 tokens
|
||||
// at 0.9 a longer pass costs more than it adds after about 4 tokens
|
||||
let mut d = Drafter::new(3, 8);
|
||||
d.acceptance = [(95.0, 5.0); BUCKETS.len() + 1];
|
||||
d.acceptance = [(90.0, 10.0); BUCKETS.len() + 1];
|
||||
let n = d.draft(&history).len();
|
||||
assert!((3..=4).contains(&n), "{n}");
|
||||
assert!((3..=5).contains(&n), "{n}");
|
||||
// acceptance around 0.6 pays for no draft at the measured costs
|
||||
let mut d = Drafter::new(3, 8);
|
||||
d.acceptance = [(6.0, 4.0); BUCKETS.len() + 1];
|
||||
|
||||
@@ -840,3 +840,35 @@ fn logits_after_each_are_bit_identical_to_feeding_tokens_one_at_a_time() {
|
||||
assert_eq!(bits(&st.logits), bits(&expected[3]));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn batches_wider_than_one_kernel_call_are_bit_identical_at_every_level() {
|
||||
// 20 tokens: the weight products run as one multi-activation call for 16 activations and one for 4
|
||||
let w = build_world(8);
|
||||
let gguf = Gguf::read(&w.file[..], w.file.len() as u64).unwrap();
|
||||
let prefix = [5u32, 17];
|
||||
let batch: Vec<u32> = (0..20).map(|i| (i * 37 + 11) % VOCAB as u32).collect();
|
||||
for isa in leleka_cpu_kernels::Isa::ALL {
|
||||
let Ok(dispatch) = Dispatch::with_isa(isa) else {
|
||||
continue;
|
||||
};
|
||||
let model = Model::load(std::sync::Arc::new(w.file.clone()), &gguf, dispatch, 3).unwrap();
|
||||
let mut seq = State::new(&model.config, 32);
|
||||
let mut expected = Vec::new();
|
||||
for (pos, t) in prefix.iter().chain(&batch).enumerate() {
|
||||
model.forward(&mut seq, *t, pos).unwrap();
|
||||
if pos >= prefix.len() {
|
||||
expected.push(seq.logits.clone());
|
||||
}
|
||||
}
|
||||
let mut st = State::new(&model.config, 32);
|
||||
model.prefill(&mut st, &prefix, 0).unwrap();
|
||||
let all = model
|
||||
.logits_after_each(&mut st, &batch, prefix.len())
|
||||
.unwrap();
|
||||
let bits = |v: &Vec<f32>| v.iter().map(|x| x.to_bits()).collect::<Vec<_>>();
|
||||
for (i, (a, e)) in all.iter().zip(&expected).enumerate() {
|
||||
assert_eq!(bits(a), bits(e), "level {isa}, position {i}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+34
-14
@@ -83,7 +83,8 @@ reads about 2.56 GB (experts 1.27, attention Q8_0 0.68, output layer 0.62), so d
|
||||
the measured 36-40 GB/s, for this runtime and for llama.cpp alike. The CPU and the integrated GPU share that channel:
|
||||
streaming from both at once gave about 37 GB/s in total (GPU 28 GB/s alone, about 21 GB/s while the CPU decoded), so
|
||||
splitting decode across them does not add bandwidth. Verifying several tokens in one CPU pass is compute-bound (about
|
||||
0.65 single steps per token), which caps CPU-side speculative decoding near 1.5x; see the `--speculate` section below.
|
||||
0.42 single steps per token since the multi-activation kernels, 0.65 before), which caps CPU-side speculative decoding
|
||||
near 2x; see the `--speculate` section below.
|
||||
Prompt-lookup drafting accepted only 1.03-1.2 tokens per step on the four set2 texts. A second memory module (dual
|
||||
channel) is the lossless way past the cap.
|
||||
|
||||
@@ -147,15 +148,27 @@ therefore exactly that of plain decoding for any sampling settings (`tests/serve
|
||||
all 96 real-model runs below). Drafts never run past the output budget, so a batch stays inside the context margin.
|
||||
`LELEKA_SPECULATION_LOG=1` prints drafted and accepted counts per request.
|
||||
|
||||
On the CPU a verifying batch is compute-bound, so it is not free (`examples/batch_cost.rs`, position 900, medians):
|
||||
On the CPU a verifying batch is compute-bound, so it is not free (`examples/batch_cost.rs`, position 900, medians).
|
||||
The batch pass first ran the one-token kernel once per (weight row, token), redoing the MXFP4 decode and scale work for
|
||||
every token: profiled, the extra cost was compute, not expert bytes (distinct experts per layer rise only from 4 to
|
||||
9.5 at 9 tokens, while the Q8_0 projections, whose weights every token shares, cost 3.6-4x a single step). The
|
||||
multi-activation kernels (`leleka-cpu-sys`, portable, AVX2 and AVX-VNNI) decode a weight row once per 64-block segment
|
||||
and run up to 16 activations over it with exactly the one-token kernel's accumulators, so every value is bit for bit
|
||||
the one-token kernel's (`tests/multi.rs`; on the real model all 90 paired passes below gave identical logits). Pass
|
||||
times with them divided by without them, paired back to back in one process (`batch_cost ... 14 ab`, 9 rounds, median
|
||||
ratio; the machine was busier than for the first row, single step 108 ms):
|
||||
|
||||
| tokens in the pass | 1 | 2 | 3 | 4 | 6 | 9 |
|
||||
| --- | --- | --- | --- | --- | --- | --- |
|
||||
| ms | 93 | 145 | 201 | 264 | 373 | 556 |
|
||||
| cost in single steps | 1.00 | 1.56 | 2.16 | 2.84 | 4.01 | 5.98 |
|
||||
| tokens in the pass | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
|
||||
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
|
||||
| ms before (quiet run, 93 ms single step) | 93 | 145 | 201 | 264 | 313 | 373 | 443 | 485 | 556 |
|
||||
| cost in single steps before | 1.00 | 1.56 | 2.16 | 2.84 | 3.37 | 4.01 | 4.76 | 5.22 | 5.98 |
|
||||
| paired time ratio, after / before | 1.01 | 0.98 | 0.92 | 0.90 | 0.83 | 0.81 | 0.77 | 0.79 | 0.76 |
|
||||
| cost in single steps after (line used by the drafter) | 1.00 | 1.58 | 2.00 | 2.42 | 2.84 | 3.27 | 3.69 | 4.11 | 4.53 |
|
||||
|
||||
A pass over n >= 4 tokens costs about 0.65 n single steps, so even perfect drafts gain at most about 1.5x, and a draft
|
||||
accepted 60% of the time gains nothing. The drafter therefore estimates the acceptance of a drafted position
|
||||
The gain grows with the batch because a token shares a weight row with more others: the Q8_0 projections see every
|
||||
token, an expert only the tokens routed to it (about 2 at 4 tokens, 4 at 9). Plain decode (one token) is unchanged.
|
||||
A pass over n tokens now costs about 0.74 + 0.42 n single steps, so even a perfect 8-token draft gains at most about 2x,
|
||||
and a draft accepted 60% of the time still gains almost nothing. The drafter therefore estimates the acceptance of a drafted position
|
||||
separately by matched-context length (3, 4-7, 8-15, 16+ tokens; decaying counts), drafts the length whose expected
|
||||
tokens per pass (1 + p + ... + p^k) divided by its cost is largest, and only if that ratio is at least 1.03; the costs
|
||||
start from the line fitted to the table and then follow the pass times the loop observes. After 16 tokens without a
|
||||
@@ -167,18 +180,25 @@ Paired A/B in one worker process (`crates/cpu-worker/examples/ab_speculation.rs`
|
||||
source file, greedy, 320 output tokens at most, 3 alternating pairs per prompt, warm model, decode time only. Paired
|
||||
speed-up of decode (mean of the three pair ratios):
|
||||
|
||||
| task (output tokens) | inherited fixed-length drafter | cost-aware, noisy machine | same, quieter machine | default policy, noisy |
|
||||
| --- | --- | --- | --- | --- |
|
||||
| rewrite the file with two names changed (320) | 1.36 | 1.26 | 1.34 | 1.25 |
|
||||
| unified diff adding an attribute (303) | 0.94 | 1.00 | 1.15 | 1.10 |
|
||||
| functions as JSON (195) | 0.97 | 0.98 | 1.04 | 0.97 |
|
||||
| explain the file (162) | 0.96 | 0.96 | 1.01 | 0.98 |
|
||||
| task (output tokens) | inherited fixed-length drafter | cost-aware, noisy machine | same, quieter machine | default policy, noisy | with multi-activation kernels |
|
||||
| --- | --- | --- | --- | --- | --- |
|
||||
| rewrite the file with two names changed (320) | 1.36 | 1.26 | 1.34 | 1.25 | 1.34 (1.41, 1.21, 1.39) |
|
||||
| unified diff adding an attribute (303) | 0.94 | 1.00 | 1.15 | 1.10 | 1.04 (1.08, 1.07, 0.98) |
|
||||
| functions as JSON (195) | 0.97 | 0.98 | 1.04 | 0.97 | 0.97 (1.02, 1.00, 0.88) |
|
||||
| explain the file (162) | 0.96 | 0.96 | 1.01 | 0.98 | 0.94 (0.91, 0.93, 0.99) |
|
||||
|
||||
Plain decode ran at 8-9 tok/s on the noisy machine and 11-12 on the quieter one; pair-to-pair spread is about 5%, so
|
||||
the last two rows are within noise of 1.0. Copying output (rewrites, patches) gains 1.1-1.35x; new text neither gains
|
||||
nor clearly loses. Three pairs per prompt are not enough for percent-level claims, and these are four prompts, not an
|
||||
agent trace: the switch stays experimental and off by default.
|
||||
|
||||
The last column was run after the multi-activation kernels (`benchmarks/results/batch-pass-multi-2026-10-16.txt`;
|
||||
plain decode 9.6-10.3 tok/s, outputs identical in all 24 runs). End to end it is within the pair-to-pair spread of the
|
||||
column before it, so the cheaper verification pass is not yet visible in decode speed: replaying the recorded outputs
|
||||
through the drafter with the new costs predicts 1.59, 1.15, 1.00 and 0.99 for the four prompts, so the serving loop
|
||||
loses time that the pass-cost model does not see (to be profiled). The explanation prompt was slower with speculation
|
||||
in all three pairs (0.91-0.99).
|
||||
|
||||
Verifying drafts on the integrated GPU or the NPU does not pay: both run a pass layer by layer with weights uploaded
|
||||
(GPU) or expanded and prefetched (NPU) every time, a fixed cost of seconds. One 9-token pass from position 0 took 7.3 s
|
||||
on the GPU (upload 1.2, attention 2.0, experts 3.0, readback 0.7) and 6.3 s through the NPU service, against 0.75-0.93 s
|
||||
|
||||
Reference in New Issue
Block a user