diff --git a/CMakeLists.txt b/CMakeLists.txt index 86b90ec1..4a6dd9da 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -424,6 +424,14 @@ if(STRATA_ENABLE_CUDA OR STRATA_ENABLE_HIP) src/core/arch_defaults.cpp) target_include_directories(strata_engine PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include) target_link_libraries(strata_engine PUBLIC strata_core strata_kernels strata_kernels_cpu ${_strata_gpu_runtime_target}) + if(STRATA_BUILD_TESTS AND EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/exchange_storage_test.cpp") + add_executable(exchange_storage_test tests/core/exchange_storage_test.cpp) + target_include_directories(exchange_storage_test PRIVATE include) + target_link_libraries(exchange_storage_test PRIVATE Threads::Threads) + add_test(NAME exchange_storage_test COMMAND exchange_storage_test) + set_tests_properties(exchange_storage_test PROPERTIES TIMEOUT 60) + endif() + if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/tests/core/file_expert_source_test.cpp") enable_testing() add_executable(file_expert_source_test tests/core/file_expert_source_test.cpp) diff --git a/bench/results/2026-10-04-rdna2-helper-pcie-share/README.md b/bench/results/2026-10-04-rdna2-helper-pcie-share/README.md new file mode 100644 index 00000000..f12e7486 --- /dev/null +++ b/bench/results/2026-10-04-rdna2-helper-pcie-share/README.md @@ -0,0 +1,55 @@ +# 2x RX 6900 XT (gfx1030): a helper GPU's experts and the PCIe share (2026-10-04) + +With a second GPU holding experts (`--expert-cache-device1`, `--remote-expert-opt`), the verify window's GPU plan counted +the experts that helper holds among the layer's misses and moved part of them - the PCIe share, `pcie_frac` of the misses +- to the primary card over PCIe, where the primary computed them while the helper sat idle for them. The plan runs before +`RemoteExperts::begin()` claims its rows, and `begin()` only takes the rows the plan left alone. #854 makes the plan treat +a helper's experts as it treats the peer tier's: not a miss, never in the PCIe share. The numbers below are the engine's +own `STRATA_DECODE_TIMING=1` report per request. + +## Rig + +- 2x AMD Radeon RX 6900 XT 16 GB (gfx1030), each PCIe 4.0 x8 through the CPU; no P2P. The engine's probe measured 14.1 + GB/s host to device and set `pcie_frac` to 0.39 (0.55 is the default without a probe). AMD Ryzen 5 5600X (6 cores, + AVX2, no AVX-512; 5 expert-pool workers plus the host thread), 128 GB DDR4-3200. +- Ubuntu 26.04, kernel 7.0.0-38-generic, ROCm 10.0.0 (HIP 7.15.26333). +- Model: Qwen3.8-Flash-Next GSQ-RCO IQ3_S (2 shards, `--native`), MTP draft layer on, `--kv int8 --kv-resident 32768 + --max-context 131072`. Configuration [strata-helper.json](strata-helper.json) (`/m` the model directory, `/work` the + build; `HIP_VISIBLE_DEVICES=1,0` makes the card on PCI bus 0f the primary): `--expert-cache auto + --expert-cache-device1 auto --remote-expert-opt --spec 4 --spec-min-p 0.5`. The primary's cache holds 4,861 experts + (9.26 GiB), the helper 8,163 more (15.46 GiB); 24,576 experts in all. +- Engines, all `-DSTRATA_ENABLE_HIP=ON -DCMAKE_HIP_ARCHITECTURES=gfx1030 -DSTRATA_PREFILL_MMQ=ON`: + - *baseline*: `origin/main` at `6f32ec0` (0.1.39) with #835 (`6add1a7`; #835 changes the prompt path's GEMMs only, + not the decode path measured here - its prompt tok/s are therefore higher than the fix's below); + - *baseline, same base* (2026-10-05): `6f32ec0` unchanged; + - *fix*: `6f32ec0` with #854 (`ffca1b0`). + +## Method + +A fresh server per arm. Two requests of about 5,000 prompt tokens each (two offsets into one text), "Summarize the +document above in about 300 words", sampled (temperature 1.0, top-p 0.95, top-k 20), up to 600 tokens; the engine's +`strata decode timing` line per request. Milliseconds per verify window and its parts are the measure; tok/s also +depends on how many drafts a sampled answer accepts and varies more. + +## Results + +| arm | ms / window | of which: GPU-reach wait | per-layer host | PCIe entries / layer-window | CPU entries / layer-window | decode tok/s | +| --- | ---: | ---: | ---: | ---: | ---: | ---: | +| baseline (`6add1a7`), probed share 0.39 | 59.6 / 58.5 | 43.4 / 43.7 | 8.6 / 8.3 | 4.00 / 3.99 | 0.83 / 0.43 | 40.6 / 39.3 | +| baseline, same base (`6f32ec0`), probed share 0.39 | 60.4 / 57.8 | 43.7 / 43.0 | 8.8 / 8.3 | 4.07 / 3.91 | 0.95 / 0.38 | 41.0 / 37.5 | +| **fix, probed share 0.39** | **37.2 / 33.8** | 19.5 / 18.6 | 9.9 / 9.1 | 0.26 / 0.06 | 1.40 / 0.57 | **65.6 / 67.7** | +| fix, probed share 0.39, run 2 (2026-10-05) | 35.2 / 33.8 | 18.8 / 18.7 | 9.3 / 9.1 | 0.20 / 0.06 | 1.17 / 0.56 | 63.0 / 64.4 | +| fix, `--pcie-frac 0` | 36.5 / 35.1 | 18.8 / 18.8 | 10.1 / 9.5 | 0 / 0 | 1.61 / 0.84 | 66.9 / 67.1 | +| baseline (`6add1a7`), `--pcie-frac 0` (the workaround) | 34.6 / 34.1 | 18.2 / 18.7 | 9.5 / 9.3 | 0 / 0 | - | 60.5 / 67.7 | + +"GPU-reach wait" is the host waiting for the GPU to reach the next layer: with the share on, the primary spent 24 ms more +per window reading and computing about 4 experts per layer-window that the helper also held (the "PCIe entries" +column), and the helper waited. With the fix the share keeps only experts no GPU holds: 0.06-0.26 per layer-window here, +and the probed share costs nothing against `--pcie-frac 0` while taking a little off the CPU (1.40 -> 1.61 CPU entries +without it). Before the fix, `--pcie-frac 0` was the way around it. + +## Limits + +One machine, one model, two prompts per arm; one server run per arm, two for the fix with the probed share (one on each day). The change +is host code and backend-independent, but only HIP and only one helper were run; three or four helpers go through the same +loop and were not tested. The prompt path does not use this plan and is unaffected by the change. diff --git a/bench/results/2026-10-04-rdna2-helper-pcie-share/strata-helper.json b/bench/results/2026-10-04-rdna2-helper-pcie-share/strata-helper.json new file mode 100644 index 00000000..40ef77ea --- /dev/null +++ b/bench/results/2026-10-04-rdna2-helper-pcie-share/strata-helper.json @@ -0,0 +1,46 @@ +{ + "exe": "/work/build-hip/strata", + "args": [ + "--pack", + "/m/packs/iq3_s", + "--native", + "/m/gguf/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00001-of-00002.gguf", + "--ple-gguf", + "/m/gguf/Qwen3.8-Flash-Next-GSQ-RCO-IQ3_S-00002-of-00002.gguf", + "--expert-profile", + "/work/data/expert-profile.bin", + "--expert-cache", + "auto", + "--prefill", + "auto", + "--spec", + "4", + "--spec-min-p", + "0.5", + "--mtp", + "/m/mtp/rt", + "--max-context", + "131072", + "--kv", + "int8", + "--kv-resident", + "32768", + "--expert-cache-device1", + "auto", + "--remote-expert-opt" + ], + "cwd": "/work", + "tokenizer": "/m/packs/iq3_s/tokenizer", + "model_name": "qwen3.8-flash-next-iq3_s", + "log": "/work/logs/strata.log", + "lib_dirs": [ + "/opt/rocm/lib" + ], + "port": 8089, + "backend": "hip", + "gpu": 1, + "gpus_asked": true, + "env": { + "HIP_VISIBLE_DEVICES": "1,0" + } +} diff --git a/bench/results/exchange-rotation-ab.json b/bench/results/exchange-rotation-ab.json new file mode 100644 index 00000000..5fedd290 --- /dev/null +++ b/bench/results/exchange-rotation-ab.json @@ -0,0 +1,288 @@ +{ + "kind": "clean-rotation-only-q2-native-same-binary-ab", + "date": "2026-10-04", + "source_commit": "18a30ad775bce86e99a54e6dc552ccb72c66d16e", + "source_archive_sha256": "a726e0be8b03c40d1c5c09b49da37e28ba6e34ef3fd247bb85adf043de927a88", + "engine_sha256": "6ed9db1dcc04b94e9816b73df30730395ff44e42f4def3b46722199aea5d881d", + "upstream_base": "6f32ec070f23ced9f50e704d854d775da52591ab", + "ggml_commit": "3cf03257f219afbe7334045ff7c6a06ac68c627d", + "hardware": { + "cpu": "AMD Ryzen 9 7950X 16-Core Processor", + "memory": "MemTotal: 130975976 kB", + "gpu": "NVIDIA RTX PRO 6000 Blackwell Workstation Edition, 97887, 595.91.07", + "kernel": "7.0.0-34-generic", + "compiler": "g++ (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0" + }, + "build": { + "type": "Release", + "cuda": "13.2", + "cuda_architectures": "120" + }, + "model": { + "repo": "ISTA-DASLab/Qwen3.8-Flash-Next-GSQ-RCO-GGUF", + "revision": "ed59f92082b1e93c0e96d60a8b11aab089b52f09", + "verification": "Both contents verified against the pinned Hugging Face LFS SHA-256 values.", + "files": [ + { + "path": "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "size": 37623740192, + "sha256": "69820c02ec7d0b45ef2ebb19d6620299db749fe2aded7f39f93c6b88b199b720" + }, + { + "path": "Q2_0/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf", + "size": 28800138432, + "sha256": "316b46f3a2dbd68c900f43136ab9449f9dcc3725dfd8c794847c204bc161e113" + } + ] + }, + "model_hash_note": "Both downloaded/reused shard contents were verified against the pinned publisher LFS hashes; size/inode/mtime are checked for stability before each arm.", + "layout": { + "layers": 48, + "experts_per_layer": 512, + "blob_bytes": 1382400, + "gate_up_type": "Q2_0", + "down_type": "Q2_0" + }, + "model_formats": "Published GSQ-RCO Q2_0 model with its matching IQ4_NL PLE shard; FP16 KV.", + "pack_command_template": [ + "python", + "{source}/tools/iq_pack.py", + "--gguf", + "{native}", + "--out", + "{pack}" + ], + "pack_hashes": { + "native_experts_sha256": "015e53d3ae36324f172be4942bcf129539b343e2eb4fcd4f25ca5eff180bfa41", + "index_sha256": "c758314d495a1261d06a806b1c415596dfabe62e0cbf44ce592dc84c53229ccd", + "dense_sha256": "a43d7d0b69525335f4b000d5197a1d3aefcd3c0014fc3e12b3455e0a5d827ba2" + }, + "qualification": "Storage parity on the standard Q2_0 model; no Q8 PLE reader extension or model conversion is required.", + "cache_note": "The 12000-slot cache is deliberately smaller than this 96 GB GPU allows to exercise RAM/GPU exchanges. This is not the fastest full-GPU Q2 configuration.", + "resident_complement_gib": 16.19, + "input_tokens": 1024, + "output_tokens": 1024, + "allocated_context": 40960, + "prompt_task": "Fixed-length storage parity and timing, not a model quality evaluation.", + "temperature": 0, + "input_token_ids_sha256": "9f8ae9eec9b56e2a04adf499638c0c1c275be8fc34cf627e632a26d3711f65a7", + "eos_note": "EOS matching uses the out-of-vocabulary sentinel 2147483647 so all arms generate the requested count even if a normal end-of-turn token occurs.", + "args_template": [ + "--pack", + "{pack}", + "--native", + "{native}", + "--expert-cache", + "12000", + "--resident-budget-gib", + "32", + "--expert-profile", + "{source}/data/expert-profile.bin", + "--adapt-every", + "4", + "--adapt-swaps", + "96", + "--adapt-decay", + "0.7", + "--pcie-frac", + "-1", + "--spec", + "2", + "--mtp", + "{mtp}", + "--mtp-max-t", + "1", + "--suffix-draft", + "0", + "--kv", + "fp16", + "--max-context", + "40960", + "--prompt-cache", + "0", + "--conversation-cache-mib", + "0", + "--prefill", + "1024", + "--no-prefill-borrow", + "--vram-reserve-mib", + "2048", + "--ple-io", + "ram", + "--ple-row-cache", + "1048576", + "--eos-ids", + "2147483647", + "--stats", + "--native-dense-gguf", + "{model}/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00001-of-00002.gguf", + "--native-dense-gguf", + "{model}/Qwen3.8-Flash-Next-GSQ-RCO-Q2_0-00002-of-00002.gguf" + ], + "environment": { + "STRATA_ADAPT_NOWAIT": "0", + "STRATA_DECODE_TIMING": "1" + }, + "profile_sha256": "8f59b4aa8873209dff11c11e37bcda9529a1335b724a1afeea37bf6388975baf", + "process_policy": "A fresh native engine per arm; no prompt or conversation reuse.", + "decoding": "Target-only: --mtp-max-t 1 --suffix-draft 0. Required MTP runtime loaded, zero offered drafts.", + "output_tokens_identical": true, + "first_differing_output_index": null, + "token_hash_encoding": "SHA-256 of UTF-8 compact JSON array, no whitespace or trailing newline.", + "token_ids_file": "exchange-rotation-token-ids.json", + "token_ids_file_sha256": "2c904cf4a7f41650ec06f54ffa773636114efed8cff059d825e5431f5aa666aa", + "arms": [ + { + "rotation": 0, + "output_tokens": 1024, + "decode_tokens_per_second": 104.89546306634843, + "startup_seconds": 23.845058003003942, + "wall_seconds": 10.330669555987697, + "timings": { + "generated": 1024, + "prompt_tokens": 1024, + "prompt_ms": 567.9, + "decode_ms": 9762.1, + "finish": "length", + "drafts_accepted": 0, + "drafts_offered": 0, + "reused": 0, + "hits": 454042, + "lookups": 480592, + "ram_blobs": 41285, + "file_blobs": 0, + "file_mb": 0.0, + "prompt_read": 1024, + "offloaded": 10928 + }, + "rotation_active": false, + "rotated_blocks": 0, + "resident_exchanges": 3802, + "avoided_memcpy_payload_bytes": 0, + "engine_info": { + "version": "0.1.39", + "context": 40960, + "kv": "fp16", + "kv_resident": 0, + "expert_slots": 12000, + "expert_cache_mib": 15820, + "expert_slots_primary": 12000, + "expert_cache_primary_mib": 15820, + "spec": 2, + "mtp_max": 1, + "lookup": 0, + "vram_free_mib": 74168, + "cvec": 0, + "arena_mib": 16579, + "pool_workers": 15, + "pcie_frac": "0.55", + "spec_min_p": "0.00", + "conversation_cache_mib": 0, + "conversation_cache_slots": 4, + "conversation_cache_min_free_mib": 2560, + "tail_role_token": -1, + "vram_elastic": 0, + "engine": "0.1.39" + }, + "diagnostics": [ + "strata decode timing: 1024 windows, avg T 1.00, 1.00 tokens/window, 9.53 ms/window = verify 8.73 (GPU-reach wait 7.11 + per-layer host 1.28 [plan 0.03 actq 0.02 jobs 0.00 CPU 1.15] + stage 0.01) + commit/emit 0.01 + draft 0.00; per layer-window: CPU experts 0.54 (0.54 entries), VRAM hits 9.24, PCIe 0.22", + "strata serve: resident RAM: 16.19 GiB of experts in RAM, 3802 exchanged with the VRAM tier, 0 blob reads from the file" + ], + "output_token_ids_sha256": "b384e4b16b5bd1c41f4739d053eb50d100a9cbfdb18fc5b76e31d188015961be" + }, + { + "rotation": 1, + "output_tokens": 1024, + "decode_tokens_per_second": 113.44249218975028, + "startup_seconds": 13.035045650991378, + "wall_seconds": 9.620121874992037, + "timings": { + "generated": 1024, + "prompt_tokens": 1024, + "prompt_ms": 592.7, + "decode_ms": 9026.6, + "finish": "length", + "drafts_accepted": 0, + "drafts_offered": 0, + "reused": 0, + "hits": 454042, + "lookups": 480592, + "ram_blobs": 41285, + "file_blobs": 0, + "file_mb": 0.0, + "prompt_read": 1024, + "offloaded": 10928 + }, + "rotation_active": true, + "rotated_blocks": 3802, + "resident_exchanges": 3802, + "avoided_memcpy_payload_bytes": 5255884800, + "engine_info": { + "version": "0.1.39", + "context": 40960, + "kv": "fp16", + "kv_resident": 0, + "expert_slots": 12000, + "expert_cache_mib": 15820, + "expert_slots_primary": 12000, + "expert_cache_primary_mib": 15820, + "spec": 2, + "mtp_max": 1, + "lookup": 0, + "vram_free_mib": 74168, + "cvec": 0, + "arena_mib": 16579, + "pool_workers": 15, + "pcie_frac": "0.55", + "spec_min_p": "0.00", + "conversation_cache_mib": 0, + "conversation_cache_slots": 4, + "conversation_cache_min_free_mib": 2560, + "tail_role_token": -1, + "vram_elastic": 0, + "engine": "0.1.39" + }, + "diagnostics": [ + "FileExpertSource: exchange buffer rotation enabled: 96 buffers, 1382400 bytes each; no host commit memcpy", + "strata decode timing: 1024 windows, avg T 1.00, 1.00 tokens/window, 8.82 ms/window = verify 8.41 (GPU-reach wait 6.83 + per-layer host 1.23 [plan 0.03 actq 0.02 jobs 0.01 CPU 1.10] + stage 0.01) + commit/emit 0.01 + draft 0.00; per layer-window: CPU experts 0.54 (0.54 entries), VRAM hits 9.24, PCIe 0.22", + "strata serve: resident RAM: 16.19 GiB of experts in RAM, 3802 exchanged with the VRAM tier, 0 blob reads from the file", + "strata serve: exchange rotation: 3802 blocks, 5255884800 host memcpy bytes avoided (cumulative payload)" + ], + "output_token_ids_sha256": "b384e4b16b5bd1c41f4739d053eb50d100a9cbfdb18fc5b76e31d188015961be" + } + ], + "validation": [ + { + "name": "configure", + "exit_code": 0, + "seconds": 2.0173747100052424 + }, + { + "name": "build", + "exit_code": 0, + "seconds": 74.66783442400629 + }, + { + "name": "ctest", + "exit_code": 0, + "seconds": 0.36451481201220304 + }, + { + "name": "rotation-gpu", + "exit_code": 0, + "seconds": 0.4641803269914817 + }, + { + "name": "memcheck", + "exit_code": 0, + "seconds": 0.5145799079909921 + } + ], + "comparison_exit_code": 0, + "limitations": [ + "One off/on pair; no general speedup or speculative-path token-parity claim.", + "GPU cache deliberately capped to exercise exchanges; Q2 can fit fully on this 96 GB card.", + "EOS ignored for exact output length; not an answer-quality measurement.", + "AMD and Windows GPU execution untested." + ] +} diff --git a/bench/results/exchange-rotation-token-ids.json b/bench/results/exchange-rotation-token-ids.json new file mode 100644 index 00000000..6e9242d5 --- /dev/null +++ b/bench/results/exchange-rotation-token-ids.json @@ -0,0 +1 @@ +{"input":[248045,846,198,8441,8129,318,1856,10895,1590,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,13,198,760,50245,8129,7276,18541,13017,321,7262,198,3601,314,8129,13,271,2427,38453,494,220,16,13,8984,1132,23173,6572,24959,18101,539,12258,13,13262,24217,2980,279,2468,3798,13,2233,16308,11,1970,11,59429,466,15673,13,248046,198,248045,74455,198,248068,271,248069,271],"off":[16,220,17,220,18,220,19,220,20,220,21,220,22,220,23,220,24,220,16,15,220,16,16,220,16,17,220,16,18,220,16,19,220,16,20,220,16,21,220,16,22,220,16,23,220,16,24,220,17,15,220,17,16,220,17,17,220,17,18,220,17,19,220,17,20,220,17,21,220,17,22,220,17,23,220,17,24,220,18,15,220,18,16,220,18,17,220,18,18,220,18,19,220,18,20,220,18,21,220,18,22,220,18,23,220,18,24,220,19,15,220,19,16,220,19,17,220,19,18,220,19,19,220,19,20,220,19,21,220,19,22,220,19,23,220,19,24,220,20,15,220,20,16,220,20,17,220,20,18,220,20,19,220,20,20,220,20,21,220,20,22,220,20,23,220,20,24,220,21,15,220,21,16,220,21,17,220,21,18,220,21,19,220,21,20,220,21,21,220,21,22,220,21,23,220,21,24,220,22,15,220,22,16,220,22,17,220,22,18,220,22,19,220,22,20,220,22,21,220,22,22,220,22,23,220,22,24,220,23,15,220,23,16,220,23,17,220,23,18,220,23,19,220,23,20,220,23,21,220,23,22,220,23,23,220,23,24,220,24,15,220,24,16,220,24,17,220,24,18,220,24,19,220,24,20,220,24,21,220,24,22,220,24,23,220,24,24,220,16,15,15,220,16,15,16,220,16,15,17,220,16,15,18,220,16,15,19,220,16,15,20,220,16,15,21,220,16,15,22,220,16,15,23,220,16,15,24,220,16,16,15,220,16,16,16,220,16,16,17,220,16,16,18,220,16,16,19,220,16,16,20,220,16,16,21,220,16,16,22,220,16,16,23,220,16,16,24,220,16,17,15,220,16,17,16,220,16,17,17,220,16,17,18,220,16,17,19,220,16,17,20,220,16,17,21,220,16,17,22,220,16,17,23,220,16,17,24,220,16,18,15,220,16,18,16,220,16,18,17,220,16,18,18,220,16,18,19,220,16,18,20,220,16,18,21,220,16,18,22,220,16,18,23,220,16,18,24,220,16,19,15,220,16,19,16,220,16,19,17,220,16,19,18,220,16,19,19,220,16,19,20,220,16,19,21,220,16,19,22,220,16,19,23,220,16,19,24,220,16,20,15,220,16,20,16,220,16,20,17,220,16,20,18,220,16,20,19,220,16,20,20,220,16,20,21,220,16,20,22,220,16,20,23,220,16,20,24,220,16,21,15,220,16,21,16,220,16,21,17,220,16,21,18,220,16,21,19,220,16,21,20,220,16,21,21,220,16,21,22,220,16,21,23,220,16,21,24,220,16,22,15,220,16,22,16,220,16,22,17,220,16,22,18,220,16,22,19,220,16,22,20,220,16,22,21,220,16,22,22,220,16,22,23,220,16,22,24,220,16,23,15,220,16,23,16,220,16,23,17,220,16,23,18,220,16,23,19,220,16,23,20,220,16,23,21,220,16,23,22,220,16,23,23,220,16,23,24,220,16,24,15,220,16,24,16,220,16,24,17,220,16,24,18,220,16,24,19,220,16,24,20,220,16,24,21,220,16,24,22,220,16,24,23,220,16,24,24,220,17,15,15,220,17,15,16,220,17,15,17,220,17,15,18,220,17,15,19,220,17,15,20,220,17,15,21,220,17,15,22,220,17,15,23,220,17,15,24,220,17,16,15,220,17,16,16,220,17,16,17,220,17,16,18,220,17,16,19,220,17,16,20,220,17,16,21,220,17,16,22,220,17,16,23,220,17,16,24,220,17,17,15,220,17,17,16,220,17,17,17,220,17,17,18,220,17,17,19,220,17,17,20,220,17,17,21,220,17,17,22,220,17,17,23,220,17,17,24,220,17,18,15,220,17,18,16,220,17,18,17,220,17,18,18,220,17,18,19,220,17,18,20,220,17,18,21,220,17,18,22,220,17,18,23,220,17,18,24,220,17,19,15,220,17,19,16,220,17,19,17,220,17,19,18,220,17,19,19,220,17,19,20,220,17,19,21,220,17,19,22,220,17,19,23,220,17,19,24,220,17,20,15,220,17,20,16,220,17,20,17,220,17,20,18,220,17,20,19,220,17,20,20,220,17,20,21,220,17,20,22,220,17,20,23,220,17,20,24,220,17,21,15,220,17,21,16,220,17,21,17,220,17,21,18,220,17,21,19,220,17,21,20,220,17,21,21,220,17,21,22,220,17,21,23,220,17,21,24,220,17,22,15,220,17,22,16,220,17,22,17,220,17,22,18,220,17,22,19,220,17,22,20,220,17,22,21,220,17,22,22,220,17,22,23,220,17,22,24,220,17,23,15,220,17,23,16,220,17,23,17,220,17,23,18,220],"on":[16,220,17,220,18,220,19,220,20,220,21,220,22,220,23,220,24,220,16,15,220,16,16,220,16,17,220,16,18,220,16,19,220,16,20,220,16,21,220,16,22,220,16,23,220,16,24,220,17,15,220,17,16,220,17,17,220,17,18,220,17,19,220,17,20,220,17,21,220,17,22,220,17,23,220,17,24,220,18,15,220,18,16,220,18,17,220,18,18,220,18,19,220,18,20,220,18,21,220,18,22,220,18,23,220,18,24,220,19,15,220,19,16,220,19,17,220,19,18,220,19,19,220,19,20,220,19,21,220,19,22,220,19,23,220,19,24,220,20,15,220,20,16,220,20,17,220,20,18,220,20,19,220,20,20,220,20,21,220,20,22,220,20,23,220,20,24,220,21,15,220,21,16,220,21,17,220,21,18,220,21,19,220,21,20,220,21,21,220,21,22,220,21,23,220,21,24,220,22,15,220,22,16,220,22,17,220,22,18,220,22,19,220,22,20,220,22,21,220,22,22,220,22,23,220,22,24,220,23,15,220,23,16,220,23,17,220,23,18,220,23,19,220,23,20,220,23,21,220,23,22,220,23,23,220,23,24,220,24,15,220,24,16,220,24,17,220,24,18,220,24,19,220,24,20,220,24,21,220,24,22,220,24,23,220,24,24,220,16,15,15,220,16,15,16,220,16,15,17,220,16,15,18,220,16,15,19,220,16,15,20,220,16,15,21,220,16,15,22,220,16,15,23,220,16,15,24,220,16,16,15,220,16,16,16,220,16,16,17,220,16,16,18,220,16,16,19,220,16,16,20,220,16,16,21,220,16,16,22,220,16,16,23,220,16,16,24,220,16,17,15,220,16,17,16,220,16,17,17,220,16,17,18,220,16,17,19,220,16,17,20,220,16,17,21,220,16,17,22,220,16,17,23,220,16,17,24,220,16,18,15,220,16,18,16,220,16,18,17,220,16,18,18,220,16,18,19,220,16,18,20,220,16,18,21,220,16,18,22,220,16,18,23,220,16,18,24,220,16,19,15,220,16,19,16,220,16,19,17,220,16,19,18,220,16,19,19,220,16,19,20,220,16,19,21,220,16,19,22,220,16,19,23,220,16,19,24,220,16,20,15,220,16,20,16,220,16,20,17,220,16,20,18,220,16,20,19,220,16,20,20,220,16,20,21,220,16,20,22,220,16,20,23,220,16,20,24,220,16,21,15,220,16,21,16,220,16,21,17,220,16,21,18,220,16,21,19,220,16,21,20,220,16,21,21,220,16,21,22,220,16,21,23,220,16,21,24,220,16,22,15,220,16,22,16,220,16,22,17,220,16,22,18,220,16,22,19,220,16,22,20,220,16,22,21,220,16,22,22,220,16,22,23,220,16,22,24,220,16,23,15,220,16,23,16,220,16,23,17,220,16,23,18,220,16,23,19,220,16,23,20,220,16,23,21,220,16,23,22,220,16,23,23,220,16,23,24,220,16,24,15,220,16,24,16,220,16,24,17,220,16,24,18,220,16,24,19,220,16,24,20,220,16,24,21,220,16,24,22,220,16,24,23,220,16,24,24,220,17,15,15,220,17,15,16,220,17,15,17,220,17,15,18,220,17,15,19,220,17,15,20,220,17,15,21,220,17,15,22,220,17,15,23,220,17,15,24,220,17,16,15,220,17,16,16,220,17,16,17,220,17,16,18,220,17,16,19,220,17,16,20,220,17,16,21,220,17,16,22,220,17,16,23,220,17,16,24,220,17,17,15,220,17,17,16,220,17,17,17,220,17,17,18,220,17,17,19,220,17,17,20,220,17,17,21,220,17,17,22,220,17,17,23,220,17,17,24,220,17,18,15,220,17,18,16,220,17,18,17,220,17,18,18,220,17,18,19,220,17,18,20,220,17,18,21,220,17,18,22,220,17,18,23,220,17,18,24,220,17,19,15,220,17,19,16,220,17,19,17,220,17,19,18,220,17,19,19,220,17,19,20,220,17,19,21,220,17,19,22,220,17,19,23,220,17,19,24,220,17,20,15,220,17,20,16,220,17,20,17,220,17,20,18,220,17,20,19,220,17,20,20,220,17,20,21,220,17,20,22,220,17,20,23,220,17,20,24,220,17,21,15,220,17,21,16,220,17,21,17,220,17,21,18,220,17,21,19,220,17,21,20,220,17,21,21,220,17,21,22,220,17,21,23,220,17,21,24,220,17,22,15,220,17,22,16,220,17,22,17,220,17,22,18,220,17,22,19,220,17,22,20,220,17,22,21,220,17,22,22,220,17,22,23,220,17,22,24,220,17,23,15,220,17,23,16,220,17,23,17,220,17,23,18,220]} diff --git a/docs/BATCHING.md b/docs/BATCHING.md index 7672dcc5..e1896fd9 100644 --- a/docs/BATCHING.md +++ b/docs/BATCHING.md @@ -19,6 +19,13 @@ asked, with a note when it is more than setup would recommend. "parallel": 2 ``` +On one GPU with MTP (`--mtp` and `--spec`), `--batch-mtp` (in the config's `args`, or `STRATA_BATCH_MTP=1` in the +server's environment) lets each batch slot verify one MTP proposal per window. It is opt-in; without it the batch +behaviour described below is exactly the one without MTP. It needs VRAM per slot for the draft state and buffers, so +check the engine's free-memory log before using it on a smaller card. If it cannot run (one slot, no `--mtp`, a layer +split or helper GPU) the engine says so and batches as usual. RTX PRO 5000 owners measured +31% to +39% total +throughput with 2 to 4 clients (a RX R9700 run too); it has not been validated with a layer split. + With a layer split, the engine options go into the config's `args`: ``` @@ -28,12 +35,12 @@ With a layer split, the engine options go into the config's `args`: | Option | What it does | | --- | --- | -| `"parallel": N` / `--batch N` / `--slots N` (2..8) | up to N conversations decoded together; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. | +| `"parallel": N` / `--batch N` / `--slots N` (2..8 normally) | up to N conversations have batch slots; more requests wait for a free slot. Each slot gets its own state (a session carved like the stage's own: GDN recurrence, QSA K/V and indexer, PLE history) on every GPU of the split. With grouped MTP, more than 8 slots can rotate through eight-row windows if memory permits. | | `--batch-groups G` | with a layer split: the N slots in G groups that flow through the GPUs as a pipeline (GPU k runs one group while GPU k+1 runs another). G must divide N. 1 = all slots in one window, GPU after GPU. | | `--trim-stage-weights` | with an **explicit** `--layer-split` (e.g. `12,24,36`, not `auto`): every GPU loads only the dense weights of its own layers instead of the whole model's (the same as `STRATA_STAGE_TRIM=1`, PR #639). The VRAM this frees goes to the expert cache. Useful without `--batch` too. | -The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots (a -window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads +The engine never refuses a count it cannot run: it says so in its log and runs what it can - at most 8 slots by +default (a window holds 8 rows), as many as fit in VRAM, or none (one request at a time) when not two fit. The server reads the count the engine reports (`INFO batch_slots=N`), and `GET /v1/status` says it (`concurrency.serving`). ### What a slot costs, and what setup recommends @@ -57,7 +64,8 @@ about 10-25% speed per request on this card". `--parallel N` is honoured as aske - **One request alone** runs on the usual solo path (verify windows with MTP drafts): the fastest single stream. - **When a second request arrives**, the first is stopped (`STOP`) and continues in a batch slot with its prompt plus what it generated so far - the engine's prompt cache holds exactly that, so nothing is read again - and the - new request is admitted next to it. A request in a slot decodes **without MTP drafts** (one token per window). + new request is admitted next to it. By default, a request in a slot decodes **without MTP drafts** (one token per window). + With `--batch-mtp`, each slot verifies one MTP proposal alongside its current token. - **A request left alone in a slot** (the others finished, nobody waits) goes back to the solo path: the slot is stopped, the engine copies its sessions back and decodes with MTP drafts again (at most twice per request; with `--prompt-cache 0` it stays in the slot; `STRATA_PARALLEL_SOLO=0` turns it off). The draft layer's own K/V was @@ -113,8 +121,9 @@ counter-based draw (Philox(seed, position)). ## Limits (for now) -- Batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo path keeps - its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone). +- By default, batch windows carry no MTP drafts: a conversation in a slot decodes one token per window (the solo + path keeps its drafts, which is why a request alone is not put in a slot, and goes back to it when left alone). +- Grouped MTP currently uses one proposal per slot and requires one GPU; it does not support a layer split. - Repetition / frequency / presence penalties are not applied in batch windows. - A prompt shorter than one chunk is read in one piece (the slots wait for it); a read gives way only at a chunk boundary, and not for pictures. diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 20e93343..0fffc11b 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -117,6 +117,11 @@ RTX 5090 (IQ3_S, the reporter's measurement). smaller subset fits, and the server's start error repeats it; setup suggests `--draft-vocab en` on cards under 14 GB (only a suggestion: nothing changes unless you pass it). +**Serving without the draft layer (`--mtp` is optional):** `serve` runs without `--mtp`. Drafts then come from the +suffix/prompt-lookup drafter only (or one token per round), every token is still verified against the model, and the +draft layer's VRAM (~0.7-1 GiB with its head) goes to the expert cache: 1,000 -> 1,678 slots in one A/B on an 8 GB +card. The conversation cache (`--conversation-cache-mib`) stays on: a parked conversation then carries no draft K/V. + **Low-RAM mode (engine 0.1.26, chosen by setup):** normally all of a model's experts are copied into RAM (23-50 GB, pinned) and the GPU holds a copy of the most-used ones. On a PC whose RAM cannot hold them beside the system (the experts plus ~10 GB), setup instead maps them from one file in the model's folder (`--mmap-experts`, the pack's @@ -136,6 +141,15 @@ other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC s as far as the RAM allows, their experts are kept in RAM too (so a prompt reads nothing from the SSD either). - The cache still follows the conversation (`--adapt-every`): a swap copies the evicted expert back from VRAM into the RAM place of the one that replaces it, so the RAM copy keeps holding exactly what the GPU does not. +- `--adapt-async 1` (opt-in, `--serve`): the swaps of a round advance between decode windows on a helper thread + (copy back, copy in, move into RAM) instead of one window waiting for the whole round. Not with `--batch` or + `--peer-device` (the blocking tier runs there). It is not bit-exact from run to run: which window first computes a + swapped-in expert on the GPU (which rounds differently from the CPU) depends on when its copy lands. + It stays on the blocking tier (said in the log) when the exchange buffers are not page-locked, and with + `--pipeline-windows`; the stats line reports ms per round. +- `STRATA_EXCHANGE_ROTATE=1` (opt-in): an adaptive swap hands buffer ownership over instead of copying the evicted + blob into the RAM copy (equal-size blobs, fully page-locked copy). Same tokens, fewer host copies; it works with + `--adapt-async 1` too. Details and the measurement: [EXCHANGE_ROTATION.md](EXCHANGE_ROTATION.md). - The answers are the plain mapped mode's for the same expert placement: the bytes are the file's. With a page-locked copy the GPU also takes its usual share of the misses over PCIe (`--pcie-frac`), as with enough RAM; `--pcie-frac 0` (or `STRATA_RESIDENT_PIN=0`) gives the mapped mode's exact tokens. diff --git a/docs/DISJOINT_EXPERT_CACHE.md b/docs/DISJOINT_EXPERT_CACHE.md new file mode 100644 index 00000000..210e23cc --- /dev/null +++ b/docs/DISJOINT_EXPERT_CACHE.md @@ -0,0 +1,59 @@ +# Avoid duplicate expert slots across helper and primary GPUs + +## Why this helps + +On a PC with two small GPUs, helper experts start out separate from the primary +cache. Later, the adaptive primary cache can promote an expert that the helper +already holds. Both cards then spend memory on the same expert. + +We observed about 1,900-2,000 duplicate slots during sustained requests. +This opt-in change keeps helper-owned experts out of primary promotion candidates, +in both the server and command-line generation paths. + +## Use + +Set `STRATA_DISJOINT_ADAPT=1` before starting the engine. It is off by default. +It leaves the existing peer-tier check and expert arithmetic unchanged. +The check is live: each promotion candidate is asked of the helper's own cache (`RemoteExperts::holds`), so an expert +the helper's tier swaps in or out later is followed (a mask copied at load would go stale). Needs the helper-share +change (#854) for `holds`. + +## Validation environment + +- Two modified RTX 3080 20 GB cards; CUDA SM86, CUDA 13.1, Linux. +- Intel Xeon E5-2686 v4 (18 cores / 36 threads), about 94 GiB usable RAM. +- PCIe 3.0, no GPU peer-to-peer access; 17 expert-pool workers. +- Qwen3.8-Flash-Next IQ3_S, 131,072-token context, INT8 KV, + 32,768 resident KV cells. +- Medium thinking: 2,048-token reasoning cap, 8,192-token output cap. +- Physical GPU power limits stayed at 250 W and 280 W. No power increase. +- Historical performance tests used an isolated engine based on official + v0.1.38 plus reviewed architectds/Strata changes (best, 05c0f36). + This PR contains only our change, ported to official main (99f3dbd). + The historical timings are NOT a measured speedup of this pure-upstream port. + +## Historical benefit + +Same binary and helper capacity, six complete JSON tasks per arm: + +| 32K cached request | Original | Ownership guard | +| --- | ---: | ---: | +| Generation | 81.5 tokens/s | 94.1 tokens/s | +| Complete request | 12.997 s | 11.417 s | + +Generation improved by 15.5%; request time fell by 12.2%. +The tasks returned complete 100-record arrays and correct source facts. +All 18 checks passed across the original, guarded, and larger-cache arms. +The larger-helper arm is not included in the comparison above. +These repetitive tasks do not represent all agent workloads. + +## Validation and remaining work + +- Standalone ownership test passes, including disabled, empty, unowned, + owned, and out-of-range entries, plus candidate filtering. +- Linux compile/link against pure official main (99f3dbd) passed. No engine + was started and no production settings were changed. +- Pure-upstream GPU performance and session/vision/cancellation regression + checks still need to be run. Keep this PR as a draft until then. +- Historical combined builds passed those safety checks, but that is not a + substitute for validating this independent port. diff --git a/docs/EXCHANGE_ROTATION.md b/docs/EXCHANGE_ROTATION.md new file mode 100644 index 00000000..a82dff6b --- /dev/null +++ b/docs/EXCHANGE_ROTATION.md @@ -0,0 +1,139 @@ +# Resident expert exchange buffer rotation + +When the resident RAM complement exchanges an expert with the GPU cache, the +evicted expert lands in a temporary host buffer. The existing path then copies +those bytes into the promoted expert's old RAM slot. Rotation removes that last +host copy: the temporary buffer becomes resident, and the old RAM slot becomes +the next temporary buffer. + +## Enable + +Rotation is **off by default**. Set `STRATA_EXCHANGE_ROTATE=1` before starting the +engine with your existing arguments: + +```bash +export STRATA_EXCHANGE_ROTATE=1 +``` + +```powershell +$env:STRATA_EXCHANGE_ROTATE = '1' +``` + +Only the exact value `1` opts in. Set it to `0` or remove it to restore the copy +path. This setting does not select resident RAM mode or change any preset. +It applies only when all layers have equal-size expert blocks, the resident +complement is fully pinned and GPU-mapped, and the exchange buffers can also be +pinned and mapped. Other layouts keep the copy path and log why rotation could +not be enabled. Configurations without a resident complement do not use it. + +The startup diagnostic confirms activation: + +```text +FileExpertSource: exchange buffer rotation enabled: ...; no host commit memcpy +``` + +Serving diagnostics report the cumulative rotated block count and avoided +`memcpy` payload bytes. This counts the copied payload once, not read plus write +traffic, and does not include the GPU transfers, which still occur. + +## Ownership and synchronization + +The original allocations own their memory until `FileExpertSource::close()`. +Rotation updates slot ownership and keeps each host pointer paired with its GPU +alias. Atomic slot IDs let background residency queries observe those immutable +pairs. Compute readers and GPU transfers must still finish before the existing +serialized commit; rotation adds no overlapping compute or new synchronization +policy. Reserve the maximum exchange capacity before rotation starts: growing a +live exchange arena is rejected because it can now hold resident experts. + +## Tests + +The ownership test can run without CUDA: + +```bash +g++ -std=c++20 -O1 -g -fsanitize=address,undefined -fno-omit-frame-pointer \ + -pthread -Iinclude tests/core/exchange_storage_test.cpp -o /tmp/exchange_storage_test +/tmp/exchange_storage_test +``` + +With an existing CUDA build configured: + +```bash +cmake --build build --target strata exchange_storage_test file_expert_source_test +ctest --test-dir build -R '^(exchange_storage_test|file_expert_source_test)$' --output-on-failure +./build/file_expert_source_test --rotation-gpu +compute-sanitizer --tool memcheck --error-exitcode 71 ./build/file_expert_source_test --rotation-gpu +``` + +The CPU test checks byte preservation, pointer/alias ownership, guards, invalid +operations and concurrent residency queries across 12,304 exchanges. The CUDA +fixture performs 64 exchanges in each of three modes: copy with pinned RAM, +rotation with pinned RAM, and requested rotation with pageable RAM (fallback). +It checks exact bytes, GPU alias reads, file fallback, capacity, and close/reopen. +The GPU fixture is explicit; the ordinary CTest invocation does not run it. + +On 2026-10-04, the clean patch on upstream +`6f32ec070f23ced9f50e704d854d775da52591ab` built on Linux with GCC 15.2 and CUDA +13.3 for an RTX 4090. Both CTest tests, the ASan/UBSan ownership test, and the +CUDA fixture passed. Compute Sanitizer reported **0 errors**. AMD and Windows +GPU execution were not tested for this patch. + +## One native token-identical A/B + +Measured on 2026-10-04 using the clean rotation build at +`18a30ad775bce86e99a54e6dc552ccb72c66d16e`, on upstream +`6f32ec070f23ced9f50e704d854d775da52591ab`. The model is the standard +GSQ-RCO **Q2_0**, with its matching IQ4_NL PLE shard. Both shards were verified +against the publisher's SHA-256 hashes at the pinned revision in the receipt. +The native pack uses the existing `tools/iq_pack.py`; no compatibility conversion +or Q8 PLE reader extension is needed. + +Both arms used the same Release binary (GCC 13.3, CUDA 13.2), RTX PRO 6000 +Blackwell 96GB, Ryzen 9 7950X and 128GB installed RAM. A fresh engine per arm +generated exactly 1,024 tokens after the same 1,024-token counting prompt. +The context allocation was 40,960, with 12,000 GPU expert slots, a 16.19 GiB +pinned/mapped resident complement, FP16 KV, greedy target-only decoding and +zero offered drafts, reused prompt tokens or file-tier blob reads during +generation. Only `STRATA_EXCHANGE_ROTATE` changed. Transfer completion is +awaited before admission. + +The GPU cache was deliberately capped at 12,000 slots (15.45 GiB) to exercise +resident RAM exchanges. Q2 can fit entirely on this 96GB GPU; this is a storage +path comparison, not the fastest full-GPU configuration. It does not change +the project's presets or enable resident mode for existing users. + +| Rotation | Decode tokens/s | Resident exchanges | Avoided host-copy payload | Output IDs | +|---|---:|---:|---:|---| +| `0` | 104.90 | 3,802 | 0 bytes | 1,024, identical | +| `1` | 113.44 | 3,802 | 5,255,884,800 bytes | 1,024, identical | + +Decode rates exclude startup and prefill. The observed throughput change was ++8.1% in this one pair; repeated timing or a general speedup is not established. +The out-of-vocabulary EOS sentinel `2147483647` forces the exact output length, +so this is not a model-quality evaluation. Speculative-path token parity, +AMD and Windows GPU execution remain untested. + +The same Blackwell binary passed both CTest checks and the three-mode CUDA +fixture; Compute Sanitizer reported 0 errors. The +[receipt](../bench/results/exchange-rotation-ab.json) contains source, binary, +model, pack and profile hashes, arguments, timings and diagnostics. The +[raw IDs](../bench/results/exchange-rotation-token-ids.json) retain the input +and both outputs. To check the token comparison without a model: + +```bash +python - <<'PY' +import hashlib, json +from pathlib import Path +p = Path('bench/results') +r = json.loads((p / 'exchange-rotation-ab.json').read_text()) +raw = (p / r['token_ids_file']).read_bytes() +assert hashlib.sha256(raw).hexdigest() == r['token_ids_file_sha256'] +d = json.loads(raw) +assert len(d['input']) == len(d['off']) == len(d['on']) == 1024 +assert d['off'] == d['on'] +for name, arm in zip(('off', 'on'), r['arms']): + sha = hashlib.sha256(json.dumps(d[name], separators=(',', ':')).encode()).hexdigest() + assert sha == arm['output_token_ids_sha256'] +print('1,024 identical output token IDs') +PY +``` diff --git a/docs/MULTI_GPU.md b/docs/MULTI_GPU.md index 5c128232..92f55bdf 100644 --- a/docs/MULTI_GPU.md +++ b/docs/MULTI_GPU.md @@ -191,6 +191,49 @@ The Coder on an RTX 5080 + RTX 3090 (Ryzen 9 9950X3D), 32K context; details in 3090 pair slower (68 / 90 tok/s decode): every extra card costs its own round per window. - More cards pay off when the model's routed experts do not fit the faster ones. +## One conversation with both cards busy (`--pipeline-windows`, opt-in) + +With a split the cards take turns on a verify window: the first card runs its layers and hands off, then waits while +the last card runs the rest, the head and the draft. `--pipeline-windows 2` lets the first card start the **next** +window while the last card still verifies this one. The next window is a guess: that this window is accepted whole +and that its bonus token is the one the draft layer predicts (the draft layer is run on through the drafts of the +window in flight). When the guess holds, half of the next window is already done; when it does not, the first card +puts its state back (a copy of its recurrent state taken while the window ran) and the next window is built from the +real tokens. A guessed window is only started when the draft layer's estimate says it is likely to be kept. Windows +copied from earlier context (`--suffix-draft`) are guessed past as well, which is where edits that copy text gain +most. `--pipeline-windows 1` overlaps only the short prompt reads that go through the verify windows +(`--short-read`). + +Two cards, exactly two stages, `--serve`. In the config: + +``` +"args": [ ..., "--pipeline-windows", "2" ], +"layer_split": "20" +``` + +- **Cost**: a second verify window on each card, 160 MiB more kept out of each card's expert cache, plus two copies + of the first card's recurrent state (about 3 MiB per GDN layer it runs) on the first card with `2`. +- **Same text**: the last card only ever runs windows that are verified, and every window row computes what it + would in any other window, so the tokens are the serial loop's. With `STRATA_IQ_MT_MIN=1 --pcie-frac 0 + --adapt-every 0` the greedy output is identical bit for bit to the serial loop's with the same expert caches. The pipeline keeps + its VRAM out of the caches, so against a run without the flag a few experts move from a card to the CPU, which + rounds them differently, and a near-tie can flip (a serial run given the same caches through `--vram-reserve-mib` + matches it exactly). +- **Off, with one line in the log saying why**, with `--batch` slots, `--peer-device`, the helper caches + (`--expert-cache-device1..3`, `--remote-expert-opt`), a split into three or more stages or onto one GPU + (`--split-device 0`), or no draft layer. A request with repetition penalties (`penalty_last_n`) or coupled + draft sampling decodes serially. +- **Measured** (Swift 1.5 IQ3_XXS, 160K context, q4_0 KV, the stock draft layer, RTX 4060 Ti (layers 0-19) + + RTX 5080 (20-47), i9-14900KF, 32 GB of RAM with the resident RAM mode on the split (#848); greedy, 500 tokens, two + interleaved pairs of three rounds, decode tok/s): Python code 90.4 -> 103.1, C code 76.6 -> 81.6, English prose + 63.0 -> 71.1, Italian prose 41.6 -> 46.3, a copy-heavy edit (a 5 KB file back with a rename) 90.5 -> 117.9; mean + 72.4 -> 84.0 (+16%). It pays when the windows are GPU-bound: with the experts read through the OS file cache + (`--mmap-experts` on that 32 GB PC) the file reads dominate and it measured no faster. + +The `STRATA_PIPELINE_*` tuning and test variables (THETA, FORCE_MISS, SWITCH, LOG, TRACE and the like) are read only with +`STRATA_PIPELINE_DEBUG=1`. `--pipeline-windows` and `--adapt-async 1` exclude each other (the engine says so and keeps the +pipeline). + ## Several conversations at once With a layer split, `--batch N --batch-groups G --trim-stage-weights` decodes several conversations together and diff --git a/docs/ORCA.md b/docs/ORCA.md index 5d0cfb67..c8ea68a5 100644 --- a/docs/ORCA.md +++ b/docs/ORCA.md @@ -30,7 +30,8 @@ from that dependency (`STRATA_GGUF_PY` can point to its `gguf-py` directory). Use this model's own tokenizer exported into the pack. Do not share another model's `dense.bin`, and do not rename the Orca files to impersonate one of setup's GSQ-RCO models. -Strata's persistent server also requires the MTP runtime, prepared by the existing tools: +Strata's persistent server also uses the MTP runtime (optional: without `--mtp` it drafts by lookup only), prepared by +the existing tools: ```sh .venv/bin/python tools/mtp_fetch.py fetch --out mtp diff --git a/docs/SECOND_GPU.md b/docs/SECOND_GPU.md index 8dd82b25..f5682bc2 100644 --- a/docs/SECOND_GPU.md +++ b/docs/SECOND_GPU.md @@ -116,8 +116,14 @@ card's truncated candidate tail is not redistributed to another card. The optimization uses the existing host scheduling and pinned-host transport, not P2P or tensor parallelism. Each layer still waits for its participating helpers. It changes floating-point summation order, so enabled output is not -claimed to be bitwise identical. Only two-card CUDA operation has been measured; -three/four cards and HIP have not been validated. Without the switch, the +claimed to be bitwise identical. Only two-card CUDA operation has been measured +by its author; a community machine measured two cards on HIP (2x RX 6900 XT, +PCIe 4.0 x8 each, IQ3_S): there the expert plan's PCIe share had been taking +experts the helper already held, which made the primary card wait 43 ms per +verify window instead of 19 (decode 40 instead of 66 tok/s). #854 keeps a +helper's experts out of that share; before it, `--pcie-frac 0` avoided the +cost ([bench/results/2026-10-04-rdna2-helper-pcie-share](../bench/results/2026-10-04-rdna2-helper-pcie-share/README.md)). +Three/four cards have not been validated. Without the switch, the existing decode path remains in use. This does not optimize the separate `--peer-device` path below or change its existing incompatibility with helper caches. diff --git a/docs/STRIX_HALO.md b/docs/STRIX_HALO.md new file mode 100644 index 00000000..e8f9c63d --- /dev/null +++ b/docs/STRIX_HALO.md @@ -0,0 +1,116 @@ +# Strix Halo (Ryzen AI Max, gfx1151): build from source on Linux + +Strata runs on the Ryzen AI Max "Strix Halo" APUs (Radeon 8060S / 8050S, RDNA3.5, `gfx1151`, one pool of LPDDR5X shared by the +CPU and the GPU) through the same HIP backend as the Radeon cards in [AMD_HIP.md](AMD_HIP.md). **Status: experimental.** +Everything here was built and measured on one machine, the maintainers' Strix Halo box (Ryzen AI Max+ 395, 128 GB, +Ubuntu 26.04, kernel 7.0, ROCm 7.14.1). There is no ready-made engine for it and setup (`setup.sh`) does not offer it: +it lists integrated Radeon GPUs as not supported. You build the engine yourself, as below. + +What the engine does differently on this chip: + +- **Unified memory.** The GPU's "VRAM" is the GTT pool of the same RAM. `device_free_bytes()` (the figure `--expert-cache auto` and + the memory plan use) counts what Linux can give back (`MemAvailable` less 6 GiB for the system, `STRATA_UMA_HEADROOM_GIB` + changes the 6) instead of only `MemFree`, per device, for any integrated GPU on Linux (this applies to a DGX Spark too). +- **gfx11 matrix cores.** The prompt attention, the block scorer, the prompt GEMMs and the prompt experts have WMMA kernels for + gfx1100 / 1101 / 1102 / 1150 / 1151. A gfx11 part outside that list (gfx1103, gfx1152) is not given them: it takes the portable path. +- **The hipBLASLt table** `tools/hip/gfx1151-hipblaslt-100401.txt` (ROCm 7.14.1's hipBLASLt 1.x `100401`), including the prompt shapes + at `--prefill 16384` (T 16383 / 16384). + +## 1. The toolchain (no root needed) + +ROCm 7.14.1 for gfx1151 from AMD's TheRock builds, extracted into a folder of your own: + +```sh +mkdir -p ~/rocm && cd ~/rocm +curl -LO https://repo.amd.com/rocm/tarball-multi-arch/therock-dist-linux-gfx1151-7.14.1.tar.gz # 1.7 GB +sha256sum therock-dist-linux-gfx1151-7.14.1.tar.gz # c40e8f2bd6630a7d11557c762b99c6fa8afb04c9bd0e51ed1675ee1ca24afb00 +mkdir install && tar -xzf therock-dist-linux-gfx1151-7.14.1.tar.gz -C install +export SDK=$HOME/rocm/install +export ROCM_PATH=$SDK HIP_PATH=$SDK HIP_PLATFORM=amd +export PATH=$SDK/bin:$SDK/lib/llvm/bin:$PATH +export LD_LIBRARY_PATH=$SDK/lib:$SDK/lib/rocm_sysdeps/lib:$SDK/lib/llvm/lib:${LD_LIBRARY_PATH:-} +``` + +You also need CMake 3.24+, Ninja, git and a C++ host toolchain with libstdc++ headers (`sudo apt install build-essential cmake ninja-build git`). +The maintainers' box has no system compiler: they point ROCm's clang at a user-space copy of gcc 15 with +`--gcc-toolchain=/usr` (added to `CMAKE_HIP_FLAGS` below; leave it out when the system has one). + +The kernel's amdgpu driver and `/dev/kfd` access (your user in the `render` and `video` groups) are all the GPU side needs. +To let the GPU use most of a 128 GB machine the maintainers' box boots with `ttm.pages_limit=29360128 ttm.page_pool_size=29360128` +(a 112 GiB GTT; the default is about half of the RAM) and `amd_iommu=off`; both are host settings the engine does not need to run, +only to have the room. + +## 2. The engine + +llama.cpp's `ggml` sources are pinned by this repository: CMake fetches the revision it needs. For an offline build, point +`STRATA_GGML_DIR` at a checkout of exactly that revision. + +```sh +git clone https://github.com/Niko1221/Strata.git && cd Strata +cmake -S . -B build-halo -G Ninja -DCMAKE_BUILD_TYPE=Release \ + -DSTRATA_ENABLE_HIP=ON -DSTRATA_ENABLE_CUDA=OFF -DSTRATA_PREFILL_MMQ=ON \ + -DCMAKE_HIP_ARCHITECTURES=gfx1151 \ + -DCMAKE_HIP_COMPILER=$SDK/lib/llvm/bin/clang++ -DCMAKE_HIP_COMPILER_ROCM_ROOT=$SDK \ + "-DCMAKE_PREFIX_PATH=$SDK;$SDK/lib/rocm_sysdeps;$SDK/lib/llvm" \ + "-DCMAKE_HIP_FLAGS=--rocm-path=$SDK --rocm-device-lib-path=$SDK/lib/llvm/amdgcn/bitcode" +cmake --build build-halo --target strata -j 8 # about 25 minutes the first time +``` + +`gfx1151` is "unvalidated" in the build's own wording (it warns). `STRATA_PREFILL_MMQ=ON` builds ggml's MMQ kernels the prompt +experts need. The tests: `cmake --build build-halo -j 8` builds them all, `ctest --test-dir build-halo` runs them; +`hip_prefill_hcd_exact_parity` and `hip_prefill_hipblaslt_gemm` need the table (next section) and skip without it. + +## 3. The prompt table, and running + +Hand the engine the table (`setup` does it for the supported cards; for gfx1151 you do it): without it the prompt's dense matrix +products use plain hipBLAS and are slower. + +```sh +export STRATA_HIPBLASLT_TUNING=$PWD/tools/hip/gfx1151-hipblaslt-100401.txt +``` + +The engine accepts it only for the architecture and the hipBLASLt version named on the table's second line +(`STRATA_HIPBLASLT_TUNING_V1 gfx1151 100401`: ROCm 7.14.1) and says so at start-up (`prefill gemm: hipBLASLt tuning enabled (90 rows, +gfx1151, version 100401)`). Then run `strata` with the same arguments as on any other card (the model packs, `--serve`, the +settings of [DETAILS.md](DETAILS.md)); a pack of the Unsloth UD-IQ4_XS or UD-Q4_K_XL GGUFs is what the numbers below used. + +## 4. What is on by default on gfx1151 + +At start the engine looks at GPU 0; on a gfx1151 it sets the switches below unless you set them yourself +(`STRATA_GFX1151_DEFAULTS=0` turns the whole table off, and the start-up line names what was set). **Every one of them gave +byte-identical output on the maintainers' box** (the same token ids, 4K / 32K / 64K and four models, and a bitwise harness per kernel): +they change speed, not answers. Nothing here applies to CUDA or to another AMD architecture. + +| Switch | What it does | +|---|---| +| `STRATA_GDN_HEAD`, `STRATA_GDN_PP=2`, `STRATA_GDN_CONVL2`, `STRATA_GDN_NOY` | the prompt's gated-delta-net recurrence: four lanes per column, two columns per lane, the convolution and the norms fused | +| `STRATA_HCD_EXACT` | the hyper-connection down projection (N 320, K 10240) in a WMMA kernel that reproduces hipBLASLt solution 1176 / 1177's summation order (`hip_prefill_hcd_exact_parity` checks it bit for bit); it runs only where the table makes hipBLASLt pick one of those two, and says once if it cannot | +| `STRATA_CVEC_FUSE`, `STRATA_PF_PAD` | a steered layer's write, control vector and next norm in one pass; padded GEMM row strides | +| `STRATA_Q8_PACKED`, `STRATA_Q6_PACKED`, `STRATA_MMVF_ROWS`, `STRATA_ATTN_LANECELL` | decode layouts and kernels (packed Q8_0 / Q6_K weights, 4-row BF16 GEMV, one-cell-per-thread attention scores) | +| `STRATA_EXPERT_V2`, `STRATA_TSUM`, `STRATA_LFUSE` | the grouped decode experts (IQ3_S / IQ4_NL), single-butterfly warp sums, fewer launches around the shared expert and the KV append | +| `STRATA_GDN_SPLIT`, `STRATA_QFUSE`, `STRATA_PLE_BATCH` | the GDN step over four blocks per head, activation images written by their producers, the PLE key / value projections of a verify window at once | + +## 5. What is not on by default (it changes bits) + +These are faster on gfx1151 and **round differently** from the default path (a different summation order or a half-precision +intermediate), so they are opt-in and the maintainers gate them with KL against the default (`STRATA_PF_SWITCH_MIN_T=4096` keeps +the short prompts on the default numerics, since these pay on long ones). The maintainers' fast configuration sets all of +them: + +```sh +export STRATA_PF_FUSED=1 # the prompt experts on the matrix cores (IQ2 / IQ3 / IQ4_XS gate/up, Q2_0 / IQ4_NL / Q8_0 down) +export STRATA_PF_GEMM=1 # the prompt's FP16 projections on the 128 x 256 WMMA GEMM +export STRATA_HC_UPMIX=1 # the hyper-connection up projection with its epilogue +export STRATA_PA_FAST=1 # the prompt attention with single FP16 q and p +export STRATA_HIP_WMMA=1 # the prompt attention on matrix cores +export STRATA_SELECT_WMMA=1 # the block scorer on matrix cores +export STRATA_HC_Q8=1 # the hyper-connection read from the GGUF's own Q8_0 projections +export STRATA_PF_SWITCH_MIN_T=4096 +``` + +Two engine flags help on long contexts and are not Strix-specific: `--mtp-window 8192` (the draft layer attends to the last 8,192 +cells: 64K output +3.5%, 32K -0.4%) and `--spec`, `--lookup-chain`, `--mtp-q4` (see [DETAILS.md](DETAILS.md)). + +## 6. Measured + +(see the end of this page for the table of this build's measurements) diff --git a/include/strata/core/exchange_storage.hpp b/include/strata/core/exchange_storage.hpp new file mode 100644 index 00000000..7e50d745 --- /dev/null +++ b/include/strata/core/exchange_storage.hpp @@ -0,0 +1,114 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace strata::core::detail { + +// Non-owning views: the complement and exchange allocations retain their original +// owners until FileExpertSource::close(). Ownership changes via slot IDs; the +// physical buffer addresses, bytes and CUDA aliases stay in place. This first path requires uniform, fully mapped/pinned expert slots. +class ExchangeStorage { +public: + struct View { + uint8_t* host = nullptr; + const uint8_t* device = nullptr; + }; + + bool initialize(const std::vector& offsets, uint8_t* resident_host, + const uint8_t* resident_device, uint64_t resident_bytes, + uint8_t* exchange_host, const uint8_t* exchange_device, + size_t count, size_t blob_bytes, std::string& error) { + error.clear(); + if (active()) { error = "exchange storage already initialized"; return false; } + if (!resident_host || !resident_device || !exchange_host || !exchange_device || + !blob_bytes || !count || !resident_bytes || resident_bytes % blob_bytes || + count > std::numeric_limits::max() / blob_bytes) { + error = "invalid uniform mapped exchange geometry"; return false; + } + const size_t resident_slots = (size_t)(resident_bytes / blob_bytes); + if (resident_slots > std::numeric_limits::max() - count) { + error = "exchange slot count overflow"; return false; + } + auto experts = std::make_unique[]>(offsets.size()); + std::vector spares(count); + std::vector buffers(resident_slots + count); + for (size_t slot = 0; slot < resident_slots; ++slot) + buffers[slot] = {resident_host + slot * blob_bytes, resident_device + slot * blob_bytes}; + std::vector used(resident_slots, false); + for (size_t i = 0; i < offsets.size(); ++i) { + const uint64_t at = offsets[i]; + experts[i].store(kAbsent, std::memory_order_relaxed); + if (at == ~uint64_t{0}) continue; + if (at >= resident_bytes || at % blob_bytes || used[(size_t)(at / blob_bytes)]) { + error = "invalid or duplicate resident slot"; return false; + } + used[(size_t)(at / blob_bytes)] = true; + experts[i].store((size_t)(at / blob_bytes), std::memory_order_relaxed); + } + for (bool present : used) if (!present) { + error = "unassigned resident slot"; return false; + } + for (size_t q = 0; q < count; ++q) { + spares[q] = resident_slots + q; + buffers[spares[q]] = {exchange_host + q * blob_bytes, exchange_device + q * blob_bytes}; + } + experts_ = std::move(experts); + expert_count_ = offsets.size(); + spares_.swap(spares); + buffers_.swap(buffers); + blob_bytes_ = blob_bytes; + return true; + } + + bool active() const { return blob_bytes_ != 0; } + View resident(size_t expert) const { + if (expert >= expert_count_) return {}; + const size_t slot = experts_[expert].load(std::memory_order_acquire); + return slot != kAbsent ? buffers_[slot] : View{}; + } + View spare(size_t q) const { return q < spares_.size() ? buffers_[spares_[q]] : View{}; } + + // Only after every CPU reader and H2D copy of `in` has completed, and `out` + // has landed in spare(q). No allocation, memcpy, or CUDA operation here. + bool commit(size_t in, size_t out, size_t q, const uint8_t* staged, size_t bytes) { + if (in >= expert_count_ || out >= expert_count_ || q >= spares_.size() || + !staged || bytes != blob_bytes_) return false; + const size_t incoming_slot = experts_[in].load(std::memory_order_acquire); + if (incoming_slot == kAbsent || experts_[out].load(std::memory_order_acquire) != kAbsent || + buffers_[spares_[q]].host != staged) return false; + // A background router lookahead can query residency to skip redundant + // file prefetches. Publish one atomic slot ID; the pointer/alias pair is + // immutable. Actual compute readers still obey the completion contract. + experts_[out].store(spares_[q], std::memory_order_release); + spares_[q] = incoming_slot; + experts_[in].store(kAbsent, std::memory_order_release); + ++exchanges_; + avoided_bytes_ += bytes; + return true; + } + + uint64_t exchanges() const { return exchanges_; } + uint64_t avoided_bytes() const { return avoided_bytes_; } // memcpy payload, not read+write total + void clear() { + experts_.reset(); expert_count_ = 0; buffers_.clear(); spares_.clear(); + blob_bytes_ = 0; exchanges_ = avoided_bytes_ = 0; + } + +private: + static constexpr size_t kAbsent = std::numeric_limits::max(); + std::unique_ptr[]> experts_; + size_t expert_count_ = 0; + std::vector buffers_; // immutable physical addresses after initialize + std::vector spares_; // touched only by the serialized cache manager + size_t blob_bytes_ = 0; + uint64_t exchanges_ = 0, avoided_bytes_ = 0; +}; + +} // namespace strata::core::detail diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 8fbc4a58..1e6285ae 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -22,6 +22,7 @@ #pragma once #include "strata/core/expert_cache.hpp" +#include "strata/core/exchange_storage.hpp" #include "strata/core/hit_hook.hpp" #include "strata/kernels/cpu/pool.hpp" @@ -475,17 +476,34 @@ public: // buffer and calls `stage_exchange`: `out` is then read from that buffer, and `in` still from here (the CPU // computes both until the swap lands). Once the slot copy has landed, `commit_exchanges` moves `out` into // `in`'s place, so the copy keeps holding exactly the experts the GPU does not - with no read of the file. + // STRATA_EXCHANGE_ROTATE=1 can instead transfer buffer ownership (uniform, fully pinned/mapped slots). /// Whether the compact copy holds `(layer, expert)`. bool has_resident(int64_t layer, int64_t expert) const; /// Host room for `n` evicted blobs (page-locked when possible). Idempotent for the same or a smaller `n`. bool reserve_exchanges(int64_t n, std::string& err); int64_t exchange_capacity() const { return xstage_cap_; } + /// The exchange buffers are page-locked (cudaHostAlloc): copies to and from them are asynchronous. + bool exchange_pinned() const { return xstage_pinned_; } uint8_t* exchange_buffer(int64_t q) const; /// Requires `has_resident(layer, in)`, `!has_resident(layer, out)` and `exchange_buffer(q)` holding out's blob. bool stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q); + /// --pipeline-windows: size the exchange table now, so a `stage_exchange` on the adaptive tier's thread never + /// reallocates it under a concurrent `blob` (the pool reads it while windows are in flight). + void prepare_overrides() { if (override_.empty()) override_.assign((size_t) blobs_, nullptr); } /// After the GPU copies of every staged swap have landed. Returns how many exchanges were applied. int64_t commit_exchanges(); + /// `commit_exchanges` in two halves, for the asynchronous adaptive tier (--adapt-async): `commit_copies` moves + /// every staged evicted blob into its `in`'s place in the copy (on another thread: safe once nothing computes `in` + /// from RAM - it is resident on the GPU - while `out` is still read from its exchange buffer), then `commit_flip` + /// (the caller's thread, between windows) points `out` there and drops the staging. Returns how many were applied. + void commit_copies(); + int64_t commit_flip(); + /// The compact copy's blob of `(layer, expert)`, or null; not counted as a read (any thread). + const uint8_t* resident_blob(int64_t layer, int64_t expert) const; int64_t exchanges() const { return exchanges_; } + bool exchange_rotation() const { return exchange_storage_.active(); } + uint64_t rotated_exchanges() const { return exchange_storage_.exchanges(); } + uint64_t avoided_exchange_copy_bytes() const { return exchange_storage_.avoided_bytes(); } /// With the compact copy ready: blobs read from the mapped file since (what the plain mmap mode may read from /// the SSD). 0 in a steady resident mode; lend-region experts that did not fit the RAM count here. int64_t file_reads() const { return file_reads_.load(std::memory_order_relaxed); } @@ -540,6 +558,7 @@ public: int64_t reads() const override { return reads_; } private: + const uint8_t* resident_blob(size_t index) const; const uint8_t* mapped_blob(int64_t layer, int64_t expert) const; /// The blob's bytes from the mapped file(s) - experts.bin, or the three GGUF role slices - into `dst`. bool copy_from_files(int64_t layer, int64_t expert, uint8_t* dst) const; @@ -609,6 +628,7 @@ private: const uint8_t* complement_device_ = nullptr; uint64_t complement_bytes_ = 0; std::vector complement_offsets_; + detail::ExchangeStorage exchange_storage_; // authoritative when active; original arenas still own memory bool complement_pinned_ = false; bool complement_partial_ = false; ///< CS-T: only the first complement_pin_limit_ bytes are registered uint64_t complement_pin_limit_ = 0; diff --git a/include/strata/core/mtp.hpp b/include/strata/core/mtp.hpp index 97da1e89..e4b1d622 100644 --- a/include/strata/core/mtp.hpp +++ b/include/strata/core/mtp.hpp @@ -43,7 +43,7 @@ public: /// Loads `rt_dir` (from tools/mtp_rt.py) and allocates the layer's K/V and buffers for up to `max_t` rows. /// Call before the VRAM expert tier is sized: this takes ~0.9 GB. bool load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, - int64_t window = 32768); + int64_t window = 32768, const MtpDrafter* shared = nullptr); /// The prompt's length: prefill() skips the cells the attention window can never reach again. void set_prompt_len(int64_t n) { prompt_len_ = n; } /// At most this many drafts per round (below max_t - 1): a window longer than the MTP's comes from elsewhere. @@ -62,6 +62,7 @@ public: /// STRATA_MTP_TOP2=1 (diagnostic): draft j's runner-up token in the last draft() (-1 = unknown) static bool top2_env(); int32_t top2(int j) const { return j >= 0 && j < (int) top2_.size() ? top2_[(size_t) j] : -1; } + int max_t() const { return max_t_; } uint64_t vram_bytes() const { return vram_; } /// The draft layer's K/V state (read-only: --serve's STRATA_STATE_HASH check hashes it) const QsaState& kv_state() const { return st_; } @@ -72,11 +73,18 @@ public: /// the draft head over rt/draft_vocab.bin's subset. The expert cache is sized before bind(), so it reserves this. uint64_t bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const; /// The main model's embedding and head, and the verify window's final residuals (T rows, hc*n_embd each). - bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err); + bool bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err, + const MtpDrafter* shared = nullptr); /// Prompt cells [cell0, cell0 + n): residual rows `R_rows` (device, hc*n_embd each) and `next_tokens` (host, - /// the token at position cell+1). Runs in batches of up to max_t rows. - bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err); + /// the token at position cell+1). Runs in batches of up to max_t rows. `sync` false: returns without waiting + /// for the drafter's stream (the caller orders on it: `stream()`). + bool prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err, + bool sync = true); + /// --pipeline-windows: capture the prefill graphs and size its input records for windows of up to max_t rows now, + /// so a later prefill(sync = false) of a window neither captures nor allocates (both wait for the device). + bool prepare_prefill(std::string& err); + cudaStream_t stream() const { return cs_; } /// One round: catch-up over T cells from `p` (rows = the window's final residuals, `tokens` = the window's /// argmaxes: row t pairs R_{p+t} with the token at p+t+1), then the draft chain from row `a` (the last @@ -99,6 +107,31 @@ public: void set_ple_session(SessionState* s) { ple_ss_ = s; } bool coupled() const { return coupled_active_; } + // ---- --pipeline-windows 2: the chain as one asynchronous launch (the round and its steps back to back, no host + // wait), its first `n_force` steps fed the given tokens instead of their own picks (teacher forcing: the drafts of + // a window already in flight), each output read once the event after its step has completed. + /// Before `load`: the round/step graphs get the forcing kernel (a no-op while its token is -1), and the drafter's + /// stream the highest priority (STRATA_MTP_PRIORITY=0: the default priority). + void set_force_capture(bool on) { force_on_ = on; } + /// The rows the next round reads (null: the bound `window_R`), copied into the bound buffer before the round. + void set_source_R(const float* rows) { src_R_ = rows; } + /// Capture the round graphs for T = 1..max_t and every step graph now (a capture syncs the drafter's stream). + bool prepare_chain(std::string& err); + /// The catch-up over T cells from `p` (as draft()), then `n_out` outputs from row `a`: output j is the chain's + /// own pick, and step j (1 <= j <= n_force) takes force[j - 1] as its input token instead of output j - 1. + /// `n_early`: an event after each of the first `n_early` outputs (chain_outputs_ready). + bool chain_launch(int T, const int32_t* tokens, int64_t p, int a, const int32_t* force, int n_force, int n_out, + int n_early, std::string& err); + /// 1: every output is in chain_tok()/chain_prob(); 0: still running; -1: an error. + int chain_poll(std::string& err); + /// How many of the chain's first outputs (up to `n_early`; all of them once the chain is done) have landed in + /// chain_tok()/chain_prob(); -1: an error. A window's size is often decided by its first outputs (a draft below + /// spec_min_p ends it), so the next launch need not wait for all of them. + int chain_outputs_ready(std::string& err); + bool chain_live() const { return chain_live_; } + const int32_t* chain_tok() const { return chain_tok_; } + const float* chain_prob() const { return chain_prob_; } + double ms_draft = 0, ms_prefill = 0; int64_t rounds = 0; @@ -160,6 +193,16 @@ private: void record_top2(int j); std::vector top2_, dvocab_host_; std::vector lg_host_; + // --pipeline-windows 2 (chain_launch) + bool stage_source_R(int T, std::string& err); ///< set_source_R's rows into the bound buffer + bool force_on_ = false, chain_live_ = false; + const float* src_R_ = nullptr; + int32_t *h_force_ = nullptr, *m_force_ = nullptr; ///< the forced tokens (mapped), -1 = the step's own pick + cudaEvent_t ev_chain_ = nullptr; + cudaEvent_t ev_step_[8] = {}; ///< after each of the first n_early outputs + int steps_seen_ = 0, chain_n_ = 0, chain_early_ = 0; + int32_t chain_tok_[8] = {}; + float chain_prob_[8] = {}; int64_t n_vocab_ = 0; uint64_t vram_ = 0; cudaStream_t cs_ = nullptr; @@ -173,6 +216,9 @@ private: std::vector tensors_; uint8_t* dense_ = nullptr; uint8_t* experts_ = nullptr; + // Slot drafters borrow immutable weights and head; each still owns its state and scratch. + bool owns_weights_ = true; + bool owns_draft_head_ = true; void* state_arena_ = nullptr; QsaState st_; void* arena_ = nullptr; diff --git a/include/strata/core/progress.hpp b/include/strata/core/progress.hpp index 46c93783..0d982c1d 100644 --- a/include/strata/core/progress.hpp +++ b/include/strata/core/progress.hpp @@ -39,6 +39,8 @@ inline std::atomic& release_gpu_fn() { static std::atomic f{null inline void release_gpu_waits(std::FILE* f) { if (auto fn = release_gpu_fn().load()) fn(f); } +/// --pipeline-windows: the pipelined loop's windows and the drafter's chain (set while that loop runs) +inline std::atomic& diag_pipeline_fn() { static std::atomic f{nullptr}; return f; } inline Progress& progress() { static Progress p; diff --git a/include/strata/core/remote_experts.hpp b/include/strata/core/remote_experts.hpp index 224d24f5..218ff55b 100644 --- a/include/strata/core/remote_experts.hpp +++ b/include/strata/core/remote_experts.hpp @@ -37,6 +37,8 @@ public: int64_t k, const int32_t* kind, const int32_t* primary_res, std::string& err); bool owns(int64_t index) const { return owned_[(size_t) index] != 0; } + /// This helper's cache holds (layer, expert): begin() will take its rows unless the plan gave them away. + bool holds(int64_t layer, int32_t expert) const { return cache_.slot_of(layer, expert) >= 0; } bool optimized_decode() const { return remote_opt_ != nullptr; } bool finish(float* out, std::string& err); int64_t resident() const { return cache_.resident(); } diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index bf572f39..119f6535 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -149,8 +149,13 @@ public: /// listed are not touched, so an idle slot keeps its state (a finished conversation it may continue later). bool run_slot_rows(const int* rows, int S, const int32_t* tokens, const int64_t* pos, PoolMultiFn pool, void* user, int32_t* out, std::string& err); - /// Keep every row of the last batch window: each slot's state advances by its one token. + /// Keep every row of the last batch window. bool commit_slots(std::string& err); + /// Commit an accepted prefix in each contiguous slot group of the last window. `keep` has + /// one entry per slot (indexed by slot ID), each in 1..that slot's group length. + bool commit_slot_prefixes(const int* keep, std::string& err); + /// --batch-mtp: slot rotation makes many row layouts, so bound the captured batch graph pairs (LRU). 0 = unbounded. + void set_batch_graph_limit(size_t n) { batch_graph_limit_ = n; } // ---- The stages of a layer split as a PIPELINE. A batch window over the slot GROUP // [base, base + S) is launched on ONE stage with its commit right behind it on the stage's stream (a batch window @@ -180,6 +185,45 @@ public: /// false with `err` when it failed. Free when nothing is pending. bool wait_commit(std::string& err); + // ---- PIPELINED WINDOWS (--pipeline-windows, a layer split on two GPUs). One conversation's windows with the + // stages overlapped: stage 0 runs window K+1 while stage 1 still runs window K. The same window as `run`, driven + // without blocking the host, so one host thread keeps a window in flight on each stage (the batch pipeline's + // pattern, batch_launch / batch_poll, for one sequence with drafts). Two verifiers per stage (one per window + // parity) share the stage's stream and each has its own hand-off. `pl_launch` stages and launches (it never + // captures: `capture_all` first, with nothing in flight), `service` serves the layers whose doorbells have rung + // and returns at once, `done` polls the window's completion, `pl_finish` reads the picks, `pl_commit_async` + // queues the commit. Nothing chains to `next_`: the caller drives every stage. + /// The compute stream to use instead of a private one (the two verifiers of one stage share it). Before `init`. + void set_stream(cudaStream_t s) { ext_stream_ = s; } + /// Every layer copies the token rows to the host (doorbell_publish), not only the layers with a routed expert + /// outside the VRAM tier by the device's residency table: with windows in flight the adaptive tier marks an + /// expert evicted on the host (the pool then computes it on the CPU) before the device table follows. Also turns + /// the device-planned layers (E-6) off. Before `init`. + void set_always_publish(bool on) { always_publish_ = on; } + cudaStream_t stream() const { return cs_; } + int device() const { return device_; } + /// Capture every window size and the commit graph now (a capture syncs the stream: never with a window in flight). + bool capture_all(std::string& err); + bool pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err); + /// Stage a window ahead of its launch (positions, and the PLE rows from `ple_prev` = the two tokens before the + /// window as they WILL be, their pages prefetched). A later `pl_launch` of the same window (T, pos0, tokens, and + /// `ss.ple_prev` equal to `ple_prev` by then) skips the staging; anything else stages again. + bool prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err); + /// 1: every layer served; 0: the GPU has not reached the next layer yet; -1: an error (`err`). + int service(PoolMultiFn pool, void* user, std::string& err); + bool in_flight() const { return fl_active_; } + /// The window's graph (and its profile copy) completed; false while it runs. An error sets `err`. + bool done(std::string& err); + /// After `done`: the profile, the last stage's host sampling and picks (`out` may be null on an earlier stage). + bool pl_finish(int32_t* out, std::string& err); + /// The commit without a host sync; `ss.ple_prev` advances now (host side). A second call for the same window + /// (after its state was restored) replays it with another count. + bool pl_commit_async(int n_keep, std::string& err); + /// Fold another verifier's counters and GPU profile into this one's (the two verifiers of one stage report once). + void absorb_stats(Verifier& o); + /// The watchdog's line for a pipelined verifier: in flight, layers served, the GPU's ring and flags, its events. + void diag_pipelined(std::FILE* f, const char* name) const; + /// Measurement hook (STRATA_LOGPOS): after run(), write one line per row t of the last window's head - /// "pos target logprob top top_logprob hit extra_logprob target_logprob_without_extra" - where row t is the /// distribution at pos0 + t, targets[t] is the token at pos0 + t + 1, extra_logprob is the log-probability of @@ -221,14 +265,21 @@ private: int row_base_ = 0; ///< ... its hand-off rows start here (a pipeline group's own rows) int brow_[8] = {}; ///< ... and row t is slot brow_[t] bool last_batch_ = false; ///< the last run was a batch window (set_plan_slot: one group) - std::map exec_bm_, commit_bm_; ///< key: batch_key(rows, S, hand-off base) + std::map, cudaGraphExec_t> exec_bm_, commit_bm_; ///< full row layout avoids slot-ID collisions + std::map, uint64_t> bm_used_; ///< last use of each captured layout (LRU, only with a graph limit) + uint64_t bm_tick_ = 0; + size_t batch_graph_limit_ = 0; ///< 0: keep every captured batch graph (0.1.39); N: LRU-evict beyond N layouts int last_rows_[8] = {}; ///< the slots of the last batch window's rows - uint64_t bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs - return batch_key(rows, S, hbase) | (ar_off_ ? (1ull << 63) : 0ull); + std::vector bkey(const int* rows, int S, int hbase) const { // #871: the doorbell variant has its own graphs + std::vector k = batch_key(rows, S, hbase); + k.push_back(ar_off_ ? 1 : 0); + return k; } - static uint64_t batch_key(const int* rows, int S, int hbase) { - uint64_t k = (uint64_t) hbase << 40 | (uint64_t) S << 32; - for (int t = 0; t < S; ++t) k |= (uint64_t) (rows[t] & 15) << (4 * t); + static std::vector batch_key(const int* rows, int S, int hbase) { + std::vector k; + k.reserve((size_t) S + 1); + k.push_back(hbase); + for (int t = 0; t < S; ++t) k.push_back(rows[t]); return k; } // batch_launch / batch_poll @@ -245,6 +296,19 @@ private: int64_t last_pos_b_[8] = {}; bool capture_batch(const int* rows, int S, int hbase, std::string& err); void collect_profile(); ///< STRATA_VERIFY_PROFILE: add the last window's stamps to prof_sum_ + void accumulate_profile(const unsigned long long* stamps); ///< one window's stamps (host copy) into prof_sum_ + // pipelined windows (pl_launch ...) + cudaStream_t ext_stream_ = nullptr; ///< set_stream: the stage's shared stream (not destroyed here) + bool always_publish_ = false; + void pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]); + cudaEvent_t ev_done_ = nullptr, ev_commit_ = nullptr; + unsigned long long* prof_pin_ = nullptr; ///< pinned host copy of the stamps (pipelined windows) + bool fl_active_ = false, fl_prof_ = false, fl_ple_ = false, commit_live_ = false, pl_prestaged_ = false; + int fl_T_ = 0; + int64_t fl_k_ = 0, fl_total_ = 0; + double fl_since_ms_ = 0, fl_flush_ms_ = 0, fl_launch_ms_ = 0; + int32_t pl_prev_[2] = {-1, -1}; + std::vector pl_ple_rows_; ///< the window's PLE rows (T x PLE_N_HEADS), gathered when layer 0 is served bool capture_commit_batch(const int* rows, int S, int hbase, std::string& err); bool stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err); strata::kernels::SamplerParams sampling_ = [] { diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index 8c80bafa..0ae55341 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -87,6 +87,9 @@ void ident_hits(const int32_t* ids, int n, int32_t* slot, int32_t* dst, int32_t* void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const int32_t* row_dev, float* R_dst, int32_t* tok_dst, int32_t* out, int j, void* stream, const float* probs = nullptr, float* out_p = nullptr); +/// --pipeline-windows, the drafter's chain teacher forced: `*tok = force[j]` when force[j] >= 0 (`force` is mapped +/// host memory, read when the kernel runs), else `*tok` is left as it is. +void force_token(int32_t* tok, const int32_t* force, int j, void* stream); /// dst row i = src row ids[i] (row_bytes each, multiple of 16), for n rows. void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream); /// ids[t] = table[ids[t]] for n entries (a subset index back to a token id). diff --git a/serve/server.py b/serve/server.py index e755e00b..f7251a87 100644 --- a/serve/server.py +++ b/serve/server.py @@ -1612,7 +1612,7 @@ def engine_args(cfg: dict) -> list[str]: return learned_profile_args(cfg, args) -PARALLEL_MAX = 8 # the engine's batch window holds at most 8 rows (kVerifyMaxT) +PARALLEL_MAX = 8 # the engine's batch window holds at most 8 rows (kVerifyMaxT); --batch-mtp waves more through it def parallel_args(cfg: dict, args: list[str]) -> list[str]: @@ -1630,7 +1630,7 @@ def parallel_args(cfg: dict, args: list[str]) -> list[str]: return [] if n <= 1: return [] - if n > PARALLEL_MAX: + if n > PARALLEL_MAX and "--batch-mtp" not in args and os.environ.get("STRATA_BATCH_MTP", "0") in ("", "0"): print(f'[strata] "parallel": {n} - the engine runs at most {PARALLEL_MAX} requests together; it will use ' f"{PARALLEL_MAX}", flush=True) return ["--batch", str(n)] diff --git a/serve/test_parallel.py b/serve/test_parallel.py index 6e140012..87171ac7 100644 --- a/serve/test_parallel.py +++ b/serve/test_parallel.py @@ -149,6 +149,30 @@ class ParallelArgs(unittest.TestCase): self.assertEqual(parallel_args({"parallel": "4"}, []), []) # said and ignored self.assertEqual(parallel_args({"parallel": True}, []), []) self.assertEqual(parallel_args({"parallel": 12}, []), ["--batch", "12"]) # the engine warns and caps + def test_parallel_above_the_window_says_so_unless_batch_mtp(self): + import contextlib, io, os + def said(args, env): + buf = io.StringIO() + old = os.environ.get("STRATA_BATCH_MTP") + if env is None: + os.environ.pop("STRATA_BATCH_MTP", None) + else: + os.environ["STRATA_BATCH_MTP"] = env + try: + with contextlib.redirect_stdout(buf): + r = parallel_args({"parallel": 12}, args) + finally: + if old is None: + os.environ.pop("STRATA_BATCH_MTP", None) + else: + os.environ["STRATA_BATCH_MTP"] = old + self.assertEqual(r, ["--batch", "12"]) + return "at most" in buf.getvalue() + self.assertTrue(said([], None)) # 0.1.39: the window holds 8 rows + self.assertTrue(said([], "0")) + self.assertFalse(said(["--batch-mtp"], None)) # --batch-mtp waves more through the window + self.assertFalse(said([], "1")) + args = engine_args({"args": ["--pack", "p"], "parallel": 2}) self.assertEqual(args[-2:], ["--batch", "2"]) diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 98e1952d..f62ea07c 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -526,6 +526,7 @@ void FileExpertSource::close() { xstage_blob_ = 0; override_.clear(); staged_.clear(); + exchange_storage_.clear(); exchanges_ = 0; file_reads_.store(0); complement_arena_ = nullptr; @@ -823,7 +824,7 @@ void FileExpertSource::prefetch(int64_t layer, const int64_t* experts, int64_t n const int64_t e = experts[i]; if (e < 0 || e >= n_expert_) continue; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + if (complement_ready_ && resident_blob(index) != nullptr) continue; // in the RAM copy if (!override_.empty() && override_[index] != nullptr) continue; size_t v = 0; @@ -1142,7 +1143,7 @@ void FileExpertSource::warm(int64_t layer, const int64_t* experts, int64_t n) { const int64_t e = experts[j]; if (e < 0 || e >= n_expert_) continue; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) e; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + if (complement_ready_ && resident_blob(index) != nullptr) continue; // in the RAM copy if (warm_stamp_) warm_stamp_[index].store(stamp, std::memory_order_relaxed); warm_count_.fetch_add(1, std::memory_order_relaxed); @@ -1285,7 +1286,7 @@ void FileExpertSource::begin_layer(int64_t layer, const int32_t* ids, int64_t k) bool FileExpertSource::transient(int64_t layer, int64_t expert) const { if (!staged() || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - if (complement_ready_ && index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement) + if (complement_ready_ && resident_blob(index) != nullptr) return false; return override_.empty() || override_[index] == nullptr; } @@ -1297,7 +1298,7 @@ bool FileExpertSource::copy_blob(int64_t layer, int64_t expert, uint8_t* dst) { const uint64_t bytes = layer_blob_bytes_[(size_t) layer]; if (complement_ready_) { const uint8_t* held = - detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + resident_blob(index); if (held == nullptr && !override_.empty()) held = override_[index]; if (held != nullptr) { std::memcpy(dst, held, (size_t) bytes); @@ -1726,16 +1727,25 @@ bool FileExpertSource::pin_cache_complement( return true; } +const uint8_t* FileExpertSource::resident_blob(size_t index) const { + if (exchange_storage_.active()) return exchange_storage_.resident(index).host; + return detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); +} + bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const { if (!complement_ready_ || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; - return index < complement_offsets_.size() && complement_offsets_[index] != kNoComplement; + return resident_blob(index) != nullptr; } bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { err.clear(); if (n <= xstage_cap_) return true; if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; } + if (exchange_storage_.active()) { + err = "FileExpertSource: reserve maximum exchange capacity before enabling rotation"; + return false; // the original exchange allocation can now contain live resident experts + } uint64_t blob = 0; for (const uint64_t b : layer_blob_bytes_) blob = std::max(blob, b); if (blob == 0 || n <= 0) { err = "FileExpertSource: no expert geometry for the exchange buffers"; return false; } @@ -1745,9 +1755,18 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { xstage_ = nullptr; xstage_cap_ = 0; } + if ((uint64_t)n > std::numeric_limits::max() / blob) { + err = "FileExpertSource: exchange allocation size overflow"; return false; + } + const char* rotate_env = std::getenv("STRATA_EXCHANGE_ROTATE"); + const bool requested = rotate_env && std::strcmp(rotate_env, "1") == 0; + const bool uniform = std::all_of(layer_blob_bytes_.begin(), layer_blob_bytes_.end(), + [blob](uint64_t b) { return b == blob; }); + const bool eligible = requested && uniform && complement_pinned_ && !complement_partial_ && + complement_host_ && complement_device_ && complement_bytes_ > 0; const size_t total = (size_t) n * (size_t) blob; void* p = nullptr; - if (cudaHostAlloc(&p, total, cudaHostAllocDefault) == cudaSuccess && p != nullptr) { + if (cudaHostAlloc(&p, total, eligible ? cudaHostAllocMapped : cudaHostAllocDefault) == cudaSuccess && p != nullptr) { xstage_pinned_ = true; } else { (void) cudaGetLastError(); @@ -1758,16 +1777,36 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { xstage_ = (uint8_t*) p; xstage_cap_ = n; xstage_blob_ = blob; + if (requested) { + std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement"; + void* device = nullptr; + if (eligible && xstage_pinned_ && cudaHostGetDevicePointer(&device, p, 0) == cudaSuccess && device) { + try { + if (exchange_storage_.initialize(complement_offsets_, (uint8_t*)complement_host_, complement_device_, + complement_bytes_, xstage_, (const uint8_t*)device, (size_t)n, (size_t)blob, reason)) { + std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers, %llu bytes each; no host commit memcpy\n", + (long long)n, (unsigned long long)blob); + } + } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; } + } else if (eligible) { + (void) cudaGetLastError(); + reason = "exchange buffers could not be pinned and mapped"; + } + if (!exchange_storage_.active()) + std::fprintf(stderr, "FileExpertSource: exchange rotation unavailable; retaining copy path: %s\n", reason.c_str()); + } return true; } uint8_t* FileExpertSource::exchange_buffer(int64_t q) const { if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr; + if (exchange_storage_.active()) return exchange_storage_.spare((size_t)q).host; return xstage_ + (size_t) q * (size_t) xstage_blob_; } bool FileExpertSource::stage_exchange(int64_t layer, int64_t in, int64_t out, int64_t q) { - if (!has_resident(layer, in) || has_resident(layer, out) || exchange_buffer(q) == nullptr) return false; + if (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) || + exchange_buffer(q) == nullptr) return false; const size_t i_in = (size_t) layer * (size_t) n_expert_ + (size_t) in; const size_t i_out = (size_t) layer * (size_t) n_expert_ + (size_t) out; if (override_.empty()) override_.assign((size_t) blobs_, nullptr); @@ -1783,6 +1822,16 @@ int64_t FileExpertSource::commit_exchanges() { int64_t n = 0; for (const Exchange& x : staged_) { const uint8_t* src = override_[x.out]; + if (exchange_storage_.active()) { + if (!exchange_storage_.commit(x.in, x.out, (size_t)x.q, src, (size_t)x.bytes)) { + // Admitting the GPU swap after a failed RAM ownership update would lose an expert. + std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n"); + std::abort(); + } + ++n; + override_[x.out] = nullptr; + continue; + } const uint64_t at = complement_offsets_[x.in]; if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && complement_host_ != nullptr) { @@ -1796,13 +1845,57 @@ int64_t FileExpertSource::commit_exchanges() { return n; } +void FileExpertSource::commit_copies() { + if (exchange_storage_.active()) return; // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy + for (const Exchange& x : staged_) { + const uint8_t* src = override_.empty() ? nullptr : override_[x.out]; + const uint64_t at = complement_offsets_[x.in]; + if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && + complement_host_ != nullptr) + std::memcpy((uint8_t*) complement_host_ + (size_t) at, src, (size_t) x.bytes); + } +} + +int64_t FileExpertSource::commit_flip() { + int64_t n = 0; + for (const Exchange& x : staged_) { + const uint8_t* src = override_[x.out]; + if (exchange_storage_.active()) { // STRATA_EXCHANGE_ROTATE: the same ownership transfer as commit_exchanges + if (!exchange_storage_.commit(x.in, x.out, (size_t) x.q, src, (size_t) x.bytes)) { + std::fprintf(stderr, "FileExpertSource: invalid exchange rotation commit; refusing corrupt residency\n"); + std::abort(); + } + ++n; + override_[x.out] = nullptr; + continue; + } + const uint64_t at = complement_offsets_[x.in]; + // the same test as commit_copies: an exchange whose bytes were copied is the one that flips + if (src != nullptr && at != kNoComplement && at <= complement_bytes_ && x.bytes <= complement_bytes_ - at && + complement_host_ != nullptr && detail::exchange_cache_complement(complement_offsets_, x.in, x.out)) + ++n; + override_[x.out] = nullptr; + } + staged_.clear(); + exchanges_ += n; + return n; +} + +const uint8_t* FileExpertSource::resident_blob(int64_t layer, int64_t expert) const { + if (!complement_ready_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || + expert >= n_expert_) return nullptr; + const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (index >= complement_offsets_.size()) return nullptr; + return resident_blob(index); // through the rotation's ownership table when STRATA_EXCHANGE_ROTATE is on +} + const uint8_t* FileExpertSource::blob(int64_t layer, int64_t expert) { if (base_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return nullptr; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; const uint8_t* result = nullptr; bool from_files = true; if (complement_ready_) { - result = detail::cache_complement_blob_or_fallback(index, complement_offsets_, complement_host_, nullptr); + result = resident_blob(index); if (result != nullptr) { ram_reads_.fetch_add(1, std::memory_order_relaxed); from_files = false; @@ -1829,6 +1922,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const { if (!complement_ready_ || !complement_pinned_ || complement_host_ == nullptr || layer < 0 || expert < 0 || layer >= n_layers_ || expert >= n_expert_) return false; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (exchange_storage_.active()) return exchange_storage_.resident(index).host != nullptr; if (index >= complement_offsets_.size() || complement_offsets_[index] == kNoComplement) return false; // a partial pin (CS-T): only the registered prefix return !complement_partial_ || @@ -1838,6 +1932,7 @@ bool FileExpertSource::pinned(int64_t layer, int64_t expert) const { const uint8_t* FileExpertSource::device_alias(int64_t layer, int64_t expert) const { if (!pinned(layer, expert) || complement_device_ == nullptr) return nullptr; const size_t index = (size_t) layer * (size_t) n_expert_ + (size_t) expert; + if (exchange_storage_.active()) return exchange_storage_.resident(index).device; return complement_device_ + (size_t) complement_offsets_[index]; } @@ -2020,6 +2115,15 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 if (d.plan != nullptr && n <= kMaxWindowEntries && n <= d.plan->cap) { int64_t distinct[kMaxWindowEntries], first_of[kMaxWindowEntries]; int nd = 0, nmiss = 0; + // a helper GPU (RemoteExperts) holding the expert computes it in its own VRAM once begin() claims the row: like + // the peer tier's, such an expert is no miss of this plan and never part of the PCIe share, which would read it + // over the primary's link instead (2x RX 6900 XT, IQ3_S, --remote-expert-opt with the probed share 0.39: ~4 + // helper experts per layer-window moved to PCIe, 59 ms per window against 34 ms) + auto helper_holds = [&](int32_t e) { + for (int r = 0; r < d.remote_count; ++r) + if (d.remote[r]->holds(d.layers, e)) return true; + return false; + }; for (int64_t i = 0; i < n; ++i) { first_of[i] = i; for (int64_t j = 0; j < i; ++j) @@ -2028,7 +2132,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 distinct[nd++] = i; const int32_t e = ids[i]; if (e >= 0 && e < d.n_expert && d.host_res[(size_t) d.layers * (size_t) d.n_expert + (size_t) e] < 0 && - !(d.peer != nullptr && d.peer->has(d.layers, e))) ++nmiss; + !(d.peer != nullptr && d.peer->has(d.layers, e)) && !helper_holds(e)) ++nmiss; } } const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); @@ -2050,6 +2154,8 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 : (size_t) slot * (size_t) d.cache_blob)); } else if (d.peer != nullptr && d.peer->has(d.layers, e)) { kd = 2; // multi-GPU: the second GPU computes it + } else if (helper_holds(e)) { + // left to the helper: kind -1 until RemoteExperts::begin() claims the row (see above) } else { if (miss_rank >= nmiss - m && fetches < P.staging_cap && fetches < 64) { const uint8_t* src = d.src->pinned(d.layers, e) ? d.src->blob(d.layers, e) : nullptr; diff --git a/src/core/mtp.cpp b/src/core/mtp.cpp index 130dc275..da0cbacd 100644 --- a/src/core/mtp.cpp +++ b/src/core/mtp.cpp @@ -129,14 +129,16 @@ MtpDrafter::~MtpDrafter() { if (h_cparams_) cudaFreeHost(h_cparams_); if (h_chist_) cudaFreeHost(h_chist_); if (cs_) cudaStreamDestroy(cs_); - if (dense_) cudaFree(dense_); - if (experts_) cudaFree(experts_); + if (owns_weights_ && dense_) cudaFree(dense_); + if (owns_weights_ && experts_) cudaFree(experts_); if (state_arena_) cudaFree(state_arena_); if (arena_) cudaFree(arena_); if (head_logits_) cudaFree(head_logits_); - if (dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } - if (dvocab_) cudaFree(dvocab_); - void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_}; + if (owns_draft_head_ && dhead_) { strata::kernels::native_q6_k_unpack(dhead_); cudaFree(dhead_); } + if (owns_draft_head_ && dvocab_) cudaFree(dvocab_); + if (ev_chain_) cudaEventDestroy(ev_chain_); + for (cudaEvent_t e : ev_step_) if (e) cudaEventDestroy(e); + void* hosts[] = {h_tok_, h_step_, h_pos_, h_row_, h_out_, h_prob_, h_force_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -222,7 +224,7 @@ bool MtpDrafter::make_q4_head(std::string& err) { } bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, SessionState& ss, int max_t, std::string& err, - int64_t window) { + int64_t window, const MtpDrafter* shared) { cudaGetDevice(&device_); // a layer split's last stage on another GPU: the drafter lives there g_ = &g; ss_ = &ss; @@ -230,11 +232,23 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session max_t_ = max_t; rt_dir_ = rt_dir; if (max_t < 1 || max_t > strata::kernels::kVerifyMaxT) { err = "mtp: max_t out of range"; return false; } + if (shared != nullptr) { + if (shared->device_ != device_ || shared->g_ != &g || shared->dense_ == nullptr || + shared->experts_ == nullptr || shared->rt_dir_ != rt_dir) { + err = "mtp: incompatible shared weights"; + return false; + } + dense_ = shared->dense_; + experts_ = shared->experts_; + tensors_ = shared->tensors_; + owns_weights_ = false; + owns_draft_head_ = false; + } // Loader fix (0.1.15+loaderfix.2): the two reads below are the whole “drafter files” cost; reporting // them apart from the rest of the stage is what makes the next regression visible. const auto t_files = std::chrono::steady_clock::now(); // ---- the index and the dense weights - { + if (shared == nullptr) { std::ifstream idx(rt_dir + "/dense.txt"); if (!idx) { err = "mtp: cannot open " + rt_dir + "/dense.txt (run tools/mtp_rt.py)"; return false; } std::string line; @@ -262,7 +276,7 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session if (q4_ && !make_q4_dense(blob, err)) return false; } // ---- the 512 routed experts, one blob each - { + if (shared == nullptr) { const uint64_t bytes = (uint64_t) g.n_expert * strata::kernels::cpu::BLOB; // Loader fix (0.1.15+loaderfix.2): each 64 MiB read below reached the disk as ~16k 4095-byte reads under // MSVC's `basic_filebuf::xsgetn`, which is what made 675 MiB of drafter experts take minutes. @@ -331,8 +345,10 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session mapped(R2 * NH * 4 + 64, (void**) &h_pos_, (void**) &m_pos_) && mapped(64, (void**) &h_row_, (void**) &m_row_) && mapped(T * 4 + 64, (void**) &h_out_, (void**) &m_out_) && - mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_); + mapped(T * 4 + 64, (void**) &h_prob_, (void**) &m_prob_) && + (!force_on_ || mapped(64, (void**) &h_force_, (void**) &m_force_)); if (!ok) { err = "mtp: mapped staging failed"; return false; } + if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1; auto carve = [&](Bump& b) { tok_ = b.take(T); step_ = b.take(R2 * 4); pos_ = b.take(R2 * NH); row_ = b.take(4); ident_ = b.take(T * (uint64_t) cap_); @@ -375,13 +391,28 @@ bool MtpDrafter::load(const std::string& rt_dir, const ModelGeometry& g, Session for (int64_t i = 0; i < cap_; ++i) id[(size_t) (t * (uint64_t) cap_ + (uint64_t) i)] = (int32_t) i; cudaMemcpy(ident_, id.data(), id.size() * 4, cudaMemcpyHostToDevice); } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } + // --pipeline-windows 2 (the forcing graphs): the chain shares its card with stage 1's windows and the next launch + // on stage 0 waits for it, so its stream gets the highest priority there (STRATA_MTP_PRIORITY=0: the default) + bool prio = false; +#if !defined(STRATA_USE_HIP) // (HIP: the default priority) + static const bool hi_prio = [] { const char* v = std::getenv("STRATA_MTP_PRIORITY"); return v == nullptr || std::atoi(v) != 0; }(); + int prio_lo = 0, prio_hi = 0; + if (force_on_ && hi_prio && cudaDeviceGetStreamPriorityRange(&prio_lo, &prio_hi) == cudaSuccess) + prio = cudaStreamCreateWithPriority(&cs_, cudaStreamNonBlocking, prio_hi) == cudaSuccess; + cudaGetLastError(); +#endif + if (!prio && cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "mtp: stream"; return false; } const double files_s = std::chrono::duration(std::chrono::steady_clock::now() - t_files).count(); - std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n", - (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0, - (double) tensors_.back().off / 1048576.0, files_s, - files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) / - 1048576.0 / files_s : 0.0); + if (shared != nullptr) { + std::fprintf(stderr, "strata mtp: shared draft weights, %.0f MiB of private state and buffers\n", + (double) vram_ / 1048576.0); + } else { + std::fprintf(stderr, "strata mtp: draft layer loaded, %.0f MiB of VRAM (experts %.0f, dense %.0f), files read in %.2f s (%.0f MiB/s)\n", + (double) vram_ / 1048576.0, (double) g.n_expert * strata::kernels::cpu::BLOB / 1048576.0, + (double) tensors_.back().off / 1048576.0, files_s, + files_s > 0 ? ((double) g.n_expert * strata::kernels::cpu::BLOB + (double) tensors_.back().off) / + 1048576.0 / files_s : 0.0); + } return true; } @@ -421,7 +452,7 @@ void MtpDrafter::record_top2(int j) { uint64_t MtpDrafter::bind_bytes(uint64_t head_row_bytes, int64_t n_vocab) const { uint64_t bytes = head_logits_ ? 0 : (uint64_t) max_t_ * (uint64_t) n_vocab * sizeof(float); - if (dhead_ == nullptr && !full_head_env()) { + if (dhead_ == nullptr && owns_draft_head_ && !full_head_env()) { if (FILE* f = std::fopen(vocab_file().c_str(), "rb")) { std::fseek(f, 0, SEEK_END); const long size = std::ftell(f); @@ -529,7 +560,8 @@ void draft_head_hint(int64_t n_tokens, int64_t row_bytes) { } } // namespace -bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err) { +bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float* window_R, std::string& err, + const MtpDrafter* shared) { const OnDevice on_device(device_); wt_ = &wt; head_ = head; @@ -543,8 +575,19 @@ bool MtpDrafter::bind(const WeightTable& wt, const NativeHead* head, const float err = "mtp: the draft logits do not fit"; return false; } + if (shared != nullptr) { + if (shared->head_ != head || shared->device_ != device_ || + shared->n_vocab_ != n_vocab_) { + err = "mtp: incompatible shared draft head"; + return false; + } + dhead_ = shared->dhead_; + dvocab_ = shared->dvocab_; + n_dvocab_ = shared->n_dvocab_; + owns_draft_head_ = false; + } // the draft head's token subset, when tools/draft_vocab.py wrote one - if (dhead_ == nullptr && !full_head_env()) { + if (dhead_ == nullptr && shared == nullptr && !full_head_env()) { std::vector raw; if (read_file(vocab_file(), raw) && raw.size() >= 4 && raw.size() % 4 == 0) { n_dvocab_ = (int64_t) (raw.size() / 4); @@ -845,6 +888,7 @@ bool MtpDrafter::capture_round(int T, bool coupled, std::string& err) { coupled_rec_ = false; } if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, 0, cs_, probs_, m_prob_); + if (ok && force_on_ && !coupled) force_token(tok_, m_force_, 0, cs_); // chain_launch: step 1's input return finish_capture(cs_, ok, exec, coupled ? "round (coupled)" : "round", err); } @@ -864,6 +908,7 @@ bool MtpDrafter::capture_step(int j, bool coupled, std::string& err) { bool ok = record_forward(1, row, cs_, err); coupled_rec_ = false; if (ok) mtp_select(R_, HCN, out_ids_, row_ + 1, Rin_, tok_, m_out_, j, cs_, probs_, m_prob_); + if (ok && force_on_ && !coupled) force_token(tok_, m_force_, j, cs_); // chain_launch: step j+1's input return finish_capture(cs_, ok, exec, coupled ? "step (coupled)" : "step", err); } @@ -877,7 +922,26 @@ void MtpDrafter::kv_restore(int64_t upto) { cudaStreamSynchronize(cs_); } -bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err) { +bool MtpDrafter::prepare_prefill(std::string& err) { + const OnDevice on_device(device_); + const int64_t per_row = 1 + 4 + g_->n_head; + if (pf_cap_ < (int64_t) max_t_ * per_row) { + if (pf_dev_) cudaFree(pf_dev_); + pf_dev_ = nullptr; + pf_cap_ = 0; + if (cudaMalloc((void**) &pf_dev_, (size_t) (max_t_ * per_row) * sizeof(int32_t)) != cudaSuccess) { + err = "mtp prefill: the input records do not fit"; + return false; + } + pf_cap_ = max_t_ * per_row; + } + for (int T = 1; T <= max_t_; ++T) + if (!capture_prefill_dev(T, err)) return false; // (STRATA_MTP_PREFILL_SYNC's loop syncs anyway) + return true; +} + +bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_t n, int64_t cell0, std::string& err, + bool sync) { const OnDevice on_device(device_); const Clock::time_point t0 = Clock::now(); const int64_t HCN = g_->hc * g_->n_embd; @@ -947,6 +1011,11 @@ bool MtpDrafter::prefill(const float* R_rows, const int32_t* next_tokens, int64_ return false; } } + if (!sync) { // the caller orders on stream(); the records are staged (a pageable copy returns once taken) + (void) cudaStreamQuery(cs_); + ms_prefill += ms_since(t0); + return true; + } if (cudaStreamSynchronize(cs_) != cudaSuccess) { err = std::string("mtp prefill: ") + cudaGetErrorString(cudaGetLastError()); return false; @@ -983,6 +1052,7 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* float* probs, float min_p, int* n_drafts) { const OnDevice on_device(device_); if (T < 1 || T > max_t_ || a < 0 || a >= T) { err = "mtp: draft arguments out of range"; return false; } + if (chain_live_) { err = "mtp: a pipelined chain is still in flight"; return false; } const bool cp = coupled_active_; // coupled draft sampling for this request: its own graphs if (!capture_round(T, cp, err)) return false; const int max_steps = std::min(max_t_ - 1, max_drafts_); @@ -1007,7 +1077,9 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* for (int j = 0; j < max_steps; ++j) ((volatile int32_t*) h_out_)[j] = -1; h_row_[0] = a; h_row_[1] = 0; + if (h_force_ != nullptr) for (int j = 0; j < 16; ++j) h_force_[j] = -1; // the forcing kernels: no-ops here std::atomic_thread_fence(std::memory_order_seq_cst); + if (!stage_source_R(T, err)) return false; SessionState* const pss = ple_ss_ ? ple_ss_ : ss_; const bool do_ple = pss != nullptr && pss->ple.ready() && pss->ple.table != nullptr; @@ -1103,6 +1175,117 @@ bool MtpDrafter::draft(int T, const int32_t* tokens, int64_t p, int a, int32_t* return true; } +bool MtpDrafter::stage_source_R(int T, std::string& err) { + if (src_R_ == nullptr || src_R_ == window_R_) return true; + if (cudaMemcpyAsync((void*) window_R_, src_R_, (size_t) T * (size_t) (g_->hc * g_->n_embd) * sizeof(float), + cudaMemcpyDeviceToDevice, cs_) != cudaSuccess) { + err = "mtp: staging the window's residual rows failed"; + return false; + } + return true; +} + +bool MtpDrafter::prepare_chain(std::string& err) { + const OnDevice on_device(device_); + if (!force_on_ || h_force_ == nullptr) { err = "mtp: chains need set_force_capture before load"; return false; } + for (int T = 1; T <= max_t_; ++T) + if (!capture_round(T, false, err)) return false; + for (int j = 1; j <= max_t_ - 2; ++j) + if (!capture_step(j, false, err)) return false; + if (ev_chain_ == nullptr && cudaEventCreateWithFlags(&ev_chain_, cudaEventDisableTiming) != cudaSuccess) { + err = "mtp: event creation failed"; + return false; + } + for (cudaEvent_t& e : ev_step_) + if (e == nullptr && cudaEventCreateWithFlags(&e, cudaEventDisableTiming) != cudaSuccess) { + err = "mtp: event creation failed"; + return false; + } + return true; +} + +bool MtpDrafter::chain_launch(int T, const int32_t* tokens, int64_t p, int a, const int32_t* force, int n_force, + int n_out, int n_early, std::string& err) { + const OnDevice on_device(device_); + if (chain_live_) { err = "mtp: a chain is already in flight"; return false; } + if (!force_on_ || ev_chain_ == nullptr) { err = "mtp: chains need prepare_chain"; return false; } + if (T < 1 || T > max_t_ || a < 0 || a >= T || n_out < 1 || n_out > max_t_ - 1 || n_force < 0 || n_force > n_out || + n_force > 16) { + err = "mtp: chain arguments out of range"; + return false; + } + if (round_exec_[T] == nullptr) { err = "mtp: chain graphs not prepared"; return false; } + for (int j = 1; j < n_out; ++j) + if (step_exec_[j] == nullptr) { err = "mtp: chain graphs not prepared"; return false; } + const Clock::time_point t0 = Clock::now(); + const int64_t NH = g_->n_head; + auto put = [&](int row, int64_t cell) { + h_step_[row * 4 + 0] = (int32_t) cell; + h_step_[row * 4 + 1] = (int32_t) (cell + 1); + h_step_[row * 4 + 2] = (int32_t) ((cell + 1) / 4); + h_step_[row * 4 + 3] = (int32_t) (cell + 1); + for (int64_t h = 0; h < NH; ++h) h_pos_[row * NH + h] = (int32_t) cell; + }; + for (int t = 0; t < T; ++t) { + h_tok_[t] = tokens[t]; + put(t, p + t); + } + put(2 * max_t_ - 1, p + a); // output 0's cell + for (int j = 1; j < n_out; ++j) put(max_t_ + j - 1, p + a + j); // every step's cell, staged at once + for (int j = 0; j < 16; ++j) h_force_[j] = j < n_force ? force[j] : -1; + h_row_[0] = a; + h_row_[1] = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + if (!stage_source_R(T, err)) return false; + chain_early_ = std::max(0, std::min(n_early, n_out)); + bool ok = cudaGraphLaunch(round_exec_[T], cs_) == cudaSuccess; + if (ok && chain_early_ >= 1) ok = cudaEventRecord(ev_step_[0], cs_) == cudaSuccess; + for (int j = 1; ok && j < n_out; ++j) { + ok = cudaGraphLaunch(step_exec_[j], cs_) == cudaSuccess; + if (ok && j < chain_early_) ok = cudaEventRecord(ev_step_[j], cs_) == cudaSuccess; + } + if (!ok || cudaEventRecord(ev_chain_, cs_) != cudaSuccess) { + err = std::string("mtp chain: ") + cudaGetErrorString(cudaGetLastError()); + return false; + } + (void) cudaStreamQuery(cs_); // WDDM: submit now + steps_seen_ = 0; + chain_live_ = true; + chain_n_ = n_out; + ms_draft += ms_since(t0); + ++rounds; + return true; +} + +int MtpDrafter::chain_outputs_ready(std::string& err) { + if (!chain_live_) return chain_n_; + const OnDevice on_device(device_); + while (steps_seen_ < chain_early_) { + const cudaError_t q = cudaEventQuery(ev_step_[steps_seen_]); + if (q == cudaErrorNotReady) break; + if (q != cudaSuccess) { err = std::string("mtp chain: ") + cudaGetErrorString(q); return -1; } + chain_tok_[steps_seen_] = ((volatile int32_t*) h_out_)[steps_seen_]; + chain_prob_[steps_seen_] = ((volatile float*) h_prob_)[steps_seen_]; + ++steps_seen_; + } + return steps_seen_; +} + +int MtpDrafter::chain_poll(std::string& err) { + if (!chain_live_) return 1; + const OnDevice on_device(device_); + const cudaError_t q = cudaEventQuery(ev_chain_); + if (q == cudaErrorNotReady) return 0; + chain_live_ = false; + if (q != cudaSuccess) { err = std::string("mtp chain: ") + cudaGetErrorString(q); return -1; } + for (int j = 0; j < chain_n_; ++j) { + chain_tok_[j] = ((volatile int32_t*) h_out_)[j]; + chain_prob_[j] = ((volatile float*) h_prob_)[j]; + } + for (int j = chain_n_; j < 8; ++j) { chain_tok_[j] = 0; chain_prob_[j] = 0.0f; } + return 1; +} + bool MtpDrafter::draft_first(int T, const float* R_row, int32_t token, int64_t cell, int32_t* drafts, std::string& err, float* probs, float min_p, int* n_drafts) { const OnDevice on_device(device_); diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 33f0a601..d6bd65d0 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -294,10 +294,13 @@ Verifier::~Verifier() { if (arena_b_) cudaFree(arena_b_); if (h_commitb_) cudaFreeHost(h_commitb_); if (qcnt_) cudaFree(qcnt_); - if (cs_) cudaStreamDestroy(cs_); + if (cs_ && cs_ != ext_stream_) cudaStreamDestroy(cs_); // set_stream: the stage's stream, shared, not ours if (sh_cs_) cudaStreamDestroy(sh_cs_); if (copy_) { cudaStreamSynchronize(copy_); cudaStreamDestroy(copy_); } if (commit_done_) cudaEventDestroy(commit_done_); + if (ev_done_) cudaEventDestroy(ev_done_); + if (ev_commit_) cudaEventDestroy(ev_commit_); + if (prof_pin_) cudaFreeHost(prof_pin_); if (ev_fork_) cudaEventDestroy(ev_fork_); if (ev_join_) cudaEventDestroy(ev_join_); if (arena_) cudaFree(arena_); @@ -488,8 +491,9 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& err = "verify: copy stream create failed"; return false; } - if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess || - cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) { + if (ext_stream_ != nullptr) cs_ = ext_stream_; // set_stream (pipelined windows): the stage's shared stream + else if (cudaStreamCreateWithFlags(&cs_, cudaStreamNonBlocking) != cudaSuccess) cs_ = nullptr; + if (cs_ == nullptr || cudaStreamCreateWithFlags(&sh_cs_, cudaStreamNonBlocking) != cudaSuccess) { err = "verify: stream create failed"; return false; } @@ -525,7 +529,8 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& // exact, but neutral on RIBPC 1-2 GPUs: off by default) { const char* v = std::getenv("STRATA_VERIFY_DEVICE_PLAN"); - device_plan_ = !all_resident_ && (v != nullptr && std::atoi(v) != 0); + // (not with set_always_publish: the device table may lag the host's while windows are in flight) + device_plan_ = !all_resident_ && !always_publish_ && (v != nullptr && std::atoi(v) != 0); } // (halo's STRATA_VERIFY_RESIDENT=1 is this window's all_resident_ graph above, which 0.1.39 has on by default) if (g_qfuse()) { // S26: the HC read's q8_1 group counters, zeroed once (each launch leaves them zero) @@ -777,13 +782,15 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { if (!q8_attn) native_quantize_q8_1(xm, xq_, (int) N, n, cs); native_mmvq(wqkv->native_type, wqkv->native_data, xq_, qkv + (size_t) tb * C, (int) N, (int) C, n, cs); stamp(l, 2, grp); - if (batch_rec_) { // each row from its own slot's conv history, one row each - for (int t = tb; t < te; ++t) { - SessionState& sx = slot_ss(t); + if (batch_rec_) { // contiguous rows may be proposals for the same slot + for (int t = tb; t < te;) { + const int first = t; + while (t < te && brow_[t] == brow_[first]) ++t; + SessionState& sx = slot_ss(first); const float* cx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - gdn_conv_l2_multi(cx, qkv + (size_t) t * C, (const float*) wc->data, hb + (size_t) t * C, (int) C, - (int) (2 * HK), EPS, 1, cs, 0); + gdn_conv_l2_multi(cx, qkv + (size_t) first * C, (const float*) wc->data, + hb + (size_t) first * C, (int) C, (int) (2 * HK), EPS, t - first, cs, 0); } } else gdn_conv_l2_multi(conv, qkv, (const float*) wc->data, hb, (int) C, (int) (2 * HK), EPS, n, cs, tb); @@ -795,13 +802,16 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { native_mmvq(wg->native_type, wg->native_data, xq_, z_ + (size_t) tb * ZV, (int) N, (int) ZV, n, cs); stamp(l, 5, grp); // the recurrence from the untouched state over tokens [0, te); outputs only for this group's - if (batch_rec_) { // each row's recurrence from its own slot's state, one token - for (int t = tb; t < te; ++t) { - SessionState& sx = slot_ss(t); + if (batch_rec_) { // each slot's recurrence over its own proposed-token group + for (int t = tb; t < te;) { + const int first = t; + while (t < te && brow_[t] == brow_[first]) ++t; + SessionState& sx = slot_ss(first); float* stx = sx.gdn_state + (size_t) (gi - sx.gdn_ord0) * gdn_floats; - gdn_step_norm_multi(stx, hb + (size_t) t * C, (int) C, gate + (size_t) t * HV, beta + (size_t) t * HV, - z_ + (size_t) t * ZV, (const float*) wnm->data, EPS, y_ + (size_t) t * ZV, - (int) HK, (int) HV, 1, nullptr, cs, 0); + gdn_step_norm_multi(stx, hb + (size_t) first * C, (int) C, gate + (size_t) first * HV, + beta + (size_t) first * HV, z_ + (size_t) first * ZV, + (const float*) wnm->data, EPS, y_ + (size_t) first * ZV, + (int) HK, (int) HV, t - first, nullptr, cs, 0); } } else gdn_step_norm_multi(state, hb, (int) C, gate, beta, z_, (const float*) wnm->data, EPS, y_, (int) HK, @@ -848,10 +858,11 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { fwht256_inplace_cuda(vcur_ + tb * NKV * HD, (int64_t) n * NKV, cs); } stamp(l, 8, grp); - if (batch_rec_) { // every slot's indexer tail, restored by its commit + if (batch_rec_) { // snapshot each slot's indexer tail before its first proposed row for (int t = tb; t < te; ++t) - copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, slot_ss(t).qsa_states[qi].idx_tail, - TS, cs); + if (t == tb || brow_[t] != brow_[t - 1]) + copy_from_mapped(tail_snap_b_ + ((size_t) brow_[t] * nQall + qi) * TS, + slot_ss(t).qsa_states[qi].idx_tail, TS, cs); } else if (grp == 0) copy_from_mapped(tail_snap_ + (size_t) qi * TS, st.idx_tail, TS, cs); const bool kv_multi = g_lfuse() && !st.kv_hybrid && !st.kv_q4 && st.kv_int8 && n > 1; // S26 STRATA_LFUSE @@ -1024,7 +1035,9 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { m_ids_ + tb * K, m_w_ + tb * K, m_seq_, (uint32_t) ((l - lb_) * G + grp + 1), cs); else #endif - if (remote_opt_) // #578: the helper GPUs reduce with the routing weights - publish them + // #578: the helper GPUs reduce with the routing weights - publish them; set_always_publish: the rows + // whatever the device's residency table says (pipelined windows) + if (remote_opt_ || always_publish_) doorbell_publish(xm, ids_ + tb * K, w_ + tb * K, (int64_t) n * N, (int64_t) n * K, m_x_ + tb * N, m_ids_ + tb * K, m_w_ + tb * K, m_seq_, cs); else { @@ -1480,10 +1493,14 @@ void Verifier::stage_inputs(int T, const int32_t* tokens, int64_t pos0) { } void Verifier::collect_profile() { - const ModelGeometry& g = *g_; cudaMemcpy(prof_h_.data(), prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost); + accumulate_profile(prof_h_.data()); +} + +void Verifier::accumulate_profile(const unsigned long long* stamps) { + const ModelGeometry& g = *g_; const int64_t L = g.n_layers; - auto at = [&](int64_t l, int i) { return prof_h_[(size_t) (l * kProfPer + i)]; }; + auto at = [&](int64_t l, int i) { return stamps[(size_t) (l * kProfPer + i)]; }; // D8: the derived columns below read stamps the hc-read kernels write themselves or the next // layer's first. A slot no kernel stamped is 0 and its unsigned difference wrapped to ~1e19 ns - // which is why (gap)/head/hc0 printed ~1e14 ms per window. A missing or out-of-order stamp now @@ -1491,7 +1508,8 @@ void Verifier::collect_profile() { const auto gap = [](unsigned long long to, unsigned long long from) { return (from != 0 && to != 0 && to >= from) ? (double) (to - from) : 0.0; }; - for (int64_t l = 0; l < L; ++l) { + // only this stage's layers [lb_, le_) are ever stamped (a layer split); the head only on the last stage + for (int64_t l = lb_; l < le_; ++l) { const int kind = is_qsa_layer(g, l) ? 1 : 0; unsigned long long prev = at(l, 0); for (int i = 1; i <= 24; ++i) { @@ -1500,7 +1518,7 @@ void Verifier::collect_profile() { prof_sum_[kind][i] += (double) (x - prev); prev = x; } - if (l + 1 < L) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); + if (l + 1 < le_) prof_sum_[kind][25] += gap(at(l + 1, 0), at(l, 24)); const double dn = gap(at(l, 27), at(l, 0)), dd = gap(at(l, 28), at(l, 27)), du = gap(at(l, 1), at(l, 28)); if (dn > 0 && dd > 0 && du > 0) { // the split exists: show it split, not twice prof_sum_[kind][27] += dn; // hc-read0: norm @@ -1509,7 +1527,7 @@ void Verifier::collect_profile() { prof_sum_[kind][1] -= gap(at(l, 1), at(l, 0)); // (hc-read0 shown split) } } - prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); + if (le_ == L) prof_sum_[0][26] += gap(at(L, 1), at(L, 0)); ++prof_windows_; } @@ -1876,8 +1894,8 @@ bool Verifier::wait_commit(std::string& err) { bool Verifier::init_slots(const std::vector& slots, std::string& err) { const OnDevice on_device(device_); if (g_ == nullptr || ss_ == nullptr) { err = "verify: init_slots before init"; return false; } - if (slots.empty() || (int) slots.size() > max_t_) { - err = "verify: init_slots needs 1.." + std::to_string(max_t_) + " sessions"; + if (slots.empty()) { + err = "verify: init_slots needs at least one session"; return false; } for (SessionState* x : slots) { @@ -1943,7 +1961,7 @@ bool Verifier::capture_batch(const int* rows, int S, int hbase, std::string& err } bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::string& err) { - cudaGraphExec_t& cex = commit_bm_[batch_key(rows, S, hbase)]; + cudaGraphExec_t& cex = commit_bm_[bkey(rows, S, hbase)]; if (cex != nullptr) return true; using namespace strata::kernels; const ModelGeometry& g = *g_; @@ -1961,7 +1979,8 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri bool ok = true; try { for (int t = 0; t < S; ++t) - copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_); + if (t == 0 || rows[t] != rows[t - 1]) + copy_i32_from_mapped(commitb_ + (size_t) rows[t] * CB, m_commitb_ + (size_t) rows[t] * CB, CB, cs_); int64_t qsa_index = 0, gdn_index = 0; for (int64_t l = 0; l < lb_; ++l) (is_qsa_layer(g, l) ? qsa_index : gdn_index) += 1; for (int64_t l = lb_; l < le_ && ok; ++l) { @@ -1969,36 +1988,50 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri if (!is_qsa_layer(g, l)) { const WeightRef* wnm = need(v, "ssm_norm.weight", err); if (!wnm) { ok = false; break; } - for (int t = 0; t < S; ++t) { - SessionState& sx = *slots_[(size_t) rows[t]]; - const int32_t* keep = commitb_ + (size_t) rows[t] * CB; + for (int t = 0; t < S;) { + const int first = t; + while (t < S && rows[t] == rows[first]) ++t; + SessionState& sx = *slots_[(size_t) rows[first]]; + const int32_t* keep = commitb_ + (size_t) rows[first] * CB; float* state = sx.gdn_state + (size_t) (gdn_index - sx.gdn_ord0) * gdn_floats; float* conv = state + (uint64_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size; - gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C, keep, cs_); - gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) t * C, (int) C, - gate_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, - beta_L_ + (size_t) gdn_index * MT * HV + (size_t) t * HV, z_ + (size_t) t * ZV, - (const float*) wnm->data, EPS, y_dummy_ + (size_t) t * ZV, (int) g.ssm_k_heads, - (int) HV, 1, keep, cs_); + gdn_conv_commit(conv, qkv_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, + (int) C, keep, cs_); + gdn_step_norm_multi(state, h_L_ + (size_t) gdn_index * MT * C + (size_t) first * C, (int) C, + gate_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV, + beta_L_ + (size_t) gdn_index * MT * HV + (size_t) first * HV, + z_ + (size_t) first * ZV, (const float*) wnm->data, EPS, + y_dummy_ + (size_t) first * ZV, (int) g.ssm_k_heads, + (int) HV, t - first, keep, cs_, + t - first > 1 ? t - first : 0); // a 1-row group keeps the 0.1.39 kernel } ++gdn_index; } else { const WeightRef* wikn = need(v, "indexer.k_norm.weight", err); if (!wikn) { ok = false; break; } - for (int t = 0; t < S; ++t) { - const QsaState& st = slots_[(size_t) rows[t]]->qsa_states[qsa_index]; - copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[t] * nQ + qsa_index) * TS, TS, cs_); + for (int t = 0; t < S;) { + const int first = t; + while (t < S && rows[t] == rows[first]) ++t; + const QsaState& st = slots_[(size_t) rows[first]]->qsa_states[qsa_index]; + copy_from_mapped(st.idx_tail, tail_snap_b_ + ((size_t) rows[first] * nQ + qsa_index) * TS, + TS, cs_); const QsaIndexerBuffers ib{st.idx_tail, st.idx_dead, st.idx_pooled, st.idx_block_pos}; - native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + t) * ID, commitb_ + (size_t) rows[t] * CB + 2, - 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, rope_scaling(), cs_); + for (int u = first; u < t; ++u) + native_qsa_indexer_append(idx_raw_L_ + (size_t) (qsa_index * MT + u) * ID, + commitb_ + (size_t) rows[first] * CB + 2 + (u - first), + 0, (const float*) wikn->data, EPS, ib, s, st.max_cells, + rope_scaling(), cs_); } ++qsa_index; } } if (ok && ss_->ple.ready() && ple_stage()) - for (int t = 0; t < S; ++t) - copy_indexed(slots_[(size_t) rows[t]]->ple_hist, hist_snap_ + (size_t) t * HS, HS, - commitb_ + (size_t) rows[t] * CB + 1, HS, cs_); + for (int t = 0; t < S;) { + const int first = t; + while (t < S && rows[t] == rows[first]) ++t; + copy_indexed(slots_[(size_t) rows[first]]->ple_hist, hist_snap_ + (size_t) first * HS, + HS, commitb_ + (size_t) rows[first] * CB + 1, HS, cs_); + } } catch (const std::exception& e) { err = std::string("verify batch commit: ") + e.what(); ok = false; @@ -2021,14 +2054,29 @@ bool Verifier::capture_commit_batch(const int* rows, int S, int hbase, std::stri bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tokens, const int64_t* pos, std::string& err) { using namespace strata::kernels; - if (S < 1 || S > max_t_ || hbase < 0 || hbase + S > (int) slots_.size()) { + if (S < 1 || S > max_t_ || hbase < 0 || + (next_ != nullptr && hbase + S > (int) slots_.size())) { err = "verify: batch rows out of range (init_slots)"; return false; } for (int t = 0; t < S; ++t) { - bool dup = false; - for (int u = 0; u < t; ++u) dup = dup || rows[u] == rows[t]; - if (rows[t] < 0 || rows[t] >= (int) slots_.size() || dup) { err = "verify: a batch row's slot is out of range or twice"; return false; } + if (rows[t] < 0 || rows[t] >= (int) slots_.size()) { + err = "verify: a batch row's slot is out of range"; + return false; + } + for (int u = 0; u < t - 1; ++u) + if (rows[u] == rows[t] && rows[t - 1] != rows[t]) { + err = "verify: a slot's proposed rows must be contiguous"; + return false; + } + if (t > 0 && rows[t] == rows[t - 1] && pos[t] != pos[t - 1] + 1) { + err = "verify: proposed rows must have consecutive positions"; + return false; + } + if (t > 0 && rows[t] == rows[t - 1] && next_ != nullptr) { + err = "verify: grouped slot rows do not support a layer split yet"; + return false; + } } if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } const ModelGeometry& g = *g_; @@ -2038,6 +2086,34 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok return false; } refresh_ar(); + // --batch-mtp only (limit 0 = 0.1.39: no eviction): slot rotation creates new layouts; bound the captured graph + // pairs, evicting the least recently used layout. + if (batch_graph_limit_ > 0) { + const auto key = bkey(rows, S, hbase); + if (exec_bm_.find(key) == exec_bm_.end() && exec_bm_.size() >= batch_graph_limit_) { + if (cudaStreamSynchronize(cs_) != cudaSuccess) { + err = "verify: synchronizing before batch graph eviction failed"; + return false; + } + auto old = exec_bm_.begin(); + uint64_t oldest = UINT64_MAX; + for (auto it = exec_bm_.begin(); it != exec_bm_.end(); ++it) { + const auto u = bm_used_.find(it->first); + const uint64_t t = u == bm_used_.end() ? 0 : u->second; + if (t < oldest) { oldest = t; old = it; } + } + const auto old_key = old->first; + if (old->second) cudaGraphExecDestroy(old->second); + exec_bm_.erase(old); + bm_used_.erase(old_key); + auto commit_old = commit_bm_.find(old_key); + if (commit_old != commit_bm_.end()) { + if (commit_old->second) cudaGraphExecDestroy(commit_old->second); + commit_bm_.erase(commit_old); + } + } + bm_used_[key] = ++bm_tick_; + } if (!capture_batch(rows, S, hbase, err) || !capture_commit_batch(rows, S, hbase, err)) return false; const Clock::time_point t0 = Clock::now(); const QsaShapes s = shapes_of(g); @@ -2055,18 +2131,25 @@ bool Verifier::stage_batch(const int* rows, int S, int hbase, const int32_t* tok for (int t = 0; t < S; ++t) { const SessionState& sx = *slots_[(size_t) rows[t]]; int32_t prev[2] = {sx.ple_prev[0], sx.ple_prev[1]}; + if (t > 0 && rows[t] == rows[t - 1]) { + prev[0] = t > 1 && rows[t - 2] == rows[t] ? tokens[t - 2] : sx.ple_prev[1]; + prev[1] = tokens[t - 1]; + } ngram_rows(&tokens[t], prev, 1, ss_->ple.consts, ple_rows + t * PLE_N_HEADS); } if (!ss_->ple.table->gather_batch(ple_rows, (size_t) S, h_ple_, err)) return false; } - // the commit's rows (a batch window keeps every row): [1, 0, position, -1 ..] per slot + // Each slot owns a contiguous group. The default commit keeps all its rows; speculative + // decoding may change the prefix length after comparing the draft with these picks. const int64_t CB = 2 + max_t_; - for (int t = 0; t < S; ++t) { - int32_t* c = h_commitb_ + (size_t) rows[t] * CB; - c[0] = 1; - c[1] = 0; - c[2] = (int32_t) pos[t]; - for (int64_t j = 3; j < CB; ++j) c[j] = -1; + for (int t = 0; t < S;) { + const int first = t; + while (t < S && rows[t] == rows[first]) ++t; + int32_t* c = h_commitb_ + (size_t) rows[first] * CB; + c[0] = t - first; + c[1] = t - first - 1; + for (int64_t j = 0; j < max_t_; ++j) + c[2 + j] = j < t - first ? (int32_t) pos[first + j] : -1; } *(volatile uint32_t*) h_seq_ = 0; *(volatile uint32_t*) h_flag_ = 0; @@ -2101,6 +2184,29 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons volatile uint32_t* const seq = h_seq_; volatile uint32_t* const flag = h_flag_; const int64_t steps = le_ - lb_; + // #646: a stage whose every expert is resident plans on the device and raises no host doorbells, so the + // per-layer spin below has nothing to wait for: without the PLE flag the graph finishes with the ring silent + // ("verify batch: layer K never rang (graph finished)" - K is that stage's first layer), and with it the graph + // sits on the PLE wait until the 20 s timeout. As run() does: raise the PLE flag the graph's first wait reads, + // let the graph run to the end, and skip the host's per-layer service (there is nothing to serve). + if (all_resident_) { + if (ss_->ple.ready() && ple_stage()) { + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + *flag = 1; + } + const cudaError_t se = cudaStreamSynchronize(cs_); + if (se != cudaSuccess) { err = std::string("verify batch: ") + cudaGetErrorString(se); return false; } + cudaStreamSynchronize(copy_); + if (prof_on_) collect_profile(); + ++windows; + if (le_ < g.n_layers) return next_ == nullptr || next_->run_slot_rows(rows, S, tokens, pos, pool, next_user_, out, err); + if (!sample_rows(S, err)) return false; + for (int t = 0; t < S; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; + progress_at("decode"); + progress_beat(); + return true; + } for (int64_t k = 0; k < steps; ++k) { const int64_t l = lb_ + k; const uint32_t want = (uint32_t) (k + 1); @@ -2162,23 +2268,49 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons } bool Verifier::commit_slots(std::string& err) { + std::vector keep(slots_.size(), 0); + for (int t = 0; t < last_t_; ++t) ++keep[(size_t) last_rows_[t]]; + return commit_slot_prefixes(keep.data(), err); +} + +bool Verifier::commit_slot_prefixes(const int* keep, std::string& err) { const OnDevice on_device(device_); if (!last_batch_ || last_t_ < 1) { err = "verify: commit_slots without a batch window"; return false; } const int S = last_t_; const Clock::time_point t0 = Clock::now(); + const int64_t CB = 2 + max_t_; + // One prefix per slot: rejected draft rows must not enter recurrent state. + for (int t = 0; t < S;) { + const int first = t; + while (t < S && last_rows_[t] == last_rows_[first]) ++t; + const int n = keep[last_rows_[first]]; + if (n < 1 || n > t - first) { + err = "verify: accepted prefix is outside its slot group"; + return false; + } + int32_t* c = h_commitb_ + (size_t) last_rows_[first] * CB; + c[0] = n; + c[1] = n - 1; + for (int j = 0; j < max_t_; ++j) + c[2 + j] = j < n ? (int32_t) last_pos_b_[first + j] : -1; + } std::atomic_thread_fence(std::memory_order_seq_cst); - const cudaError_t le = cudaGraphLaunch(commit_bm_[batch_key(last_rows_, S, row_base_)], cs_); + const cudaError_t le = cudaGraphLaunch(commit_bm_[bkey(last_rows_, S, row_base_)], cs_); if (le != cudaSuccess) { err = std::string("verify: batch commit launch: ") + cudaGetErrorString(le); return false; } const cudaError_t se = cudaStreamSynchronize(cs_); if (se != cudaSuccess) { err = std::string("verify: batch commit: ") + cudaGetErrorString(se); return false; } if (ple_stage()) - for (int t = 0; t < S; ++t) { - SessionState& sx = *slots_[(size_t) last_rows_[t]]; - sx.ple_prev[0] = sx.ple_prev[1]; - sx.ple_prev[1] = last_tokens_[t]; + for (int t = 0; t < S;) { + const int first = t; + while (t < S && last_rows_[t] == last_rows_[first]) ++t; + SessionState& sx = *slots_[(size_t) last_rows_[first]]; + for (int u = first; u < first + keep[last_rows_[first]]; ++u) { + sx.ple_prev[0] = sx.ple_prev[1]; + sx.ple_prev[1] = last_tokens_[u]; + } } ms_commit += ms_since(t0); - return next_ == nullptr || next_->commit_slots(err); + return next_ == nullptr || next_->commit_slot_prefixes(keep, err); } bool Verifier::sample_rows(int S, std::string& err) { @@ -2203,7 +2335,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; if (!stage_batch(rows, S, base, tokens, pos, err)) return false; cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, base)], cs_); - if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[batch_key(rows, S, base)], cs_); // right behind it: every row is kept + if (le == cudaSuccess) le = cudaGraphLaunch(commit_bm_[bkey(rows, S, base)], cs_); // right behind it: every row is kept if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } (void) cudaStreamQuery(cs_); if (ple_stage()) // the host's side of the commit (the hash's last two tokens) @@ -2224,7 +2356,15 @@ int Verifier::batch_poll(PoolMultiFn pool, void* user, std::string& err) { const OnDevice on_device(device_); volatile uint32_t* const seq = h_seq_; const int S = last_t_; - while (b_k_ < b_steps_) { + // #646: an all-resident stage's graph raises no host doorbells (see run_slot_rows): nothing to serve per layer, + // so the poll is just "has the graph finished" - except the PLE flag, which the graph's first wait reads and + // only the host can raise (the same raise run_slot_rows makes). + if (all_resident_ && ss_->ple.ready() && ple_stage()) { + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + *h_flag_ = 1; + } + while (!all_resident_ && b_k_ < b_steps_) { const uint32_t want = (uint32_t) (b_k_ + 1); if (*seq < want) { const auto now = Clock::now(); @@ -2289,4 +2429,289 @@ bool Verifier::copy_logits(int t, float* host) const { cudaMemcpyDeviceToHost) == cudaSuccess; } + +// ================================ PIPELINED WINDOWS (see verify.hpp) ================================ +// +// The window is run()'s, step for step: the same graph, the same staging, the same per-layer service (the PLE rows +// gathered while layer 0 is served, the zero-doorbell graph's one flag), the same commit graph. Only the waits are +// split up: the host polls instead of spinning, so it can serve the other stage's window in between. + +namespace { +double now_ms() { return std::chrono::duration(Clock::now().time_since_epoch()).count(); } +} // namespace + +void Verifier::diag_pipelined(std::FILE* f, const char* name) const { + auto rd = [](const uint32_t* p) { return p ? *(const volatile uint32_t*) p : 0u; }; + auto ev = [](cudaEvent_t e) { + if (e == nullptr) return "none"; + const cudaError_t q = cudaEventQuery(e); + return q == cudaSuccess ? "done" : q == cudaErrorNotReady ? "PENDING" : "error"; + }; + std::fprintf(f, " %s: %s T=%d pos %lld served %lld/%lld; GPU rang %u, flags served %u A %u B %u; window event %s, " + "commit event %s (commit launched %d)\n", name, fl_active_ ? "IN FLIGHT" : "idle", last_t_, + (long long) last_pos0_, (long long) fl_k_, (long long) fl_total_, rd(h_seq_), rd(h_flag_), rd(h_flagA_), + rd(h_flagB_), ev(ev_done_), ev(ev_commit_), (int) commit_live_); +} + +bool Verifier::capture_all(std::string& err) { + const OnDevice on_device(device_); + if (g_ == nullptr) { err = "verify: capture_all before init"; return false; } + if (remote_opt_ != nullptr) { err = "verify: pipelined windows do not serve --remote-expert-opt"; return false; } + if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } + for (int T = 1; T <= max_t_; ++T) + if (!capture(T, err)) return false; + if (!capture_commit(err)) return false; + if ((ev_done_ == nullptr && cudaEventCreateWithFlags(&ev_done_, cudaEventDisableTiming) != cudaSuccess) || + (ev_commit_ == nullptr && cudaEventCreateWithFlags(&ev_commit_, cudaEventDisableTiming) != cudaSuccess)) { + err = "verify: event create failed"; + return false; + } + if (prof_on_ && prof_pin_ == nullptr && + cudaHostAlloc((void**) &prof_pin_, prof_h_.size() * 8, cudaHostAllocDefault) != cudaSuccess) { + prof_pin_ = nullptr; // the pipelined windows go unprofiled + cudaGetLastError(); + } + pl_ple_rows_.assign((size_t) strata::kernels::kVerifyMaxT * strata::kernels::PLE_N_HEADS, 0u); + return true; +} + +// The host staging of a pipelined window: run()'s (stage_inputs), and its PLE rows from `ple_prev` with their pages +// prefetched (they are gathered into the mapped rows when layer 0 is served, as run() does). +void Verifier::pl_stage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2]) { + using namespace strata::kernels; + stage_inputs(T, tokens, pos0); + staged_ = false; // a later run() stages its own window + SessionState& ss = *ss_; + fl_ple_ = ss.ple.ready() && ple_stage(); + if (fl_ple_) { + int32_t prev[2] = {ple_prev[0], ple_prev[1]}; + for (int t = 0; t < T; ++t) { + ngram_rows(&tokens[t], prev, 1, ss.ple.consts, pl_ple_rows_.data() + t * PLE_N_HEADS); + prev[0] = prev[1]; + prev[1] = tokens[t]; + ss.ple.table->prefetch_rows(pl_ple_rows_.data() + t * PLE_N_HEADS); + } + } + pl_prev_[0] = ple_prev[0]; + pl_prev_[1] = ple_prev[1]; +} + +bool Verifier::prestage(int T, const int32_t* tokens, int64_t pos0, const int32_t ple_prev[2], std::string& err) { + if (fl_active_) { err = "verify: a window is in flight on this verifier"; return false; } + if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } + if (pl_ple_rows_.empty()) { err = "verify: pipelined window not prepared (capture_all)"; return false; } + const Clock::time_point t0 = Clock::now(); + pl_stage(T, tokens, pos0, ple_prev); + pl_prestaged_ = true; + ms_host += ms_since(t0); + return true; +} + +bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string& err) { + const OnDevice on_device(device_); + if (fl_active_) { err = "verify: a window is already in flight on this verifier"; return false; } + if (released_.load()) { err = "verify: an earlier window never finished on the GPU (#267); restart the engine"; return false; } + if (T < 1 || T > max_t_) { err = "verify: window size out of range"; return false; } + SessionState& ss = *ss_; + if (pos0 + T > ss.qsa_states[ss.qsa_primary()].max_cells) { err = "verify: the window runs past the context"; return false; } + if (exec_[T] == nullptr || commit_exec_ == nullptr || ev_done_ == nullptr || pl_ple_rows_.empty()) { + err = "verify: pipelined window not prepared (capture_all)"; + return false; + } + const Clock::time_point t0 = Clock::now(); + last_batch_ = false; + bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0; + for (int t = 0; staged && t < T; ++t) staged = last_tokens_[t] == tokens[t]; + if (staged && ss.ple.ready() && ple_stage()) + staged = pl_prev_[0] == ss.ple_prev[0] && pl_prev_[1] == ss.ple_prev[1]; + pl_prestaged_ = false; + if (!staged) pl_stage(T, tokens, pos0, ss.ple_prev); + const int G = groups_[T] > 0 ? groups_[T] : 1; + fl_T_ = T; + fl_k_ = 0; + fl_total_ = (le_ - lb_) * G; + fl_prof_ = prof_on_ && G == 1 && prof_pin_ != nullptr; + if (trace_h_ != nullptr) std::memset(trace_h_, 0, trace_n_ * 8); // #649: this window's breadcrumbs only + std::atomic_thread_fence(std::memory_order_seq_cst); + trace_ev("WINDOW (pipelined)", -1, -1, pos0 * 16 + T); + ms_host += ms_since(t0); + const cudaError_t le = cudaGraphLaunch(exec_[T], cs_); + trace_ev("LAUNCHED", -1, -1, (int64_t) le); + if (le != cudaSuccess) { err = std::string("verify: launch: ") + cudaGetErrorString(le); return false; } + if (fl_prof_) cudaMemcpyAsync(prof_pin_, prof_, prof_h_.size() * 8, cudaMemcpyDeviceToHost, cs_); + if (cudaEventRecord(ev_done_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; } + (void) cudaStreamQuery(cs_); // WDDM: submit now + fl_active_ = true; + fl_since_ms_ = fl_flush_ms_ = fl_launch_ms_ = now_ms(); + return true; +} + +int Verifier::service(PoolMultiFn pool, void* user, std::string& err) { + if (!fl_active_) return 1; + if (fl_k_ >= fl_total_) return 1; + const OnDevice on_device(device_); + const ModelGeometry& g = *g_; + SessionState& ss = *ss_; + const int T = fl_T_; + // the PLE rows into the mapped staging (layer 1's pre() copies them once flag 1 is up), as run() does at k == 0 + auto gather_ple = [&]() -> bool { + if (!fl_ple_) return true; + const Clock::time_point tp = Clock::now(); + if (!ss.ple.table->gather_batch(pl_ple_rows_.data(), (size_t) T, h_ple_, err)) return false; + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + ms_host += ms_since(tp); + return true; + }; + if (all_resident_) { // the zero-doorbell graph never rings: it waits only for flag 1 (stage 0's PLE rows) + if (!gather_ple()) return -1; + *(volatile uint32_t*) h_flag_ = 1; + fl_k_ = fl_total_; + progress_tick(); + return 1; + } + const int G = groups_[T] > 0 ? groups_[T] : 1; + const int gtb[2] = {0, (T + 1) / 2}, gte[2] = {G == 2 ? (T + 1) / 2 : T, T}; + while (fl_k_ < fl_total_) { + const int64_t l = lb_ + fl_k_ / G; + const uint32_t want = (uint32_t) (fl_k_ + 1); + if (*(volatile uint32_t*) h_seq_ < want) { + const double now = now_ms(); + if (now - fl_flush_ms_ > 2.0) { // flush WDDM and notice a dead graph, as run() does + fl_flush_ms_ = now; + const cudaError_t q = cudaEventQuery(ev_done_); + if (q != cudaErrorNotReady && *(volatile uint32_t*) h_seq_ < want) { + trace_ev("NEVER-RANG", fl_k_, l, (int64_t) q); + err = "verify: layer " + std::to_string(l) + " never rang (" + + (q == cudaSuccess ? std::string("graph finished") : std::string(cudaGetErrorString(q))) + ")"; + return -1; + } + (void) cudaStreamQuery(cs_); + } + if (now - fl_since_ms_ > 20000.0) { // #267: no spin kernel may outlive the engine + trace_ev("TIMEOUT", fl_k_, l, 0); + err = "verify: timed out at layer " + std::to_string(l) + released_note(release_gpu_waits(5000)); + return -1; + } + return 0; + } + const Clock::time_point b = Clock::now(); + ms_wait += now_ms() - fl_since_ms_; + const int grp = (int) (fl_k_ % G); + cur_layer_ = want - 1; + set_plan_slot(grp); + const int tb = gtb[grp], n = gte[grp] - gtb[grp]; + progress_at("verify window (pipelined): the CPU experts of layer", l); + if (pool != nullptr) + pool(user, h_x_ + (size_t) tb * g.n_embd, h_ids_ + (size_t) tb * ss.k, n, ss.k, + h_ymiss_ + (size_t) tb * ss.k * g.n_embd, l); + if (g_trace) trace_ev(*(volatile uint32_t*) h_flagA_ == want ? "SERVED" : "SERVED-NO-PLAN-YET", fl_k_, l, + (int64_t) ms_since(b)); + progress_tick(); + std::atomic_thread_fence(std::memory_order_seq_cst); + _mm_sfence(); + if (*(volatile uint32_t*) h_flagA_ != want) { // the pool did not publish a plan: an empty one + sink_.counts[0] = 0; + sink_.counts[1] = 0; + sink_.counts[2] = 0; + sink_.start[0] = 0; + sink_.start2[0] = 0; + std::atomic_thread_fence(std::memory_order_seq_cst); + *(volatile uint32_t*) h_flagA_ = want; + raise_flag(h_flagB_, want); + } + if (fl_k_ == 0 && !gather_ple()) return -1; + *(volatile uint32_t*) h_flag_ = want; + ++fl_k_; + ms_pool += ms_since(b); + fl_since_ms_ = fl_flush_ms_ = now_ms(); + } + return 1; +} + +bool Verifier::done(std::string& err) { + if (!fl_active_ || fl_k_ < fl_total_) return false; + const OnDevice on_device(device_); + const cudaError_t q = cudaEventQuery(ev_done_); + if (q == cudaErrorNotReady) { + const double now = now_ms(); + if (now - fl_flush_ms_ > 2.0) { fl_flush_ms_ = now; (void) cudaStreamQuery(cs_); } + if (now - fl_since_ms_ > 20000.0) { // every layer served, and the graph still runs: #267 as above + err = "verify: the window never finished" + released_note(release_gpu_waits(5000)); + } + return false; + } + if (q != cudaSuccess) { err = std::string("verify: ") + cudaGetErrorString(q); return false; } + if (copy_used_) { // no host function of this window may raise flag B in the next one + if (cudaStreamQuery(copy_) == cudaErrorNotReady) return false; + copy_used_ = false; + } + return true; +} + +bool Verifier::pl_finish(int32_t* out, std::string& err) { + using namespace strata::kernels; + const OnDevice on_device(device_); + const ModelGeometry& g = *g_; + fl_active_ = false; + if (fl_prof_) accumulate_profile(prof_pin_); + ++windows; + trace_ev("DONE (pipelined)", -1, -1, (int64_t) (now_ms() - fl_launch_ms_)); + if (le_ < g.n_layers) return true; // an earlier stage: the hand-off is written + const int T = fl_T_; + const bool sampled = !sampling_.greedy && sampling_.temperature > 0.0f; + if (head_sampling_ && (sampled || hist_d_ != nullptr)) { // run()'s host-side sampling, Philox(seed, pos0 + t) + SamplerParams sp = sampling_; + sp.counter = (uint64_t) last_pos0_; + sample_tokens(head_logits_, T, (int) n_vocab_, hist_d_, hist_len_, sp, m_out_, cs_); + if (cudaStreamSynchronize(cs_) != cudaSuccess) { + err = "verify: the head sampling failed"; + return false; + } + } + if (out != nullptr) + for (int t = 0; t < T; ++t) out[t] = ((volatile int32_t*) h_out_)[t]; + progress_beat(); + return true; +} + +bool Verifier::pl_commit_async(int n_keep, std::string& err) { + const OnDevice on_device(device_); + if (n_keep < 1 || n_keep > last_t_) { err = "verify: commit count out of range"; return false; } + if (commit_exec_ == nullptr || ev_commit_ == nullptr) { err = "verify: pipelined commit not prepared"; return false; } + const Clock::time_point t0 = Clock::now(); + if (commit_live_) { // its graph reads the words below when it starts: the previous one has (a window ago) + cudaError_t q; + while ((q = cudaEventQuery(ev_commit_)) == cudaErrorNotReady) _mm_pause(); + if (q != cudaSuccess) { err = std::string("verify: commit: ") + cudaGetErrorString(q); return false; } + } + h_commit_[0] = n_keep; + h_commit_[1] = n_keep - 1; + for (int t = 0; t < max_t_; ++t) h_commit_[2 + t] = t < n_keep ? (int32_t) (last_pos0_ + t) : -1; + std::atomic_thread_fence(std::memory_order_seq_cst); + const cudaError_t le = cudaGraphLaunch(commit_exec_, cs_); + if (le != cudaSuccess) { err = std::string("verify: commit launch: ") + cudaGetErrorString(le); return false; } + if (cudaEventRecord(ev_commit_, cs_) != cudaSuccess) { err = "verify: event record failed"; return false; } + (void) cudaStreamQuery(cs_); + commit_live_ = true; + if (ple_stage()) + for (int t = 0; t < n_keep; ++t) { + ss_->ple_prev[0] = ss_->ple_prev[1]; + ss_->ple_prev[1] = last_tokens_[t]; + } + ms_commit += ms_since(t0); + return true; +} + +void Verifier::absorb_stats(Verifier& o) { + ms_wait += o.ms_wait; ms_pool += o.ms_pool; ms_host += o.ms_host; ms_commit += o.ms_commit; + windows += o.windows; + o.ms_wait = o.ms_pool = o.ms_host = o.ms_commit = 0; + o.windows = 0; + for (int k = 0; k < 2; ++k) + for (int i = 0; i < kProfPer; ++i) { prof_sum_[k][i] += o.prof_sum_[k][i]; o.prof_sum_[k][i] = 0; } + prof_windows_ += o.prof_windows_; + o.prof_windows_ = 0; +} + } // namespace strata::core diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index f12f1251..e4f0e31a 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -557,6 +557,12 @@ __global__ void dense_steps_kernel(const int32_t* __restrict__ cells, int n, int steps[i * 4 + 3] = c + 1; } +// --pipeline-windows: the drafter's chain, teacher forced (see force_token) +__global__ void force_token_kernel(int32_t* tok, const int32_t* force, int j) { + const int32_t f = ((const volatile int32_t*) force)[j]; + if (f >= 0) *tok = f; +} + } // namespace void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream) { @@ -590,6 +596,11 @@ void mtp_select(const float* R_src, int64_t R_stride, const int32_t* ids, const check("mtp_select"); } +void force_token(int32_t* tok, const int32_t* force, int j, void* stream) { + force_token_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(tok, force, j); + check("force_token"); +} + void gather_rows(const uint8_t* src, int64_t row_bytes, const int32_t* ids, int64_t n, uint8_t* dst, void* stream) { cudaStream_t s = (cudaStream_t) stream; if (row_bytes % 16 == 0) diff --git a/src/program/generate.cpp b/src/program/generate.cpp index d37fdecb..af31325d 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -83,6 +83,7 @@ #include #include #include +#include #include #include #include @@ -204,6 +205,13 @@ bool refill_blocking() { using Clock = std::chrono::steady_clock; +// --pipeline-windows: every STRATA_PIPELINE_* test and tuning variable (THETA, FORCE_MISS, SWITCH, LOG, TRACE, DOOM_SKIP, +// LOOKUP_PON, PRESTAGE, AGREE, SNAP_OVERLAP) is read only with STRATA_PIPELINE_DEBUG=1; without it the defaults apply. +static const char* pipe_dbg_env(const char* name) { + static const bool on = [] { const char* v = std::getenv("STRATA_PIPELINE_DEBUG"); return v != nullptr && v[0] != 0 && v[0] != '0'; }(); + return on ? std::getenv(name) : nullptr; +} + // The resident RAM mode and the adaptive tier. A swap copies `in` (held in RAM) into the slot of `out` (held only // by that slot). Before the slot is overwritten, `out`'s bytes are copied back from it into an exchange buffer, so // the CPU computes `out` from RAM while the swap is in flight; when the swap has landed, `commit_exchanges` moves @@ -493,6 +501,7 @@ struct Options { /// The --batch slots in this many groups pipelined through the stages of a layer split (stage k /// runs one group while stage k+1 runs another). 1 = every slot in one window, stage after stage. int batch_groups = 1; + bool batch_mtp = false; ///< --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): one MTP proposal per batch slot std::string spec_oracle; int spec_corrupt = 0; /// Plan v0.3 P6: the MTP draft layer's runtime directory (tools/mtp_rt.py); drafts come from it. @@ -506,6 +515,10 @@ struct Options { /// the VRAM tier in place of the least-routed resident ones (decayed counts). 0 = static residency. int adapt_every = 4; float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay) + /// --adapt-async 1 (--serve with the resident RAM mode; opt-in): the adaptive tier's rounds advance between verify + /// windows on a helper thread instead of one window waiting for a whole round (see the tier in the --serve block). + /// Not bit-exact run to run. 0 = the blocking tier. + int adapt_async = 0; /// Plan v0.3 P6: a draft enters the verify window only while every draft before it (and itself) has at least /// this probability under the draft layer; 0 = always --spec-1 drafts. double spec_min_p = 0.0; @@ -552,6 +565,11 @@ struct Options { /// result) goes through the verify windows, S tokens at a time, instead of the batched prompt path (0 = always /// the batched path) int64_t short_read = 64; + /// --pipeline-windows N (--serve, a layer split on exactly two GPUs; opt-in): 1 = a prompt's short reads through + /// the verify windows run with the stages overlapped (stage 0 reads window K+1 while stage 1 reads window K); + /// 2 = the decode windows too: stage 0 runs window K+1 speculatively while stage 1 verifies window K (rolled back + /// when K is not accepted as guessed). 0 = off (the stages take turns). + int pipeline_windows = 0; /// The suffix drafter (prompt lookup): when the text being written repeats an earlier stretch of the context (code /// edits, quoted input, tool-call JSON) by at least this many tokens, the window may be filled with what followed /// it there instead of the MTP's drafts, where the MTP's own first guess agrees and the draft policy expects it to @@ -665,9 +683,15 @@ void usage() { " --vram-elastic --serve (#533, opt-in, NVIDIA): the expert cache in segments (--vram-segment-mib,\n" " default 512), so the command `VRAM ` (the server's POST /v1/vram) can\n" " give VRAM back to other programs between requests and take it back later\n" - " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8),\n" + " --batch N / --slots N --serve (opt-in): up to N requests decode together in batch slots (2..8\n" + " normally; --batch-mtp waves more through eight-row windows),\n" " each slot with its own session (VRAM like the main one); docs/BATCHING.md\n" + " --batch-mtp --batch (opt-in, one GPU, needs --mtp and --spec): each slot also verifies one MTP\n" + " proposal per window (STRATA_BATCH_MTP=1 does the same); needs VRAM per slot\n" " --batch-groups G --batch with a layer split: the slots in G groups pipelined through the GPUs\n" + " --pipeline-windows N --serve with a layer split on two GPUs (opt-in): one conversation's verify windows\n" + " with the GPUs overlapped - 1 = the prompt's short reads, 2 = decode as well\n" + " (stage 0 runs the next window while stage 1 verifies this one); docs/MULTI_GPU.md\n" " --trim-stage-weights an explicit --layer-split: each GPU loads only its own layers' dense weights\n" " --prompt-cache-every N --serve: also checkpoint every N fresh prompt tokens (default 16384, 0 = off)\n" " --turn-token ID --serve: the token that opens a chat turn (default 248045, <|im_start|>)\n" @@ -767,7 +791,10 @@ void usage() { " RAM allows); adaptive swaps exchange them, so none is read from the file again.\n" " --resident-experts the low-RAM PC's resident mode (setup): --mmap-experts --resident-cpu-experts\n" " with the copy page-locked when possible, 4 GiB headroom, plain mmap if it\n" - " does not fit. Same answers as --mmap-experts for the same placement.\n"); + " does not fit. Same answers as --mmap-experts for the same placement.\n" + " --adapt-async 1 --serve with the resident RAM mode (opt-in): the adaptive tier's swaps\n" + " advance between verify windows instead of a window waiting for a whole\n" + " round. Not bit-exact run to run. 0 (default) = the blocking tier.\n"); } // --lookup-chain: the context's last tokens for the draft sources (at most 64), the MTP's pending drafts last @@ -913,6 +940,7 @@ struct GpuStage { std::vector> profile; ///< its layers' share of the profile, hottest first int32_t* d_res = nullptr; ///< the residency table on its device strata::core::Verifier ver; + strata::core::Verifier ver_b; ///< --pipeline-windows: the odd windows' verifier strata::prefill::Prefill sp; cudaStream_t adapt_stream = nullptr; cudaEvent_t adapt_ev = nullptr; @@ -1021,6 +1049,31 @@ void disk_wait_threads(std::FILE* f) { } #endif +// --pipeline-windows: what the watchdog prints about the pipelined decode loop (set while it runs) +struct PlDiag { + strata::core::Verifier* v[2][2] = {}; + std::atomic a_seq{0}, a_bits{0}, b_bits{0}, d_bits{0}, chain_kind{0}, doomed{0}, ending{0}, chain_live{0}; + std::atomic iters{0}; +}; +PlDiag g_pl_diag; +void pl_diag_print(std::FILE* f) { + PlDiag& d = g_pl_diag; + auto bits = [](int b, char* o) { + std::snprintf(o, 16, "%c%c%c%c%c%c", b & 1 ? 'R' : '-', b & 2 ? 'L' : '-', b & 4 ? 'F' : '-', b & 8 ? 'C' : '-', + b & 16 ? 'S' : '-', b & 32 ? 'V' : '-'); + return (const char*) o; + }; + char ba[16], bb[16], bd[16]; + std::fprintf(f, " pipelined loop: %lld iterations; A seq %d [%s] B [%s] D [%s] (Ready Launched Finished Committed " + "S1-launched S1-done); chain kind %d live %d; doomed %d ending %d\n", d.iters.load(), d.a_seq.load(), + bits(d.a_bits.load(), ba), bits(d.b_bits.load(), bb), bits(d.d_bits.load(), bd), d.chain_kind.load(), + d.chain_live.load(), d.doomed.load(), d.ending.load()); + const char* names[2][2] = {{"stage 0 even", "stage 0 odd"}, {"stage 1 even", "stage 1 odd"}}; + for (int st = 0; st < 2; ++st) + for (int par = 0; par < 2; ++par) + if (d.v[st][par] != nullptr) d.v[st][par]->diag_pipelined(f, names[st][par]); +} + void stall_report(std::FILE* f, uint64_t layers_during) { strata::core::Progress& p = strata::core::progress(); std::fprintf(f, "strata serve: stall report (engine %s): stage \"%s\" for %lld s; %llu layers served since the " @@ -1034,6 +1087,7 @@ void stall_report(std::FILE* f, uint64_t layers_during) { } if (auto fn = strata::core::diag_pool_fn().load()) fn(f); if (auto fn = strata::core::diag_verify_fn().load()) fn(f); + if (auto fn = strata::core::diag_pipeline_fn().load()) fn(f); #if !defined(_WIN32) disk_wait_threads(f); #endif @@ -1085,6 +1139,82 @@ bool adapt_nowait() { return v; } +/// --adapt-async: one background job at a time (the asynchronous adaptive tier's copies and memcpys). `post` hands +/// it over, `idle` says whether it has finished; the owner never posts while a job runs. +class JobThread { +public: + JobThread() : th_([this] { loop(); }) {} + ~JobThread() { + { std::lock_guard lk(mu_); quit_ = true; } + cv_.notify_one(); + th_.join(); + } + JobThread(const JobThread&) = delete; + JobThread& operator=(const JobThread&) = delete; + void post(std::function f) { + { + std::lock_guard lk(mu_); + job_ = std::move(f); + has_ = true; + done_.store(false, std::memory_order_release); + } + cv_.notify_one(); + } + bool idle() const { return done_.load(std::memory_order_acquire); } + void wait() const { while (!idle()) std::this_thread::yield(); } +private: + // The second logical processor of the last physical core that has two: an SMT sibling no pool worker or host loop + // is pinned to (the pool takes the first of every core but the first, the host the first core), or -1. + static int smt_spare_cpu() { +#if defined(_WIN32) + DWORD len = 0; + GetLogicalProcessorInformationEx(RelationProcessorCore, nullptr, &len); + if (len == 0) return -1; + std::vector buf(len); + if (!GetLogicalProcessorInformationEx(RelationProcessorCore, (PSYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX) buf.data(), + &len)) + return -1; + int best = -1, core = 0; + for (const char* p = buf.data(); p < buf.data() + len; + p += ((const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p)->Size, ++core) { + const auto* e = (const SYSTEM_LOGICAL_PROCESSOR_INFORMATION_EX*) p; + const GROUP_AFFINITY& ga = e->Processor.GroupMask[0]; + int seen = 0; + for (int bit = 0; bit < 64; ++bit) + if ((ga.Mask & (1ull << bit)) && ++seen == 2 && core > 0) best = ga.Group * 64 + bit; + } + return best; +#else + return -1; +#endif + } + void loop() { + // the job's memcpys stay off the host's core and the pool's: by default the spare SMT sibling of the last + // two-thread core (Windows); STRATA_ADAPT_JOB_CPU=, or -1 for no pinning + const char* c = std::getenv("STRATA_ADAPT_JOB_CPU"); + const int cpu = c != nullptr ? std::atoi(c) : smt_spare_cpu(); + if (cpu >= 0) (void) strata::kernels::cpu::pin_current_thread(cpu); + for (;;) { + std::function f; + { + std::unique_lock lk(mu_); + cv_.wait(lk, [&] { return has_ || quit_; }); + if (!has_) return; + f = std::move(job_); + has_ = false; + } + f(); + done_.store(true, std::memory_order_release); + } + } + std::mutex mu_; + std::condition_variable cv_; + std::function job_; + bool has_ = false, quit_ = false; + std::atomic done_{true}; + std::thread th_; // last: started once the members above exist +}; + int argmax(const std::vector& v) { int best = 0; for (size_t i = 1; i < v.size(); ++i) @@ -1468,6 +1598,7 @@ int main(int argc, char** argv) { else if (a == "--slots") o.batch = std::atoi(next("--slots")); // the same as --batch else if (a == "--trim-stage-weights") o.trim_stage_weights = true; else if (a == "--batch-groups") o.batch_groups = std::atoi(next("--batch-groups")); + else if (a == "--batch-mtp") o.batch_mtp = true; else if (a == "--spec-oracle") o.spec_oracle = next("--spec-oracle"); else if (a == "--spec-corrupt") o.spec_corrupt = std::atoi(next("--spec-corrupt")); else if (a == "--mtp") o.mtp = next("--mtp"); @@ -1475,6 +1606,7 @@ int main(int argc, char** argv) { else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac")); else if (a == "--adapt-every") o.adapt_every = std::atoi(next("--adapt-every")); else if (a == "--adapt-decay") o.adapt_decay = (float) std::atof(next("--adapt-decay")); + else if (a == "--adapt-async") o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p")); else if (a == "--stop-eos") o.stop_eos = true; else if (a == "--spec-split") o.spec_split = true; @@ -1504,6 +1636,7 @@ int main(int argc, char** argv) { else if (a == "--turn-token") o.turn_token = std::atoll(next("--turn-token")); else if (a == "--tail-role-token") o.tail_role_token = std::atoll(next("--tail-role-token")); else if (a == "--short-read") o.short_read = std::max(0LL, std::atoll(next("--short-read"))); + else if (a == "--pipeline-windows") o.pipeline_windows = std::max(0, std::min(2, std::atoi(next("--pipeline-windows")))); else if (a == "--suffix-draft") o.suffix_draft = std::max(0, std::atoi(next("--suffix-draft"))); else if (a == "--mtp-max-t") o.mtp_max_t = std::max(0, std::atoi(next("--mtp-max-t"))); else if (a == "--lookup-chain") o.lookup_chain = std::clamp(std::atoi(next("--lookup-chain")), 0, 7); @@ -2292,18 +2425,29 @@ int main(int argc, char** argv) { } if (native_pack) skip.insert("token_embd.weight"); } - // Layer split with explicit split points: every GPU holds only the dense weights of ITS layers (the PLE tensors - // stay everywhere). Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never - // reads - VRAM the expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 - // (PR #639), and the default waits for its author's re-run of the release branch on his cards. + // Layer split: every GPU holds only the dense weights of ITS layers (the PLE tensors stay everywhere). + // Without this each card keeps a full copy (~3.4 GB for the Coder) that its stage never reads - VRAM the + // expert cache wants. Opt-in, STRATA_STAGE_TRIM=1, on HIP and CUDA alike: measured on 2x MI50 (PR #639), + // and the default waits for its author's re-run of the release branch on his cards. const std::set skip_base = skip; // --trim-stage-weights (PR #559) is the same switch as STRATA_STAGE_TRIM=1 (PR #639) - const bool stage_trim = multi_gpu && !split_auto && !split_at.empty() && (o.trim_stage_weights || [] { + const bool trim_asked = o.trim_stage_weights || [] { const char* v = std::getenv("STRATA_STAGE_TRIM"); return v != nullptr && v[0] != 0 && std::string(v) != "0"; - }()); - if (o.trim_stage_weights && !stage_trim) - std::fprintf(stderr, "strata generate: --trim-stage-weights needs an explicit --layer-split (ignored)\n"); + }(); + // CUDA0'S ARENA IS BUILT BEFORE THE SPLIT IS KNOWN. The prompt path's PLE tables are read out of it, here, + // and `auto` does not choose its split points until 590 lines below - so CUDA0 can still only trim an + // explicit --layer-split. It is also the cheapest card to leave alone: it runs layers 0..split_at[0] on + // the device with the most room, and on the 4-way IQ3_S rig the trim buys it 4598 -> 4608 slots. The VRAM + // is on the later cards (CUDA2 1241 -> 2485, CUDA3 533 -> 1772), and THEIR weights load after the search, + // so they trim under `auto` too - see the block past it. + const bool stage_trim = trim_asked && multi_gpu && !split_auto && !split_at.empty(); + if (o.trim_stage_weights && !multi_gpu) + std::fprintf(stderr, "strata generate: --trim-stage-weights needs a layer split across GPUs (ignored)\n"); + // Only `--layer-split auto` WITH the trim asked loads the later stages' weights after the split search (they can + // only be trimmed once the split is known). Every other run keeps the 0.1.39 order: weights first, then the + // search - so without the trim nothing about a split moves. + const bool late_weights = trim_asked && multi_gpu && split_auto; // keep_routers: CUDA0 with --mmap-experts keeps every layer's router (ffn_gate_inp, ~2.5 MiB a layer) - the file // tier's routing-aware prefetch (RouterLookahead, below) copies all of them from CUDA0's arena, and would // otherwise turn itself off @@ -2645,28 +2789,38 @@ int main(int argc, char** argv) { } } strata::core::Verifier::set_commit_async(!multi_gpu); // see Verifier::set_commit_async + // --pipeline-windows (opt-in): one conversation's windows with the two stages of a layer split overlapped. Decided + // here, before any stage sizes its expert cache (the second verifier per stage and the snapshots are allocated + // after the caches, so their room is kept out of them). What it does not support turns it off, said once. + if (o.pipeline_windows > 0) { + const bool helpers = o.expert_cache_remote[0] > 0 || o.expert_cache_remote[1] > 0 || o.expert_cache_remote[2] > 0; + const char* off = !o.serve ? "it needs --serve" + : split_same ? "it needs each stage of the layer split on its own GPU" + : !multi_gpu ? "it needs a layer split on two GPUs" + : split_devs.size() != 1 ? "it needs a layer split into exactly two stages" + : o.mtp.empty() || o.spec < 2 ? "it needs the MTP drafter (--mtp, --spec)" + : o.batch != 0 ? "not with --batch slots" + : o.peer_device >= 1 ? "not with --peer-device" + : helpers ? "not with the helper caches (--expert-cache-device1..3, --remote-expert-opt)" + : nullptr; + if (off != nullptr) { + std::fprintf(stderr, "strata generate: --pipeline-windows %d is off: %s\n", o.pipeline_windows, off); + o.pipeline_windows = 0; + } + } // ---- layer split across GPUs: each later stage's own copy of the dense weights, its session and (the last) the // head, made on its device before the host arena is mapped (as the drafter below, for the same WDDM reason) std::vector> stages; - for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) { - stages.push_back(std::make_unique()); - GpuStage& st = *stages.back(); - st.dev = split_devs[i]; - double free_gib = 0; - if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) { - std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; - } - const strata::core::OnDevice on(st.dev); + // One stage's dense weights on its device (the caller has made it current): `trim` = only layers [lb, le). + auto load_stage_weights = [&](GpuStage& st, int64_t lb, int64_t le, bool trim) -> bool { std::set skip_s = skip_base; uint64_t pool_s = pool_bytes; - if (stage_trim) { - const int64_t lb = split_at[i], le = i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers; + if (trim) { add_foreign(lb, le, skip_s, false); strata::core::NativeDense::set_layer_range((int) lb, (int) le); if (!strata::core::WeightTable::pool_bytes(o.pack, pool_s, err, &skip_s)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); - return 1; + return false; } std::fprintf(stderr, "strata generate: layer split: CUDA%d loads the dense weights of layers %lld-%lld only\n", st.dev, (long long) lb, (long long) le - 1); @@ -2684,13 +2838,32 @@ int main(int argc, char** argv) { err.empty() ? "the weight arena does not fit" : err.c_str(), (unsigned long long) (pool_s >> 20), (unsigned long long) (free_b >> 20), (unsigned long long) (total_b >> 20)); - return 1; + return false; } if (!o.native_dense_gguf.empty() && !st.dense.load(o.native_dense_gguf, st.wt, err, o.native_ple_key)) { std::fprintf(stderr, "strata generate: layer split, CUDA%d native dense projections: %s\n", st.dev, err.c_str()); + return false; + } + return true; + }; + for (size_t i = 0; multi_gpu && i < split_devs.size(); ++i) { + stages.push_back(std::make_unique()); + GpuStage& st = *stages.back(); + st.dev = split_devs[i]; + double free_gib = 0; + if (!strata::core::RemoteExperts::preflight(st.dev, free_gib, err)) { + std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } + const strata::core::OnDevice on(st.dev); + // Later stages' weights load here (0.1.39), except `--layer-split auto` with the trim asked: those load after + // the split search (see late_weights), so `auto` can trim them too. + if (!late_weights) { + const int64_t lb = stage_trim ? split_at[i] : 0; + const int64_t le = stage_trim ? (i + 1 < split_at.size() ? split_at[i + 1] : g.n_layers) : 0; + if (!load_stage_weights(st, lb, le, stage_trim)) return 1; + } // THE SESSION AND THE HEAD WAIT FOR THE SPLIT SEARCH. `session_bytes` prices a stage's session by its // LAYER RANGE (the carve - every stage used to hold all 48 layers' state whatever it ran), so the // sessions are allocated after the search below has set `st.lb`/`st.le`; the last stage's head follows. @@ -2726,10 +2899,12 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: layer split: CUDA%d PCIe probe %.1f GB/s (best of %s) -> pcie_frac " "%.2f\n", st.dev, bw, bursts.c_str(), st.pcie_frac); } - size_t fb = 0, tb = 0; - cudaMemGetInfo(&fb, &tb); - std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " - "follows the split search)\n", st.dev, (double) fb / 1073741824.0); + if (!late_weights) { + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " + "follows the split search)\n", st.dev, (double) fb / 1073741824.0); + } } GpuStage* const last_st = stages.empty() ? nullptr : stages.back().get(); @@ -2820,11 +2995,28 @@ int main(int argc, char** argv) { // the windows and - only on the stage that carries them - the drafter and the head. const int64_t kWindowMib = 96; // the verify windows; 75 MiB measured, rounded up const int64_t kDrafterMib = 1000; // the MTP drafter (839 MiB) + the head, on the last stage only + // --pipeline-windows: a second verifier on every stage (its arena alone is 70-75 MiB and its graphs come on top: + // 64 MiB left two RTX 5070 Ti under Linux short of it) and, with the decode pipelined, two copies of the first + // stage's GDN state (sized from its session where the first card's cache is sized; this is the split search's + // estimate). Allocated after the caches, so kept out of them. + const int64_t kPipeWindowMib = o.pipeline_windows > 0 ? 160 : 0; + const int64_t kPipeSnapMib = o.pipeline_windows >= 2 ? 96 : 0; // ~3 MiB per GDN layer, twice, ~15 layers + auto gdn_snapshot_bytes = [&](const strata::core::SessionState& s0) -> size_t { + return (size_t) s0.gdn_alloc * ((size_t) g.ssm_state_size * g.ssm_v_heads * g.ssm_state_size + + (size_t) g.ssm_conv_channels * (g.ssm_d_conv - 1)) * sizeof(float); + }; // #340: with the own prompt buffers chosen by the split's rule (not asked for with --no-prefill-borrow) the // boundary is searched as the borrowing configuration would (no reserve): the reserve then only makes the caches // smaller, which measured cost no decode (K=28 on 9070 XT + R9700: 58.4 tok/s own vs 58.5 borrowing), while a // search with the reserve moved the boundary to K=32 and decode to 54.8. STRATA_SPLIT_OWN_PLACE=reserve: the // search sees the reserve. + // ---- `--layer-split auto` with the trim asked: a later stage's weights load after this search, so its arena is + // not in `cudaMemGetInfo` yet. Price it from the pack index as the full (untrimmed) copy the search has always + // seen on the card (`pool_bytes` reads the index and allocates nothing), so the split it picks is the split it + // has always picked: this buys cache, not a different placement. Every other run has its weights loaded: 0. + std::vector stage_pool(stages.size() + 1, 0); + if (late_weights) + for (size_t i = 1; i < stage_pool.size(); ++i) stage_pool[i] = pool_bytes; static const bool place_with_reserve = [] { const char* v = std::getenv("STRATA_SPLIT_OWN_PLACE"); return v != nullptr && std::string(v) == "reserve"; @@ -2838,8 +3030,8 @@ int main(int argc, char** argv) { const int64_t pf = search && split_own_auto && !place_with_reserve ? 0 : split_pf_mib; const int64_t base_reserve = later && o.vram_reserve_later_mib >= 0 ? o.vram_reserve_later_mib : o.vram_reserve_mib; - const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : 0) + - (drafter ? kDrafterMib : 0)) << 20; + const int64_t reserve = (base_reserve + pf + (later ? kWindowMib : kPipeSnapMib) + + kPipeWindowMib + (drafter ? kDrafterMib : 0)) << 20; return std::max((int64_t) fb - reserve, 0); }; if (multi_gpu && split_auto) { @@ -2850,6 +3042,7 @@ int main(int argc, char** argv) { for (int i = 0; i < ns; ++i) { const int dev = i == 0 ? 0 : stages[(size_t) i - 1]->dev; cap[(size_t) i] = stage_room(i == 0 ? -1 : dev, i > 0, i + 1 == ns, true); + if (late_weights) cap[(size_t) i] = std::max(cap[(size_t) i] - (int64_t) stage_pool[(size_t) i], 0); int sms = 0, khz = 0; cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev); if (cudaDeviceGetAttribute(&khz, cudaDevAttrClockRate, dev) != cudaSuccess || khz <= 0) khz = 1800000; @@ -2963,6 +3156,21 @@ int main(int argc, char** argv) { } } + // ---- `--layer-split auto` with the trim asked: THE STAGES' WEIGHTS, NOW THAT THE SPLIT IS KNOWN. Each later card + // loads the dense weights of the layers it runs and nothing else (before this they loaded in the loop above, a + // full copy per card: on the 4-way IQ3_S rig CUDA1 3650 expert slots, CUDA2 1241, CUDA3 533 and a 768-token prompt + // chunk; carved 4608 / 2485 / 1772 and 6144). The search priced these arenas from the pack index (`stage_pool`). + if (late_weights) + for (size_t i = 0; i < stages.size(); ++i) { + GpuStage& st = *stages[i]; + const strata::core::OnDevice on(st.dev); + if (!load_stage_weights(st, st.lb, st.le, true)) return 1; + size_t fb = 0, tb = 0; + cudaMemGetInfo(&fb, &tb); + std::fprintf(stderr, "strata generate: layer split: CUDA%d holds its weights; %.2f GiB free (its session " + "follows)\n", st.dev, (double) fb / 1073741824.0); + } + // ---- CUDA0's session, and the stages' sessions: sized to each device's own layer range (the carve). A // stage that runs [lb, le) carves only those layers' GDN rows and QSA pools - before the carve every stage // held all 48 layers' state whatever layers it ran, which is the same disease the chunked-QSA-prefill PR @@ -3030,6 +3238,19 @@ int main(int argc, char** argv) { // slot of the batch windows. Before the expert cache is sized, so `--expert-cache auto` leaves them room. // Recommend, never force: a count the engine cannot run is said and adjusted (or batching left off) - the // engine still starts and serves one request at a time. + // --batch-mtp / STRATA_BATCH_MTP=1 (opt-in): a slot also verifies one MTP proposal per window. Recommend, never + // force: when it cannot run it is said and left off (plain batching still starts); default off = exactly 0.1.39. + const char* batch_mtp_env = std::getenv("STRATA_BATCH_MTP"); + bool batch_mtp = o.batch_mtp || (batch_mtp_env != nullptr && batch_mtp_env[0] != '\0' && batch_mtp_env[0] != '0'); + if (batch_mtp) { + const char* why = o.batch < 2 ? "it needs --batch 2 or more" : o.mtp.empty() ? "it needs --mtp" + : o.spec < 2 ? "it needs --spec T (T >= 2)" : (multi_gpu || split_same || !stages.empty()) + ? "it is for one GPU (no layer split or helper) for now" : !o.serve ? "it needs --serve" : nullptr; + if (why != nullptr) { + std::fprintf(stderr, "strata generate: WARNING: --batch-mtp is off: %s\n", why); + batch_mtp = false; + } + } std::vector>> bslot_ss; if (o.batch != 0) { const int cap = strata::kernels::kVerifyMaxT; @@ -3038,7 +3259,7 @@ int main(int argc, char** argv) { if (off != nullptr) { std::fprintf(stderr, "strata generate: WARNING: --batch %d is off: %s\n", o.batch, off); o.batch = 0; - } else if (o.batch > cap) { + } else if (o.batch > cap && !batch_mtp) { std::fprintf(stderr, "strata generate: WARNING: --batch %d: a batch window holds at most %d rows, so %d " "slots\n", o.batch, cap, cap); o.batch = cap; @@ -3102,6 +3323,10 @@ int main(int argc, char** argv) { // Secure MTP's CUDA0 allocations before the large host arena is registered with both CUDA contexts. // In particular WDDM can refuse the draft weights after mapping tens of GiB of host pages. strata::core::MtpDrafter mtp; + // the draft layer's geometry (the canonical model's MTP head), `static` because MtpDrafter keeps a reference; the batch + // slots' draft-KV copies use this one too + static const strata::core::ModelGeometry draft_geometry{}; + std::vector> slot_mtp; if (!o.mtp.empty()) { if (o.spec < 2) { std::fprintf(stderr, "strata generate: --mtp is ignored without --spec T (T >= 2)\n"); @@ -3113,11 +3338,27 @@ int main(int argc, char** argv) { if (!o.mtp_draft_vocab.empty()) mtp.set_draft_vocab(o.mtp_draft_vocab); // the draft layer is the canonical model's MTP head (512 experts) even when the target is pruned, // so it always sees the canonical geometry; `static` because MtpDrafter keeps a reference - static const strata::core::ModelGeometry draft_geometry{}; // with a layer split across GPUs the drafter reads the last stage's residual: it lives on that device const strata::core::OnDevice on_mtp(last_st ? last_st->dev : -1); - if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, o.spec, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } + // --pipeline-windows 2: 8 rows (the chain runs on past the window in flight: its drafts, its bonus token and + // the next window's drafts), and the round/step graphs carry the forcing kernel + const int mtp_t = o.pipeline_windows >= 2 ? strata::kernels::kVerifyMaxT : o.spec; + if (o.pipeline_windows >= 2) mtp.set_force_capture(true); + if (!o.mtp.empty() && !mtp.load(o.mtp, draft_geometry, last_st ? last_st->ss : ss, mtp_t, err, o.mtp_window)) { std::fprintf(stderr, "strata generate: %s%s\n", err.c_str(), vram_free_note().c_str()); return 1; } mtp.set_ple_session(&ss); + if (batch_mtp) { + for (int b = 0; b < o.batch; ++b) { + auto d = std::make_unique(); + if (!d->load(o.mtp, draft_geometry, *bslot_ss[0][(size_t) b], o.spec, err, o.mtp_window, &mtp)) { + std::fprintf(stderr, "strata generate: batch MTP slot %d: %s%s\n", b, err.c_str(), + vram_free_note().c_str()); + return 1; + } + d->set_max_drafts(1); // the first candidate verifies one proposal per slot + d->set_ple_session(bslot_ss[0][(size_t) b].get()); + slot_mtp.push_back(std::move(d)); + } + } } // THE HEAD BEFORE THE CACHE, AND BEFORE THE ARENA. The expert cache takes what is free minus the reserve, so // everything allocated after it comes out of the reserve. The native head (~0.5 GB with IQ3_S) was loaded after @@ -3306,6 +3547,13 @@ int main(int argc, char** argv) { // THE HEAD BEFORE THE CACHE: the native head and the logits are allocated above, before the expert arena (#620) const bool auto_cache = o.expert_cache < 0; bool reserve_adapted = false; // #496: the auto sizing lowered the reserve so a small card's cache fits + // --pipeline-windows: what it allocates on CUDA0 after the cache (see kPipeWindowMib) + const int64_t pipe_first = o.pipeline_windows <= 0 ? 0 + : (kPipeWindowMib << 20) + (o.pipeline_windows >= 2 ? 2 * (int64_t) gdn_snapshot_bytes(ss) : 0); + if (pipe_first > 0) + std::fprintf(stderr, "strata generate: --pipeline-windows %d: %lld MiB of CUDA0 kept out of the expert cache " + "(the second verifier%s)\n", o.pipeline_windows, (long long) (pipe_first >> 20), + o.pipeline_windows >= 2 ? ", the GDN snapshots" : ""); if (o.expert_cache < 0) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; @@ -3316,9 +3564,11 @@ int main(int argc, char** argv) { const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; // the draft layer's head and logits are allocated when it binds, after this: 0.1.27's CJK subset made them // ~110-180 MiB larger, and out of the reserve they left 16 GB cards below the stall line (#199) - const int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) - ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; - const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind; + int64_t mtp_bind = (!o.mtp.empty() && native_head.loaded()) + ? (int64_t) mtp.bind_bytes(native_head.row_bytes(), n_vocab) : 0; + for (const auto& d : slot_mtp) + mtp_bind += (int64_t) d->bind_bytes(native_head.row_bytes(), n_vocab); + const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first; const int64_t blob = (int64_t) strata::kernels::cpu::expert_layout().max_blob; int64_t slots = ((int64_t) free_b - reserve) / blob; if (!profile.empty()) slots = std::min(slots, (int64_t) profile.size()); @@ -3341,10 +3591,10 @@ int main(int argc, char** argv) { ? ((int64_t) strata::prefill::Prefill::bytes_needed(g, ss, 256) + blob - 1) / blob + 128 : 1; if (o.expert_cache < min_slots && !o.vram_reserve_given && o.vram_reserve_mib > kSmallReserveMib) { // the largest reserve (in MiB) that still leaves min_slots - const int64_t fit_mib = ((int64_t) free_b - mtp_bind - min_slots * blob) / (1 << 20) - prefill_mib; + const int64_t fit_mib = ((int64_t) free_b - mtp_bind - pipe_first - min_slots * blob) / (1 << 20) - prefill_mib; if (fit_mib >= kSmallReserveMib) { const int r = (int) std::min(fit_mib, o.vram_reserve_mib); - int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind)) / blob; + int64_t s2 = ((int64_t) free_b - ((((int64_t) r + prefill_mib) << 20) + mtp_bind + pipe_first)) / blob; if (!profile.empty()) s2 = std::min(s2, (int64_t) profile.size()); std::fprintf(stderr, "strata generate: expert cache auto: the %d MiB reserve leaves too few slots on " "this card (a working cache needs %lld): a %d MiB reserve instead -> %lld slots\n", @@ -3358,7 +3608,7 @@ int main(int argc, char** argv) { // what is short, and what makes room: the numbers a small card picks from const int64_t at_reserve = o.vram_reserve_given ? o.vram_reserve_mib : std::min(o.vram_reserve_mib, kSmallReserveMib); - const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + min_slots * blob; + const int64_t need_b = (((int64_t) at_reserve + prefill_mib) << 20) + mtp_bind + pipe_first + min_slots * blob; const int64_t short_mib = std::max(1, (need_b - (int64_t) free_b + (1 << 20) - 1) >> 20); const int64_t session_mib = (int64_t) (strata::core::session_bytes(g, o.max_context, K, 0, g.n_layers) >> 20); @@ -3383,7 +3633,7 @@ int main(int argc, char** argv) { size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; const int64_t prefill_mib = (o.prefill_chunk > 0 && !pf_borrow) ? 160 + (o.prefill_chunk * 680) / 1024 : 0; - const int64_t reserve = ((int64_t) o.vram_reserve_mib + prefill_mib) << 20; + const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + pipe_first; const int64_t fit = std::max(((int64_t) free_b - reserve) / (int64_t) strata::kernels::cpu::expert_layout().max_blob, 0); if (o.expert_cache > fit) { // a WARNING that names the knob: the user asked for this size, and gets fewer slots @@ -3405,7 +3655,8 @@ int main(int argc, char** argv) { const auto& lay = strata::kernels::cpu::expert_layout(); const uint64_t budget = (uint64_t) o.expert_cache * lay.max_blob; // what the uniform sizing granted uint64_t used = 0; - size_t free_room = free_b > ((size_t) o.vram_reserve_mib << 20) ? free_b - ((size_t) o.vram_reserve_mib << 20) : 0; + const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first; + size_t free_room = free_b > keep_free ? free_b - keep_free : 0; const uint64_t cap = std::min(budget, (uint64_t) free_room); for (const auto& pr : profile) { const uint64_t b = (lay.blob_bytes(pr.first) + 255) / 256 * 256; @@ -3506,7 +3757,7 @@ int main(int argc, char** argv) { cudaDeviceSynchronize(); size_t free_b = 0, total_b = 0; free_b = strata::core::device_free_bytes(); (void) total_b; - const int64_t want = (int64_t) o.vram_reserve_mib << 20; + const int64_t want = ((int64_t) o.vram_reserve_mib << 20) + pipe_first; if ((int64_t) free_b >= want - (64ll << 20)) break; // short by (want - free); a figure of 0 only says "at least": the first two such reads give back 1 GiB // each (under WDDM the free figure read before the allocation runs ~0.7 GiB high), later ones a quarter @@ -3763,6 +4014,16 @@ int main(int argc, char** argv) { if (remote_opt && !remote_opt->init(err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; } Drive drive; + // #731 (opt-in, STRATA_DISJOINT_ADAPT=1): the adaptive tiers leave an expert a helper GPU holds out of the primary's + // promotion candidates (it would sit in both caches). Asked live, from the helper's own cache (RemoteExperts::holds, + // #854), so an expert the helper's tier swaps in or out later is followed - never a copy taken at load. + const bool disjoint_adapt = [] { const char* v = std::getenv("STRATA_DISJOINT_ADAPT"); return v != nullptr && std::atoi(v) != 0; }(); + auto helper_holds = [&](int64_t l, int32_t e) -> bool { + if (!disjoint_adapt) return false; + for (int r = 0; r < drive.d.remote_count; ++r) + if (drive.d.remote[r]->holds(l, e)) return true; + return false; + }; for (int r = 0; r < 3; ++r) if (o.expert_cache_remote[(size_t) r] > 0) drive.d.remote[drive.d.remote_count++] = &remote_experts[(size_t) r]; drive.d.peer = peer.valid() ? &peer : nullptr; @@ -4647,6 +4908,26 @@ int main(int argc, char** argv) { // streamed during a prompt and copied back after it, so those are kept in RAM too as far as RAM allows. The // bytes are the file's bytes and the placement is the same, so the answers are the plain mmap mode's; the // share-of-pinned figure above (which sizes the prompt path) is left as the mmap mode's for the same reason. + // --adapt-async (opt-in): where the asynchronous adaptive tier does not apply, the blocking tier runs, said once. + // It exchanges experts between the GPU caches and the resident RAM copy only (the copy is checked once it is + // built, below). Not beside the --batch slots (their windows run between a request's prompt chunks), a peer + // tier or the helper GPUs' tier, which pick their swaps from the same table. (A pipelined decode loop that + // adapts beside windows in flight needs the blocking tier too: such a mode belongs on this list.) + auto adapt_async_off = [&](const char* why) { + std::fprintf(stderr, "strata generate: --adapt-async 1 is off (%s): the blocking adaptive tier\n", why); + o.adapt_async = 0; + }; + if (o.adapt_async) { + const char* why = !o.serve ? "it needs --serve" + : o.adapt_every <= 0 || o.adapt_swaps <= 0 ? "the adaptive tier is off" + : !o.resident_cpu_experts ? "it needs the resident RAM mode, --resident-experts" + : o.batch > 0 ? "not with --batch slots" + : o.pipeline_windows > 0 ? "not with --pipeline-windows (its windows are in flight while the tier adapts)" + : peer.valid() ? "not with --peer-device" + : remote_opt ? "not with --remote-expert-opt" + : nullptr; + if (why != nullptr) adapt_async_off(why); + } if (o.resident_cpu_experts) { int64_t lend_from = -1; if (o.prefill_chunk > 0 && !o.no_prefill_borrow && d_res != nullptr && xcache.slots() > 0) { @@ -4682,6 +4963,14 @@ int main(int argc, char** argv) { err = whole_err + "; " + err; } if (resident_ok) { + // --adapt-async: twice the exchange buffers - the second half bounces the copies in whose source is not + // page-locked (an asynchronous copy instead of the driver's staged, synchronous one) + if (o.adapt_async && !src.reserve_exchanges(2 * std::min(o.adapt_swaps, 96), err)) + adapt_async_off(err.c_str()); + // pageable buffers would make every copy of a round synchronous (the driver stages them): that is the + // blocking tier's cost, so the asynchronous tier is not worth running - said, and the blocking tier stays + if (o.adapt_async && !src.exchange_pinned()) + adapt_async_off("the exchange buffers could not be page-locked"); if (o.adapt_every > 0 && o.adapt_swaps > 0 && !src.reserve_exchanges(std::min(o.adapt_swaps, 96), err)) { std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str()); @@ -4722,13 +5011,20 @@ int main(int argc, char** argv) { } #endif } + if (o.adapt_async && !src.complement_ready()) adapt_async_off("the resident RAM mode is not running"); if (o.serve) { - if (o.spec < 2 || o.mtp.empty() || o.prefill_chunk <= 0 || + if (o.spec < 2 || o.prefill_chunk <= 0 || (graph_hits && (thits.d_res == nullptr || host_res.empty()))) { - std::fprintf(stderr, "strata serve: needs --spec T, --mtp DIR and --prefill CHUNK (and a fillable " + std::fprintf(stderr, "strata serve: needs --spec T and --prefill CHUNK (and a fillable " "--expert-cache; the graphed hit path additionally needs --expert-profile P)\n"); return 2; } + // STRATA_VOLTA_BUILD backport (see docs/ and ninfer-flash-next-v100-backport): --mtp is optional here, + // mirroring the plain `generate` command's own use_mtp handling below. Without it, drafting falls back + // to the suffix/prompt-lookup drafter (DraftPolicy still picks Lookup vs plain per round) or, when + // neither fires, plain one-token-per-round decoding - slower, never wrong: the verify window still + // confirms every emitted token against the real model regardless of where the draft came from. + const bool use_mtp = !o.mtp.empty(); strata::prefill::Prefill sp; void* borrow = nullptr; uint64_t borrow_bytes = 0; @@ -5193,6 +5489,29 @@ int main(int argc, char** argv) { }; auto pcie_num_of = [](double f) { return std::max(0, std::min(256, (int) (f * 256.0 + 0.5))); }; const int n_stages = split_devs.empty() ? 1 : (int) split_at.size() + 1; + // --pipeline-windows (decided where the split was): two verifiers per stage, one for the even windows and one + // for the odd ones, sharing one stream of their card, and a hand-off per parity - so stage 0 can run window + // K+1 while stage 1 still reads window K's hand-off + const bool pipe = o.pipeline_windows > 0 && n_stages == 2 && !split_same && stages.size() == 1; + strata::core::Verifier ver_b; + SplitDrive split_drive_b; + cudaStream_t pl_stream[2] = {nullptr, nullptr}; + if (pipe) { + bool ok_p = cudaStreamCreateWithFlags(&pl_stream[0], cudaStreamNonBlocking) == cudaSuccess; + { + const strata::core::OnDevice on(stages[0]->dev); + ok_p = ok_p && cudaStreamCreateWithFlags(&pl_stream[1], cudaStreamNonBlocking) == cudaSuccess; + } + if (!ok_p) { std::fprintf(stderr, "strata serve: --pipeline-windows: stream creation failed\n"); return 1; } + for (strata::core::Verifier* v : {&ver, &ver_b}) { + v->set_stream(pl_stream[0]); + v->set_always_publish(true); + } + for (strata::core::Verifier* v : {&stages[0]->ver, &stages[0]->ver_b}) { + v->set_stream(pl_stream[1]); + v->set_always_publish(true); + } + } if (n_stages > 1) { const size_t hb = (size_t) strata::kernels::kVerifyMaxT * (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); @@ -5248,12 +5567,79 @@ int main(int argc, char** argv) { " (CUDA" + std::to_string(split_same ? 0 : stages[(size_t) st - 1]->dev) + ")"; std::fprintf(stderr, "strata serve: layer split: layers %s, one hand-off per window\n", plan_s.c_str()); } + // --pipeline-windows: the odd windows' verifiers and their hand-off (initialized before `ver`, which stays the + // watchdog's verifier), and the drafter's own row buffer, which either parity's rows are copied into + float* pl_mtp_R = nullptr; + if (pipe) { + const size_t hb = (size_t) strata::kernels::kVerifyMaxT * + (size_t) strata::core::Verifier::handoff_floats(g) * sizeof(float); + float *hh = nullptr, *hand_b = nullptr; + if (cudaHostAlloc((void**) &hh, hb, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + cudaHostGetDevicePointer((void**) &hand_b, hh, 0) != cudaSuccess) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the second hand-off allocation failed\n"); + return 1; + } + std::memset(hh, 0, hb); + GpuStage& gs = *stages[0]; + ver_b.set_stage(0, split_at[0], nullptr, hand_b); + gs.ver_b.set_stage(split_at[0], -1, hand_b, nullptr); + { + const strata::core::OnDevice on(gs.dev); + strata::core::VerifyHits vs; + vs.d_res = gs.d_res; + vs.h_res = host_res.empty() ? nullptr : host_res.data(); + vs.cache_base = gs.cache.device_slot(0); + vs.blob = thits.blob; + vs.slot_off = gs.cache.slot_offsets(); + vs.n_slots = gs.cache.slots(); + if (!gs.ver_b.init(gs.wt, g, gs.ss, vs, gs.head.loaded() ? &gs.head : nullptr, o.spec, err)) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA%d (the later " + "card): %s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", + gs.dev, err.c_str()); + return 1; + } + if (cudaMalloc((void**) &pl_mtp_R, (size_t) strata::kernels::kVerifyMaxT * (size_t) (g.hc * g.n_embd) * + sizeof(float)) != cudaSuccess) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the drafter's row buffer does not fit\n"); + return 1; + } + } + if (!ver_b.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { + std::fprintf(stderr, "strata serve: --pipeline-windows: the second verifier on CUDA0 (the first card): " + "%s (raise --vram-reserve-mib by ~200, or --pipeline-windows 0)\n", err.c_str()); + return 1; + } + ver_b.set_next(&gs.ver_b, &split_drive_b); // the setters reach it; the pipeline never chains run/commit + } ver.set_remote_expert_opt(remote_opt.get()); - if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, std::max(o.spec, o.batch), err) || - !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, ver.final_R_all(), err)) { + if (batch_mtp) ver.set_batch_graph_limit(64); // --batch-mtp only: slot rotation makes many layouts (LRU); 0.1.39 keeps all + if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, + batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, o.batch), err) || + (use_mtp && !mtp.bind(last_st ? last_st->wt : wt, last_st ? &last_st->head : &native_head, + pipe ? pl_mtp_R : ver.final_R_all(), err))) { std::fprintf(stderr, "strata serve: %s\n", err.c_str()); return 1; } + if (pipe) mtp.set_source_R(ver.final_R_all()); // the serial decode's rows (the last stage's even verifier) + auto free_slot_mtp_rows = [](float* p) { if (p != nullptr) (void) cudaFree(p); }; + std::vector> slot_mtp_rows; + if (batch_mtp) { + for (int b = 0; b < o.batch; ++b) { + float* r = nullptr; + const size_t bytes = (size_t) o.spec * (size_t) g.hc * (size_t) g.n_embd * sizeof(float); + if (cudaMalloc((void**) &r, bytes) != cudaSuccess) { + std::fprintf(stderr, "strata serve: batch MTP slot %d residual buffer does not fit%s\n", + b, vram_free_note().c_str()); + return 1; + } + slot_mtp_rows.emplace_back(r, free_slot_mtp_rows); + if (!slot_mtp[(size_t) b]->bind(wt, &native_head, r, err, &mtp)) { + std::fprintf(stderr, "strata serve: batch MTP slot %d: %s%s\n", b, err.c_str(), + vram_free_note().c_str()); + return 1; + } + } + } // each stage's verifier gets its stage's slot sessions if (o.batch > 0) { for (size_t k = 0; k < bslot_ss.size(); ++k) { @@ -5274,6 +5660,15 @@ int main(int argc, char** argv) { stage_ver(st).set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); } } + if (pipe) { // the odd windows' pool routing: the same as the even ones', with their plans + split_drive_b = split_drive; + split_drive_b.plan[0] = ver_b.plan_sink(); + split_drive_b.plan[1] = stages[0]->ver_b.plan_sink(); + stages[0]->ver_b.set_split(o.spec_split); + stages[0]->ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + ver_b.set_split(o.spec_split); + ver_b.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + } // the pool the verify windows call: with a layer split, the wrapper that routes each layer to its stage const strata::core::PoolMultiFn win_pool_fn = n_stages > 1 ? &drive_pool_split : &drive_pool_multi; void* const win_pool_user = n_stages > 1 ? (void*) &split_drive : (void*) &drive; @@ -5284,6 +5679,86 @@ int main(int argc, char** argv) { // issue #31's thread dumps show the host stuck in that cudaMemcpyAsync on a driver lock for good. The copy // kernel needs no host CUDA call there, and costs ~1-3% decode on IQ3_S (45.3 -> 44.8 tok/s, 8 requests). ver.set_pcie_mode(o.pcie_mode == "dma" ? 0 : o.pcie_mode == "direct" ? 1 : 2); + // --pipeline-windows 2: stage 0's GDN state before a speculative commit, restored when the guess was wrong. + // Window W reads the state its snapshot must hold and no window writes it (only commits do), so it is copied + // on a side stream while W runs, into the buffer of W's parity, and only W's speculative commit waits for it + // (STRATA_PIPELINE_SNAP_OVERLAP=0: one buffer, copied on the critical path). + const size_t pl_snap_bytes = pipe ? gdn_snapshot_bytes(ss) : 0; + float* pl_snap2[2] = {nullptr, nullptr}; + cudaStream_t pl_snap_stream = nullptr; + cudaEvent_t pl_snap_pre[2] = {nullptr, nullptr}, pl_snap_ev[2] = {nullptr, nullptr}; + bool pl_snap_overlap = false; + if (pipe && o.pipeline_windows >= 2) { + if (cudaMalloc((void**) &pl_snap2[0], pl_snap_bytes) != cudaSuccess) { + std::fprintf(stderr, "strata serve: --pipeline-windows 2: the GDN snapshot (%.1f MiB) does not fit; the " + "decode stays serial\n", (double) pl_snap_bytes / 1048576.0); + cudaGetLastError(); + pl_snap2[0] = nullptr; + } else if ([] { const char* v = pipe_dbg_env("STRATA_PIPELINE_SNAP_OVERLAP"); return v == nullptr || std::atoi(v) != 0; }()) { + pl_snap_overlap = cudaMalloc((void**) &pl_snap2[1], pl_snap_bytes) == cudaSuccess && + cudaStreamCreateWithFlags(&pl_snap_stream, cudaStreamNonBlocking) == cudaSuccess; + for (int i = 0; i < 2 && pl_snap_overlap; ++i) + pl_snap_overlap = cudaEventCreateWithFlags(&pl_snap_pre[i], cudaEventDisableTiming) == cudaSuccess && + cudaEventCreateWithFlags(&pl_snap_ev[i], cudaEventDisableTiming) == cudaSuccess; + if (!pl_snap_overlap) cudaGetLastError(); + } + } + if (pipe) + std::fprintf(stderr, "strata serve: --pipeline-windows %d: two verifiers per stage, the stages overlap across " + "windows%s\n", o.pipeline_windows, + pl_snap2[0] == nullptr ? "" : pl_snap_overlap ? " (decode too; the GDN snapshots beside the window)" + : " (decode too; the GDN snapshot on the critical path)"); + // the verifiers by [stage][parity], their pool routing, and the drafter's events (in a pipelined prompt read, a + // stage-1 window waits until the drafter has read the rows of the same parity's previous window) + strata::core::Verifier* PV[2][2] = {{&ver, &ver_b}, {pipe ? &stages[0]->ver : nullptr, pipe ? &stages[0]->ver_b : nullptr}}; + SplitDrive* PSD[2] = {&split_drive, &split_drive_b}; + cudaEvent_t pl_mtp_ev[2] = {nullptr, nullptr}; + bool pl_mtp_live[2] = {false, false}; + bool pl_prepared = false; + // every graph captured and the drafter's prompt path sized while nothing is in flight (a capture syncs its stream) + auto pl_prepare = [&](std::string& e) -> bool { + if (pl_prepared) return true; + for (int st = 0; st < 2; ++st) + for (int par = 0; par < 2; ++par) { + const strata::core::OnDevice on(PV[st][par]->device()); + if (!PV[st][par]->capture_all(e)) return false; + } + if (!mtp.prepare_prefill(e)) return false; + if (o.pipeline_windows >= 2 && pl_snap2[0] != nullptr && !mtp.prepare_chain(e)) return false; + const strata::core::OnDevice on(mtp.device()); + for (cudaEvent_t& ev : pl_mtp_ev) + if (ev == nullptr && cudaEventCreateWithFlags(&ev, cudaEventDisableTiming) != cudaSuccess) { + e = "pipeline: event creation failed"; + return false; + } + pl_prepared = true; + return true; + }; + // INVARIANT: nothing pipelined is in flight outside read_windows_pl and the pipelined decode loop - both end + // here (a checkpoint, a park, the next request and the serial paths all find both stages and the drafter idle). + // Every window in flight is served to its end (its picks discarded), then both stages and the drafter idle. + auto pl_drain = [&]() { + std::string e2; + for (int round = 0; round < 10000000; ++round) { + bool any = false; + for (int st = 0; st < 2; ++st) + for (int par = 0; par < 2; ++par) { + strata::core::Verifier& v = *PV[st][par]; + if (!v.in_flight()) continue; + any = true; + if (v.service(&drive_pool_split, PSD[par], e2) < 0) return; + if (v.done(e2)) v.pl_finish(nullptr, e2); + else if (!e2.empty()) return; + } + if (!any) break; + } + for (int st = 0; st < 2; ++st) { + const strata::core::OnDevice on(PV[st][0]->device()); + cudaStreamSynchronize(PV[st][0]->stream()); + } + const strata::core::OnDevice on(mtp.device()); + cudaStreamSynchronize(mtp.stream()); + }; std::vector cur; // ---- the conversation cache (see ConvCheckpoint). `live` is what the session holds right now: the tokens // it has consumed, so a request that starts with exactly them continues without any copy. `checks` are the @@ -5298,6 +5773,8 @@ int main(int argc, char** argv) { std::vector checks; uint64_t check_clock = 0; // the checkpoints' LRU clock; creation and every use advance it bool cvec_cached = true; // the control vector's state the live session and the checkpoints were read with + // without --mtp the conversation cache stays on: a parked image carries the draft layer's K/V only when there is one + // (the snapshots accept a null draft) strata::core::ConversationCache conversations( o.prompt_cache > 0 ? (size_t) o.conversation_cache_mib * 1024 * 1024 : 0, (size_t) o.conversation_cache_slots); @@ -5316,8 +5793,8 @@ int main(int argc, char** argv) { const size_t n_st = stages.size(); // the draft layer's K/V lives on the last stage's GPU (the drafter is loaded there): with a split it is // saved with that stage's image, under its device; stage 0's image holds none - const strata::core::QsaState* draft0 = n_st > 0 ? nullptr : &mtp.kv_state(); - auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return k + 1 == n_st ? &mtp.kv_state() : nullptr; }; + const strata::core::QsaState* draft0 = n_st > 0 || !use_mtp ? nullptr : &mtp.kv_state(); // no --mtp: no draft K/V (snapshots accept null) + auto draft_of = [&](size_t k) -> const strata::core::QsaState* { return use_mtp && k + 1 == n_st ? &mtp.kv_state() : nullptr; }; strata::core::ConversationCheckpointSplit cs; if (n_st > 0) cs = strata::core::conversation_checkpoints_split(std::move(checks), n_st); // #752: two-phase; a bad_alloc leaves `checks` whole struct MergeBack { @@ -5503,9 +5980,9 @@ int main(int argc, char** argv) { std::vector nxt((size_t) T); for (int64_t t = 0; t < T; ++t) nxt[(size_t) t] = (int32_t) cur[(size_t) (p0 + t + 1)]; // E-9: batched through the prompt path when it can (one GPU: a layer split's drafter is on the last stage) - const bool batched = !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); - if (!e.empty() || (!batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; - if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) + const bool batched = use_mtp && !multi_gpu && sp.draft_kv(mtp, R_rows, nxt.data(), T, p0, e); + if (!e.empty() || (use_mtp && !batched && !mtp.prefill(R_rows, nxt.data(), T, p0, e))) return false; + if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) std::fprintf(stderr, "strata serve: DRAFT_PREFILL path=%s mode=%d cells=%lld\n", batched ? "batched" : "token", mtp.kv_state().kv_mode, (long long) T); // progress for the server window: PP @@ -5614,6 +6091,8 @@ int main(int argc, char** argv) { pending.clear(); res_upload(); }; + // --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt) + std::function adapt_fence; // the VRAM tier follows the conversation (the same rule as the speculative loop below) auto adapt = [&]() -> bool { if (!pending.empty()) return true; // the previous swaps are still in flight @@ -5627,7 +6106,7 @@ int main(int argc, char** argv) { const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { - if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e)) && !(remote_opt && remote_opt->owns(l, e))) cand.emplace_back(u[e], e); } + if (r[e] < 0) { if (u[e] >= 2.0f && !(peer.valid() && peer.has(l, e)) && !(remote_opt && remote_opt->owns(l, e)) && !helper_holds(l, e)) cand.emplace_back(u[e], e); } else vict.emplace_back(u[e], e); } if (cand.empty() || vict.empty()) continue; @@ -5660,10 +6139,25 @@ int main(int argc, char** argv) { (uintptr_t) b + strata::kernels::cpu::expert_layout().blob_bytes(s.layer)); pin_blobs(std::move(spans), pin_live); } + // --pipeline-windows: windows are in flight while the tier adapts. The evicted experts stop being planned + // for the GPU first (the pool computes them on the CPU from the rows every layer publishes, see + // Verifier::set_always_publish); then every copy into their slots waits until all the work the stages' + // streams hold now has completed: any window that may still read those slots was launched before this. + std::vector fenced_slots; + if (adapt_fence && !swaps.empty()) { + for (const Swap& s : swaps) { + const size_t out = (size_t) s.layer * g.n_expert + s.out; + fenced_slots.push_back(host_res[out]); + host_res[out] = strata::core::kNotResident; + } + std::atomic_thread_fence(std::memory_order_seq_cst); + adapt_fence(); + } bool main_live = false; - for (const Swap& s : swaps) { + for (size_t si = 0; si < swaps.size(); ++si) { + const Swap& s = swaps[si]; const size_t in = (size_t) s.layer * g.n_expert + s.in, out = (size_t) s.layer * g.n_expert + s.out; - const int32_t slot = host_res[out]; + const int32_t slot = fenced_slots.empty() ? host_res[out] : fenced_slots[si]; const uint8_t* b = srcp->blob(s.layer, s.in); const int stn = multi_gpu ? stage_of(s.layer) : 0; // the swap stays in the layer's own cache GpuStage* gs = stn > 0 ? stages[(size_t) stn - 1].get() : nullptr; @@ -5706,6 +6200,210 @@ int main(int argc, char** argv) { for (float& v : drive.d.usage) v *= o.adapt_decay; return true; }; + // ---- --adapt-async 1: the asynchronous adaptive tier (opt-in; the resident RAM mode, see the checks where + // the RAM copy is built). adapt() runs a whole round - choose, copy the evicted slots back with a stream sync, + // copy the new experts in from the RAM copy - on a thread the decode loop joins after the draft: ~24 ms every + // 4th window with ~90 swaps. Here a round moves through four steps, each started by `adapt_tick` between + // windows once the previous step's copies (events) and host work (the job thread) are done: + // 1. job: choose (adapt()'s rule, over snapshots of the routing counts and the residency) and copy the + // evicted slots back into exchange buffers (D2H), each from the cache of the card that owns its layer; + // 2. stage the exchanges and mark the evicted experts non-resident (the CPU reads them from the exchange + // buffers from the next window on); job: copy the new experts in (straight from a page-locked RAM copy, + // else through a pinned bounce buffer), on the owning card's refill stream; + // 3. mark the new experts resident; job: move the evicted blobs into the RAM places the new ones left; + // 4. flip the copy's offsets. + // A slot is overwritten only after its old expert stopped being planned for the GPU (step 2, between windows, + // with the device copies of the residency table uploaded as apply_pending does), and a RAM place only once its + // expert is resident (step 3), so no window computes from memory that is changing. A request starts with the + // round drained (adapt_tick(true)), before its prompt lends any slot. Not bit-exact run to run: which window + // first computes a swapped-in expert on the GPU (which rounds differently from the CPU) depends on when its + // copy lands. `j`: the swap's exchange buffer (its copy back) and bounce buffer (a_cap + j). + struct ASwap { int32_t layer, in, out, slot; int home; int64_t j; bool exchange; }; + struct AHome { strata::core::ExpertCache* cache; cudaStream_t stream; cudaEvent_t ev; int dev; bool used; }; + enum class AState { Idle, CopyBack, SwapIn, Commit }; + AState astate = AState::Idle; + std::vector aswaps; + std::vector a_usage; + std::vector a_res; + int64_t a_win = 0, a_last = 0, a_rounds = 0, a_swapped = 0; + double a_ms = 0; // wall time from a round's start to its flip, summed (the "ms/round" stat) + Clock::time_point a_t0; + std::atomic a_err{false}; + std::vector ahomes; // [0] = CUDA0's cache, [k] = layer split stage k's + std::unique_ptr ajob; + const int64_t a_cap = std::min(o.adapt_swaps, 96); // as the blocking tier's exchange buffers + if (o.adapt_async && !drive.d.usage.empty() && src.complement_ready() && src.exchange_capacity() >= 2 * a_cap) { + ahomes.push_back({&xcache, adapt_stream, adapt_ev, 0, false}); + for (auto& st : stages) ahomes.push_back({&st->cache, st->adapt_stream, st->adapt_ev, st->dev, false}); + ajob = std::make_unique(); + std::fprintf(stderr, "strata serve: adaptive tier asynchronous (--adapt-async 1): up to %lld swaps per round, " + "a round every %d windows\n", (long long) a_cap, o.adapt_every); + } + auto a_flush = [&]() { // the job's copies: an event after them on every stream used, submitted now (WDDM) + for (AHome& h : ahomes) + if (h.used) { + const strata::core::OnDevice on(h.dev); + if (cudaEventRecord(h.ev, h.stream) != cudaSuccess) a_err = true; + (void) cudaStreamQuery(h.stream); + } + }; + auto a_choose = [&]() { // step 1, on the job thread + struct C { float gain; int32_t layer, in, out; }; + std::vector all; + std::vector> cand, vict; + for (int64_t l = 0; l < g.n_layers; ++l) { + cand.clear(); + vict.clear(); + const float* u = a_usage.data() + l * g.n_expert; + const int32_t* r = a_res.data() + l * g.n_expert; + for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { + if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); } + else vict.emplace_back(u[e], e); + } + if (cand.empty() || vict.empty()) continue; + std::sort(cand.begin(), cand.end(), [](auto& a, auto& b) { return a.first > b.first; }); + const size_t nc = std::min(cand.size(), vict.size()); + std::partial_sort(vict.begin(), vict.begin() + (ptrdiff_t) nc, vict.end(), + [](auto& a, auto& b) { return a.first < b.first; }); + for (size_t i = 0; i < nc; ++i) { + if (cand[i].first < vict[i].first + 1.5f) break; + all.push_back({cand[i].first - vict[i].first, (int32_t) l, cand[i].second, vict[i].second}); + } + } + std::sort(all.begin(), all.end(), [](const C& a, const C& b) { return a.gain > b.gain; }); + aswaps.clear(); + for (const C& c : all) { + if ((int64_t) aswaps.size() >= a_cap) break; + const int32_t slot = a_res[(size_t) c.layer * g.n_expert + c.out]; + if (slot < 0) continue; + // an exchange (as resident_stage_swaps): `in` from the RAM copy, `out` held by its slot alone takes its + // place there; otherwise `out` is in the copy already (the lend region) or `in` is not (a RAM budget) + const bool x = src.has_resident(c.layer, c.in) && !src.has_resident(c.layer, c.out); + aswaps.push_back({c.layer, c.in, c.out, slot, multi_gpu ? stage_of(c.layer) : 0, (int64_t) aswaps.size(), x}); + } + for (AHome& h : ahomes) h.used = false; + for (const ASwap& w : aswaps) { + if (!w.exchange) continue; + AHome& h = ahomes[(size_t) w.home]; + const strata::core::OnDevice on(h.dev); + if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j), h.cache->device_slot(w.slot), + (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer), + cudaMemcpyDeviceToHost, h.stream); e != cudaSuccess) { + std::fprintf(stderr, "strata serve: adaptive tier: copy back of layer %d slot %d (CUDA%d) failed: %s\n", + (int) w.layer, (int) w.slot, h.dev, cudaGetErrorString(e)); + a_err = true; + } + h.used = true; + } + a_flush(); + }; + auto a_copy_in = [&]() { // step 2, on the job thread + for (AHome& h : ahomes) h.used = false; + for (const ASwap& w : aswaps) { + AHome& h = ahomes[(size_t) w.home]; + const size_t nb = (size_t) strata::kernels::cpu::expert_layout().blob_bytes(w.layer); + const uint8_t* b = src.pinned(w.layer, w.in) ? src.resident_blob(w.layer, w.in) : nullptr; + if (b == nullptr) { // pageable, or not in the RAM copy: through a bounce buffer (an async copy) + uint8_t* bb = src.exchange_buffer(a_cap + w.j); + if (bb == nullptr || !src.copy_blob(w.layer, w.in, bb)) { + std::fprintf(stderr, "strata serve: adaptive tier: layer %d expert %d could not be read\n", + (int) w.layer, (int) w.in); + a_err = true; + continue; + } + b = bb; + } + const strata::core::OnDevice on(h.dev); + if (const cudaError_t e = cudaMemcpyAsync(h.cache->device_slot(w.slot), b, nb, cudaMemcpyHostToDevice, + h.stream); e != cudaSuccess) { + std::fprintf(stderr, "strata serve: adaptive tier: copy of layer %d into slot %d (CUDA%d) failed: %s\n", + (int) w.layer, (int) w.slot, h.dev, cudaGetErrorString(e)); + a_err = true; + } + h.used = true; + } + a_flush(); + }; + auto a_ready = [&](bool wait) -> bool { // the job and its copies are done + if (wait) ajob->wait(); + else if (!ajob->idle()) return false; + for (AHome& h : ahomes) + if (h.used) { + const strata::core::OnDevice on(h.dev); + if (wait) { if (cudaEventSynchronize(h.ev) != cudaSuccess) a_err = true; } + else if (const cudaError_t q = cudaEventQuery(h.ev); q == cudaErrorNotReady) return false; + else if (q != cudaSuccess) a_err = true; + } + return true; + }; + // between windows: `drain` finishes the round in flight and starts none. False when a copy failed. + auto adapt_tick = [&](bool drain) -> bool { + if (!ajob) return true; + if (!drain) ++a_win; // one tick per window + for (;;) { + if (a_err.load()) return false; + switch (astate) { + case AState::Idle: + if (drain || a_win - a_last < (int64_t) o.adapt_every) return true; + a_last = a_win; + ++a_rounds; + a_t0 = Clock::now(); + a_usage = drive.d.usage; + a_res = host_res; + // #477: the routing counted, as adapt() counts it (--expert-profile-save; else `heat` is empty) + for (size_t i = 0; i < heat.size(); ++i) heat[i] += (double) drive.d.usage[i]; + for (float& v : drive.d.usage) v *= o.adapt_decay; + ajob->post(a_choose); + astate = AState::CopyBack; + return true; + case AState::CopyBack: { // step 2: the evicted experts leave the GPU's plan + if (!a_ready(drain)) return true; + if (a_err.load()) return false; + size_t k = 0; + for (size_t i = 0; i < aswaps.size(); ++i) { + const ASwap w = aswaps[i]; + const size_t out = (size_t) w.layer * g.n_expert + w.out; + if (host_res[out] != w.slot) continue; // the table moved since the snapshot: not this one + if (w.exchange && !src.stage_exchange(w.layer, w.in, w.out, w.j)) { + std::fprintf(stderr, "strata serve: adaptive tier: stage_exchange refused layer %d in %d out %d\n", + (int) w.layer, (int) w.in, (int) w.out); + return false; + } + host_res[out] = strata::core::kNotResident; // the CPU computes it from the next window on + srcp->prefetch(w.layer, w.out); + aswaps[k++] = w; + } + aswaps.resize(k); + res_upload(); + ajob->post(a_copy_in); + astate = AState::SwapIn; + if (!drain) return true; + continue; + } + case AState::SwapIn: // step 3: the new experts are in their slots + if (!a_ready(drain)) return true; + if (a_err.load()) return false; + for (const ASwap& w : aswaps) { + host_res[(size_t) w.layer * g.n_expert + w.in] = w.slot; + srcp->release(w.layer, w.in); + } + res_upload(); + a_swapped += (int64_t) aswaps.size(); + ajob->post([&] { src.commit_copies(); }); + astate = AState::Commit; + if (!drain) return true; + continue; + case AState::Commit: // step 4 + if (!a_ready(drain)) return true; + if (a_err.load()) return false; + src.commit_flip(); + a_ms += std::chrono::duration(Clock::now() - a_t0).count(); + aswaps.clear(); + astate = AState::Idle; + continue; // a round due now starts at this same boundary + } + } + }; // #477: write the learned profile (between requests and at QUIT: a prompt's lent slots are back by then). // A swap still in flight counts as done - its expert is resident once the copy lands. `why`: for the log. auto save_profile = [&](const char* why) { @@ -5713,6 +6411,8 @@ int main(int argc, char** argv) { std::vector resident(host_res.size(), 0); for (size_t i = 0; i < host_res.size(); ++i) resident[i] = host_res[i] >= 0; for (const auto& p : pending) resident[(size_t) p.first] = 1; + if (astate == AState::SwapIn) // --adapt-async: the same for a round past its step 2 + for (const ASwap& w : aswaps) resident[(size_t) w.layer * g.n_expert + w.in] = 1; std::string e; const auto ranked = strata::core::rank_learned_profile(g.n_layers, g.n_expert, resident, heat, profile_loaded); @@ -5882,7 +6582,9 @@ int main(int argc, char** argv) { int64_t rounds = 0; const int S = o.spec; const int S_mtp = o.mtp_max_t > 0 ? std::min(o.mtp_max_t, S) : S; // the MTP's windows; suffixes go up to S - if (S_mtp < S) mtp.set_max_drafts(S_mtp - 1); + if (use_mtp && S_mtp < S) mtp.set_max_drafts(S_mtp - 1); + // --pipeline-windows 2 loads the drafter with 8 rows: the serial loop's chain keeps its own length + else if (use_mtp && mtp.max_t() > S_mtp) mtp.set_max_drafts(S_mtp - 1); strata::spec::SuffixDrafter sfx(std::max(1, o.suffix_draft), 64, (size_t) o.max_context + 4096); strata::spec::DraftPolicy policy(S); // MTP or lookup window, learned over the whole process // The vision path (--vision): GENI carries images. The file is one @@ -6016,6 +6718,8 @@ int main(int argc, char** argv) { struct BSlot { bool active = false, stop = false; int32_t x = 0; ///< the token the next window feeds (not yet in the slot's state) + std::array draft{}; ///< the slot's next MTP proposal + bool draft_ready = false; int64_t p = 0; ///< its position int64_t produced = 0, max_new = 0; Clock::time_point t0; @@ -6074,6 +6778,17 @@ int main(int argc, char** argv) { } if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch admission: device sync failed"; return false; } } + if (batch_mtp) { + // Admission first builds the solo draft KV; copy it into the slot before drafting. + strata::core::ConversationKv image; + if (!mtp.idle(e) || !slot_mtp[(size_t) b]->idle(e) || + !strata::core::conversation_kv_save(image, mtp.kv_state(), draft_geometry, upto, false, e) || + !strata::core::conversation_kv_restore(image, slot_mtp[(size_t) b]->kv_state(), + draft_geometry, upto, false, e) || + cudaDeviceSynchronize() != cudaSuccess) + return false; + slot_mtp[(size_t) b]->set_prompt_len(upto); + } return true; }; // slot b's sessions -> the main ones (the reverse of copy_to_slot): a request that continues the @@ -6107,6 +6822,17 @@ int main(int argc, char** argv) { } if (cudaDeviceSynchronize() != cudaSuccess) { e = "batch slot restore: device sync failed"; return false; } } + if (batch_mtp) { + // A returning solo request resumes from its slot's draft KV. + strata::core::ConversationKv image; + if (!slot_mtp[(size_t) b]->idle(e) || !mtp.idle(e) || + !strata::core::conversation_kv_save(image, slot_mtp[(size_t) b]->kv_state(), + draft_geometry, upto, false, e) || + !strata::core::conversation_kv_restore(image, mtp.kv_state(), draft_geometry, upto, false, e) || + cudaDeviceSynchronize() != cudaSuccess) + return false; + mtp.set_prompt_len(upto); + } return true; }; // one batch window over the active slots only (row t is the t-th active slot): an idle slot is not touched, @@ -6116,13 +6842,32 @@ int main(int argc, char** argv) { int rows[strata::kernels::kVerifyMaxT] = {}; int32_t tok[strata::kernels::kVerifyMaxT] = {}, outb[strata::kernels::kVerifyMaxT] = {}; int64_t pos[strata::kernels::kVerifyMaxT] = {}; - for (int b = 0; b < (int) bs.size() && S < strata::kernels::kVerifyMaxT; ++b) + int first[strata::kernels::kVerifyMaxT] = {}, active[strata::kernels::kVerifyMaxT] = {}; + static size_t next_slot = 0; + // Each MTP slot uses two rows; rotate slots when more than four are active. + int A = 0; + for (size_t offset = 0; offset < bs.size() && S + (batch_mtp ? 2 : 1) <= strata::kernels::kVerifyMaxT; ++offset) { + const int b = (int) ((next_slot + offset) % bs.size()); if (bs[(size_t) b].active) { + first[A] = S; + active[A++] = b; rows[S] = b; tok[S] = bs[(size_t) b].x; pos[S] = bs[(size_t) b].p; ++S; + if (batch_mtp) { + rows[S] = b; + if (!bs[(size_t) b].draft_ready) { + err = "batch MTP: a live slot has no draft"; + return false; + } + tok[S] = bs[(size_t) b].draft[0]; + pos[S] = bs[(size_t) b].p + 1; + ++S; + } } + } + if (batch_mtp && A > 0) next_slot = ((size_t) active[A - 1] + 1) % bs.size(); if (S == 0) return true; const bool was_busy = strata::core::progress().busy.load(); strata::core::progress().busy.store(true); @@ -6141,7 +6886,16 @@ int main(int argc, char** argv) { return false; } const Clock::time_point w1 = Clock::now(); - if (!ver.commit_slots(err)) { + // Accept the proposal only when the target picked it and there is room to emit both tokens. + std::vector keep(bs.size(), 0); + for (int a = 0; a < A; ++a) { + const int b = active[a], i = first[a]; + const BSlot& sl = bs[(size_t) b]; + const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outb[i]) != o.eos_ids.end(); + keep[b] = batch_mtp && outb[i] == tok[i + 1] && !eos && !sl.stop && + sl.produced + 2 <= sl.max_new && sl.p + 3 <= o.max_context ? 2 : 1; + } + if (!(batch_mtp ? ver.commit_slot_prefixes(keep.data(), err) : ver.commit_slots(err))) { std::printf("ERR %s\n", err.c_str()); return false; } @@ -6150,26 +6904,40 @@ int main(int argc, char** argv) { bt_run += msd(w0, w1); bt_commit += msd(w1, w2); ++bt_windows; - bt_rows += S; - for (int t = 0; t < S; ++t) { - const int b = rows[t]; + for (int a = 0; a < A; ++a) bt_rows += keep[active[a]]; + for (int t = 0; t < A; ++t) { + const int b = active[t]; BSlot& sl = bs[(size_t) b]; - const int32_t y = outb[t]; - sl.ids.push_back(sl.x); // the window fed it: the slot's sessions hold it now - std::printf("BT %d %d\n", b, (int) y); - ++sl.produced; - const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); - const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" - : sl.p + 2 > o.max_context ? "length" : nullptr; - if (fin != nullptr) { - const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); - std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms); - sl.active = false; - sl.cached = o.prompt_cache > 0 && !sl.img; // its sessions hold sl.ids for the next turn - } else { + for (int j = 0; j < keep[b]; ++j) { + const int32_t y = outb[first[t] + j]; + sl.ids.push_back(tok[first[t] + j]); + std::printf("BT %d %d\n", b, (int) y); + ++sl.produced; + const bool eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) y) != o.eos_ids.end(); + const char* fin = eos ? "stop" : sl.stop ? "cancel" : sl.produced >= sl.max_new ? "length" + : sl.p + 2 > o.max_context ? "length" : nullptr; + if (fin != nullptr) { + const double ms = std::chrono::duration(Clock::now() - sl.t0).count(); + std::printf("BDONE %d %lld %s %.1f\n", b, (long long) sl.produced, fin, ms); + sl.active = false; + sl.cached = o.prompt_cache > 0 && !sl.img; + break; + } sl.x = y; sl.p += 1; } + if (batch_mtp && sl.active) { + const size_t stride = (size_t) g.hc * (size_t) g.n_embd; + if (cudaMemcpy(slot_mtp_rows[(size_t) b].get(), + ver.final_R_all() + (size_t) first[t] * stride, + 2 * stride * sizeof(float), cudaMemcpyDeviceToDevice) != cudaSuccess || + !slot_mtp[(size_t) b]->draft(2, outb + first[t], pos[first[t]], keep[b] - 1, + sl.draft.data(), err)) { + std::printf("ERR batch MTP slot %d: %s\n", b, err.c_str()); + return false; + } + sl.draft_ready = true; + } } std::fflush(stdout); bt_emit += msd(w2, Clock::now()); @@ -6616,7 +7384,7 @@ int main(int argc, char** argv) { if (incoming) for (size_t i = 0; i < stages.size(); ++i) { const strata::core::OnDevice on(stages[i]->dev); if (!strata::core::conversation_snapshot_validate(incoming->stage_images[i], stages[i]->ss, g, - i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err)) { // the draft: the last stage's + use_mtp && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err)) { // the draft: the last stage's std::fprintf(stderr, "strata serve: conversation cache: discard invalid stage snapshot (%s)\n", err.c_str()); incoming.reset(); @@ -6625,7 +7393,7 @@ int main(int argc, char** argv) { } } if (incoming && !strata::core::conversation_snapshot_validate(*incoming, ss, g, - stages.empty() ? &mtp.kv_state() : nullptr, err)) { + use_mtp && stages.empty() ? &mtp.kv_state() : nullptr, err)) { std::fprintf(stderr, "strata serve: conversation cache: discard invalid snapshot (%s)\n", err.c_str()); incoming.reset(); err.clear(); @@ -6676,7 +7444,7 @@ int main(int argc, char** argv) { if (incoming) { const auto t0 = Clock::now(); if (strata::core::conversation_snapshot_restore(*incoming, ss, g, - stages.empty() ? &mtp.kv_state() : nullptr, err) != + use_mtp && stages.empty() ? &mtp.kv_state() : nullptr, err) != strata::core::ConversationRestore::restored) { // Already prevalidated above: a failure here is fatal, never // permission to decode from a partially restored session. @@ -6686,7 +7454,7 @@ int main(int argc, char** argv) { for (size_t i = 0; i < stages.size(); ++i) { // the later stages' parts const strata::core::OnDevice on(stages[i]->dev); if (strata::core::conversation_snapshot_restore(incoming->stage_images[i], stages[i]->ss, g, - i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err) != + use_mtp && i + 1 == stages.size() ? &mtp.kv_state() : nullptr, err) != strata::core::ConversationRestore::restored) { std::printf("ERR restoring parked conversation (stage CUDA%d): %s\n", stages[i]->dev, err.c_str()); @@ -6694,7 +7462,7 @@ int main(int argc, char** argv) { } if (cudaDeviceSynchronize() != cudaSuccess) { std::printf("ERR stage sync\n"); return 1; } } - if (std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { + if (use_mtp && std::getenv("STRATA_SNAPSHOT_VERIFY") != nullptr) { uint64_t draft_hash = 0; const auto& draft_kv = stages.empty() ? incoming->kv.back() : incoming->stage_images.back().kv.back(); const strata::core::OnDevice on_d(stages.empty() ? 0 : stages.back()->dev); @@ -6789,9 +7557,9 @@ int main(int argc, char** argv) { } // KV streaming: the drafter's ring may hold cells past `resume` from a longer turn; the main layers' // host copies and slots are always current (every writer writes both), so they need nothing - if (resume > 0 && reread_to <= 0) mtp.kv_restore(resume); + if (use_mtp && resume > 0 && reread_to <= 0) mtp.kv_restore(resume); tr("request", n, geni ? 1 : 0); - mtp.set_prompt_len(n); + if (use_mtp) mtp.set_prompt_len(n); const int64_t read_from = reread_to > 0 ? 0 : resume; conversations.limit_reuse(read_from); pp_total = n; @@ -6815,15 +7583,132 @@ int main(int argc, char** argv) { // read batched and its header still goes through the windows. Picture rows need the batched path. // STRATA_CKPT_REREAD compares a restored checkpoint with a batched re-read, so it keeps every read batched. static const bool no_short = std::getenv("STRATA_CKPT_REREAD") != nullptr; + int64_t req_short_read = o.short_read; // STRATA_PIPELINE_SWITCH may set it per request (short_read=) auto windows_ok = [&](int64_t a, int64_t b) -> bool { - if (no_short || b - a > o.short_read) return false; + if (no_short || b - a > req_short_read) return false; if (sp.embd_rows != nullptr) for (int64_t i = a; i < b; ++i) if (sp.embd_rows[i] != nullptr) return false; return true; }; + // --pipeline-windows, testing: STRATA_PIPELINE_SWITCH= is read at every request, "pw=<0|1|2> + // theta= force_miss= short_read=" - an A/B of the pipelined and the serial loops (and forced + // rollbacks) on one server, with the same expert placement + int pl_pw = pipe ? o.pipeline_windows : 0; + float pl_theta = [] { // a speculative window is launched only when its estimated chance is at least this + const char* v = pipe_dbg_env("STRATA_PIPELINE_THETA"); + return v ? (float) std::atof(v) : 0.2f; + }(); + int pl_force_miss = [] { // exactness test: every k-th speculative window gets a wrong first token + const char* v = pipe_dbg_env("STRATA_PIPELINE_FORCE_MISS"); + return v ? std::max(0, std::atoi(v)) : 0; + }(); + if (static const char* sw = pipe_dbg_env("STRATA_PIPELINE_SWITCH"); sw != nullptr && pipe) { + if (std::FILE* f = std::fopen(sw, "r")) { + char buf[256] = {}; + const size_t nr = std::fread(buf, 1, sizeof buf - 1, f); + std::fclose(f); + buf[nr] = 0; + if (const char* q = std::strstr(buf, "pw=")) pl_pw = std::max(0, std::min(2, std::atoi(q + 3))); + if (const char* q = std::strstr(buf, "theta=")) pl_theta = (float) std::atof(q + 6); + if (const char* q = std::strstr(buf, "force_miss=")) pl_force_miss = std::max(0, std::atoi(q + 11)); + if (const char* q = std::strstr(buf, "short_read=")) req_short_read = std::max(0LL, std::atoll(q + 11)); + std::fprintf(stderr, "strata pipeline switch: pw=%d theta=%.3f force_miss=%d short_read=%lld\n", pl_pw, + pl_theta, pl_force_miss, (long long) req_short_read); + } + } + // --pipeline-windows: tokens [a, b) through the windows with the stages overlapped. The tokens are known, + // so every window commits whole: stage 0 queues window K, its commit and window K+1 back to back (each + // parity's verifier keeps its own window), and stage 1 runs window K once stage 0 is done with it. Every + // stage runs the same windows in the same order as read_windows below, so the session ends the same. + auto read_windows_pl = [&](int64_t a, int64_t b, std::string& e) -> bool { + strata::core::progress_at("reading the prompt (pipelined verify windows), from token", a); + if (!pl_prepare(e)) return false; + for (int par = 0; par < 2; ++par) PV[0][par]->set_head_sampling(false); // reaches stage 1 (set_next) + struct Restore { + strata::core::Verifier* v[2]; + ~Restore() { v[0]->set_head_sampling(true); v[1]->set_head_sampling(true); } + } restore{{PV[0][0], PV[0][1]}}; + struct Win { int T; int64_t q; }; + std::vector wins; + for (int64_t q = a; q < b;) { + const int T = (int) std::min(S, b - q); + wins.push_back({T, q}); + q += T; + } + const size_t N = wins.size(); + std::vector w0((size_t) S), w1((size_t) S), nx((size_t) S); + size_t l0 = 0, f0 = 0, l1 = 0, f1 = 0; // stage 0 launched / finished, stage 1 launched / finished + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + auto fail = [&](std::string why) -> bool { + pl_drain(); + e = why.empty() ? std::string("a pipelined prompt window failed") : why; + return false; + }; + while (f1 < N) { + if (stop_req.load()) return fail("cancelled"); + // stage 0: up to two windows queued; window K+2 (K's parity) only once stage 1 has finished window + // K, whose hand-off K+2 overwrites + while (l0 < N && l0 < f0 + 2 && l0 < f1 + 2) { + const Win& w = wins[l0]; + for (int t = 0; t < w.T; ++t) w0[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)]; + strata::core::Verifier& v = *PV[0][l0 & 1]; + if (!v.pl_launch(w.T, w0.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e); + ++l0; + } + if (f0 < l0) { + strata::core::Verifier& v = *PV[0][f0 & 1]; + if (v.service(win_pool_fn, PSD[f0 & 1], e) < 0) return fail(e); + if (v.done(e)) { + if (!v.pl_finish(nullptr, e)) return fail(e); + ++f0; + } else if (!e.empty()) return fail(e); + } + if (l1 < f0 && l1 == f1) { // stage 1: the next window, its stage 0 done + const Win& w = wins[l1]; + for (int t = 0; t < w.T; ++t) w1[(size_t) t] = (int32_t) cur[(size_t) (w.q + t)]; + strata::core::Verifier& v = *PV[1][l1 & 1]; + if (pl_mtp_live[l1 & 1]) { // the drafter has read this parity's previous rows first + const strata::core::OnDevice on(mtp.device()); + cudaStreamWaitEvent(v.stream(), pl_mtp_ev[l1 & 1], 0); + } + if (!v.pl_launch(w.T, w1.data(), w.q, e) || !v.pl_commit_async(w.T, e)) return fail(e); + ++l1; + } + if (f1 < l1) { + strata::core::Verifier& v = *PV[1][f1 & 1]; + if (v.service(win_pool_fn, PSD[f1 & 1], e) < 0) return fail(e); + if (v.done(e)) { + if (!v.pl_finish(nullptr, e)) return fail(e); + const Win& w = wins[f1]; + for (int t = 0; t < w.T; ++t) nx[(size_t) t] = (int32_t) cur[(size_t) (w.q + t + 1)]; + if (!mtp.prefill(v.final_R(0), nx.data(), w.T, w.q, e, false)) return fail(e); + { + const strata::core::OnDevice on(mtp.device()); + cudaEventRecord(pl_mtp_ev[f1 & 1], mtp.stream()); + } + pl_mtp_live[f1 & 1] = true; + pp_reached = w.q + w.T; // #471 + ++f1; + } else if (!e.empty()) return fail(e); + } + if (drive.d.failed) return fail(drive.d.fail ? drive.d.fail : "the expert pool failed"); + } + pl_drain(); // nothing in flight: both stages' commits and the drafter's rows have landed + pl_mtp_live[0] = pl_mtp_live[1] = false; + const double ms = std::chrono::duration(Clock::now() - pp_t0).count(); + std::printf("PP %lld %lld %.0f %.1f\n", (long long) b, (long long) pp_total, ms, + ms > 0.0 ? 1000.0 * (double) (b - pp_from) / ms : 0.0); + strata::core::progress_beat(); + std::fflush(stdout); + return true; + }; // tokens [a, b) through the windows: commit all of them, then give the draft layer their residuals auto read_windows = [&](int64_t a, int64_t b, std::string& e) -> bool { + // (STRATA_LOGPOS reads every window's logits: the serial loop) + if (pipe && pl_pw >= 1 && std::getenv("STRATA_LOGPOS") == nullptr) return read_windows_pl(a, b, e); strata::core::progress_at("reading the prompt (verify windows), from token", a); // #217: not "batched" // every token is committed and the picks are discarded: no head sampling (see set_head_sampling) struct NoHeadSampling { @@ -6860,7 +7745,7 @@ int main(int argc, char** argv) { }(); if (logpos != nullptr && !ver.window_logprobs(nxt.data(), T, q, logpos_extra, logpos, e)) return false; - if (!ver.commit(T, e) || !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e)) return false; + if (!ver.commit(T, e) || (use_mtp && !mtp.prefill(ver.final_R_all(), nxt.data(), T, q, e))) return false; q += T; pp_reached = q; // #471 } @@ -7078,6 +7963,10 @@ int main(int argc, char** argv) { return true; }; apply_pending(true); + if (!adapt_tick(true)) { // --adapt-async: the round in flight lands before the prompt lends any slot + std::printf("ERR an adaptive refill failed\n"); + return 1; + } // per-request sampling for the verify window's head (greedy when temperature is absent) strata::kernels::SamplerParams req_sp; req_sp.greedy = req_temperature <= 0.0f; @@ -7093,14 +7982,17 @@ int main(int argc, char** argv) { req_sp.penalty_present = req_penalty_present; req_sp.counter = 0; ver.set_sampling(req_sp); - mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) + if (pipe) ver_b.set_sampling(req_sp); // (reaches the later stage's odd verifier) + if (use_mtp) mtp.set_draft_sampling(req_sp); // STRATA_SPEC_COUPLED=1: sampled drafts (a no-op otherwise) drive.d.pcie_num = std::max(0, std::min(256, (int) (req_pcie_frac * 256.0 + 0.5))); // a layer split: CUDA0's share as asked; a later GPU keeps its own (its link) unless the request sets one for (int st = 0; st < split_drive.n; ++st) split_drive.pcie_num[st] = (st == 0 || split_same || req_pcie_frac != o.pcie_frac) ? drive.d.pcie_num : pcie_num_of(stages[(size_t) st - 1]->pcie_frac); + if (pipe) for (int st = 0; st < split_drive.n; ++st) split_drive_b.pcie_num[st] = split_drive.pcie_num[st]; const int hist_n = std::min(req_sp.penalty_last_n, kPenaltyWindowCap); ver.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); + if (pipe) ver_b.set_history(hist_n > 0 ? d_hist : nullptr, hist_n); bool cancelled = false; tr("prompt start", n - 1); // The prompt is read in two parts when it has a turn boundary past `resume`: up to the last <|im_start|> @@ -7191,8 +8083,10 @@ int main(int argc, char** argv) { // the verify windows: the first holds the last prompt token alone int64_t p = n - 1; int32_t x = (int32_t) ids[(size_t) (n - 1)]; - std::vector drafts((size_t) S, 0), window((size_t) S), outv((size_t) S); - std::vector dprob((size_t) S, 0.0f); + // (the drafter writes max_t - 1 drafts: 8 rows with --pipeline-windows 2) + const size_t DS = (size_t) std::max(S, use_mtp ? mtp.max_t() : 0); + std::vector drafts(DS, 0), window((size_t) S), outv((size_t) S); + std::vector dprob(DS, 0.0f); std::vector sbuf((size_t) S, 0); const bool sfx_on = o.suffix_draft > 0 || o.lookup_chain > 0; if (sfx_on) { @@ -7238,9 +8132,597 @@ int main(int argc, char** argv) { const int64_t decode_look0 = drive.d.cache_hits + drive.d.cache_admitted + drive.d.cache_refused; const int64_t offload0 = drive.d.offload_entries; // #588 if (cancelled) finish = "cancel"; - while (!cancelled && produced_n < max_new) { - int T = S_mtp; - if (req_spec_min_p > 0.0) { + // ======== --pipeline-windows 2: the decode windows with the two cards overlapped ======== + // Stage 0 (the first card) runs window K+1 while stage 1 verifies window K, on the guess that K is accepted + // whole and that its bonus token is the drafter's. The drafter, teacher-forced through K+1's drafts, + // guesses K+1's bonus and drafts K+2 while stage 1 runs K+1. A wrong guess costs the speculative window: + // stage 0's GDN state comes back from a snapshot and K's commit is replayed with its real count (the + // window's own commit inputs are intact in its parity's verifier). Stage 1 never runs a speculative window + // and a window row computes what it would in any other window, so every emitted token is the serial loop's + // (with STRATA_IQ_MT_MIN=1 bit for bit; sampled requests with the same Philox draw per position). + bool pl_ran = false; + const bool pl_want = pipe && pl_pw >= 2 && pl_snap2[0] != nullptr; + const char* pl_serial = !pl_want ? nullptr + : hist_n > 0 ? "repetition penalties (penalty_last_n)" + : mtp.coupled() ? "coupled draft sampling" : nullptr; + if (pl_serial != nullptr) { // said once per reason + static std::set said; + if (said.insert(pl_serial).second) + std::fprintf(stderr, "strata serve: --pipeline-windows: a request with %s decodes serially\n", + pl_serial); + } + if (pl_want && pl_serial == nullptr && !cancelled && produced_n < max_new) { + pl_ran = true; + if (!pl_prepare(err)) { + std::printf("ERR %s\n", err.c_str()); + return 1; + } + struct PW { + int T = 0, seq = 0; + int64_t p = 0; + int32_t tok[8] = {}; + float prob[8] = {}; // prob[i]: the drafter's probability of tok[i + 1] + float p_on = 0.0f; // the chain's estimate that the window before is accepted whole, tok[0] its bonus + bool ready = false, launched = false, finished = false, committed = false, s1 = false, s1_done = false; + bool spec = false; // launched speculatively (behind the window before, ahead of its verdict) + bool made = false; // made from a chain (its outcome can be scored even when the gate held it) + bool sfx = false; // a lookup window (the suffix drafter's drafts) + int sfx_match = 0; + }; + auto V0 = [&](const PW& w) -> strata::core::Verifier& { return *PV[0][w.seq & 1]; }; + auto V1 = [&](const PW& w) -> strata::core::Verifier& { return *PV[1][w.seq & 1]; }; + auto SDf = [&](const PW& w) { return (void*) PSD[w.seq & 1]; }; + const float theta = pl_theta; + const int force_miss = pl_force_miss; + static const bool pl_log = pipe_dbg_env("STRATA_PIPELINE_LOG") != nullptr; + const int dev0 = PV[0][0]->device(); + cudaStream_t s0 = PV[0][0]->stream(); + // the snapshot of the GDN state window `seq` reads (overlapped: before its launch, on the side stream) + auto snap_take = [&](int seq) -> bool { + if (!pl_snap_overlap) return true; + const strata::core::OnDevice on(dev0); + const int q = seq & 1; + return cudaEventRecord(pl_snap_pre[q], s0) == cudaSuccess && + cudaStreamWaitEvent(pl_snap_stream, pl_snap_pre[q], 0) == cudaSuccess && + cudaMemcpyAsync(pl_snap2[q], ss.gdn_state, pl_snap_bytes, cudaMemcpyDeviceToDevice, + pl_snap_stream) == cudaSuccess && + cudaEventRecord(pl_snap_ev[q], pl_snap_stream) == cudaSuccess && + (cudaStreamQuery(pl_snap_stream), true); + }; + PW A, B, D; // A: the oldest window not verified; B: the next; D: a wrong speculative window + bool doomed = false; // D still runs: when it finishes, stage 0 goes back to undo_w's real commit + PW undo_w; + int undo_keep = 0; + int32_t undo_ple[2] = {-1, -1}; + int chain_kind = 0; // 1: after an on-path verdict (A's drafts forced); 2: fresh (A's drafts from it) + bool early_used = false; + bool b_done = false; // B has been made from the chain in flight + int chain_n = 0; + int64_t pl_spec = 0, pl_on = 0, pl_undo = 0, pl_gate = 0, pl_fm = 0; + std::vector outp(8, 0); + bool ending = false; + A.T = 1; + A.p = p; + A.tok[0] = x; + A.ready = true; + drive.d.layers = 0; + drive.d.experts = 0; + drive.d.failed = false; + // the adaptive tier beside the pipeline: the serial loop's rule and adapt() on a thread of its own (its + // copies wait for the windows in flight, which this loop keeps serving meanwhile) + std::thread pl_adapt_thr; + std::atomic pl_adapt_done{true}; + bool pl_adapt_ok = true; + // an error ends the engine, as the serial loop's do: every GPU wait is released first (#267), so no + // window in flight keeps spinning on a flag nobody raises, and the tier's thread can finish + auto die = [&](const std::string& m) -> int { + std::fprintf(stderr, "strata serve: pipelined decode: %s\n", m.c_str()); + strata::core::diag_pipeline_fn().store(nullptr); + strata::core::release_gpu_waits(stderr); + if (pl_adapt_thr.joinable()) pl_adapt_thr.join(); + std::printf("ERR %s\n", m.c_str()); + std::fflush(stdout); + return 1; + }; + // STRATA_PIPELINE_TRACE=: every event of the loop with its time (appended per request) + static const char* pl_trace_path = pipe_dbg_env("STRATA_PIPELINE_TRACE"); + std::string pl_trace; + const Clock::time_point pl_tr0 = Clock::now(); + auto tre = [&](const char* ev, int seq, int x0 = 0, int x1 = 0) { + if (pl_trace_path == nullptr) return; + char b[96]; + std::snprintf(b, sizeof b, "%.3f %s %d %d %d\n", + std::chrono::duration(Clock::now() - pl_tr0).count(), ev, seq, x0, x1); + pl_trace += b; + }; + auto pump0 = [&](PW& w) -> bool { + if (!w.launched || w.finished) return true; + strata::core::Verifier& v = V0(w); + // a doomed window (its guess was wrong) gets empty plans: no expert work on the CPU or the GPU for + // its remaining layers, so it frees stage 0 and the pool sooner (its rows are discarded and the + // undo restores everything it wrote). STRATA_PIPELINE_DOOM_SKIP=0: served in full. + static const bool doom_skip = [] { const char* e = pipe_dbg_env("STRATA_PIPELINE_DOOM_SKIP"); return e == nullptr || std::atoi(e) != 0; }(); + const bool skip = doom_skip && doomed && &w == &D; + if (v.service(skip ? nullptr : &drive_pool_split, SDf(w), err) < 0) return false; + if (v.done(err)) { + if (!v.pl_finish(nullptr, err)) return false; + w.finished = true; + tre("F0", w.seq, w.T, w.spec); + } + return err.empty(); + }; + // the serial loop's window size over the chain's outputs from index `from` (`avail` of them) + auto t_rule = [&](const float* pr, int from, int avail) { + int T = S_mtp; + if (req_spec_min_p > 0.0) { + T = 1; + while (T < S_mtp && from + T - 1 < avail && pr[from + T - 1] >= (float) req_spec_min_p) ++T; + } + return std::max(1, std::min(T, 1 + avail - from)); + }; + // B from the chain's outputs: its row 0 is the guess at index `base`, its drafts follow + auto make_b = [&](const int32_t* oc, const float* op, int base, int avail, float pa) { + B = PW{}; + if (base >= avail) return; + B.seq = A.seq + 1; + B.p = A.p + A.T; + B.tok[0] = oc[base]; + B.T = t_rule(op, base + 1, avail); + for (int i = 1; i < B.T; ++i) { + B.tok[i] = oc[base + i]; + B.prob[i - 1] = op[base + i]; + } + B.p_on = pa * op[base]; + if (force_miss > 0 && ++pl_fm % force_miss == 0) B.tok[0] = B.tok[0] == 0 ? 1 : 0; + B.ready = true; + B.made = true; + }; + // events after all the work both stages' streams hold now, and whether they have passed + cudaEvent_t fence_ev[2] = {nullptr, nullptr}, exch_ev[2] = {nullptr, nullptr}; + { + const strata::core::OnDevice on0(dev0); + cudaEventCreateWithFlags(&fence_ev[0], cudaEventDisableTiming); + cudaEventCreateWithFlags(&exch_ev[0], cudaEventDisableTiming); + } + { + const strata::core::OnDevice on1(stages[0]->dev); + cudaEventCreateWithFlags(&fence_ev[1], cudaEventDisableTiming); + cudaEventCreateWithFlags(&exch_ev[1], cudaEventDisableTiming); + } + auto stage_record = [&](cudaEvent_t* ev) { + { + const strata::core::OnDevice on(dev0); + cudaEventRecord(ev[0], s0); + (void) cudaStreamQuery(s0); + } + const strata::core::OnDevice on(stages[0]->dev); + cudaEventRecord(ev[1], PV[1][0]->stream()); + (void) cudaStreamQuery(PV[1][0]->stream()); + }; + auto stage_passed = [&](cudaEvent_t* ev) { + return cudaEventQuery(ev[0]) != cudaErrorNotReady && cudaEventQuery(ev[1]) != cudaErrorNotReady; + }; + // adapt()'s fence, on the tier's thread: it waits on the HOST. A device-side wait (the refill streams + // waiting for the stages' events) would queue copies behind windows that need this loop, beside it. + adapt_fence = [&]() { + stage_record(fence_ev); + while (!stage_passed(fence_ev)) std::this_thread::yield(); + }; + src.prepare_overrides(); + // The swaps land in two steps. Once their copies are done, the incoming experts are resident (the plans + // from then on use their slots). What gives their RAM back - the resident RAM mode's exchange, the + // released or unpinned pages - waits until every window that may still pull them over PCIe (a plan + // published before that point) has completed: both stages' streams are fenced there. + bool exch_wait = false; + std::vector pl_landed; + auto pl_release = [&]() { + unpin_blobs(pin_live); + src.commit_exchanges(); + for (const int32_t i : pl_landed) srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); + pl_landed.clear(); + exch_wait = false; + }; + auto pl_apply = [&]() { + if (exch_wait) { + if (stage_passed(exch_ev)) pl_release(); + return; + } + if (pending.empty() || cudaEventQuery(adapt_ev) != cudaSuccess) return; + for (auto& st : stages) + if (st->adapt_live && cudaEventQuery(st->adapt_ev) != cudaSuccess) return; + for (auto& st : stages) st->adapt_live = false; + for (const auto& [i, slot] : pending) { + host_res[(size_t) i] = slot; + pl_landed.push_back(i); + } + pending.clear(); + res_upload(); + stage_record(exch_ev); + exch_wait = true; + }; + auto pl_adapt = [&]() -> bool { + if (pl_adapt_thr.joinable() && pl_adapt_done.load()) { + pl_adapt_thr.join(); + if (!pl_adapt_ok) return false; + } + if (pl_adapt_thr.joinable()) return true; // still adapting + pl_apply(); + if (!drive.d.usage.empty() && o.adapt_every > 0 && (rounds % o.adapt_every) == 0 && pending.empty() && + !exch_wait) { + pl_adapt_done = false; + pl_adapt_thr = std::thread([&] { pl_adapt_ok = adapt(); pl_adapt_done = true; }); + } + return true; + }; + // the serial loop's prompt lookup for a fresh window: where the text repeats an earlier stretch and the + // drafter's own first guess agrees, the policy may take the lookup's continuation (up to S rows) + std::vector pl_sbuf((size_t) (2 * S), 0); + // a lookup window's continuation goes on past it: the next window (B) is taken from the same lookup and + // speculated behind it (a copied stretch is mostly accepted whole). STRATA_PIPELINE_LOOKUP_PON: B's + // estimate (default 0.75; 0 = no lookup B) + static const float pl_lookup_pon = [] { + const char* v = pipe_dbg_env("STRATA_PIPELINE_LOOKUP_PON"); + return v ? (float) std::atof(v) : 0.75f; + }(); + auto pick_lookup = [&](PW& w, const int32_t* chain0) { + if (o.suffix_draft <= 0 || w.seq == 0) return; + const int k = sfx.propose(2 * S - 1, pl_sbuf.data()); + const int match = sfx.last_match(); + if (k <= 0 || pl_sbuf[0] != chain0[0]) return; + const strata::spec::DraftPolicy::Pick pk = policy.choose(w.T, std::min(k, S - 1), match); + if (!pk.lookup) return; + w.T = pk.t; + for (int i = 1; i < w.T; ++i) { + w.tok[i] = pl_sbuf[(size_t) i - 1]; + w.prob[i - 1] = 1.0f; + } + w.sfx = true; + w.sfx_match = match; + const int rest = k - (w.T - 1); // lookup tokens past w: B's row 0 (w's bonus guess) and its drafts + if (&w == &A && rest >= 1 && pl_lookup_pon > 0.0f && !b_done) { + B = PW{}; + B.seq = A.seq + 1; + B.p = A.p + A.T; + B.T = std::min(S, rest); + for (int i = 0; i < B.T; ++i) B.tok[i] = pl_sbuf[(size_t) (A.T - 1 + i)]; + for (int i = 1; i < B.T; ++i) B.prob[i - 1] = 1.0f; + B.p_on = pl_lookup_pon; + B.ready = true; + B.made = true; + b_done = true; // the chain in flight makes no B for this A + tre("CD", A.seq + 1, 3, (int) (1000.0f * B.p_on)); + } + }; + const Clock::time_point pl_t0 = Clock::now(); + for (int st = 0; st < 2; ++st) + for (int par = 0; par < 2; ++par) g_pl_diag.v[st][par] = PV[st][par]; + strata::core::diag_pipeline_fn().store(&pl_diag_print); + auto pw_bits = [](const PW& w) { + return (w.ready ? 1 : 0) | (w.launched ? 2 : 0) | (w.finished ? 4 : 0) | (w.committed ? 8 : 0) | + (w.s1 ? 16 : 0) | (w.s1_done ? 32 : 0); + }; + // per window class (0: fresh, 1: run speculatively ahead of its predecessor's verdict): the time from + // the previous verdict, the tokens it emitted, how many + double cls_ms[2] = {0, 0}, cls_tok[2] = {0, 0}, cls_n[2] = {0, 0}; + int64_t cal_n[10] = {}, cal_on[10] = {}; // per p_on decile: windows scored, on the path + double last_verdict = 0.0; + int64_t pl_disagree = 0, pl_late = 0; + static const bool pl_prestage = [] { // STRATA_PIPELINE_PRESTAGE=0: B staged at its launch + const char* v = pipe_dbg_env("STRATA_PIPELINE_PRESTAGE"); + return v == nullptr || std::atoi(v) != 0; + }(); + static const bool pl_agree = [] { // STRATA_PIPELINE_AGREE=0: only the old chain's probabilities + const char* v = pipe_dbg_env("STRATA_PIPELINE_AGREE"); + return v == nullptr || std::atoi(v) != 0; + }(); + auto ms_now = [&]() { return std::chrono::duration(Clock::now() - pl_t0).count(); }; + while (true) { + g_pl_diag.iters.fetch_add(1, std::memory_order_relaxed); + g_pl_diag.a_seq.store(A.seq, std::memory_order_relaxed); + g_pl_diag.a_bits.store(pw_bits(A), std::memory_order_relaxed); + g_pl_diag.b_bits.store(pw_bits(B), std::memory_order_relaxed); + g_pl_diag.d_bits.store(pw_bits(D), std::memory_order_relaxed); + g_pl_diag.chain_kind.store(chain_kind, std::memory_order_relaxed); + g_pl_diag.chain_live.store(mtp.chain_live() ? 1 : 0, std::memory_order_relaxed); + g_pl_diag.doomed.store(doomed ? 1 : 0, std::memory_order_relaxed); + g_pl_diag.ending.store(ending ? 1 : 0, std::memory_order_relaxed); + // ---- every window in flight served + if ((doomed && !pump0(D)) || !pump0(A) || !pump0(B)) return die(err); + if (A.s1 && !A.s1_done) { + strata::core::Verifier& v = V1(A); + if (v.service(&drive_pool_split, SDf(A), err) < 0) return die(err); + if (v.done(err)) { + if (!v.pl_finish(outp.data(), err)) return die(err); + A.s1_done = true; + tre("F1", A.seq, A.T); + } else if (!err.empty()) return die(err); + } + if (drive.d.failed) return die(drive.d.fail ? drive.d.fail : "the expert pool failed"); + // ---- a wrong speculative window has finished: stage 0 back to the verified window's real commit + if (doomed && D.finished) { + { + const strata::core::OnDevice on(dev0); + if (cudaMemcpyAsync(ss.gdn_state, pl_snap2[pl_snap_overlap ? (undo_w.seq & 1) : 0], + pl_snap_bytes, cudaMemcpyDeviceToDevice, s0) != cudaSuccess) + return die("restoring the GDN snapshot failed"); + } + ss.ple_prev[0] = undo_ple[0]; + ss.ple_prev[1] = undo_ple[1]; + if (!V0(undo_w).pl_commit_async(undo_keep, err)) return die(err); + doomed = false; + ++pl_undo; + tre("U", undo_w.seq, undo_keep); + } + if (ending) { + if (!doomed) break; + continue; + } + // ---- the drafter's chain, read as its outputs land (an event after each): a fresh A once its size + // is decided, then B once ITS size is decided - its bonus guess and a draft below spec_min_p (or + // S_mtp - 1 drafts) - so stage 0 need not wait for the whole chain + if (chain_kind != 0) { + const int k_ready = mtp.chain_outputs_ready(err); + if (k_ready < 0) return die(err); + if (chain_kind == 2 && !early_used) { + // A's size is decided by its first outputs: a draft below spec_min_p ends it (the serial + // loop's rule), so A goes to stage 0 as soon as that is known, not after all S_mtp - 1 + const int k = k_ready; + bool decided = k >= S_mtp - 1; + if (!decided && req_spec_min_p > 0.0) + for (int j = 0; j < k; ++j) + if (mtp.chain_prob()[j] < (float) req_spec_min_p) { decided = true; break; } + if (decided) { + A.T = t_rule(mtp.chain_prob(), 0, std::min(k, S_mtp - 1)); + for (int i = 1; i < A.T; ++i) { + A.tok[i] = mtp.chain_tok()[i - 1]; + A.prob[i - 1] = mtp.chain_prob()[i - 1]; + } + pick_lookup(A, mtp.chain_tok()); + A.ready = true; + early_used = true; + tre("CE", A.seq, A.T); + } + } + const int r = mtp.chain_poll(err); + if (r < 0) return die(err); + const int k = r == 1 ? chain_n : k_ready; + const int32_t* oc = mtp.chain_tok(); + const float* op = mtp.chain_prob(); + if (r == 1 && chain_kind == 2 && !early_used) { + A.T = t_rule(op, 0, std::min(chain_n, S_mtp - 1)); + for (int i = 1; i < A.T; ++i) { + A.tok[i] = oc[i - 1]; + A.prob[i - 1] = op[i - 1]; + } + pick_lookup(A, oc); + A.ready = true; + early_used = true; + } + if (!b_done && (chain_kind == 1 || early_used)) { + const int base = A.T - 1; // B's row 0: the guess of A's bonus + bool decided = r == 1 || k >= base + S_mtp; + if (!decided && k > base + 1 && req_spec_min_p > 0.0) + for (int j = base + 1; j < k; ++j) + if (op[j] < (float) req_spec_min_p) { decided = true; break; } + if (decided) { + float pa = 1.0f; + if (chain_kind == 1) { + // forced through A's drafts: its outputs there are the drafter's own picks from + // A's verified predecessor, a better estimate of A's acceptance than the chain that + // drafted A; a disagreement means A is unlikely to be accepted whole + bool agree = true; + for (int i = 0; i + 1 < A.T; ++i) { + if (oc[i] != A.tok[i + 1]) agree = false; + pa *= pl_agree ? op[i] : A.prob[i]; + } + if (pl_agree && !agree) { pa = 0.0f; ++pl_disagree; } + } else { + for (int i = 0; i + 1 < A.T; ++i) pa *= A.prob[i]; + } + if (!A.sfx) make_b(oc, op, base, k, pa); // a lookup window's bonus is not the chain's + // stage B now (its PLE rows from the tokens before it as they will be once A is + // committed whole), so its launch behind A is only the graph launch (never while a + // rollback is pending: B's verifier is the one the undo commit reads) + if (B.ready && B.p_on >= theta && pl_prestage && !V0(B).in_flight() && !doomed) { + int32_t prev[2] = {ss.ple_prev[0], ss.ple_prev[1]}; + for (int i = 0; i < A.T; ++i) { prev[0] = prev[1]; prev[1] = A.tok[i]; } + if (!V0(B).prestage(B.T, B.tok, B.p, prev, err)) return die(err); + } + b_done = true; + tre("CD", A.seq, chain_kind, (int) (1000.0f * B.p_on)); + if (pl_log) + std::fprintf(stderr, "strata pipeline: chain %d for p=%lld T=%d: B T=%d p_on %.3f (%d " + "outputs)\n", chain_kind, (long long) A.p, A.T, B.T, B.p_on, k); + } + } + if (r == 1) chain_kind = 0; + } + // ---- stage 0: A (never while a wrong window still holds stage 0's state) + if (A.ready && !A.launched && !doomed) { + if (A.p + A.T > o.max_context) { ending = true; continue; } + if (!snap_take(A.seq)) return die("the GDN snapshot failed"); + if (!V0(A).pl_launch(A.T, A.tok, A.p, err)) return die(err); + A.launched = true; + tre("L0", A.seq, A.T, 0); + } + // ---- stage 0: B, speculatively, right behind A + if (B.ready && !B.launched && A.finished && !A.committed && !doomed) { + if (B.p_on >= theta && B.p + B.T <= o.max_context) { + { + const strata::core::OnDevice on(dev0); + if (pl_snap_overlap ? cudaStreamWaitEvent(s0, pl_snap_ev[A.seq & 1], 0) != cudaSuccess + : cudaMemcpyAsync(pl_snap2[0], ss.gdn_state, pl_snap_bytes, + cudaMemcpyDeviceToDevice, s0) != cudaSuccess) + return die("the GDN snapshot failed"); + } + undo_ple[0] = ss.ple_prev[0]; + undo_ple[1] = ss.ple_prev[1]; + if (!V0(A).pl_commit_async(A.T, err) || !snap_take(B.seq) || + !V0(B).pl_launch(B.T, B.tok, B.p, err)) + return die(err.empty() ? std::string("the GDN snapshot failed") : err); + A.committed = true; + B.launched = true; + B.spec = true; + tre("L0", B.seq, B.T, 1); + ++pl_spec; + } else { + B.ready = false; // not worth it: A's verdict decides the next window + ++pl_gate; + } + } + // ---- stage 1: A, once its stage 0 is done + if (A.finished && !A.s1) { + if (chain_kind == 1 && !B.ready) ++pl_late; // stage 0 idles until the chain has B + if (!V1(A).pl_launch(A.T, A.tok, A.p, err)) return die(err); + A.s1 = true; + tre("L1", A.seq, A.T); + } + // ---- A's verdict + if (!A.s1_done) continue; + // the drafter must be idle before the next chain. The chain needs nothing from the host, so this + // wait is bounded even with B (made from its first outputs) in flight on stage 0; in practice the + // chain ended long before a verdict that needs a whole stage-1 window. + while (chain_kind != 0 && mtp.chain_live()) + if (mtp.chain_poll(err) < 0) return die(err); + if (chain_kind != 0 && !B.launched && !B.made) B = PW{}; + chain_kind = 0; + int a = 0; + while (a < A.T - 1 && A.tok[a + 1] == outp[(size_t) a]) ++a; + if (!V1(A).pl_commit_async(a + 1, err)) return die(err); + for (int i = 0; i <= a; ++i) consumed.push_back(A.tok[i]); + draft_offered += A.T - 1; + draft_accepted += a; + ++rounds; + ++dec_windows; + dec_T += A.T; + bool eos = false; + for (int i = 0; i <= a && produced_n < max_new && !eos; ++i) { + std::printf("T %d\n", (int) outp[(size_t) i]); + strata::core::progress_beat(); + ++produced_n; + if (o.suffix_draft > 0) sfx.append(outp[(size_t) i]); + eos = std::find(o.eos_ids.begin(), o.eos_ids.end(), (int64_t) outp[(size_t) i]) != o.eos_ids.end(); + } + std::fflush(stdout); + if (eos) finish = "stop"; + else if (stop_req.load()) finish = "cancel"; + const bool last = eos || produced_n >= max_new || stop_req.load(); + const bool on = B.launched && a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1]; + if (B.made) { // the gate's calibration: would B have been on the path, by its estimate p_on + const bool would = a == A.T - 1 && B.tok[0] == outp[(size_t) A.T - 1]; + const int bin = std::min(9, std::max(0, (int) (B.p_on * 10.0f))); + cal_n[bin] += 1; + cal_on[bin] += would ? 1 : 0; + } + tre("V", A.seq, a, on ? 1 : (B.launched ? -1 : 0)); + { + const double now = ms_now(); + const int c = A.spec ? 1 : 0; + if (A.sfx) { ++sfx_windows; sfx_drafts += A.T - 1; sfx_ok += a; } + if (A.seq > 0 && !last) policy.observe(A.sfx, A.T, a, A.sfx_match, now - last_verdict); + cls_ms[c] += now - last_verdict; + cls_tok[c] += a + 1; + cls_n[c] += 1; + last_verdict = now; + } + if (pl_log) + std::fprintf(stderr, "strata pipeline: verdict p=%lld T=%d a=%d B %s%s\n", (long long) A.p, A.T, a, + B.launched ? "launched" : B.ready ? "ready" : "none", on ? " ON" : ""); + x = outp[(size_t) a]; + p = A.p + a + 1; + if (!last && !pl_adapt()) return die("an adaptive refill failed"); + if (on && !last) { + ++pl_on; + // the chain over A, forced through B's drafts: B's bonus guess and the next window's drafts + mtp.set_source_R(V1(A).final_R(0)); + chain_n = std::min(strata::kernels::kVerifyMaxT - 1, B.T + S_mtp - 1); + if (!mtp.chain_launch(A.T, outp.data(), A.p, a, B.tok + 1, B.T - 1, chain_n, chain_n, err)) + return die(err); + chain_kind = 1; + tre("CL", A.seq, 1); + early_used = false; + b_done = false; + A = B; + B = PW{}; + } else { + if (B.launched) { // a wrong guess (or the end): undo once it has finished + doomed = true; + D = B; + undo_w = A; + undo_keep = a + 1; + } else if (!A.committed) { + if (!V0(A).pl_commit_async(a + 1, err)) return die(err); + } + // B is D now (or dropped): never pump it twice (whichever copy saw the window complete first + // would finish it, and the other would wait for it forever) + B = PW{}; + if (!last) { + mtp.set_source_R(V1(A).final_R(0)); + chain_n = strata::kernels::kVerifyMaxT - 1; + if (!mtp.chain_launch(A.T, outp.data(), A.p, a, nullptr, 0, chain_n, chain_n, err)) + return die(err); + chain_kind = 2; + tre("CL", A.seq, 2); + early_used = false; + b_done = false; + PW nA; + nA.seq = A.seq + 1; + nA.p = A.p + a + 1; + nA.tok[0] = outp[(size_t) a]; + A = nA; + } + } + if (last) ending = true; + } + pl_drain(); // nothing in flight: both stages' commits and the drafter have landed + strata::core::diag_pipeline_fn().store(nullptr); + if (pl_adapt_thr.joinable()) pl_adapt_thr.join(); // its copies waited only for finished work + adapt_fence = nullptr; + if (exch_wait) pl_release(); // every window has completed (drained) + for (cudaEvent_t ev : fence_ev) if (ev) cudaEventDestroy(ev); + for (cudaEvent_t ev : exch_ev) if (ev) cudaEventDestroy(ev); + if (pl_trace_path != nullptr && !pl_trace.empty()) { + if (std::FILE* f = std::fopen(pl_trace_path, "a")) { + std::fprintf(f, "# request p0=%lld\n", (long long) (n - 1)); + std::fwrite(pl_trace.data(), 1, pl_trace.size(), f); + std::fclose(f); + } + } + // the odd windows' counters and GPU profiles into the verifiers that report them + PV[0][0]->absorb_stats(*PV[0][1]); + PV[1][0]->absorb_stats(*PV[1][1]); + if (!pl_adapt_ok) { + std::printf("ERR an adaptive refill failed\n"); + return 1; + } + while (mtp.chain_live() && mtp.chain_poll(err) == 0) {} + mtp.set_source_R(ver.final_R_all()); // the serial loop's rows again + const double pl_ms = std::chrono::duration(Clock::now() - pl_t0).count(); + dt_run += pl_ms; + if (dec_timing) { + auto avg = [](double s_, double n_) { return n_ > 0 ? s_ / n_ : 0.0; }; + std::fprintf(stderr, "strata pipeline: %lld windows in %.0f ms (%.2f ms/window): %lld speculative, %lld on " + "the path, %lld rolled back, %lld below the gate (theta %.2f)\n", + (long long) dec_windows, pl_ms, avg(pl_ms, (double) dec_windows), (long long) pl_spec, + (long long) pl_on, (long long) pl_undo, (long long) pl_gate, theta); + std::fprintf(stderr, "strata pipeline classes: fresh %.0f windows %.2f ms %.2f tok | speculative %.0f " + "windows %.2f ms %.2f tok | forced-chain disagreements %lld, chain late %lld\n", + cls_n[0], avg(cls_ms[0], cls_n[0]), avg(cls_tok[0], cls_n[0]), cls_n[1], + avg(cls_ms[1], cls_n[1]), avg(cls_tok[1], cls_n[1]), (long long) pl_disagree, + (long long) pl_late); + std::string cal; + char b[48]; + for (int i = 0; i < 10; ++i) + if (cal_n[i] > 0) { + std::snprintf(b, sizeof b, " %.1f:%lld/%lld", i / 10.0, (long long) cal_on[i], (long long) cal_n[i]); + cal += b; + } + std::fprintf(stderr, "strata pipeline calibration (p_on decile: on/scored):%s\n", cal.c_str()); + } + } + while (!pl_ran && !cancelled && produced_n < max_new) { + int T = use_mtp ? S_mtp : 1; // no --mtp: one token a round unless a lookup draft fires + if (use_mtp && req_spec_min_p > 0.0) { T = 1; while (T < S_mtp && dprob[(size_t) T - 1] >= (float) req_spec_min_p) ++T; } @@ -7252,7 +8734,7 @@ int main(int argc, char** argv) { if (o.suffix_draft > 0 && !first_window) { const int k = sfx.propose(S - 1, sbuf.data()); sfx_match = sfx.last_match(); - if (k > 0 && sbuf[0] == drafts[0]) { + if (k > 0 && (!use_mtp || sbuf[0] == drafts[0])) { const strata::spec::DraftPolicy::Pick pk = policy.choose(T, k, sfx_match); if (pk.lookup) { T = pk.t; from_sfx = true; } } @@ -7287,6 +8769,10 @@ int main(int argc, char** argv) { // expert ran on the GPU or the CPU (they round differently) depended on the copy's timing // (STRATA_ADAPT_NOWAIT=1: 0.1.37's non-blocking query, the A/B) apply_pending(!adapt_nowait()); + if (!adapt_tick(false)) { // --adapt-async: the round in flight moves on a step when it can + std::printf("ERR an adaptive refill failed\n"); + return 1; + } if (hist_n > 0) { // the tails the penalties count over, ONE PER ROW: the tokens the state has consumed, the // fed-back head `x` (it joins `consumed` only after this window commits), then the drafts @@ -7315,7 +8801,8 @@ int main(int argc, char** argv) { const Clock::time_point tw1 = Clock::now(); std::thread adapt_thr; // the adaptive tier beside the commit and the draft (as in generate) bool adapt_ok = true; - if (!drive.d.usage.empty() && ((rounds + 1) % o.adapt_every) == 0) + // (--adapt-async 1: the asynchronous tier above instead, ticked before the window) + if (!drive.d.usage.empty() && !ajob && ((rounds + 1) % o.adapt_every) == 0) adapt_thr = std::thread([&] { adapt_ok = adapt(); }); if (!ver.commit(a + 1, err)) { if (adapt_thr.joinable()) adapt_thr.join(); @@ -7341,9 +8828,9 @@ int main(int argc, char** argv) { const Clock::time_point tw2 = Clock::now(); // coupled drafts with penalties: the next window's row-0 history (`consumed` holds this window's // commit, outv[a] is its row 0) - the drafts extend it on the device as the verify rows will - if (hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new) + if (use_mtp && hist_n > 0 && mtp.coupled() && !eos && produced_n < max_new) mtp.set_draft_history(consumed.data(), (int64_t) consumed.size(), outv[(size_t) a]); - const bool drafted = eos || produced_n >= max_new || + const bool drafted = !use_mtp || eos || produced_n >= max_new || mtp.draft(T, outv.data(), p, a, drafts.data(), err, dprob.data(), (float) req_spec_min_p); { const Clock::time_point tw3 = Clock::now(); @@ -7497,11 +8984,13 @@ int main(int argc, char** argv) { h_stale = hash_cells(pool, w, L, end_cell, h_stale); } } - const strata::core::QsaState& ms = mtp.kv_state(); uint64_t h_mtp = 1469598103934665603ull; - const int64_t mL = std::min(L, ms.max_cells); - for (const auto& [pool, w] : kv_arrays(ms)) - if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); + if (use_mtp) { + const strata::core::QsaState& ms = mtp.kv_state(); + const int64_t mL = std::min(L, ms.max_cells); + for (const auto& [pool, w] : kv_arrays(ms)) + if (pool != nullptr) h_mtp = hash_cells(pool, w, 0, mL, h_mtp); + } if (!hash_ok) { std::printf("ERR reading state fingerprint\n"); return 1; @@ -7560,6 +9049,15 @@ int main(int argc, char** argv) { sl.max_new = admit_max_new; sl.t0 = Clock::now(); sl.ids = live; + if (batch_mtp) { + if (!slot_mtp[(size_t) admit_slot]->draft_first(1, ver.final_R_all(), sl.x, + sl.p - 1, sl.draft.data(), err)) { + std::fprintf(stderr, "strata batch: MTP admission for slot %d failed: %s\n", + admit_slot, err.c_str()); + return 1; + } + sl.draft_ready = true; + } sl.cvec = cvec_cached; sl.img = !live_imgs.empty(); // pictures: not matched again by tokens alone, so not cached const ConvCheckpoint* best = nullptr; @@ -7609,6 +9107,14 @@ int main(int argc, char** argv) { "VRAM tier, %lld blob reads from the file\n", (double) src.resident_bytes() / 1073741824.0, (long long) src.exchanges(), (long long) src.file_reads()); + if (ajob) // --adapt-async, cumulative (a round may still be in flight: it lands before the next request) + std::fprintf(stderr, "strata serve: asynchronous adaptive tier: %lld rounds, %lld experts swapped in, " + "%.1f ms per round (start to flip, between windows)\n", + (long long) a_rounds, (long long) a_swapped, a_rounds > 0 ? a_ms / (double) a_rounds : 0.0); + if (src.exchange_rotation()) + std::fprintf(stderr, "strata serve: exchange rotation: %llu blocks, %llu host memcpy bytes avoided (cumulative payload)\n", + (unsigned long long)src.rotated_exchanges(), + (unsigned long long)src.avoided_exchange_copy_bytes()); // CS-T: the tiers, cumulative - GPU cache hits (the decode lookups above), RAM copy, files (SSD / OS cache) if (srcp == &src) std::fprintf(stderr, "strata serve: expert tiers: GPU %lld hits this request; since the start RAM %lld blobs, files %lld blobs " @@ -8117,7 +9623,7 @@ int main(int argc, char** argv) { const float* u = drive.d.usage.data() + l * g.n_expert; const int32_t* r = host_res.data() + l * g.n_expert; for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { - if (r[e] < 0) { if (u[e] >= 2.0f) cand.emplace_back(u[e], e); } + if (r[e] < 0) { if (u[e] >= 2.0f && !helper_holds(l, e)) cand.emplace_back(u[e], e); } else vict.emplace_back(u[e], e); } if (cand.empty() || vict.empty()) continue; diff --git a/tests/core/exchange_storage_test.cpp b/tests/core/exchange_storage_test.cpp new file mode 100644 index 00000000..b790b4f2 --- /dev/null +++ b/tests/core/exchange_storage_test.cpp @@ -0,0 +1,133 @@ +#include "strata/core/exchange_storage.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +using strata::core::detail::ExchangeStorage; +constexpr uint64_t absent = ~uint64_t{0}; +void require(bool ok, const char* why) { if (!ok) throw std::runtime_error(why); } + +void exercise(size_t bytes, size_t rounds) { + constexpr size_t n = 24, resident = 16, spare_count = 4, guard = 19; + std::vector arena(guard + resident * bytes + guard, 0xcd); + std::vector spare(guard + spare_count * bytes + guard, 0xef); + // Distinct alias arrays catch accidentally retaining the old CUDA address. + std::vector aliases(resident * bytes), spare_aliases(spare_count * bytes); + std::vector> reference(n, std::vector(bytes)); + std::mt19937 random(601); + for (auto& row : reference) for (auto& v : row) v = (uint8_t)random(); + std::vector offsets(n, absent); + for (size_t i = 0; i < resident; ++i) { + offsets[i] = i * bytes; + std::memcpy(arena.data() + guard + offsets[i], reference[i].data(), bytes); + } + ExchangeStorage storage; + std::string error; + require(storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes, + spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), error.c_str()); + std::set original; + for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) original.insert(p); + for (size_t q = 0; q < spare_count; ++q) original.insert(storage.spare(q).host); + // A lookahead thread may inspect residency while ownership is committed. + // It only observes immutable address pairs, never reads mutable expert bytes. + std::atomic stop{false}, reader_failed{false}; + std::atomic observations{0}; + std::vector valid; + for (size_t i = 0; i < n; ++i) if (storage.resident(i).host) valid.push_back(storage.resident(i)); + for (size_t q = 0; q < spare_count; ++q) valid.push_back(storage.spare(q)); + std::thread reader([&] { + while (!stop.load()) { + for (size_t i = 0; i < n; ++i) { + const auto view = storage.resident(i); + if (view.host && std::none_of(valid.begin(), valid.end(), [&](auto v) { + return v.host == view.host && v.device == view.device; })) reader_failed.store(true); + } + ++observations; + } + }); + struct Join { + std::atomic& stop; std::thread& reader; + void finish() { stop.store(true); if (reader.joinable()) reader.join(); } + ~Join() { finish(); } + } join{stop, reader}; + while (!observations.load()) std::this_thread::yield(); + uint64_t exchanges = 0; + for (size_t round = 0; round < rounds; ++round) { + std::vector ins, outs; + for (size_t i = 0; i < n; ++i) (storage.resident(i).host ? ins : outs).push_back(i); + std::shuffle(ins.begin(), ins.end(), random); + std::shuffle(outs.begin(), outs.end(), random); + ExchangeStorage::View before[spare_count], staged[spare_count]; + for (size_t q = 0; q < spare_count; ++q) { + before[q] = storage.resident(ins[q]); staged[q] = storage.spare(q); + // Simulated completed D2H eviction. The old RAM input stays readable + // until simulated H2D and all readers finish, before commit. + std::memcpy(staged[q].host, reference[outs[q]].data(), bytes); + require(!std::memcmp(before[q].host, reference[ins[q]].data(), bytes), "incoming expert overwritten early"); + } + for (size_t q = 0; q < spare_count; ++q) { + require(!storage.commit(ins[q], ins[q], q, staged[q].host, bytes), "self swap accepted"); + require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes + 1), "wrong size accepted"); + require(!storage.commit(ins[q], outs[q], q, nullptr, bytes), "missing staged buffer accepted"); + require(!storage.commit(ins[q], outs[q], spare_count, staged[q].host, bytes), "bad spare accepted"); + require(!storage.commit(n, outs[q], q, staged[q].host, bytes), "bad expert accepted"); + require(storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "valid swap rejected"); + require(!storage.commit(ins[q], outs[q], q, staged[q].host, bytes), "duplicate commit accepted"); + require(storage.resident(outs[q]).host == staged[q].host && + storage.resident(outs[q]).device == staged[q].device, "evicted buffer was not adopted with its alias"); + require(storage.spare(q).host == before[q].host && storage.spare(q).device == before[q].device, + "old RAM input was not recycled with its alias"); + // Even the old incoming bytes have not changed: commit copies metadata only. + require(!std::memcmp(storage.spare(q).host, reference[ins[q]].data(), bytes), "commit changed spare bytes"); + ++exchanges; + } + std::set live; + for (size_t i = 0; i < n; ++i) if (auto p = storage.resident(i).host) { + require(live.insert(p).second, "two experts share storage"); + require(!std::memcmp(p, reference[i].data(), bytes), "resident bytes corrupted"); + } + for (size_t q = 0; q < spare_count; ++q) + require(live.insert(storage.spare(q).host).second, "spare aliases live expert"); + require(live == original, "storage leaked or duplicated"); + } + require(storage.exchanges() == exchanges && storage.avoided_bytes() == exchanges * bytes, "wrong accounting"); + require(std::all_of(arena.begin(), arena.begin() + guard, [](auto x) { return x == 0xcd; }) && + std::all_of(arena.end() - guard, arena.end(), [](auto x) { return x == 0xcd; }) && + std::all_of(spare.begin(), spare.begin() + guard, [](auto x) { return x == 0xef; }) && + std::all_of(spare.end() - guard, spare.end(), [](auto x) { return x == 0xef; }), "guard overwritten"); + require(!storage.initialize(offsets, arena.data() + guard, aliases.data(), resident * bytes, + spare.data() + guard, spare_aliases.data(), spare_count, bytes, error), "live storage reinitialized"); + join.finish(); + require(!reader_failed.load() && observations.load(), "concurrent residency reader observed invalid alias"); + storage.clear(); + require(!storage.active() && !storage.resident(0).host && !storage.spare(0).host && + !storage.exchanges() && !storage.avoided_bytes(), "clear retained state"); +} + +void invalid_geometry() { + uint8_t h[64]{}, d[64]{}, x[64]{}, xd[64]{}; + ExchangeStorage s; std::string e; + require(!s.initialize({0, 3}, h, d, 8, x, xd, 2, 4, e), "unaligned slot accepted"); + require(!s.initialize({0, 0}, h, d, 8, x, xd, 2, 4, e), "duplicate offset accepted"); + require(!s.initialize({0, 8}, h, d, 8, x, xd, 2, 4, e), "out of bounds accepted"); + require(!s.initialize({0, absent}, h, d, 8, x, xd, 2, 4, e), "lost slot accepted"); + require(!s.initialize({0, 4}, h, nullptr, 8, x, xd, 2, 4, e), "unmapped resident accepted"); + require(!s.initialize({0, 4}, h, d, 8, x, nullptr, 2, 4, e), "unmapped spare accepted"); + require(!s.initialize({0, 4}, h, d, 8, x, xd, 2, 0, e), "zero blob accepted"); + require(!s.active(), "failed initialization left active state"); +} + +int main() { + try { + invalid_geometry(); + for (size_t bytes : {1u, 33u, 4097u}) exercise(bytes, 1024); + exercise(5222400, 4); // actual Q8 expert size + std::cout << "exchange_storage_test: PASS (byte/alias/ownership checks, 12304 exchanges)\n"; + } catch (const std::exception& e) { std::cerr << e.what() << '\n'; return 1; } +} diff --git a/tests/core/file_expert_source_test.cpp b/tests/core/file_expert_source_test.cpp index 104507d1..f0b47c78 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -7,6 +7,9 @@ #include "ggml.h" #endif +#include +#include +#include #include #include #include @@ -338,9 +341,96 @@ void test_host_memory() { #endif } +void test_rotating_source(bool rotate, bool pin) { + using namespace strata::core; + using namespace strata::kernels::cpu; +#if defined(_WIN32) + _putenv_s("STRATA_EXCHANGE_ROTATE", rotate ? "1" : "0"); +#else + setenv("STRATA_EXCHANGE_ROTATE", rotate ? "1" : "0", 1); +#endif + TempDirectory dir; + std::string err; + require(expert_layout_load(dir.path.string(), 1, 5, err), err); + const size_t bytes = (size_t)BLOB; + std::vector> truth(5, std::vector(bytes)); + { + std::ofstream out(dir.path / "experts.bin", std::ios::binary); + for (size_t e = 0; e < truth.size(); ++e) { + for (size_t i = 0; i < bytes; ++i) truth[e][i] = (uint8_t)((i * 131u + e * 37u) ^ (i >> 8)); + out.write((const char*)truth[e].data(), (std::streamsize)bytes); + } + require((bool)out, "fixture write failed"); + } + FileExpertSource src; + ExpertCache cache; + require(src.open(dir.path.string(), 1, 5, err), err); + require(cache.open(2, 1, 5, BLOB, err), err); + for (int e : {2, 3}) { + const int slot = cache.admit(0, e); + require(slot >= 0 && cache.fill_slot_blocking(slot, truth[e].data(), err), err); + } + const std::vector> rank{{0,0},{0,1},{0,2},{0,3},{0,4}}; + // Keep expert 4 on the file tier to check that the fallback survives rotation. + require(src.pin_cache_complement(cache, err, pin, {}, -1, 0, 2 * bytes, &rank), err); + require(src.reserve_exchanges(2, err), err); + require(src.exchange_rotation() == (rotate && pin), "rotation activation/fallback wrong"); + require(src.reserve_exchanges(1, err), "smaller capacity rejected"); + if (rotate && pin) require(!src.reserve_exchanges(3, err), "live arena growth accepted"); + int incoming[2] = {0, 1}, outgoing[2] = {2, 3}; + std::vector actual(bytes); + double commit_ms = 0; + for (int round = 0; round < 32; ++round) { + const uint8_t* prior[2]{}; + uint8_t* eviction[2]{}; + for (int q = 0; q < 2; ++q) { + prior[q] = src.blob(0, incoming[q]); eviction[q] = src.exchange_buffer(q); + require(prior[q] && !std::memcmp(prior[q], truth[incoming[q]].data(), bytes), "wrong incoming bytes"); + require(cudaMemcpy(eviction[q], cache.device_slot(q), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, + "D2H eviction failed"); + require(src.stage_exchange(0, incoming[q], outgoing[q], q), "stage rejected"); + require(!std::memcmp(src.blob(0, outgoing[q]), truth[outgoing[q]].data(), bytes), "staged override wrong"); + require(cache.fill_slot_blocking(q, prior[q], err), err); // H2D completed before commit + } + require(!src.stage_exchange(0, incoming[0], outgoing[0], 0), "duplicate stage accepted"); + require(!src.stage_exchange(0, incoming[0], 5, 0), "invalid expert accepted"); + const auto t0 = std::chrono::steady_clock::now(); + require(src.commit_exchanges() == 2, "commit count wrong"); + commit_ms += std::chrono::duration(std::chrono::steady_clock::now() - t0).count(); + require(src.commit_exchanges() == 0, "empty commit not empty"); + for (int q = 0; q < 2; ++q) { + require(!src.has_resident(0, incoming[q]) && src.has_resident(0, outgoing[q]), "residency wrong"); + const uint8_t* held = src.blob(0, outgoing[q]); + require(!std::memcmp(held, truth[outgoing[q]].data(), bytes), "evicted bytes corrupted"); + require(held == ((rotate && pin) ? eviction[q] : prior[q]), "wrong storage selected"); + if (rotate && pin) require(src.exchange_buffer(q) == prior[q], "old input not recycled"); + require(src.copy_blob(0, outgoing[q], actual.data()) && actual == truth[outgoing[q]], "copy_blob mismatch"); + require(!src.transient(0, outgoing[q]), "resident became transient"); + if (pin) { + require(src.pinned(0, outgoing[q]) && src.device_alias(0, outgoing[q]), "mapping lost"); + require(cudaMemcpy(actual.data(), src.device_alias(0, outgoing[q]), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, + "device alias read failed"); + require(actual == truth[outgoing[q]], "CUDA alias points at stale expert"); + } + require(cache.verify_slot(q, truth[incoming[q]].data(), err), err); + std::swap(incoming[q], outgoing[q]); + } + require(!src.has_resident(0, 4) && src.copy_blob(0, 4, actual.data()) && actual == truth[4], "file fallback changed"); + } + require(src.exchanges() == 64, "exchange accounting wrong"); + require(src.rotated_exchanges() == ((rotate && pin) ? 64u : 0u), "rotation accounting wrong"); + require(src.avoided_exchange_copy_bytes() == ((rotate && pin) ? 64 * bytes : 0u), "avoided bytes wrong"); + std::cout << "rotation integration: rotate=" << rotate << " pinned=" << pin + << " exchanges=64 commit_ms=" << commit_ms << " exact_bytes=PASS\n"; + src.close(); + require(!src.exchange_rotation() && !src.exchange_buffer(0), "close retained storage"); + require(src.open(dir.path.string(), 1, 5, err), err); + require(!src.has_resident(0, 0) && !src.exchange_rotation(), "reopen retained residency"); +} + } // namespace -int main() { +int main(int argc, char** argv) { try { test_complement_plan(); test_resident_lend_region(); @@ -351,6 +441,11 @@ int main() { #if defined(STRATA_NATIVE_EXPERTS) test_native_variable_layout(); #endif + if (argc == 2 && std::string(argv[1]) == "--rotation-gpu") { + test_rotating_source(false, true); + test_rotating_source(true, true); + test_rotating_source(true, false); + } std::cout << "file_expert_source_test: PASS\n"; return 0; } catch (const std::exception& error) { diff --git a/tools/batch_test.py b/tools/batch_test.py index 4cb76027..ea384d9b 100644 --- a/tools/batch_test.py +++ b/tools/batch_test.py @@ -74,6 +74,7 @@ def main(): ap.add_argument("--skip-solo", action="store_true") ap.add_argument("--keys", default="", help='sampling keys for every request, e.g. "temperature=0.7 top_k=20"') ap.add_argument("--extra", default="", help='more engine arguments in one string, e.g. "--adapt-every 1000000"') + ap.add_argument("--dump", default="", help="write every slot's tokens (solo and batch) as JSON: an A/B of two engine builds") ap.add_argument("--mt-min", default="1", help="STRATA_IQ_MT_MIN for the engine (1: exact; empty: the default)") a = ap.parse_args() cfg = json.loads(Path(a.config).read_text()) @@ -152,6 +153,8 @@ def main(): first_diff = next((k for k in range(min(len(b), len(solo[i]))) if b[k] != solo[i][k]), None) print(f"slot {i}: {len(b)} tokens, solo {len(solo[i])}: {'IDENTICAL' if same else f'DIFFERS at {first_diff}'}") print(" ", ascii(tok.decode(b)[:160])) + if a.dump: + Path(a.dump).write_text(json.dumps({"solo": solo, "batch": [got[i] for i in range(len(prompts))]}), encoding="utf-8") eng.send("QUIT") eng.p.wait(timeout=180) # the next run needs the GPUs back return 0 if ok else 2