From 4725df5bdfd9932f3231a2a70c7ba6f7fa9f1c5f Mon Sep 17 00:00:00 2001 From: Pavlo Ratushnyi Date: Sat, 17 Oct 2026 03:45:20 +0200 Subject: [PATCH] feat: --cache-slots, one worker keeps the KV caches of several agents and picks the right one (STRA-220) GptOssEngine holds up to N conversation caches (--cache-slots N on the four workers, default 1 = unchanged). crates/cpu-worker/src/slots.rs chooses per prompt: continue in place a slot that is wholly a prefix of the prompt (the same agent's next turn); otherwise take the slot sharing the longest prefix as a donor and either continue it (losing its tail) or copy the shared part into a new/empty/least recently used slot (State::copy_prefix_from), whichever discards fewer cached tokens, so a new agent gets the shared system prompt without destroying another agent's cache. Results are bit-identical to a fresh prefill (synthetic test: copied prefix continues bit for bit, donor untouched). Measured: CPU only, 3 agents, 36 requests: 1.37x/1.46x prompt time, outputs identical. Through the control plane, 4 agents on one iGPU worker, 3 clean alternating pairs: 986/993/995 s with 1 slot against 569/575/575 s with 4 slots (1.73x), answers identical in all six runs. The first run of pair 1 was disturbed by the UTC date in the system prompt changing mid-run and was repeated. Compare-ConcurrentEpisodes.ps1 takes -Agents, -SharedInstructionTokens and the 'slots' arm and records output hashes. Co-Authored-By: Claude Sonnet 5.5 --- .../results/ab-slots-cpu-2026-10-17.txt | 86 +++++ ...ache-slots-ab-2026-10-17-pair1-rerun.jsonl | 28 ++ ...agent-pool-cache-slots-ab-2026-10-17.jsonl | 82 +++++ .../tools/Compare-ConcurrentEpisodes.ps1 | 49 ++- crates/cpu-worker/examples/ab_slots.rs | 267 ++++++++++++++ crates/cpu-worker/src/engine.rs | 137 ++++++- crates/cpu-worker/src/lib.rs | 1 + crates/cpu-worker/src/main.rs | 11 +- crates/cpu-worker/src/slots.rs | 342 ++++++++++++++++++ crates/gptoss/src/lib.rs | 27 ++ crates/gptoss/tests/synthetic_model.rs | 48 +++ crates/gpu-npu-worker/src/main.rs | 11 +- crates/igpu-worker/src/main.rs | 11 +- crates/npu-worker/src/main.rs | 11 +- docs/worker-pool.md | 81 ++++- 15 files changed, 1158 insertions(+), 34 deletions(-) create mode 100644 benchmarks/results/ab-slots-cpu-2026-10-17.txt create mode 100644 benchmarks/results/agent-pool-cache-slots-ab-2026-10-17-pair1-rerun.jsonl create mode 100644 benchmarks/results/agent-pool-cache-slots-ab-2026-10-17.jsonl create mode 100644 crates/cpu-worker/examples/ab_slots.rs create mode 100644 crates/cpu-worker/src/slots.rs diff --git a/benchmarks/results/ab-slots-cpu-2026-10-17.txt b/benchmarks/results/ab-slots-cpu-2026-10-17.txt new file mode 100644 index 00000000..ceba67ea --- /dev/null +++ b/benchmarks/results/ab-slots-cpu-2026-10-17.txt @@ -0,0 +1,86 @@ +# one cache slot vs several in one worker, CPU prefill only (crates/cpu-worker/examples/ab_slots.rs), 2026-10-17 +model: gpt-oss-20b-MXFP4.gguf (sha256 65D06D31A3977D553CB3AF137B5C26B5F1E9297A6AAA29AE7CAA98788CDE53AB); Core Ultra 7 265U, 14 threads, kernels avx-vnni; base commit 4821fc4 plus this change +3 agents x 3 turns, shared prefix 603 tokens, 24 output tokens greedy, 2 pairs alternating, cold cache per arm; machine otherwise idle, power and clocks not controlled +slot choices of every prompt (LELEKA_SLOT_LOG) are in the second block + +3 agents x 3 turns, prompt tokens per agent and turn [[619, 1398, 2162], [619, 1383, 2143], [619, 1398, 2163]], shared prefix 603 tokens, max_new 24, 14 threads +pair 0 1 slot(s) agent 0 turn 0: 619 prompt tokens, 0 reused, prompt 17961 ms, decode 1890 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 1 turn 0: 619 prompt tokens, 603 reused, prompt 595 ms, decode 1876 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 2 turn 0: 619 prompt tokens, 603 reused, prompt 549 ms, decode 1821 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 0 turn 1: 1398 prompt tokens, 603 reused, prompt 25483 ms, decode 1914 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 1 turn 1: 1383 prompt tokens, 603 reused, prompt 25639 ms, decode 1967 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 2 turn 1: 1398 prompt tokens, 603 reused, prompt 26008 ms, decode 1960 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 0 turn 2: 2162 prompt tokens, 603 reused, prompt 53080 ms, decode 2020 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 1 turn 2: 2143 prompt tokens, 603 reused, prompt 52467 ms, decode 2037 ms, 24 tokens, identical=true +pair 0 1 slot(s) agent 2 turn 2: 2163 prompt tokens, 603 reused, prompt 54655 ms, decode 2121 ms, 24 tokens, identical=true +pair 0 1 slot(s): prompt time 256.4 s, 7680 tokens computed, 4824 reused +pair 0 3 slot(s) agent 0 turn 0: 619 prompt tokens, 0 reused, prompt 20406 ms, decode 1896 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 1 turn 0: 619 prompt tokens, 603 reused, prompt 634 ms, decode 1913 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 2 turn 0: 619 prompt tokens, 603 reused, prompt 625 ms, decode 1927 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 0 turn 1: 1398 prompt tokens, 620 reused, prompt 28465 ms, decode 1968 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 1 turn 1: 1383 prompt tokens, 620 reused, prompt 26551 ms, decode 1966 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 2 turn 1: 1398 prompt tokens, 620 reused, prompt 27810 ms, decode 2053 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 0 turn 2: 2162 prompt tokens, 1399 reused, prompt 27505 ms, decode 2130 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 1 turn 2: 2143 prompt tokens, 1384 reused, prompt 28006 ms, decode 2049 ms, 24 tokens, identical=true +pair 0 3 slot(s) agent 2 turn 2: 2163 prompt tokens, 1399 reused, prompt 27548 ms, decode 2023 ms, 24 tokens, identical=true +pair 0 3 slot(s): prompt time 187.6 s, 5256 tokens computed, 7248 reused +pair 1 3 slot(s) agent 0 turn 0: 619 prompt tokens, 0 reused, prompt 21301 ms, decode 1920 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 1 turn 0: 619 prompt tokens, 603 reused, prompt 634 ms, decode 1927 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 2 turn 0: 619 prompt tokens, 603 reused, prompt 632 ms, decode 1968 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 0 turn 1: 1398 prompt tokens, 620 reused, prompt 27314 ms, decode 1974 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 1 turn 1: 1383 prompt tokens, 620 reused, prompt 27519 ms, decode 1990 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 2 turn 1: 1398 prompt tokens, 620 reused, prompt 27813 ms, decode 1990 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 0 turn 2: 2162 prompt tokens, 1399 reused, prompt 28601 ms, decode 2158 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 1 turn 2: 2143 prompt tokens, 1384 reused, prompt 28104 ms, decode 2037 ms, 24 tokens, identical=true +pair 1 3 slot(s) agent 2 turn 2: 2163 prompt tokens, 1399 reused, prompt 28253 ms, decode 2052 ms, 24 tokens, identical=true +pair 1 3 slot(s): prompt time 190.2 s, 5256 tokens computed, 7248 reused +pair 1 1 slot(s) agent 0 turn 0: 619 prompt tokens, 0 reused, prompt 21236 ms, decode 1946 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 1 turn 0: 619 prompt tokens, 603 reused, prompt 650 ms, decode 1943 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 2 turn 0: 619 prompt tokens, 603 reused, prompt 628 ms, decode 1942 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 0 turn 1: 1398 prompt tokens, 603 reused, prompt 28908 ms, decode 2003 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 1 turn 1: 1383 prompt tokens, 603 reused, prompt 27621 ms, decode 1989 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 2 turn 1: 1398 prompt tokens, 603 reused, prompt 27915 ms, decode 1988 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 0 turn 2: 2162 prompt tokens, 603 reused, prompt 56533 ms, decode 2060 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 1 turn 2: 2143 prompt tokens, 603 reused, prompt 55894 ms, decode 2046 ms, 24 tokens, identical=true +pair 1 1 slot(s) agent 2 turn 2: 2163 prompt tokens, 603 reused, prompt 57855 ms, decode 2054 ms, 24 tokens, identical=true +pair 1 1 slot(s): prompt time 277.2 s, 7680 tokens computed, 4824 reused +total prompt time, 1 slot [256.0, 277.0] s, 3 slots [188.0, 190.0] s; paired speed-up [1.37, 1.46]; outputs of all runs identical: true + +# slot log (worker standard error) +prompt of 64 tokens: Fresh { slot: 0 }; slots hold [0] +prompt of 619 tokens: Fresh { slot: 0 }; slots hold [0] +prompt of 619 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 619 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 1383 tokens: Continue { slot: 0 }; slots hold [1421] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [1406] +prompt of 2162 tokens: Continue { slot: 0 }; slots hold [1421] +prompt of 2143 tokens: Continue { slot: 0 }; slots hold [2185] +prompt of 2163 tokens: Continue { slot: 0 }; slots hold [2166] +prompt of 619 tokens: Fresh { slot: 1 }; slots hold [0, 0] +prompt of 619 tokens: Copy { from: 1, into: 2, len: 603 }; slots hold [0, 642, 603] +prompt of 619 tokens: Copy { from: 2, into: 0, len: 603 }; slots hold [603, 642, 642] +prompt of 1398 tokens: Continue { slot: 1 }; slots hold [642, 642, 642] +prompt of 1383 tokens: Continue { slot: 2 }; slots hold [642, 1421, 642] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [642, 1421, 1406] +prompt of 2162 tokens: Continue { slot: 1 }; slots hold [1421, 1421, 1406] +prompt of 2143 tokens: Continue { slot: 2 }; slots hold [1421, 2185, 1406] +prompt of 2163 tokens: Continue { slot: 0 }; slots hold [1421, 2185, 2166] +prompt of 619 tokens: Fresh { slot: 0 }; slots hold [0, 0, 0] +prompt of 619 tokens: Copy { from: 0, into: 1, len: 603 }; slots hold [642, 603, 0] +prompt of 619 tokens: Copy { from: 1, into: 2, len: 603 }; slots hold [642, 642, 603] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [642, 642, 642] +prompt of 1383 tokens: Continue { slot: 1 }; slots hold [1421, 642, 642] +prompt of 1398 tokens: Continue { slot: 2 }; slots hold [1421, 1406, 642] +prompt of 2162 tokens: Continue { slot: 0 }; slots hold [1421, 1406, 1421] +prompt of 2143 tokens: Continue { slot: 1 }; slots hold [2185, 1406, 1421] +prompt of 2163 tokens: Continue { slot: 2 }; slots hold [2185, 2166, 1421] +prompt of 619 tokens: Fresh { slot: 0 }; slots hold [0] +prompt of 619 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 619 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [642] +prompt of 1383 tokens: Continue { slot: 0 }; slots hold [1421] +prompt of 1398 tokens: Continue { slot: 0 }; slots hold [1406] +prompt of 2162 tokens: Continue { slot: 0 }; slots hold [1421] +prompt of 2143 tokens: Continue { slot: 0 }; slots hold [2185] +prompt of 2163 tokens: Continue { slot: 0 }; slots hold [2166] diff --git a/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17-pair1-rerun.jsonl b/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17-pair1-rerun.jsonl new file mode 100644 index 00000000..6dd1d3f5 --- /dev/null +++ b/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17-pair1-rerun.jsonl @@ -0,0 +1,28 @@ +{"turns":3,"model":"gpt-oss-20b-MXFP4.gguf","agents":4,"single_threads":10,"gpu_min_tokens":256,"max_output":32,"shared_instruction_tokens":1500,"kind":"meta","single":"leleka-igpu-worker","pool":"leleka-igpu-worker + leleka-npu-worker","tool_tokens":1500,"context":16384,"pool_threads":7,"date":"2026-10-17 03:18","pairs":1} +{"episode":1,"turn":1,"start_s":0.05,"wall_s":137.2,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"single","pair":1} +{"episode":1,"turn":2,"start_s":137.25,"wall_s":277,"input_tokens":6190,"cached_tokens":2050,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"single","pair":1} +{"episode":1,"turn":3,"start_s":414.26,"wall_s":447.51,"input_tokens":8248,"cached_tokens":2050,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"single","pair":1} +{"episode":2,"turn":1,"start_s":0.05,"wall_s":176.76,"input_tokens":4160,"cached_tokens":2050,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"single","pair":1} +{"episode":2,"turn":2,"start_s":176.81,"wall_s":316.4,"input_tokens":6238,"cached_tokens":2050,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"single","pair":1} +{"episode":2,"turn":3,"start_s":493.21,"wall_s":492.93,"input_tokens":8318,"cached_tokens":2050,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"single","pair":1} +{"episode":3,"turn":1,"start_s":0.05,"wall_s":60.63,"input_tokens":4117,"cached_tokens":59,"output_tokens":32,"output_sha":"3528BB18436C","arm":"single","pair":1} +{"episode":3,"turn":2,"start_s":60.72,"wall_s":195.81,"input_tokens":6175,"cached_tokens":2050,"output_tokens":32,"output_sha":"88C84F134391","arm":"single","pair":1} +{"episode":3,"turn":3,"start_s":256.53,"wall_s":359.5,"input_tokens":8237,"cached_tokens":2050,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"single","pair":1} +{"episode":4,"turn":1,"start_s":0.05,"wall_s":99.23,"input_tokens":4164,"cached_tokens":2050,"output_tokens":32,"output_sha":"52032CE22614","arm":"single","pair":1} +{"episode":4,"turn":2,"start_s":99.28,"wall_s":236.53,"input_tokens":6222,"cached_tokens":2050,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"single","pair":1} +{"episode":4,"turn":3,"start_s":335.81,"wall_s":404.07,"input_tokens":8296,"cached_tokens":2050,"output_tokens":32,"output_sha":"078A1029B307","arm":"single","pair":1} +{"kind":"arm","arm":"single","pair":1,"both_done_s":986.15} +{"episode":1,"turn":1,"start_s":0.03,"wall_s":61.11,"input_tokens":4130,"cached_tokens":59,"output_tokens":32,"output_sha":"3ED938794905","arm":"slots","pair":1} +{"episode":1,"turn":2,"start_s":61.14,"wall_s":166.37,"input_tokens":6190,"cached_tokens":4130,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"slots","pair":1} +{"episode":1,"turn":3,"start_s":227.52,"wall_s":187.63,"input_tokens":8248,"cached_tokens":6190,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"slots","pair":1} +{"episode":2,"turn":1,"start_s":0.03,"wall_s":180.16,"input_tokens":4160,"cached_tokens":2051,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"slots","pair":1} +{"episode":2,"turn":2,"start_s":180.19,"wall_s":184.27,"input_tokens":6238,"cached_tokens":4160,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"slots","pair":1} +{"episode":2,"turn":3,"start_s":364.46,"wall_s":204.75,"input_tokens":8318,"cached_tokens":6238,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"slots","pair":1} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":99.31,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"3528BB18436C","arm":"slots","pair":1} +{"episode":3,"turn":2,"start_s":99.34,"wall_s":172.7,"input_tokens":6175,"cached_tokens":4117,"output_tokens":32,"output_sha":"88C84F134391","arm":"slots","pair":1} +{"episode":3,"turn":3,"start_s":272.05,"wall_s":193.93,"input_tokens":8237,"cached_tokens":6175,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"slots","pair":1} +{"episode":4,"turn":1,"start_s":0.03,"wall_s":140.65,"input_tokens":4164,"cached_tokens":2050,"output_tokens":32,"output_sha":"52032CE22614","arm":"slots","pair":1} +{"episode":4,"turn":2,"start_s":140.69,"wall_s":175.95,"input_tokens":6222,"cached_tokens":4164,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"slots","pair":1} +{"episode":4,"turn":3,"start_s":316.64,"wall_s":200.43,"input_tokens":8296,"cached_tokens":6222,"output_tokens":32,"output_sha":"078A1029B307","arm":"slots","pair":1} +{"kind":"arm","arm":"slots","pair":1,"both_done_s":569.22} +{"kind":"compare","pair":1,"identical_answers":true,"differing":[]} diff --git a/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17.jsonl b/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17.jsonl new file mode 100644 index 00000000..4a76f44b --- /dev/null +++ b/benchmarks/results/agent-pool-cache-slots-ab-2026-10-17.jsonl @@ -0,0 +1,82 @@ +{"turns":3,"model":"gpt-oss-20b-MXFP4.gguf","agents":4,"single_threads":10,"gpu_min_tokens":256,"max_output":32,"shared_instruction_tokens":1500,"kind":"meta","single":"leleka-igpu-worker","pool":"leleka-igpu-worker + leleka-npu-worker","tool_tokens":1500,"context":16384,"pool_threads":7,"date":"2026-10-17 01:55","pairs":3} +{"episode":1,"turn":1,"start_s":0.05,"wall_s":182.49,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"single","pair":1} +{"episode":1,"turn":2,"start_s":182.55,"wall_s":318.31,"input_tokens":6190,"cached_tokens":2050,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"single","pair":1} +{"episode":1,"turn":3,"start_s":500.86,"wall_s":524.19,"input_tokens":8248,"cached_tokens":2050,"output_tokens":32,"output_sha":"406F094440F1","arm":"single","pair":1} +{"episode":2,"turn":1,"start_s":0.05,"wall_s":64.69,"input_tokens":4160,"cached_tokens":59,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"single","pair":1} +{"episode":2,"turn":2,"start_s":64.79,"wall_s":200.41,"input_tokens":6238,"cached_tokens":2050,"output_tokens":32,"output_sha":"07065FAC9A34","arm":"single","pair":1} +{"episode":2,"turn":3,"start_s":265.2,"wall_s":388.96,"input_tokens":8318,"cached_tokens":35,"output_tokens":32,"output_sha":"68663279629E","arm":"single","pair":1} +{"episode":3,"turn":1,"start_s":0.05,"wall_s":102.95,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"B77D9C8E7014","arm":"single","pair":1} +{"episode":3,"turn":2,"start_s":103.01,"wall_s":240.23,"input_tokens":6175,"cached_tokens":2050,"output_tokens":32,"output_sha":"56B42A9550D6","arm":"single","pair":1} +{"episode":3,"turn":3,"start_s":343.24,"wall_s":433.83,"input_tokens":8237,"cached_tokens":2050,"output_tokens":32,"output_sha":"C5D874DCDDEE","arm":"single","pair":1} +{"episode":4,"turn":1,"start_s":0.05,"wall_s":143.84,"input_tokens":4164,"cached_tokens":2050,"output_tokens":32,"output_sha":"52032CE22614","arm":"single","pair":1} +{"episode":4,"turn":2,"start_s":143.9,"wall_s":278.78,"input_tokens":6222,"cached_tokens":2050,"output_tokens":32,"output_sha":"450DE01C2B57","arm":"single","pair":1} +{"episode":4,"turn":3,"start_s":422.68,"wall_s":479.37,"input_tokens":8296,"cached_tokens":2050,"output_tokens":32,"output_sha":"D0D60318E6D1","arm":"single","pair":1} +{"kind":"arm","arm":"single","pair":1,"both_done_s":1025.06} +{"episode":1,"turn":1,"start_s":0.03,"wall_s":101.63,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"slots","pair":1} +{"episode":1,"turn":2,"start_s":101.66,"wall_s":173.3,"input_tokens":6190,"cached_tokens":4130,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"slots","pair":1} +{"episode":1,"turn":3,"start_s":274.97,"wall_s":195.57,"input_tokens":8248,"cached_tokens":6190,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"slots","pair":1} +{"episode":2,"turn":1,"start_s":0.03,"wall_s":182.38,"input_tokens":4160,"cached_tokens":2051,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"slots","pair":1} +{"episode":2,"turn":2,"start_s":182.43,"wall_s":184.94,"input_tokens":6238,"cached_tokens":4160,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"slots","pair":1} +{"episode":2,"turn":3,"start_s":367.38,"wall_s":208.55,"input_tokens":8318,"cached_tokens":6238,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"slots","pair":1} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":142.81,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"3528BB18436C","arm":"slots","pair":1} +{"episode":3,"turn":2,"start_s":142.84,"wall_s":176.9,"input_tokens":6175,"cached_tokens":4117,"output_tokens":32,"output_sha":"88C84F134391","arm":"slots","pair":1} +{"episode":3,"turn":3,"start_s":319.74,"wall_s":204.19,"input_tokens":8237,"cached_tokens":6175,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"slots","pair":1} +{"episode":4,"turn":1,"start_s":0.03,"wall_s":62.73,"input_tokens":4164,"cached_tokens":59,"output_tokens":32,"output_sha":"52032CE22614","arm":"slots","pair":1} +{"episode":4,"turn":2,"start_s":62.76,"wall_s":166.91,"input_tokens":6222,"cached_tokens":4164,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"slots","pair":1} +{"episode":4,"turn":3,"start_s":229.67,"wall_s":189.62,"input_tokens":8296,"cached_tokens":6222,"output_tokens":32,"output_sha":"078A1029B307","arm":"slots","pair":1} +{"kind":"arm","arm":"slots","pair":1,"both_done_s":575.94} +{"kind":"compare","pair":1,"identical_answers":false,"differing":["1.3","2.3","4.3","4.2","3.1","3.2","3.3","2.2"]} +{"episode":1,"turn":1,"start_s":0.02,"wall_s":101.77,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"slots","pair":2} +{"episode":1,"turn":2,"start_s":101.8,"wall_s":173.6,"input_tokens":6190,"cached_tokens":4130,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"slots","pair":2} +{"episode":1,"turn":3,"start_s":275.4,"wall_s":195.13,"input_tokens":8248,"cached_tokens":6190,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"slots","pair":2} +{"episode":2,"turn":1,"start_s":0.02,"wall_s":63.29,"input_tokens":4160,"cached_tokens":59,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"slots","pair":2} +{"episode":2,"turn":2,"start_s":63.32,"wall_s":167.55,"input_tokens":6238,"cached_tokens":4160,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"slots","pair":2} +{"episode":2,"turn":3,"start_s":230.87,"wall_s":188.19,"input_tokens":8318,"cached_tokens":6238,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"slots","pair":2} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":143.25,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"3528BB18436C","arm":"slots","pair":2} +{"episode":3,"turn":2,"start_s":143.29,"wall_s":176.68,"input_tokens":6175,"cached_tokens":4117,"output_tokens":32,"output_sha":"88C84F134391","arm":"slots","pair":2} +{"episode":3,"turn":3,"start_s":319.96,"wall_s":201.5,"input_tokens":8237,"cached_tokens":6175,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"slots","pair":2} +{"episode":4,"turn":1,"start_s":0.02,"wall_s":182.57,"input_tokens":4164,"cached_tokens":2051,"output_tokens":32,"output_sha":"52032CE22614","arm":"slots","pair":2} +{"episode":4,"turn":2,"start_s":182.6,"wall_s":184.68,"input_tokens":6222,"cached_tokens":4164,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"slots","pair":2} +{"episode":4,"turn":3,"start_s":367.27,"wall_s":207.96,"input_tokens":8296,"cached_tokens":6222,"output_tokens":32,"output_sha":"078A1029B307","arm":"slots","pair":2} +{"kind":"arm","arm":"slots","pair":2,"both_done_s":575.23} +{"episode":1,"turn":1,"start_s":0.03,"wall_s":101.89,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"single","pair":2} +{"episode":1,"turn":2,"start_s":101.92,"wall_s":242.24,"input_tokens":6190,"cached_tokens":2050,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"single","pair":2} +{"episode":1,"turn":3,"start_s":344.16,"wall_s":403.21,"input_tokens":8248,"cached_tokens":2050,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"single","pair":2} +{"episode":2,"turn":1,"start_s":0.03,"wall_s":63.28,"input_tokens":4160,"cached_tokens":59,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"single","pair":2} +{"episode":2,"turn":2,"start_s":63.3,"wall_s":200.49,"input_tokens":6238,"cached_tokens":2050,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"single","pair":2} +{"episode":2,"turn":3,"start_s":263.8,"wall_s":361.44,"input_tokens":8318,"cached_tokens":2050,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"single","pair":2} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":185.03,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"3528BB18436C","arm":"single","pair":2} +{"episode":3,"turn":2,"start_s":185.06,"wall_s":316.47,"input_tokens":6175,"cached_tokens":2050,"output_tokens":32,"output_sha":"88C84F134391","arm":"single","pair":2} +{"episode":3,"turn":3,"start_s":501.54,"wall_s":491.55,"input_tokens":8237,"cached_tokens":2050,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"single","pair":2} +{"episode":4,"turn":1,"start_s":0.03,"wall_s":143.48,"input_tokens":4164,"cached_tokens":2050,"output_tokens":32,"output_sha":"52032CE22614","arm":"single","pair":2} +{"episode":4,"turn":2,"start_s":143.51,"wall_s":279.44,"input_tokens":6222,"cached_tokens":2050,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"single","pair":2} +{"episode":4,"turn":3,"start_s":422.95,"wall_s":447.63,"input_tokens":8296,"cached_tokens":2050,"output_tokens":32,"output_sha":"078A1029B307","arm":"single","pair":2} +{"kind":"arm","arm":"single","pair":2,"both_done_s":993.09} +{"kind":"compare","pair":2,"identical_answers":true,"differing":[]} +{"episode":1,"turn":1,"start_s":0.03,"wall_s":182.82,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"single","pair":3} +{"episode":1,"turn":2,"start_s":182.85,"wall_s":319.19,"input_tokens":6190,"cached_tokens":2050,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"single","pair":3} +{"episode":1,"turn":3,"start_s":502.04,"wall_s":493.15,"input_tokens":8248,"cached_tokens":2050,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"single","pair":3} +{"episode":2,"turn":1,"start_s":0.03,"wall_s":99.9,"input_tokens":4160,"cached_tokens":2050,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"single","pair":3} +{"episode":2,"turn":2,"start_s":99.93,"wall_s":245.06,"input_tokens":6238,"cached_tokens":2050,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"single","pair":3} +{"episode":2,"turn":3,"start_s":345,"wall_s":403,"input_tokens":8318,"cached_tokens":2050,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"single","pair":3} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":61.05,"input_tokens":4117,"cached_tokens":59,"output_tokens":32,"output_sha":"3528BB18436C","arm":"single","pair":3} +{"episode":3,"turn":2,"start_s":61.08,"wall_s":199.34,"input_tokens":6175,"cached_tokens":2050,"output_tokens":32,"output_sha":"88C84F134391","arm":"single","pair":3} +{"episode":3,"turn":3,"start_s":260.41,"wall_s":363.72,"input_tokens":8237,"cached_tokens":2050,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"single","pair":3} +{"episode":4,"turn":1,"start_s":0.03,"wall_s":141.56,"input_tokens":4164,"cached_tokens":2051,"output_tokens":32,"output_sha":"52032CE22614","arm":"single","pair":3} +{"episode":4,"turn":2,"start_s":141.59,"wall_s":279.92,"input_tokens":6222,"cached_tokens":2051,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"single","pair":3} +{"episode":4,"turn":3,"start_s":421.51,"wall_s":451.05,"input_tokens":8296,"cached_tokens":2051,"output_tokens":32,"output_sha":"078A1029B307","arm":"single","pair":3} +{"kind":"arm","arm":"single","pair":3,"both_done_s":995.19} +{"episode":1,"turn":1,"start_s":0.02,"wall_s":101.81,"input_tokens":4130,"cached_tokens":2050,"output_tokens":32,"output_sha":"3ED938794905","arm":"slots","pair":3} +{"episode":1,"turn":2,"start_s":101.83,"wall_s":174.45,"input_tokens":6190,"cached_tokens":4130,"output_tokens":32,"output_sha":"78EEEB2F9A2A","arm":"slots","pair":3} +{"episode":1,"turn":3,"start_s":276.28,"wall_s":194.12,"input_tokens":8248,"cached_tokens":6190,"output_tokens":32,"output_sha":"AFE366E6D189","arm":"slots","pair":3} +{"episode":2,"turn":1,"start_s":0.03,"wall_s":184.43,"input_tokens":4160,"cached_tokens":2051,"output_tokens":32,"output_sha":"1AF8E315EFE9","arm":"slots","pair":3} +{"episode":2,"turn":2,"start_s":184.46,"wall_s":183.53,"input_tokens":6238,"cached_tokens":4160,"output_tokens":32,"output_sha":"7B1FAD743E3A","arm":"slots","pair":3} +{"episode":2,"turn":3,"start_s":367.98,"wall_s":206.92,"input_tokens":8318,"cached_tokens":6238,"output_tokens":32,"output_sha":"41F1A8A0635C","arm":"slots","pair":3} +{"episode":3,"turn":1,"start_s":0.03,"wall_s":142.52,"input_tokens":4117,"cached_tokens":2050,"output_tokens":32,"output_sha":"3528BB18436C","arm":"slots","pair":3} +{"episode":3,"turn":2,"start_s":142.55,"wall_s":177.77,"input_tokens":6175,"cached_tokens":4117,"output_tokens":32,"output_sha":"88C84F134391","arm":"slots","pair":3} +{"episode":3,"turn":3,"start_s":320.31,"wall_s":201.05,"input_tokens":8237,"cached_tokens":6175,"output_tokens":32,"output_sha":"8707D7B0862F","arm":"slots","pair":3} +{"episode":4,"turn":1,"start_s":0.02,"wall_s":63.54,"input_tokens":4164,"cached_tokens":59,"output_tokens":32,"output_sha":"52032CE22614","arm":"slots","pair":3} +{"episode":4,"turn":2,"start_s":63.57,"wall_s":165.3,"input_tokens":6222,"cached_tokens":4164,"output_tokens":32,"output_sha":"C7FE08B36859","arm":"slots","pair":3} +{"episode":4,"turn":3,"start_s":228.87,"wall_s":190.58,"input_tokens":8296,"cached_tokens":6222,"output_tokens":32,"output_sha":"078A1029B307","arm":"slots","pair":3} +{"kind":"arm","arm":"slots","pair":3,"both_done_s":574.9} +{"kind":"compare","pair":3,"identical_answers":true,"differing":[]} diff --git a/benchmarks/tools/Compare-ConcurrentEpisodes.ps1 b/benchmarks/tools/Compare-ConcurrentEpisodes.ps1 index 8c21202e..96cbf2ab 100644 --- a/benchmarks/tools/Compare-ConcurrentEpisodes.ps1 +++ b/benchmarks/tools/Compare-ConcurrentEpisodes.ps1 @@ -17,20 +17,24 @@ param( [Parameter(Mandatory)] [string] $Model, [Parameter(Mandatory)] [string] $Output, - [Parameter(Mandatory)] [string] $OpenvinoRoot, + [string] $OpenvinoRoot = $env:LELEKA_OPENVINO_ROOT, # needed by the pool arm only [string] $RepoRoot, [int] $Port = 8082, [int] $Context = 16384, [int] $SingleThreads = 10, [int] $PoolThreads = 7, [int] $Turns = 4, + [int] $Agents = 2, + # tokens of instructions shared by every agent (a system prompt and tool descriptions that the agents have in common) + [int] $SharedInstructionTokens = 0, [int] $ToolTokens = 1500, [int] $MaxOutput = 32, [int] $Pairs = 3, [int] $GpuMinTokens = 256, [string] $LogDir, - # the two arms to pair: 'single', 'pool', or 'single-seq' (the single worker running the two episodes one after - # the other, so its cache always holds the running episode: separates the second device from the second cache) + # the two arms to pair: 'single' (one iGPU worker, one cache), 'slots' (the same worker with one cache slot per + # agent, --cache-slots), 'pool' (iGPU worker + NPU worker), or 'single-seq' (the single worker running the + # episodes one after the other, so its cache always holds the running episode) [string[]] $Arms = @('single', 'pool') ) $ErrorActionPreference = 'Stop' @@ -52,16 +56,22 @@ function New-ToolOutput([int]$seed, [int]$tokens) { } $sb.ToString() } -$episodes = @( - @{ task = 'Review the repository and summarize what each file does.'; outputs = @(1..$Turns | ForEach-Object { New-ToolOutput (1000 + $_) $ToolTokens }) }, - @{ task = 'Find the functions that allocate in a loop and list them by file.'; outputs = @(1..$Turns | ForEach-Object { New-ToolOutput (2000 + $_) $ToolTokens }) } -) +$tasks = 'Review the repository and summarize what each file does.', 'Find the functions that allocate in a loop and list them by file.', + 'List every public type and the module that defines it.', 'Find unused imports and say which files have them.', + 'Describe the error handling of each module.', 'Find every place that spawns a thread.', 'Summarize the tests and what they cover.', + 'List the configuration options and their defaults.' +$episodes = @(0..($Agents - 1) | ForEach-Object { + $e = $_ + @{ task = $tasks[$e % $tasks.Count] + " (agent $e)"; outputs = @(1..$Turns | ForEach-Object { New-ToolOutput (1000 * ($e + 1) + $_) $ToolTokens }) } +}) +$instructions = if ($SharedInstructionTokens -gt 0) { "You are a coding agent. Follow these notes.`n" + (New-ToolOutput 7777 $SharedInstructionTokens) } else { $null } function Start-Arm([string]$arm, [int]$pair) { $work = Join-Path ([IO.Path]::GetTempPath()) ("leleka-cc-" + [Guid]::NewGuid().ToString('N')) New-Item -ItemType Directory $work | Out-Null $threads = if ($arm -eq 'pool') { $PoolThreads } else { $SingleThreads } $gpuArgs = @('--model', $Model, '--ctx', "$Context", '--threads', "$threads", '--gpu-min-tokens', "$GpuMinTokens") + if ($arm -eq 'slots') { $gpuArgs += @('--cache-slots', "$Agents") } $engine = @{ executable = (Join-Path $bin 'leleka-igpu-worker.exe'); args = $gpuArgs; gptoss_gguf = $Model startup_timeout_s = 300; generation_timeout_s = 1500 } if ($arm -eq 'pool') { @@ -98,7 +108,7 @@ function Stop-Arm($handle) { # one episode, run inside its own runspace $episodeScript = { - param($Port, $Episode, $Index, $Turns, $MaxOutput, $Clock) + param($Port, $Episode, $Index, $Turns, $MaxOutput, $Clock, $Instructions) $tool = @{ type = 'function'; name = 'read_file'; description = 'Read a source file.' parameters = @{ type = 'object'; properties = @{ path = @{ type = 'string' } }; required = @('path') } } $uri = "http://127.0.0.1:$Port/v1/responses" @@ -110,11 +120,18 @@ $episodeScript = { $items += @{ type = 'function_call_output'; call_id = "call_$i"; output = $Episode.outputs[$i - 1] } } $body = @{ model = 'gpt-oss-20b'; input = $items; tools = @($tool); max_output_tokens = $MaxOutput; reasoning = @{ effort = 'low' } } + if ($Instructions) { $body.instructions = $Instructions } $start = $Clock.Elapsed.TotalSeconds $r = Invoke-RestMethod $uri -Method Post -Body ($body | ConvertTo-Json -Depth 10 -Compress) -ContentType 'application/json' -TimeoutSec 3000 $end = $Clock.Elapsed.TotalSeconds + # the answer, without ids and times, so arms can be compared + $answer = @(foreach ($o in $r.output) { + foreach ($c in @($o.content)) { $c.text } + if ($o.arguments) { "$($o.name)$($o.arguments)" } + }) -join "`n" + $sha = ([BitConverter]::ToString([Security.Cryptography.SHA256]::Create().ComputeHash([Text.Encoding]::UTF8.GetBytes($answer))) -replace '-', '').Substring(0, 12) $rows += [pscustomobject]@{ episode = $Index; turn = $k; start_s = [math]::Round($start, 2); wall_s = [math]::Round($end - $start, 2) - input_tokens = $r.usage.input_tokens; cached_tokens = $r.usage.input_tokens_details.cached_tokens; output_tokens = $r.usage.output_tokens } + input_tokens = $r.usage.input_tokens; cached_tokens = $r.usage.input_tokens_details.cached_tokens; output_tokens = $r.usage.output_tokens; output_sha = $sha } } $rows } @@ -134,7 +151,7 @@ function Run-Arm([string]$arm, [int]$pair) { $start = { param($e) $ps = [powershell]::Create() - [void]$ps.AddScript($episodeScript).AddArgument($Port).AddArgument($episodes[$e]).AddArgument($e + 1).AddArgument($Turns).AddArgument($MaxOutput).AddArgument($clock) + [void]$ps.AddScript($episodeScript).AddArgument($Port).AddArgument($episodes[$e]).AddArgument($e + 1).AddArgument($Turns).AddArgument($MaxOutput).AddArgument($clock).AddArgument($instructions) [pscustomobject]@{ PS = $ps; Async = $ps.BeginInvoke() } } $finish = { @@ -146,9 +163,9 @@ function Run-Arm([string]$arm, [int]$pair) { } $rows = @() if ($arm -eq 'single-seq') { - foreach ($e in 0..1) { $rows += & $finish (& $start $e) } + foreach ($e in 0..($Agents - 1)) { $rows += & $finish (& $start $e) } } else { - $jobs = 0..1 | ForEach-Object { & $start $_ } + $jobs = 0..($Agents - 1) | ForEach-Object { & $start $_ } foreach ($j in $jobs) { $rows += & $finish $j } } $both = [math]::Round($clock.Elapsed.TotalSeconds, 2) @@ -157,19 +174,25 @@ function Run-Arm([string]$arm, [int]$pair) { } $meta = @{ kind = 'meta'; date = (Get-Date -Format 'yyyy-MM-dd HH:mm'); model = (Split-Path -Leaf $Model); turns = $Turns - tool_tokens = $ToolTokens; max_output = $MaxOutput; pairs = $Pairs; context = $Context; single_threads = $SingleThreads + agents = $Agents; shared_instruction_tokens = $SharedInstructionTokens; tool_tokens = $ToolTokens; max_output = $MaxOutput; pairs = $Pairs; context = $Context; single_threads = $SingleThreads pool_threads = $PoolThreads; gpu_min_tokens = $GpuMinTokens; single = 'leleka-igpu-worker'; pool = 'leleka-igpu-worker + leleka-npu-worker' } ($meta | ConvertTo-Json -Compress) | Add-Content $Output foreach ($p in 1..$Pairs) { + $answers = @{} $order = if ($p % 2 -eq 1) { $Arms[0], $Arms[1] } else { $Arms[1], $Arms[0] } foreach ($arm in $order) { "pair $p, $arm" $result = Run-Arm $arm $p + $answers[$arm] = @{} foreach ($row in ($result.Rows | Sort-Object episode, turn)) { + $answers[$arm]["$($row.episode).$($row.turn)"] = $row.output_sha $row | Add-Member arm $arm -PassThru | Add-Member pair $p -PassThru | ConvertTo-Json -Compress | Add-Content $Output " episode $($row.episode) turn $($row.turn): start $($row.start_s) s, $($row.wall_s) s, input $($row.input_tokens), cached $($row.cached_tokens)" } ([pscustomobject]@{ kind = 'arm'; arm = $arm; pair = $p; both_done_s = $result.Both } | ConvertTo-Json -Compress) | Add-Content $Output " both episodes done after $($result.Both) s" } + $differ = @($answers[$Arms[0]].Keys | Where-Object { $answers[$Arms[0]][$_] -ne $answers[$Arms[1]][$_] }) + " answers identical between $($Arms[0]) and $($Arms[1]): $($differ.Count -eq 0)" + $(if ($differ.Count) { " (differ at $($differ -join ', '))" } else { '' }) + ([pscustomobject]@{ kind = 'compare'; pair = $p; identical_answers = ($differ.Count -eq 0); differing = $differ } | ConvertTo-Json -Compress) | Add-Content $Output } diff --git a/crates/cpu-worker/examples/ab_slots.rs b/crates/cpu-worker/examples/ab_slots.rs new file mode 100644 index 00000000..934c1c01 --- /dev/null +++ b/crates/cpu-worker/examples/ab_slots.rs @@ -0,0 +1,267 @@ +//! Paired A/B of one cache slot against several in one worker process, for a pool of agents sending requests one +//! after the other (CPU prefill only, so the outputs can be compared exactly). +//! +//! Run: `cargo run --release -p leleka-cpu-worker --example ab_slots -- [agents] [turns] [pairs] +//! [max_new] [threads] [header chars] [tool chars]` +//! +//! `agents` agents share one system and developer prefix (`header chars` of instructions) and each has its own task. +//! They take turns round-robin. A turn's prompt is the previous prompt, then the assistant message re-rendered the +//! way Harmony history is (the generated reasoning is dropped: `<|channel|>final<|message|>Noted.<|end|>`), then a +//! new user message with `tool chars` characters of tool output. So the tokens the worker generated never match the +//! next prompt past their first token, and each agent's cache diverges from its next prompt right after the old +//! prompt, as in a real Harmony agent. Every prompt is tokenized whole, as the control plane does. +//! +//! Arm `1 slot` serves them with the worker's single cache, arm `N slots` with one slot per agent +//! (`GptOssEngine::set_cache_slots`). Each arm starts from a cold cache; arms alternate in order per pair. Prints per +//! request the prompt tokens, the tokens reused from the cache and the prompt time, then per arm the totals, and +//! whether the greedy outputs of the two arms are identical (they must be: reuse is bit-exact). + +use leleka_cpu_worker::engine::{self, LoadOptions}; +use leleka_cpu_worker::serve::serve; +use leleka_gguf::Gguf; +use leleka_tokenizer::gguf_bpe::GgufBpe; +use std::fs::File; +use std::io::{BufReader, Cursor, Read, Write}; +use std::path::Path; +use std::sync::{Arc, Mutex, mpsc}; + +/// The worker's output; once a request is answered it sends `QUIT` on the input channel. +#[derive(Clone)] +struct Shared(Arc>>, mpsc::Sender>); + +impl Write for Shared { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.0.lock().unwrap().extend_from_slice(buf); + if buf.starts_with(b"DONE ") || buf.starts_with(b"ERR") { + let _ = self.1.send(b"QUIT\n".to_vec()); + } + Ok(buf.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +/// Input lines arriving on a channel; blocks until the next one. +struct Input(mpsc::Receiver>, Cursor>); + +impl Read for Input { + fn read(&mut self, buf: &mut [u8]) -> std::io::Result { + if self.1.position() as usize >= self.1.get_ref().len() { + match self.0.recv() { + Ok(line) => self.1 = Cursor::new(line), + Err(_) => return Ok(0), + } + } + self.1.read(buf) + } +} + +struct Run { + tokens: Vec, + prompt_ms: f64, + decode_ms: f64, + reused: u64, +} + +fn run(engine: &mut engine::GptOssEngine, stops: &[u32], prompt: &[u32], max_new: usize) -> Run { + let ids = prompt + .iter() + .map(u32::to_string) + .collect::>() + .join(","); + let (tx, rx) = mpsc::channel(); + tx.send(format!("GEN {max_new} temperature=0 {ids}\n").into_bytes()) + .expect("send"); + let out = Shared(Arc::default(), tx); + serve( + engine, + BufReader::new(Input(rx, Cursor::default())), + out.clone(), + stops, + 0, + ) + .expect("serve"); + let text = String::from_utf8(out.0.lock().unwrap().clone()).expect("utf-8"); + let mut tokens = Vec::new(); + for line in text.lines() { + if let Some(t) = line.strip_prefix("T ") { + tokens.push(t.parse().expect("token id")); + } else if let Some(done) = line.strip_prefix("DONE ") { + let f: Vec<&str> = done.split(' ').collect(); + return Run { + tokens, + prompt_ms: f[2].parse().expect("prompt ms"), + decode_ms: f[3].parse().expect("decode ms"), + reused: f[7].parse().expect("reused"), + }; + } else if line.starts_with("ERR") { + panic!("worker error: {line}"); + } + } + panic!("no DONE line in {text}"); +} + +/// Deterministic pseudo-source of about `chars` characters. +fn filler(seed: u64, chars: usize) -> String { + const WORDS: [&str; 24] = [ + "fn", "let", "mut", "self", "return", "match", "impl", "struct", "Vec", "String", "Result", + "Option", "usize", "for", "in", "if", "else", "pub", "use", "mod", "const", "loop", + "while", "break", + ]; + let mut state = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + let mut next = move |n: u64| { + state ^= state << 13; + state ^= state >> 7; + state ^= state << 17; + state % n + }; + let mut out = String::new(); + let mut line = 0; + while out.len() < chars { + out.push_str(&format!("{line} ")); + for _ in 0..4 + next(6) { + out.push_str(&format!( + "{}{} ", + WORDS[next(WORDS.len() as u64) as usize], + next(99) + )); + } + out.push_str(";\n"); + line += 1; + } + out +} + +fn main() { + let args: Vec = std::env::args().skip(1).collect(); + if args.is_empty() { + eprintln!( + "usage: ab_slots [agents] [turns] [pairs] [max_new] [threads] [header chars] [tool chars]" + ); + std::process::exit(2); + } + let arg = + |i: usize, default: usize| args.get(i).and_then(|s| s.parse().ok()).unwrap_or(default); + let (agents, turns, pairs, max_new) = (arg(1, 3), arg(2, 3), arg(3, 2), arg(4, 24)); + let threads = arg( + 5, + std::thread::available_parallelism().map_or(1, |n| n.get()), + ); + let (header_chars, tool_chars) = (arg(6, 1600), arg(7, 2400)); + let model = Path::new(&args[0]); + + let size = std::fs::metadata(model).expect("model file").len(); + let gguf = Gguf::read( + BufReader::with_capacity(1 << 20, File::open(model).expect("open")), + size, + ) + .expect("valid GGUF"); + let tokenizer = GgufBpe::from_gguf(&gguf).expect("tokenizer"); + let header = format!( + "<|start|>system<|message|>You are ChatGPT, a large language model trained by OpenAI.\nKnowledge cutoff: 2024-06\nCurrent date: 2026-10-17\n\nReasoning: low\n\n# Valid channels: analysis, commentary, final. Channel must be included for every message.<|end|><|start|>developer<|message|># Instructions\n\nYou are a coding agent in a Rust repository.\n{}<|end|>", + filler(7, header_chars) + ); + // prompts[agent][turn]: each tokenized whole, as the control plane does + let prompts: Vec>> = (0..agents) + .map(|a| { + let mut text = format!( + "{header}<|start|>user<|message|>Task {a}: review module number {} and report what it does.<|end|><|start|>assistant", + a * 7 + 3 + ); + (0..turns) + .map(|t| { + if t > 0 { + text.push_str(&format!( + "<|channel|>final<|message|>Noted.<|end|><|start|>user<|message|>{}<|end|><|start|>assistant", + filler(100 + (a * 10 + t) as u64, tool_chars) + )); + } + tokenizer.encode(&text, true) + }) + .collect() + }) + .collect(); + let sizes: Vec> = prompts + .iter() + .map(|p| p.iter().map(Vec::len).collect()) + .collect(); + let shared = prompts[0][0] + .iter() + .zip(&prompts[agents - 1][0]) + .take_while(|(a, b)| a == b) + .count(); + println!( + "{agents} agents x {turns} turns, prompt tokens per agent and turn {sizes:?}, shared prefix {shared} tokens, max_new {max_new}, {threads} threads" + ); + + let longest = prompts.iter().flatten().map(Vec::len).max().unwrap_or(0); + let loaded = engine::load(&LoadOptions { + model, + threads, + context: longest + max_new + 64, + warm: true, + }) + .expect("load"); + let (mut engine, stops) = (loaded.engine, loaded.stop_tokens); + run(&mut engine, &stops, &prompts[0][0][..64], 1); + + let mut reference: Vec> = Vec::new(); + let mut identical = true; + let mut totals: [Vec; 2] = [Vec::new(), Vec::new()]; + for pair in 0..pairs { + let order = if pair % 2 == 0 { + [1, agents] + } else { + [agents, 1] + }; + for slots in order { + engine.set_cache_slots(slots); + engine.reset_cache(); + let (mut prompt_ms, mut computed, mut reused_total, mut index) = (0.0, 0u64, 0u64, 0); + for t in 0..turns { + for (a, agent_prompts) in prompts.iter().enumerate() { + let prompt = &agent_prompts[t]; + let r = run(&mut engine, &stops, prompt, max_new); + prompt_ms += r.prompt_ms; + reused_total += r.reused; + computed += prompt.len() as u64 - r.reused; + if reference.len() <= index { + reference.push(r.tokens.clone()); + } + let same = reference[index] == r.tokens; + identical &= same; + println!( + "pair {pair} {} slot(s) agent {a} turn {t}: {} prompt tokens, {} reused, prompt {:.0} ms, decode {:.0} ms, {} tokens, identical={same}", + slots, + prompt.len(), + r.reused, + r.prompt_ms, + r.decode_ms, + r.tokens.len() + ); + index += 1; + } + } + println!( + "pair {pair} {slots} slot(s): prompt time {:.1} s, {computed} tokens computed, {reused_total} reused", + prompt_ms / 1000.0 + ); + totals[usize::from(slots != 1)].push(prompt_ms / 1000.0); + } + } + let ratios: Vec = totals[0] + .iter() + .zip(&totals[1]) + .map(|(a, b)| a / b) + .collect(); + println!( + "total prompt time, 1 slot {:?} s, {agents} slots {:?} s; paired speed-up {:?}; outputs of all runs identical: {identical}", + totals[0].iter().map(|x| x.round()).collect::>(), + totals[1].iter().map(|x| x.round()).collect::>(), + ratios + .iter() + .map(|r| (r * 100.0).round() / 100.0) + .collect::>() + ); +} diff --git a/crates/cpu-worker/src/engine.rs b/crates/cpu-worker/src/engine.rs index 2124bdf4..b970fd57 100644 --- a/crates/cpu-worker/src/engine.rs +++ b/crates/cpu-worker/src/engine.rs @@ -1,6 +1,7 @@ //! The real engine: the gpt-oss decoder behind the [`Decoder`] trait. use crate::serve::Decoder; +use crate::slots::{self, Choice, SlotView}; use leleka_cpu_kernels::Dispatch; use leleka_cpu_sys::mapping::Mapping; use leleka_gguf::Gguf; @@ -12,9 +13,22 @@ use std::path::Path; use std::sync::Arc; use std::time::Instant; +/// One conversation's cache: a decoder state and when it was last used. +struct Slot { + state: State, + last_used: u64, +} + pub struct GptOssEngine { model: Model, - state: State, + /// Caches of up to `max_slots` conversations, created when first needed (see `crate::slots`). + slots: Vec, + max_slots: usize, + /// The slot of the request being served. + active: usize, + clock: u64, + /// Print the slot chosen for every prompt on standard error. + log_slots: bool, context: usize, /// Optional prefill on other hardware, used when at least `accelerate_from` prompt tokens need /// computing. The CPU worker itself has none; the GPU worker installs one. @@ -30,6 +44,96 @@ impl GptOssEngine { self.speculate = on; } + /// Keep the caches of up to `slots` conversations (1 by default: only the last request's). A request continues + /// the slot that holds its conversation, a new agent that shares a system prompt with a cached one gets a copy + /// of the shared part, and the least recently used slot is overwritten when all are taken. Slots are created when + /// needed; each costs `context * 49 KB` of memory once filled (about 0.8 GB at 16,384 tokens). + pub fn set_cache_slots(&mut self, slots: usize) { + self.max_slots = slots.clamp(1, 64); + if self.slots.len() > self.max_slots { + self.slots.truncate(self.max_slots); + self.active = self.active.min(self.slots.len() - 1); + } + let per_slot = self.context as u64 + * self.model.config.kv_width() as u64 + * 4 + * self.model.config.blocks as u64; + eprintln!( + "leleka-cpu-worker: {} cache slot(s) of {} tokens, {} MiB each once filled", + self.max_slots, + self.context, + per_slot >> 20 + ); + } + + /// Forget every cached conversation (all slots start empty; used to start measurements cold). + pub fn reset_cache(&mut self) { + for slot in &mut self.slots { + slot.state.truncate(0); + slot.last_used = 0; + } + self.clock = 0; + } + + /// Make `active` the slot to run `prompt` in, copying a shared prefix from another slot when that is better. + fn select_slot(&mut self, prompt: &[u32]) { + let views: Vec> = self + .slots + .iter() + .map(|slot| SlotView { + tokens: slot.state.cached_tokens(), + last_used: slot.last_used, + }) + .collect(); + let choice = slots::choose(&views, self.max_slots, prompt); + drop(views); + let (config, context) = (&self.model.config, self.context); + let ensure = |slots: &mut Vec, index: usize| { + if index == slots.len() { + slots.push(Slot { + state: State::new(config, context), + last_used: 0, + }); + } + }; + let target = match choice { + Choice::Continue { slot } => slot, + Choice::Fresh { slot } => { + ensure(&mut self.slots, slot); + slot + } + Choice::Copy { from, into, len } => { + ensure(&mut self.slots, into); + let (donor, target) = if from < into { + let (head, tail) = self.slots.split_at_mut(into); + (&head[from], &mut tail[0]) + } else { + let (head, tail) = self.slots.split_at_mut(from); + (&tail[0], &mut head[into]) + }; + target.state.copy_prefix_from(&donor.state, len); + into + } + }; + self.clock += 1; + self.slots[target].last_used = self.clock; + self.active = target; + if self.log_slots { + eprintln!( + "leleka-cpu-worker: prompt of {} tokens: {choice:?}; slots hold {:?}", + prompt.len(), + self.slots + .iter() + .map(|slot| slot.state.cached_tokens().len()) + .collect::>() + ); + } + } + + fn state(&self) -> &State { + &self.slots[self.active].state + } + /// Run long prefills (at least `min_tokens` tokens to compute) on `accelerator`. If it fails, the /// request is redone on the CPU and the accelerator is dropped for the rest of the session. pub fn set_accelerator( @@ -102,7 +206,14 @@ pub fn load(options: &LoadOptions) -> Result { Ok(Loaded { engine: GptOssEngine { model, - state, + slots: vec![Slot { + state, + last_used: 0, + }], + max_slots: 1, + active: 0, + clock: 0, + log_slots: std::env::var_os("LELEKA_SLOT_LOG").is_some(), context, accelerator: None, accelerate_from: usize::MAX, @@ -122,9 +233,11 @@ impl Decoder for GptOssEngine { prompt: &[u32], progress: &mut dyn FnMut(usize, usize) -> bool, ) -> Result, String> { + self.select_slot(prompt); + let state = &mut self.slots[self.active].state; if let Some(accelerator) = self.accelerator.as_mut() { match self.model.prefill_reuse_accelerated( - &mut self.state, + state, prompt, accelerator.as_mut(), self.accelerate_from, @@ -140,19 +253,20 @@ impl Decoder for GptOssEngine { } } self.model - .prefill_reuse_with(&mut self.state, prompt, progress) + .prefill_reuse_with(state, prompt, progress) .map(|r| r.map(|r| r.reused)) .map_err(|e| e.to_string()) } fn logits(&self) -> &[f32] { - &self.state.logits + &self.state().logits } fn advance(&mut self, token: u32) -> Result<(), String> { - let position = self.state.cached_tokens().len(); + let state = &mut self.slots[self.active].state; + let position = state.cached_tokens().len(); self.model - .forward(&mut self.state, token, position) + .forward(state, token, position) .map(|_| ()) .map_err(|e| e.to_string()) } @@ -162,17 +276,18 @@ impl Decoder for GptOssEngine { } fn cached_len(&self) -> usize { - self.state.cached_tokens().len() + self.state().cached_tokens().len() } fn advance_many(&mut self, tokens: &[u32]) -> Result>, String> { - let position = self.state.cached_tokens().len(); + let state = &mut self.slots[self.active].state; + let position = state.cached_tokens().len(); self.model - .logits_after_each(&mut self.state, tokens, position) + .logits_after_each(state, tokens, position) .map_err(|e| e.to_string()) } fn truncate(&mut self, len: usize) { - self.state.truncate(len); + self.slots[self.active].state.truncate(len); } } diff --git a/crates/cpu-worker/src/lib.rs b/crates/cpu-worker/src/lib.rs index ded400e0..5355152a 100644 --- a/crates/cpu-worker/src/lib.rs +++ b/crates/cpu-worker/src/lib.rs @@ -4,3 +4,4 @@ pub mod engine; pub mod protocol; pub mod serve; +pub mod slots; diff --git a/crates/cpu-worker/src/main.rs b/crates/cpu-worker/src/main.rs index dca4fa60..ee273577 100644 --- a/crates/cpu-worker/src/main.rs +++ b/crates/cpu-worker/src/main.rs @@ -1,4 +1,4 @@ -//! `leleka-cpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]` +//! `leleka-cpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]` //! //! Started by the control plane, which writes requests to its standard input and reads protocol lines //! from its standard output (see `protocol`). Logs go to standard error. @@ -18,10 +18,11 @@ struct Args { warm: bool, seed: u64, speculate: bool, + cache_slots: usize, } fn usage() -> &'static str { - "usage: leleka-cpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]" + "usage: leleka-cpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" } fn parse_args() -> Result { @@ -34,6 +35,7 @@ fn parse_args() -> Result { .duration_since(std::time::UNIX_EPOCH) .map_or(0x5EED, |d| d.as_nanos() as u64); let mut speculate = false; + let mut cache_slots = 1usize; let mut serving = false; let number = |name: &str, value: Option| -> Result { value @@ -48,6 +50,9 @@ fn parse_args() -> Result { "--ctx" => context = number("--ctx", args.next())?.max(16) as usize, "--no-warm" => warm = false, "--speculate" => speculate = true, + "--cache-slots" => { + cache_slots = number("--cache-slots", args.next())?.clamp(1, 64) as usize + } "--seed" => seed = number("--seed", args.next())?, other => return Err(format!("unknown argument {other}")), } @@ -62,6 +67,7 @@ fn parse_args() -> Result { warm, seed, speculate, + cache_slots, }) } @@ -87,6 +93,7 @@ fn main() -> ExitCode { }; let mut engine = loaded.engine; engine.set_speculation(args.speculate); + engine.set_cache_slots(args.cache_slots); let stdin = BufReader::new(io::stdin()); match serve( &mut engine, diff --git a/crates/cpu-worker/src/slots.rs b/crates/cpu-worker/src/slots.rs new file mode 100644 index 00000000..eb021867 --- /dev/null +++ b/crates/cpu-worker/src/slots.rs @@ -0,0 +1,342 @@ +//! Which cached conversation a prompt should continue (pure policy, no model). +//! +//! A worker can keep the keys and values of several conversations in "slots". With a pool of agents sending requests +//! one after the other, the right slot is not simply the one with the longest common prefix: continuing a slot that +//! the prompt only partly matches cuts off the rest of its cache (`Model::prefill_reuse` truncates to the common +//! prefix), and that rest may be another agent's whole history. So the choice is: +//! +//! 1. A slot that is entirely a prefix of the prompt (the same agent's next turn, or a retry) is continued in place; +//! nothing is lost. The longest such slot wins, ties go to the most recently used. +//! 2. Otherwise the slot sharing the longest prefix is the donor. Continuing it would drop its tail (everything it +//! holds past the shared part); copying the shared part into another slot drops that slot's whole content instead. +//! The cheaper loss in cached tokens wins: a new agent that shares only the system prompt and tools with others +//! gets a copy of that part in a free (or least recently used) slot and leaves the donor intact, while an agent +//! whose own history changed slightly continues its slot and loses only the changed tail. +//! 3. A prompt sharing nothing takes a new slot, then an empty one, then the least recently used. +//! +//! The first token of a prompt that no slot can supply is always computed, as is the last token of every prompt, so a +//! reusable prefix is at most `prompt.len() - 1` tokens. + +/// What the planner needs to know about one slot. +pub struct SlotView<'a> { + /// The tokens whose keys and values the slot holds (empty for a slot that was never used). + pub tokens: &'a [u32], + /// Larger is more recent. + pub last_used: u64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Choice { + /// Run the prompt in `slot`, keeping the longest prefix it shares with the slot's tokens. + Continue { slot: usize }, + /// Run the prompt in `slot`, whose content is not worth keeping. An index equal to the number of slots means a + /// new slot. + Fresh { slot: usize }, + /// Copy the first `len` tokens of slot `from` into slot `into` (replacing its content; an index equal to the + /// number of slots means a new slot), then run the prompt in `into`. `from` keeps everything. + Copy { + from: usize, + into: usize, + len: usize, + }, +} + +fn common(a: &[u32], b: &[u32]) -> usize { + a.iter().zip(b).take_while(|(x, y)| x == y).count() +} + +/// A slot index and how many prompt tokens it can supply. +type Match = (usize, usize); + +/// Pick the slot for `prompt` among `slots`, of which at most `max_slots` may exist. +pub fn choose(slots: &[SlotView<'_>], max_slots: usize, prompt: &[u32]) -> Choice { + let max_slots = max_slots.max(slots.len()).max(1); + let cap = prompt.len().saturating_sub(1); + let more_recent = + |candidate: usize, best: usize| slots[candidate].last_used > slots[best].last_used; + + // (slot, reusable tokens) of the best slot that is wholly a prefix of the prompt, and of the best other one + let mut whole: Option = None; + let mut partial: Option = None; + for (index, slot) in slots.iter().enumerate() { + let shared = common(slot.tokens, prompt); + let reusable = shared.min(cap); + if reusable == 0 { + continue; + } + let best = if shared == slot.tokens.len() { + &mut whole + } else { + &mut partial + }; + let better = match *best { + None => true, + Some((other, tokens)) => { + reusable > tokens || (reusable == tokens && more_recent(index, other)) + } + }; + if better { + *best = Some((index, reusable)); + } + } + + if let Some((slot, reusable)) = whole + && partial.is_none_or(|(_, other)| reusable >= other) + { + return Choice::Continue { slot }; + } + + // a slot to overwrite: a new one, an empty one, else the least recently used (never `keep`) + let victim = |keep: Option| -> Option<(usize, usize)> { + if slots.len() < max_slots { + return Some((slots.len(), 0)); + } + let candidates = slots + .iter() + .enumerate() + .filter(|(index, _)| Some(*index) != keep); + let empty = candidates + .clone() + .find(|(_, slot)| slot.tokens.is_empty()) + .map(|(index, _)| index); + let chosen = empty.or_else(|| { + candidates + .min_by_key(|(index, slot)| (slot.last_used, *index)) + .map(|(index, _)| index) + })?; + Some((chosen, slots[chosen].tokens.len())) + }; + + if let Some((donor, reusable)) = partial { + let tail = slots[donor].tokens.len() - reusable; + if let Some((into, lost)) = victim(Some(donor)) + && lost < tail + { + return Choice::Copy { + from: donor, + into, + len: reusable, + }; + } + return Choice::Continue { slot: donor }; + } + let (slot, _) = victim(None).expect("at least one slot can be used"); + Choice::Fresh { slot } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn view(tokens: &[u32], last_used: u64) -> SlotView<'_> { + SlotView { tokens, last_used } + } + + fn range(from: u32, to: u32) -> Vec { + (from..to).collect() + } + + #[test] + fn a_single_slot_behaves_as_before() { + let held = range(0, 100); + // extension: continue + let mut prompt = held.clone(); + prompt.extend(1000..1010); + assert_eq!( + choose(&[view(&held, 1)], 1, &prompt), + Choice::Continue { slot: 0 } + ); + // partial overlap: the only slot is used in place whatever it loses + let mut diverging = range(0, 50); + diverging.extend(2000..2010); + assert_eq!( + choose(&[view(&held, 1)], 1, &diverging), + Choice::Continue { slot: 0 } + ); + // no overlap: the same slot, freshly + assert_eq!( + choose(&[view(&held, 1)], 1, &range(500, 520)), + Choice::Fresh { slot: 0 } + ); + } + + #[test] + fn each_agent_finds_its_own_slot_whatever_the_order() { + let a = range(0, 300); + let b = range(10_000, 10_400); + let slots = [view(&a, 1), view(&b, 2)]; + let mut next_a = a.clone(); + next_a.extend(50_000..50_020); + let mut next_b = b.clone(); + next_b.extend(60_000..60_020); + assert_eq!(choose(&slots, 2, &next_b), Choice::Continue { slot: 1 }); + assert_eq!(choose(&slots, 2, &next_a), Choice::Continue { slot: 0 }); + } + + #[test] + fn a_new_agent_copies_the_shared_system_prompt_and_leaves_the_donor_intact() { + let a: Vec = range(0, 100).into_iter().chain(1000..1400).collect(); + let mut c = range(0, 100); + c.extend(7000..7050); + // room for another slot: copy into a new one + assert_eq!( + choose(&[view(&a, 1)], 4, &c), + Choice::Copy { + from: 0, + into: 1, + len: 100 + } + ); + // no room: the least recently used other slot is overwritten, not the donor + let b = range(20_000, 20_300); + let slots = [view(&a, 1), view(&b, 5)]; + assert_eq!( + choose(&slots, 2, &c), + Choice::Copy { + from: 0, + into: 1, + len: 100 + } + ); + let slots = [view(&a, 9), view(&b, 5)]; + assert_eq!( + choose(&slots, 2, &c), + Choice::Copy { + from: 0, + into: 1, + len: 100 + } + ); + // the donor is the older slot: it is still never the victim + let slots = [view(&a, 1), view(&b, 5)]; + let Choice::Copy { into, .. } = choose(&slots, 2, &c) else { + panic!("a copy was expected") + }; + assert_ne!(into, 0); + } + + #[test] + fn an_agent_whose_history_changed_a_little_continues_its_slot_and_keeps_the_others() { + let a = range(0, 5000); + let b = range(20_000, 23_000); + // the same agent, the last 100 tokens of its previous turn were rewritten + let mut prompt = range(0, 4900); + prompt.extend(9000..9300); + let slots = [view(&a, 3), view(&b, 1)]; + assert_eq!(choose(&slots, 2, &prompt), Choice::Continue { slot: 0 }); + } + + #[test] + fn a_short_shared_prefix_does_not_destroy_a_long_history_when_a_slot_is_free() { + let a = range(0, 5000); + let mut prompt = range(0, 60); + prompt.extend(9000..9300); + let slots = [view(&a, 3)]; + assert_eq!( + choose(&slots, 3, &prompt), + Choice::Copy { + from: 0, + into: 1, + len: 60 + } + ); + } + + #[test] + fn a_whole_slot_beats_a_longer_partial_match_only_when_it_reuses_at_least_as_much() { + let own = range(0, 40); + let other: Vec = range(0, 200).into_iter().chain(5000..5500).collect(); + let mut prompt = range(0, 200); + prompt.extend(8000..8010); + // the other agent's slot shares 200 tokens, the own slot only 40: copy the longer prefix + let slots = [view(&own, 9), view(&other, 1)]; + assert_eq!( + choose(&slots, 3, &prompt), + Choice::Copy { + from: 1, + into: 2, + len: 200 + } + ); + // reversed sizes: the whole slot wins and is continued + let own = range(0, 300); + let mut prompt = range(0, 320); + prompt.extend(8000..8010); + let slots = [view(&own, 1), view(&other, 9)]; + assert_eq!(choose(&slots, 3, &prompt), Choice::Continue { slot: 0 }); + } + + #[test] + fn the_longest_whole_slot_wins_and_ties_go_to_the_most_recent() { + let short = range(0, 100); + let long = range(0, 250); + let mut prompt = range(0, 400); + prompt.push(99_999); + assert_eq!( + choose(&[view(&short, 9), view(&long, 1)], 2, &prompt), + Choice::Continue { slot: 1 } + ); + let twin = range(0, 250); + assert_eq!( + choose(&[view(&long, 1), view(&twin, 2)], 2, &prompt), + Choice::Continue { slot: 1 } + ); + } + + #[test] + fn an_identical_retry_reuses_all_but_the_last_token_in_place() { + let held = range(0, 100); + assert_eq!( + choose(&[view(&held, 1)], 2, &held), + Choice::Continue { slot: 0 } + ); + // one-token prompts have nothing to reuse + assert_eq!( + choose(&[view(&held, 1)], 1, &[0]), + Choice::Fresh { slot: 0 } + ); + } + + #[test] + fn a_prompt_sharing_nothing_takes_a_new_then_an_empty_then_the_oldest_slot() { + let a = range(0, 50); + let b = range(100, 150); + let prompt = range(900, 950); + assert_eq!( + choose(&[view(&a, 1)], 3, &prompt), + Choice::Fresh { slot: 1 } + ); + let empty: [u32; 0] = []; + assert_eq!( + choose(&[view(&a, 1), view(&empty, 0)], 2, &prompt), + Choice::Fresh { slot: 1 } + ); + assert_eq!( + choose(&[view(&a, 7), view(&b, 3)], 2, &prompt), + Choice::Fresh { slot: 1 } + ); + assert_eq!( + choose(&[view(&a, 3), view(&b, 3)], 2, &prompt), + Choice::Fresh { slot: 0 } + ); + } + + #[test] + fn a_prompt_shorter_than_the_cache_that_starts_it_is_a_partial_match() { + // the agent resends a shorter history: continuing loses the tail, a free slot keeps it + let held = range(0, 500); + let prompt = range(0, 300); + assert_eq!( + choose(&[view(&held, 1)], 1, &prompt), + Choice::Continue { slot: 0 } + ); + assert_eq!( + choose(&[view(&held, 1)], 2, &prompt), + Choice::Copy { + from: 0, + into: 1, + len: 299 + } + ); + } +} diff --git a/crates/gptoss/src/lib.rs b/crates/gptoss/src/lib.rs index 77768b7f..19264052 100644 --- a/crates/gptoss/src/lib.rs +++ b/crates/gptoss/src/lib.rs @@ -891,6 +891,33 @@ impl State { pub fn truncate(&mut self, len: usize) { self.tokens.truncate(len); } + + /// Make this state hold the first `len` cached tokens of `other` with their keys and values, so a prompt that + /// starts with them can continue from here while `other` keeps everything it had. Both states must come from + /// the same model and have the same capacity. The copy costs about 49 KB per token for gpt-oss-20b. + /// + /// # Panics + /// If the capacities differ or `other` holds fewer than `len` tokens. + pub fn copy_prefix_from(&mut self, other: &State, len: usize) { + assert_eq!( + self.capacity, other.capacity, + "states of different capacity" + ); + assert!(len <= other.tokens.len(), "copying more tokens than cached"); + for (mine, theirs) in self + .k + .iter() + .zip(&other.k) + .chain(self.v.iter().zip(&other.v)) + { + let source = theirs.read().expect("KV cache lock"); + let width = source.len() / self.capacity; + mine.write().expect("KV cache lock")[..len * width] + .copy_from_slice(&source[..len * width]); + } + self.tokens.clear(); + self.tokens.extend_from_slice(&other.tokens[..len]); + } } /// The key and value cache as a layer-by-layer prefill on other hardware sees it: it reads the rows before its diff --git a/crates/gptoss/tests/synthetic_model.rs b/crates/gptoss/tests/synthetic_model.rs index 3cfeb376..18fcfd53 100644 --- a/crates/gptoss/tests/synthetic_model.rs +++ b/crates/gptoss/tests/synthetic_model.rs @@ -872,3 +872,51 @@ fn batches_wider_than_one_kernel_call_are_bit_identical_at_every_level() { } } } + +#[test] +fn a_copied_prefix_continues_bit_identically_and_leaves_the_source_alone() { + let w = build_world(8); + let gguf = Gguf::read(&w.file[..], w.file.len() as u64).unwrap(); + let model = Model::load( + std::sync::Arc::new(w.file.clone()), + &gguf, + Dispatch::best(), + 2, + ) + .unwrap(); + let bits = |s: &State| s.logits.iter().map(|v| v.to_bits()).collect::>(); + let fresh = |tokens: &[u32]| { + let mut s = State::new(&model.config, 16); + let r = model.prefill_reuse(&mut s, tokens).unwrap(); + (bits(&s), r.next) + }; + // conversation A, with a generated token in its cache + let a_prompt = [4u32, 9, 22, 31, 6, 18, 40]; + let mut a = State::new(&model.config, 16); + model.prefill_reuse(&mut a, &a_prompt).unwrap(); + model.forward(&mut a, 13, 7).unwrap(); + let a_tokens = a.cached_tokens().to_vec(); + + // conversation B shares the first four tokens, then goes its own way + let b_prompt = [4u32, 9, 22, 31, 50, 2, 8, 60]; + let mut b = State::new(&model.config, 16); + b.copy_prefix_from(&a, 4); + assert_eq!(b.cached_tokens(), &a_tokens[..4]); + let r = model.prefill_reuse(&mut b, &b_prompt).unwrap(); + assert_eq!((r.reused, r.computed), (4, 4)); + assert_eq!((bits(&b), r.next), fresh(&b_prompt)); + + // A is untouched: it still holds everything and continues as if B had never existed + assert_eq!(a.cached_tokens(), a_tokens); + let a_next = [4u32, 9, 22, 31, 6, 18, 40, 13, 3, 77]; + let r = model.prefill_reuse(&mut a, &a_next).unwrap(); + assert_eq!((r.reused, r.computed), (8, 2)); + assert_eq!((bits(&a), r.next), fresh(&a_next)); + + // copying over a state that already holds something replaces it + b.copy_prefix_from(&a, 5); + assert_eq!(b.cached_tokens(), &a.cached_tokens()[..5]); + let r = model.prefill_reuse(&mut b, &a_next).unwrap(); + assert_eq!((r.reused, r.computed), (5, 5)); + assert_eq!((bits(&b), r.next), fresh(&a_next)); +} diff --git a/crates/gpu-npu-worker/src/main.rs b/crates/gpu-npu-worker/src/main.rs index 51aa5365..ed908181 100644 --- a/crates/gpu-npu-worker/src/main.rs +++ b/crates/gpu-npu-worker/src/main.rs @@ -1,6 +1,6 @@ //! `leleka-gpu-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] //! [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] -//! [--no-warm] [--seed N] [--speculate]` (experimental) +//! [--no-warm] [--seed N] [--speculate] [--cache-slots N]` (experimental) //! //! The CPU worker's decoder and protocol, with long prompts prefilled by the integrated GPU and the NPU together //! (`leleka_gpu_npu_worker::GpuNpuPrefill`): prompts with at least `--split-min-tokens` tokens to compute give the @@ -31,6 +31,7 @@ struct Args { warm: bool, seed: u64, speculate: bool, + cache_slots: usize, openvino_root: Option, service: Option, device: String, @@ -42,7 +43,7 @@ struct Args { } fn usage() -> &'static str { - "usage: leleka-gpu-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]" + "usage: leleka-gpu-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--gpu-min-tokens N] [--gpu-batch N] [--npu-batch N] [--npu-share F] [--split-min-tokens N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" } fn parse_args() -> Result { @@ -55,6 +56,7 @@ fn parse_args() -> Result { .duration_since(std::time::UNIX_EPOCH) .map_or(0x5EED, |d| d.as_nanos() as u64); let mut speculate = false; + let mut cache_slots = 1usize; let mut openvino_root = std::env::var_os("LELEKA_OPENVINO_ROOT").map(PathBuf::from); let mut service = None; let mut device = "NPU".to_owned(); @@ -77,6 +79,9 @@ fn parse_args() -> Result { "--ctx" => context = number("--ctx", args.next())?.max(16) as usize, "--no-warm" => warm = false, "--speculate" => speculate = true, + "--cache-slots" => { + cache_slots = number("--cache-slots", args.next())?.clamp(1, 64) as usize + } "--seed" => seed = number("--seed", args.next())?, "--openvino-root" => { openvino_root = Some(PathBuf::from( @@ -117,6 +122,7 @@ fn parse_args() -> Result { warm, seed, speculate, + cache_slots, openvino_root, service, device, @@ -163,6 +169,7 @@ fn main() -> ExitCode { }; let mut engine = loaded.engine; engine.set_speculation(args.speculate); + engine.set_cache_slots(args.cache_slots); let gpu = match GpuPrefill::new() { Ok(gpu) => gpu.with_batch(args.gpu_batch), Err(e) => { diff --git a/crates/igpu-worker/src/main.rs b/crates/igpu-worker/src/main.rs index e0581f83..07704a49 100644 --- a/crates/igpu-worker/src/main.rs +++ b/crates/igpu-worker/src/main.rs @@ -1,5 +1,5 @@ //! `leleka-igpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] -//! [--gpu-min-tokens N] [--gpu-batch N] [--speculate]` (experimental) +//! [--gpu-min-tokens N] [--gpu-batch N] [--speculate] [--cache-slots N]` (experimental) //! //! The CPU worker's decoder and protocol with one addition: prompts that need at least `--gpu-min-tokens` //! tokens computed are prefilled on the integrated GPU (STRA-219, `docs/igpu-prefill.md`); decoding stays on @@ -26,10 +26,11 @@ struct Args { gpu_min_tokens: usize, gpu_batch: usize, speculate: bool, + cache_slots: usize, } fn usage() -> &'static str { - "usage: leleka-igpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--gpu-min-tokens N] [--gpu-batch N] [--speculate]" + "usage: leleka-igpu-worker --serve --model [--threads N] [--ctx N] [--no-warm] [--seed N] [--gpu-min-tokens N] [--gpu-batch N] [--speculate] [--cache-slots N]" } fn parse_args() -> Result { @@ -44,6 +45,7 @@ fn parse_args() -> Result { let mut gpu_min_tokens = DEFAULT_GPU_MIN_TOKENS; let mut gpu_batch = leleka_gptoss_igpu::DEFAULT_BATCH; let mut speculate = false; + let mut cache_slots = 1usize; let mut serving = false; let number = |name: &str, value: Option| -> Result { value @@ -58,6 +60,9 @@ fn parse_args() -> Result { "--ctx" => context = number("--ctx", args.next())?.max(16) as usize, "--no-warm" => warm = false, "--speculate" => speculate = true, + "--cache-slots" => { + cache_slots = number("--cache-slots", args.next())?.clamp(1, 64) as usize + } "--seed" => seed = number("--seed", args.next())?, "--gpu-min-tokens" => { gpu_min_tokens = number("--gpu-min-tokens", args.next())?.max(1) as usize; @@ -78,6 +83,7 @@ fn parse_args() -> Result { gpu_min_tokens, gpu_batch, speculate, + cache_slots, }) } @@ -103,6 +109,7 @@ fn main() -> ExitCode { }; let mut engine = loaded.engine; engine.set_speculation(args.speculate); + engine.set_cache_slots(args.cache_slots); match GpuPrefill::new() { Ok(gpu) => { eprintln!( diff --git a/crates/npu-worker/src/main.rs b/crates/npu-worker/src/main.rs index c00bfffc..cc0022aa 100644 --- a/crates/npu-worker/src/main.rs +++ b/crates/npu-worker/src/main.rs @@ -1,5 +1,5 @@ //! `leleka-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] -//! [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]` (experimental) +//! [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]` (experimental) //! //! The CPU worker's decoder and protocol with one addition: prompts that need at least `--npu-min-tokens` //! tokens computed have their matrix products run by the NPU service process (`leleka-npu-service`, which @@ -31,10 +31,11 @@ struct Args { min_tokens: usize, batch: usize, speculate: bool, + cache_slots: usize, } fn usage() -> &'static str { - "usage: leleka-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate]" + "usage: leleka-npu-worker --serve --model --openvino-root [--npu-service ] [--npu-device NPU] [--npu-min-tokens N] [--npu-batch N] [--threads N] [--ctx N] [--no-warm] [--seed N] [--speculate] [--cache-slots N]" } fn parse_args() -> Result { @@ -52,6 +53,7 @@ fn parse_args() -> Result { let mut min_tokens = DEFAULT_NPU_MIN_TOKENS; let mut batch = DEFAULT_BATCH; let mut speculate = false; + let mut cache_slots = 1usize; let mut serving = false; let number = |name: &str, value: Option| -> Result { value @@ -66,6 +68,9 @@ fn parse_args() -> Result { "--ctx" => context = number("--ctx", args.next())?.max(16) as usize, "--no-warm" => warm = false, "--speculate" => speculate = true, + "--cache-slots" => { + cache_slots = number("--cache-slots", args.next())?.clamp(1, 64) as usize + } "--seed" => seed = number("--seed", args.next())?, "--openvino-root" => { openvino_root = Some(PathBuf::from( @@ -100,6 +105,7 @@ fn parse_args() -> Result { min_tokens, batch, speculate, + cache_slots, }) } @@ -138,6 +144,7 @@ fn main() -> ExitCode { }; let mut engine = loaded.engine; engine.set_speculation(args.speculate); + engine.set_cache_slots(args.cache_slots); match args.openvino_root.clone() { None => eprintln!( "leleka-npu-worker: no --openvino-root (or LELEKA_OPENVINO_ROOT); serving from the CPU only" diff --git a/docs/worker-pool.md b/docs/worker-pool.md index 34c7e4bc..076b9140 100644 --- a/docs/worker-pool.md +++ b/docs/worker-pool.md @@ -49,5 +49,82 @@ What the two comparisons separate: Limits: scripted episodes rather than an agent trace, three pairs per comparison, uncontrolled power state; the answers were not compared between arms (the decoders are the same; the NPU path's numerics are the experimental ones of -`docs/npu-service.md`). A single worker that kept several conversations' caches would get most of the 2.5x without a -second device; that is not built. +`docs/npu-service.md`). A single worker that keeps several conversations' caches should get most of the 2.5x without a +second device; that is the next section. + +## Cache slots: one worker, several agents' caches (`--cache-slots`, 2026-10-17) + +The measurement above showed that most of the pool's gain was the second KV cache, not the second device. A worker now +keeps the caches of up to N conversations: `--cache-slots N` on `leleka-cpu-worker`, `leleka-igpu-worker`, +`leleka-npu-worker` and `leleka-gpu-npu-worker` (default 1: only the last request's, as before). Slots are created when +first needed; each costs `ctx x 49 KB` once filled (0.8 GB at 16,384 tokens, 6.4 GB at 131,072). The line protocol and +the control plane are unchanged; `usage.input_tokens_details.cached_tokens` still reports what the chosen slot supplied. +`LELEKA_SLOT_LOG=1` prints the choice for every prompt. + +### Choosing the slot (`crates/cpu-worker/src/slots.rs`, unit-tested) + +Taking the slot with the longest common prefix is not enough: `Model::prefill_reuse` truncates the slot to the common +prefix, which destroys the rest of a cache that may be another agent's whole history. The planner therefore: + +1. continues in place a slot that is entirely a prefix of the prompt (the same agent's next turn, or a retry); the + longest wins, ties go to the most recently used; +2. otherwise takes the slot sharing the longest prefix as a donor and compares two losses, in cached tokens: continuing + the donor drops its tail (everything past the shared part), copying the shared part into another slot + (`State::copy_prefix_from`, a memory copy of about 49 KB per token) drops that slot's whole content, and a new or empty + slot loses nothing. The smaller loss wins. A new agent that shares only the system prompt and tools with others gets a + copy of that part in a free (else the least recently used) slot and leaves the donor intact; an agent whose own history + was rewritten near its end (Harmony drops the reasoning of earlier turns) continues its slot and loses only the tail; +3. a prompt sharing nothing takes a new slot, then an empty one, then the least recently used. + +The last token of every prompt is always computed (its logits are needed), as before. Results are bit-identical to a +fresh prefill (`gptoss/tests/synthetic_model.rs`: a copied prefix continues bit for bit and the donor is untouched). + +### Measured on the CPU path (`crates/cpu-worker/examples/ab_slots.rs`, real model, 2026-10-17) + +Three agents sharing a 603-token system and developer prefix take turns round-robin for three turns (prompts of 619, +about 1,390 and about 2,150 tokens); each turn's prompt is the previous one plus the assistant message re-rendered as +Harmony history is (reasoning dropped), plus a new tool output, tokenized whole; 24 output tokens, greedy; CPU prefill +only, 14 threads, two alternating pairs: + +| | 1 slot | 3 slots | +| --- | --- | --- | +| prompt time, pair 1 / pair 2 | 256 s / 277 s | 188 s / 190 s | +| tokens computed / reused | 7,680 / 4,824 | 5,256 / 7,248 | +| paired speed-up | | 1.37x, 1.46x | + +Agents 2 and 3 copied the shared 603 tokens from agent 1's slot on their first turn (the slot log shows +`Copy { from, into, len: 603 }`), and from then on each continued its own slot (1,399 tokens reused on the third turn +instead of 603). The greedy outputs of all 36 requests were identical between the arms. The gain grows with the share +of each agent's own history in the prompt and with the number of agents. + +### Measured through the control plane: four agents, one iGPU worker (2026-10-17) + +`benchmarks/tools/Compare-ConcurrentEpisodes.ps1 -Agents 4 -Turns 3 -SharedInstructionTokens 1500 -Arms single,slots`, +raw lines in `benchmarks/results/agent-pool-cache-slots-ab-2026-10-17*.jsonl`. Four scripted agents sent their requests +at the same time, so the worker served them one after the other in arrival order; each agent has its own task and +tool outputs and all share 1,500 tokens of instructions (2,050 shared prompt tokens with the system and tool parts); +turns of about 2,060 new tokens, 32 output tokens, three turns each (prompts of about 2,100-8,300 tokens, context 16,384). +`leleka-igpu-worker` alone, once with one cache slot and once with `--cache-slots 4`, three alternating pairs, otherwise +idle machine, power and clocks not controlled, model gpt-oss-20b-MXFP4 (SHA-256 65d06d31...cde53ab), base commit 4821fc4 +plus this change. Time until all four episodes are done: + +| pair | 1 slot | 4 slots | speed-up | +| --- | --- | --- | --- | +| 1 (rerun, see below) | 986.2 s | 569.2 s | 1.73x | +| 2 | 993.1 s | 575.2 s | 1.73x | +| 3 | 995.2 s | 574.9 s | 1.73x | + +Per run, 74,495 prompt tokens were sent; the one-slot worker computed 51,885 of them (22,610 cached: only the shared +2,050-token prefix) and the four-slot worker 26,889 (47,606 cached: each turn continued its own agent's slot). The mean +time of a turn, which includes waiting behind the other agents, fell from 269 s to 165 s. The answers of all 12 agent +turns were identical, character for character, in all six runs. + +The first run of pair 1 is not used. The control plane puts the current UTC date into the system prompt, and the date +changed (02:00 local time) while that run was going; one request therefore found only 35 tokens of its slot's cache +still valid (the date is the 35th token on), its answers and about 3% of the time differ, and the pair was rerun +(`...-pair1-rerun.jsonl`). The same effect means that once a day, at midnight UTC, the first request of every agent +misses its cache in the whole prefix after the date. + +Memory: a slot costs `ctx x 49 KB` once filled, 768 MiB at 16,384 tokens, so four slots hold up to 3 GiB of cache; the +worker logs this at start. The working set was not measured. Limits: scripted episodes, not an agent trace; three pairs; +the shared prefix here is 2,050 tokens, so the gain depends on how much of a real agent's prompt is its own history.