diff --git a/docs/DETAILS.md b/docs/DETAILS.md index 82e4f216..7fb8aa0e 100644 --- a/docs/DETAILS.md +++ b/docs/DETAILS.md @@ -83,6 +83,8 @@ costs ~13.7 KB of RAM per context token (1.7 GB at 128K). Existing installs: run it on. Setup turns it on when the RAM has room for it; `--kv-streaming on|off` overrides that (on past the RAM test with a note; never under WSL, which cannot stream). +Under WSL2 the driver caps what `cudaHostAlloc` may pin at about 1 GiB, so the KV host copy is pinned with `cudaHostRegister` of ordinary memory there (detected through `/dev/dxg`); `STRATA_KV_HOST_REGISTER=1` forces that order on any system and `=0` forces `cudaHostAlloc` first (the other method is the fallback in both cases). On Linux without WSL nothing changes by default; with the switch the engine prints `KV streaming: the host copy is pinned with cudaHostRegister` (#1498 by yjamil8; WSL not tested here, the forced path was run on a Tesla P100: `--kv int8 --kv-resident 32768`, answers and decode speed unchanged). + **4-bit KV cache (engine 0.1.8, optional):** `START-HERE.bat --setup` asks above 8K context (or pass `--kv q4_0`). It halves the KV cache's memory with a Hadamard rotation before 4-bit rounding (PR #21), about 4% faster at 128K, but it is measurably less precise on long documents (perplexity +8-12%; needle tests still pass). 8-bit stays the default. @@ -167,6 +169,26 @@ 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. +- `STRATA_RAM_ADAPT=` (opt-in, `--serve`, one GPU): the RAM copy follows the conversation too. Without it the + copy is chosen once, at start, so when the RAM cannot hold every expert the GPU does not, an expert outside the copy + is read from the SSD every time the conversation routes to it. With it, before a decode window and while no adaptive + round is in flight, up to `n` experts the windows keep routing to (the adaptive tier's decayed count, 2 or more) take + the RAM places of experts of their own layer that are not routed to (count below 0.5): one pair per layer, the + largest difference first, one blob read each. The RAM stays the same size; the routing, the weights and the VRAM + tier's rule are untouched, and an expert that left the copy is read from the file again when it is needed. It needs + the adaptive tier (`--adapt-every`), and does nothing with `STRATA_EXCHANGE_ROTATE=1`, a layer split, a peer or + helper GPU, or `--batch`. Prompt routing is not used to choose replacements, and no selection runs during prefill. + Later prompts can read from a RAM copy changed by earlier decode requests. The log reports how many experts moved. + Measured on an RTX 3060 12 GB with 32 GB of RAM (Linux, IQ2_XS, 20.5 GiB of experts in RAM and about 6,000 experts on + the file tier, `--adapt-async 1`, `--spec 3`, power-saver), against v0.1.43: 47 frozen Korean requests from + my own use (tools, follow-ups and background tasks, 281-33,241 prompt tokens), replayed in order in fresh engines: + release, this option, release. Each starts from the same held learned profile; the private prompts are not attached. + With default tail skip (7), decode is 43.26 -> 50.40 tok/s (+16.5%) against the closing release, computed as total + generated tokens / total decode time; the two release arms are within 0.2%. Short/long new-input requests gain + 16.3%/16.9%; total prompt speed differs by 2.5%, within run variation. Decode file-tier demand reads per generated + token fall from 14.15 -> 2.67; 8,056 successful RAM promotions read another blob each, giving 3.16 with those added. + These are file-tier counts, not physical SSD I/O. RAM residency does not exempt an expert from tail skip. One machine, + one quantization; tail skip off, blocking adaptation, `--spec 2` and the soak were not repeated on v0.1.43. - `--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. With `--batch` slots it advances between their windows too (docs/BATCHING.md); not with `--batch-groups` or `--peer-device` (the blocking @@ -193,8 +215,10 @@ other ~18 GB), a 32 GB PC with a 12-16 GB GPU the Coder; IQ3_XXS on a 32 GB PC s tokens; decode level alone, +2-3 % with `--adapt-async 1` and `--pcie-frac 0.6` ([report](../bench/results/2026-10-11-community-rtx3090-5600x-arena-pin-by-need/README.md)). - `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). + blob into the RAM copy (fully page-locked copy; layers of different blob sizes keep spare buffers per size). Same + tokens, fewer host copies; it works with `--adapt-async 1` too. Swift 1.5 IQ3_S on an RTX 5090 with 64 GB RAM + (Windows, about 30 swaps per verify window): 164 -> 188 tok/s on one forced 1,500-token text, 155 -> 178 over 23 + coding-agent turns. Details and the measurements: [EXCHANGE_ROTATION.md](EXCHANGE_ROTATION.md). Measured by us on an RTX 3060 12 GB (IQ3_XXS, resident RAM, default flags, 5 interleaved pairs): decode 58.96 -> 62.03 tok/s (+5.2%, 5/5 pairs), prompt speed unchanged; tokens identical with real adaptive swaps (Tesla P100, resident, blocking adaptation). It adds about 1.4 GiB of page-locked RAM, so leave it off when the RAM is already tight. - 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. @@ -265,7 +289,13 @@ start (locked; page-locked when the driver allows the whole budget), and the res It implies `--mmap-experts` and leaves 4 GiB of headroom. On Windows, available commit capacity also limits the budget; a larger N is clamped to the smaller limit less 4 GiB and a 256 MiB margin, with a message. A clamped budget no longer fails the safety check that follows (#403). A budget that cannot be kept at all is a -warning, with every expert read from the files. Setup sets N with `--resident-budget-gib N`. With +warning, with every expert read from the files. Setup sets N with `--resident-budget-gib N`. When the budget has room +left after the ranked experts, the slots the prompt path borrows keep their experts in RAM too, as they do without a +budget (the engine prints `the prompt path's lend region: N of its M slots keep their experts in RAM too`); before, a +budget always left them out, and every prompt read the lent slots' experts from the model files again (RX 6900 XT, +UD-Q4_K_XL, budget 71 GiB with 7.5 GiB unused: 0.5-2.6 GB of file reads per agent turn and 1.9-2.8 GB from the SSD +per fresh 8K-16K prompt went to zero; fresh prompts read 3-8% faster, the prompt path's host staging fell from +0.8-2.1 s to 0.06-0.5 s per request). With the GGUF read in place it also warms the next layer's likely experts: while the CPU works on a layer, a thread applies the next layer's router to this layer's input and asks the OS for the pages of the predicted experts that neither the GPU nor the RAM budget holds (only pages - the experts computed are the same; `STRATA_LOOKAHEAD=0` turns it off). This @@ -1813,6 +1843,11 @@ from the old default, as any change of the share does (CPU and GPU round differe (run-to-run floor 0.0013) and 0.0011 on the A4000 (floor 0.0012; at that time the share was 0.25). The sweeps behind the constant: `phaseA-tests/notes-142-pciefrac.md`. +`STRATA_PCIE_BALANCE=1` (opt-in, CUDA, one GPU, no `--batch`, no `--pcie-frac`; #1548 by sergiywith / stuchapin909): instead of one share for every layer, each verify layer +reads over PCIe the number of its missed experts that balances the two sides. The spin kernels stamp the GPU's clock (the plan's arrival, the PCIe part's start, the wait for the CPU rows), +the host times its pool, and least squares with forgetting fit the pool's `a + c*n_cpu + d*n_pcie` and the GPU's `g0 + g*n_pcie`; the engine prints the fit (`pcie model`) at the end of `generate`. +Every 64th layer with a miss moves one expert to the other side so both fits stay measured. Unset, nothing changes (the logits equal the build before). Measured by us (5 interleaved pairs, box default flags, IQ3_XXS): RTX A4000 arena decode 48.45 -> 51.15 tok/s (+5.6%, 5/5 pairs), RTX 3060 resident 59.12 -> 58.15 (-1.6%), Tesla P100 37.95 -> 37.48 (-1.3%): opt-in, worth trying on A4000-class cards. + ## More opt-in switches measured for 0.1.41 (all off unless you set them) None of these changes the default answers; each was measured against the default with interleaved off/on pairs of whole @@ -1844,6 +1879,7 @@ the pairs in which the switched arm won). They are here so you can try them on y -0.1% (5/6). Boxes that hold all experts in RAM never use the stage buffers. - **`STRATA_ADAPT_LAG=2`: the adaptive tier's copies are waited for one window later** (#764). Decode, 6 pairs: Tesla P100 (PCIe 3.0 x16) +3.5% (6/6 pairs faster), RTX 5070 +0.2% (4/6), RTX 3060 -1.3% (0/6), so it stays opt-in. + Where the tier does not wait for its copies (`STRATA_ADAPT_NOWAIT=1`, `STRATA_ADAPT_LAG` above 1) the device's residency table now follows each eviction before the next window (a small patch kernel before every verifier launch; #1517 by sergiywith): before, the pool could compute an evicted expert on the CPU from a stale activation (`STRATA_ADAPT_CHECKRES=1` counts such layers; `STRATA_ADAPT_EVICT_SYNC=0` turns the fix off). The default (the tier waits) is untouched. - **`STRATA_ADAPT_OVERLAP` (`=1` turns it on, on every backend; the startup log names the state and, when it cannot run, why): the adaptive tier's copies land while the next window runs, with the same tokens.** The window takes the swaps at the same moment as with #463's wait (so the same experts run on the GPU and the CPU in every window), but the copies go in layer order and the verify window holds a layer's plan back diff --git a/docs/EXCHANGE_ROTATION.md b/docs/EXCHANGE_ROTATION.md index a82dff6b..5d4911fd 100644 --- a/docs/EXCHANGE_ROTATION.md +++ b/docs/EXCHANGE_ROTATION.md @@ -21,10 +21,12 @@ $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. +It applies only when 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. Layers may differ in expert block size (a +GGUF with mixed quantizations per layer): see +[Layers of different block sizes](#layers-of-different-block-sizes). The startup diagnostic confirms activation: @@ -46,6 +48,71 @@ 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. +## Layers of different block sizes + +A swap exchanges two experts of the same layer, so the RAM slot the promoted +expert leaves has exactly the size of the block the evicted one needs. Rotation +therefore keeps its spare buffers per block size: an exchange of a layer takes +a spare of that layer's size and hands back one of the same size, and every +size keeps its number of spares for good. The first version required one size +for all layers and fell back to the copy path on any other pack; Swift 1.5 +IQ3_S has seven sizes (1,510,400 to 2,662,400 bytes) and IQ3_XXS has nine +too, so neither could rotate. + +The exchange allocation holds one spare of every size per swap of a round: +`--adapt-swaps` (at most 96) times the sum of the distinct sizes. With +`--adapt-async 1` the second half of the buffers only stages copies and is +kept in the largest size alone. On IQ3_S with `--adapt-swaps 80` that is +1.06 GiB of page-locked RAM (1.26 GiB with `--adapt-async 1`), against 0.20 +and 0.40 GiB for the copy path's buffers. The startup line says how many sizes +and how much: + +```text +FileExpertSource: exchange buffer rotation enabled: 80 buffers in 7 block sizes (largest 2662400 bytes, 1.06 GiB page-locked); no host commit memcpy +``` + +With `--adapt-async 1` a rotated round also ends one verify window sooner: +there are no bytes for the background job to move, so the ownership flip runs +in the tick that sees the copies in. + +`tests/core/exchange_storage_test.cpp` covers it without CUDA (three sizes, +6,144 exchanges: bytes, aliases, a spare of another size or an expert of +another layer refused, overlapping resident blocks refused). + +### Measured: Swift 1.5 IQ3_S on an RTX 5090 with 64 GB (Windows 11) + +Core i7-13700K, RTX 5090 32 GB, 64 GB DDR5, Windows 11, driver 617.42, CUDA +13.0.88, engine 0.1.42 built from source with this change. Swift 1.5 IQ3_S, +128K context, `--resident-experts` (31.4 GiB of experts page-locked in RAM, +about 10,800 of 24,576 in VRAM), `--adapt-every 1 --adapt-swaps 80 +--adapt-decay 0.97`, `--spec 4`, `--pool-affinity p-cores`. In the first and third +rows one binary ran both arms and only `STRATA_EXCHANGE_ROTATE` differs; in the +second the off arm is the build before this change (the third row's binary also +carried extra timers). + +| Run | Rotation off | Rotation on | +|---|---|---| +| One 8K prompt, the same 1,500 forced tokens (`--spec-follow`), blocking tier, decode tok/s | 163.4, 165.1, 163.1, 161.6, 162.6 | 187.4, 188.7, 185.8, 184.9 | +| `--serve`, 23 coding-agent turns (`tools/agent_turns_bench.py`'s turns, greedy, up to 400 new tokens), blocking tier, tok/s over all turns, three interleaved rounds | 147.8, 159.2, 158.4 | 175.2, 184.9, 172.8 | +| The same turns with `--adapt-async 1`, one binary, two interleaved rounds | 166.0, 170.1 | 185.6, 182.5 | + +In the first row, two runs of each arm that sized the expert cache alike (10,681 +slots) wrote the same `--window-hashes` file for all 434 windows: the same +arithmetic, window by window. (`--expert-cache auto` sizes the cache from the +free VRAM at start, and a run with another slot count places experts +differently, so its hashes differ with or without rotation.) The tier swapped +about 14,000 experts in such a run, 10,100 to 10,600 of them exchanges. In the serve rows the +rotated arm was faster on 23 of 23 turns (blocking tier) and 22 of 23 +(`--adapt-async 1`). On this box the tier swaps about 30 experts per verify +window all through a run (the cache holds 44% of the experts), so the copy +path moved about 50 MiB of RAM per window on the decode thread; that is the +time rotation removes. With `--adapt-async 1` the same copy ran on the +background job, and the decode thread still lost about 1 ms per window (0.4 to 2.5 by request) +while it ran; rotated, the tier's part of a window is 0.06 ms. + +Not measured: Linux, AMD cards, a layer split, a pack with one block size on +this machine (the code path for it is the one above with a single size). + ## Tests The ownership test can run without CUDA: diff --git a/include/strata/core/exchange_storage.hpp b/include/strata/core/exchange_storage.hpp index 7e50d745..e077c8a6 100644 --- a/include/strata/core/exchange_storage.hpp +++ b/include/strata/core/exchange_storage.hpp @@ -1,5 +1,6 @@ #pragma once +#include #include #include #include @@ -13,7 +14,12 @@ 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. +// physical buffer addresses, bytes and CUDA aliases stay in place. Requires fully mapped/pinned expert slots. +// +// Block sizes: `initialize` is the uniform geometry (every expert block the same size). `initialize_sized` takes a +// size per expert (a pack whose layers differ, as the GGUF's mixed i-quants): the spares are kept per size, and +// since a swap exchanges two experts of one layer, the buffer a commit hands back has the size of the one it took, +// so every size keeps its number of spares for good. class ExchangeStorage { public: struct View { @@ -36,34 +42,93 @@ public: 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}; + const std::vector sizes(offsets.size(), (uint64_t) blob_bytes); + return initialize_sized(offsets, sizes, resident_host, resident_device, resident_bytes, exchange_host, + exchange_device, (uint64_t) count * (uint64_t) blob_bytes, count, 0, error); + } + + /// The exchange allocation `initialize_sized` lays out: `count - bounce` buffers of every distinct size in + /// `sizes` (zeros skipped), then `bounce` buffers of the largest. 0 when the geometry is empty or overflows. + static uint64_t exchange_bytes_needed(const std::vector& sizes, size_t count, size_t bounce) { + const std::vector classes = classes_of(sizes); + if (classes.empty() || count == 0 || bounce > count) return 0; + uint64_t sum = 0; + for (const size_t c : classes) sum += c; + const uint64_t lim = std::numeric_limits::max(); + if (sum > lim / count) return 0; + return (uint64_t) (count - bounce) * sum + (uint64_t) bounce * classes.back(); + } + + /// `sizes[i]`: expert i's block size (its layer's). Spare ordinals `q < count - bounce` exist in every size; + /// the last `bounce` ordinals only in the largest (buffers that are staged through and never committed). + bool initialize_sized(const std::vector& offsets, const std::vector& sizes, + uint8_t* resident_host, const uint8_t* resident_device, uint64_t resident_bytes, + uint8_t* exchange_host, const uint8_t* exchange_device, uint64_t exchange_bytes, + size_t count, size_t bounce, std::string& error) { + error.clear(); + if (active()) { error = "exchange storage already initialized"; return false; } + if (!resident_host || !resident_device || !exchange_host || !exchange_device || !count || bounce > count || + !resident_bytes || sizes.size() != offsets.size()) { + error = "invalid mapped exchange geometry"; return false; } + const std::vector classes = classes_of(sizes); + const uint64_t need = exchange_bytes_needed(sizes, count, bounce); + if (classes.empty() || need == 0 || need > exchange_bytes || + classes.size() > std::numeric_limits::max() / count) { + error = "the exchange allocation does not hold the spares of every block size"; return false; + } + auto experts = std::make_unique[]>(offsets.size()); + std::vector buffers; + std::vector buffer_bytes; + std::vector> spans; // (offset, size) of the resident blocks: none may overlap + 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 (sizes[i] == 0 || at >= resident_bytes || sizes[i] > resident_bytes - at) { + error = "invalid resident slot"; return false; + } + experts[i].store(buffers.size(), std::memory_order_relaxed); + buffers.push_back({resident_host + (size_t) at, resident_device + (size_t) at}); + buffer_bytes.push_back((size_t) sizes[i]); + spans.emplace_back(at, sizes[i]); + } + std::sort(spans.begin(), spans.end()); + for (size_t i = 1; i < spans.size(); ++i) + if (spans[i - 1].first + spans[i - 1].second > spans[i].first) { + error = "invalid or duplicate resident slot"; return false; + } + std::vector spares(classes.size() * count, kAbsent); + uint64_t at = 0; + for (size_t c = 0; c < classes.size(); ++c) + for (size_t q = 0; q < count; ++q) { + if (q >= count - bounce && c + 1 != classes.size()) continue; // the bounce ordinals: the largest size only + spares[c * count + q] = buffers.size(); + buffers.push_back({exchange_host + (size_t) at, exchange_device + (size_t) at}); + buffer_bytes.push_back(classes[c]); + at += classes[c]; + } experts_ = std::move(experts); expert_count_ = offsets.size(); + expert_bytes_.assign(sizes.begin(), sizes.end()); spares_.swap(spares); buffers_.swap(buffers); - blob_bytes_ = blob_bytes; + buffer_bytes_.swap(buffer_bytes); + classes_ = classes; + count_ = count; + blob_bytes_ = classes.back(); return true; } @@ -73,21 +138,31 @@ public: 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{}; } + /// Spare `q` of the largest block size (any block fits it). + View spare(size_t q) const { return active() ? spare(q, blob_bytes_) : View{}; } + /// Spare `q` of blocks of exactly `bytes`. + View spare(size_t q, size_t bytes) const { + const size_t c = class_of(bytes); + if (c == kAbsent || q >= count_) return {}; + const size_t id = spares_[c * count_ + q]; + return id != kAbsent ? buffers_[id] : 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. + // has landed in spare(q, bytes). 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 c = class_of(bytes); + if (in >= expert_count_ || out >= expert_count_ || c == kAbsent || q >= count_ || !staged) return false; + size_t& spare_id = spares_[c * count_ + q]; 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; + if (spare_id == kAbsent || incoming_slot == kAbsent || experts_[out].load(std::memory_order_acquire) != kAbsent || + buffer_bytes_[incoming_slot] != bytes || expert_bytes_[out] != bytes || buffers_[spare_id].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_[out].store(spare_id, std::memory_order_release); + spare_id = incoming_slot; experts_[in].store(kAbsent, std::memory_order_release); ++exchanges_; avoided_bytes_ += bytes; @@ -96,18 +171,36 @@ public: uint64_t exchanges() const { return exchanges_; } uint64_t avoided_bytes() const { return avoided_bytes_; } // memcpy payload, not read+write total + size_t block_sizes() const { return classes_.size(); } void clear() { - experts_.reset(); expert_count_ = 0; buffers_.clear(); spares_.clear(); - blob_bytes_ = 0; exchanges_ = avoided_bytes_ = 0; + experts_.reset(); expert_count_ = 0; expert_bytes_.clear(); buffers_.clear(); buffer_bytes_.clear(); spares_.clear(); + classes_.clear(); + count_ = 0; blob_bytes_ = 0; exchanges_ = avoided_bytes_ = 0; } private: static constexpr size_t kAbsent = std::numeric_limits::max(); + static std::vector classes_of(const std::vector& sizes) { + std::vector c; + for (const uint64_t b : sizes) + if (b != 0 && b <= std::numeric_limits::max()) c.push_back((size_t) b); + std::sort(c.begin(), c.end()); + c.erase(std::unique(c.begin(), c.end()), c.end()); + return c; + } + size_t class_of(size_t bytes) const { + const auto it = std::lower_bound(classes_.begin(), classes_.end(), bytes); + return it != classes_.end() && *it == bytes ? (size_t) (it - classes_.begin()) : kAbsent; + } std::unique_ptr[]> experts_; size_t expert_count_ = 0; + std::vector expert_bytes_; // each expert's block size, immutable std::vector buffers_; // immutable physical addresses after initialize - std::vector spares_; // touched only by the serialized cache manager - size_t blob_bytes_ = 0; + std::vector buffer_bytes_; // each buffer's block size, immutable + std::vector spares_; // [size class * count_ + q]; touched only by the serialized cache manager + std::vector classes_; // the distinct block sizes, ascending + size_t count_ = 0; + size_t blob_bytes_ = 0; // the largest block size; 0 = not initialized uint64_t exchanges_ = 0, avoided_bytes_ = 0; }; diff --git a/include/strata/core/expert_source.hpp b/include/strata/core/expert_source.hpp index 327067f6..90cf64b2 100644 --- a/include/strata/core/expert_source.hpp +++ b/include/strata/core/expert_source.hpp @@ -27,6 +27,8 @@ #include "strata/core/hit_hook.hpp" #include "strata/kernels/cpu/pool.hpp" +#include +#include #include #include #include @@ -331,6 +333,97 @@ struct GpuPlanSink { /// kernel reads the mapped arena directly; 2 = a copy kernel stages it inside the graph. For 1 and 2 `ptr2` /// holds the arena's device alias. int pcie_mode = 0; + int32_t cpu_jobs = 0; ///< host only: the distinct experts the pool computes for the layer just published +}; + +/// Verifier::set_pcie_balance: a verify window's costs, fitted to each layer's measured times (ms, least squares with +/// forgetting): the CPU pool's time with n_c CPU and n_p PCIe experts, a + c n_c + d n_p (none: p0) - d is the PCIe +/// copies' DRAM reads slowing the pool, as the pool and the link read the same RAM - and the GPU's, g0 + g n_p. A +/// layer then reads over PCIe the m of its nmiss misses that minimizes max(GPU, CPU). Measured: an RTX 5090 + 9950X3D +/// pool is DRAM-bound (moving experts to PCIe left the pool's time where it was, d ~ c: few move), one worker on +/// ggml-cpu's dot is not (d ~ 0: most move). Until both fits have data, and while `on` is off, pcie_num's share. +struct PcieModel { + bool on = false; + double a = 0, c = 0, d = 0, p0 = 0, g0 = 0, g = 0; ///< the fits (read by `pick`) + int np0 = 0; + double A[3][3] = {}, B[3] = {}; ///< the CPU fit's normal equations, [1, n_c, n_p] + double C[2][2] = {}, D[2] = {}; ///< the GPU fit's, [1, n_p] + int ncpu = 0, ngpu = 0, ngpu_p = 0; ///< samples in each (ngpu_p: with a PCIe expert) + uint32_t explore = 0; + static void mean(double& v, int& n, double x) { // the first 16 evenly, then 1/20 each + if (n < 16) v += (x - v) / ++n; + else v += 0.05 * (x - v); + } + /// One layer's times: the pool's `p` with `n_c` CPU and `n_p` PCIe experts, the GPU's `gpu` (ms). + void sample(int n_c, int n_p, double p, double gpu) { + constexpr double lam = 0.995; // ~200 layers' memory: a few windows + if (n_c == 0) mean(p0, np0, p); + else { + const double x[3] = {1.0, (double) n_c, (double) n_p}; + for (int i = 0; i < 3; ++i) { + B[i] = lam * B[i] + x[i] * p; + for (int j = 0; j < 3; ++j) A[i][j] = lam * A[i][j] + x[i] * x[j]; + } + ++ncpu; + } + const double y[2] = {1.0, (double) n_p}; + for (int i = 0; i < 2; ++i) { + D[i] = lam * D[i] + y[i] * gpu; + for (int j = 0; j < 2; ++j) C[i][j] = lam * C[i][j] + y[i] * y[j]; + } + ++ngpu; + ngpu_p += n_p > 0; + } + /// Solve both fits (after a window). A ridge keeps a fit whose counts barely vary near its mean ratio. + void solve() { + if (ncpu >= 8) { + double M[3][4]; + for (int i = 0; i < 3; ++i) { + for (int j = 0; j < 3; ++j) M[i][j] = A[i][j] + (i == j && i > 0 ? 1e-3 * A[0][0] : 0.0); + M[i][3] = B[i]; + } + bool ok = true; + for (int k = 0; k < 3 && ok; ++k) { // Gauss-Jordan, partial pivot + int piv = k; + for (int i = k + 1; i < 3; ++i) if (std::abs(M[i][k]) > std::abs(M[piv][k])) piv = i; + if (std::abs(M[piv][k]) < 1e-12) { ok = false; break; } + for (int j = 0; j < 4; ++j) std::swap(M[k][j], M[piv][j]); + for (int i = 0; i < 3; ++i) { + if (i == k) continue; + const double f = M[i][k] / M[k][k]; + for (int j = k; j < 4; ++j) M[i][j] -= f * M[k][j]; + } + } + if (ok) { + a = std::max(M[0][3] / M[0][0], 0.0); + c = std::max(M[1][3] / M[1][1], 0.0); + d = std::clamp(M[2][3] / M[2][2], 0.0, c); // a PCIe expert slows the pool at most as one of its own + } + } + if (ngpu >= 8 && ngpu_p >= 4) { + const double det = C[0][0] * C[1][1] - C[0][1] * C[1][0]; + if (std::abs(det) > 1e-12) { + g0 = std::max((D[0] * C[1][1] - C[0][1] * D[1]) / det, 0.0); + g = std::max((C[0][0] * D[1] - C[1][0] * D[0]) / det, 0.0); + } + } + } + bool ready() const { return on && ncpu >= 8 && ngpu_p >= 4; } + /// The PCIe count for a layer of `nmiss` misses (`fixed`: pcie_num's). Every 64th layer with a miss that would + /// keep them all on one side moves one to the other, so both fits keep seeing both. + int pick(int nmiss, int fixed) { + int m = fixed; + if (ready()) { + double best = 1e300; + for (int k = 0; k <= nmiss; ++k) { + const double cpu = nmiss - k > 0 ? a + c * (nmiss - k) + d * k : p0; + const double t = std::max(g0 + g * k, cpu); + if (t < best - 1e-6) { best = t; m = k; } + } + } + if (on && nmiss >= 1 && (++explore & 63u) == 0) m = m == 0 ? 1 : m == nmiss ? nmiss - 1 : m; + return m; + } }; /// The adapter's own state. One per session, reused every layer so the token path allocates nothing (P2.T10). @@ -456,6 +549,7 @@ struct ExpertDispatch { /// each layer's distinct missed experts (the last ones in routing order) are read by the GPU over PCIe. GpuPlanSink* plan = nullptr; int pcie_num = 0; + PcieModel pcie_model; ///< Verifier::set_pcie_balance: the PCIe count from measured costs int64_t pcie_experts = 0; ///< distinct experts the GPU read over PCIe in verify windows /// #588: routed (token, expert) entries the GPU computed from outside its cache in verify windows: read over PCIe /// (--pcie-frac, kind 1) or on another GPU (kind 2). In neither cache_hits nor cache_refused. @@ -468,6 +562,18 @@ struct ExpertDispatch { /// Plan v0.3 P6: decayed routing counts per (layer, expert) during decode (sized by the caller; empty = off), /// which the driver uses to swap the most-routed missing experts into the VRAM tier between rounds. std::vector usage; + /// The adaptive tier's evictions reach the device's table before the next window, not when the round's copies + /// land: until then doorbell_publish_res can skip a layer's activation while the pool computes an evicted expert + /// from the one published before. The driver sets it where the tier does not wait for its copies + /// (STRATA_ADAPT_NOWAIT=1, STRATA_ADAPT_LAG > 1; STRATA_ADAPT_EVICT_SYNC=0: off, for an A/B). `res_dirty` asks the + /// driver to patch the device's copy before the next window, `res_dirty_idx` lists the entries changed since. + bool evict_sync = false; + bool res_dirty = false; + std::vector res_dirty_idx; + /// STRATA_ADAPT_CHECKRES: the device's residency table as read back before the window; a layer with CPU experts + /// whose routed ids all look resident there publishes no activation (doorbell_publish_res) - counted + const int32_t* dres_check = nullptr; + int64_t stale_x = 0; int64_t multi_misses = 0; ///< distinct (layer, expert) pairs the CPU computed in verify windows int64_t multi_entries = 0; ///< routed (token, expert) entries the CPU served in verify windows /// Multi-GPU: the second GPU's tier. Its experts are computed there instead of on the CPU (kind 2). @@ -598,15 +704,20 @@ 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). + // STRATA_EXCHANGE_ROTATE=1 can instead transfer buffer ownership (fully pinned/mapped slots; a pack whose layers + // differ in block size keeps spares per size). /// 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); + /// `bounce`: how many of the last buffers are only staged through and never hold an exchange (STRATA_EXCHANGE_ROTATE + /// keeps those in the largest block size alone). + bool reserve_exchanges(int64_t n, std::string& err, int64_t bounce = 0); 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; + /// Buffer `q`. `layer` >= 0: the buffer an exchange of that layer's experts stages into (STRATA_EXCHANGE_ROTATE with + /// several block sizes keeps one per size); without it, one that holds any layer's block. + uint8_t* exchange_buffer(int64_t q, int64_t layer = -1) 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 @@ -633,6 +744,13 @@ public: /// 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_; } + /// STRATA_RAM_ADAPT: the compact copy gives `out`'s place to `in`, read from the file, so the RAM tier can follow + /// the conversation as the VRAM tier does. Both are experts of `layer` (one blob size), `out` is held by the copy + /// and `in` is not, no exchange is staged, and nothing may be reading `out`'s blob: the caller's thread, between + /// windows, with no adaptive round in flight. A failed read leaves the copy as it was. Not with + /// STRATA_EXCHANGE_ROTATE (false, nothing changes). + bool replace_resident(int64_t layer, int64_t in, int64_t out); + int64_t ram_adapts() const { return ram_adapts_; } 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(); } @@ -821,6 +939,8 @@ private: std::unordered_map stage_of_; uint64_t stage_blob_ = 0; uint64_t stage_seq_ = 0; + int64_t ram_adapts_ = 0; ///< replace_resident: experts moved from the file into the compact copy + std::vector ram_adapt_buf_; ///< ...one blob, read here before it replaces another uint64_t epoch_ = 0; int64_t last_layer_ = -1; bool stage_grew_ = false; diff --git a/include/strata/core/verify.hpp b/include/strata/core/verify.hpp index f4d98251..a7387236 100644 --- a/include/strata/core/verify.hpp +++ b/include/strata/core/verify.hpp @@ -32,6 +32,7 @@ #include #include +#include #include #include #include @@ -272,8 +273,12 @@ public: /// 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; } + /// the device-planned layers (E-6) off, which read the device table this mode lets lag. Before the first window + /// (its graphs are captured there). + void set_always_publish(bool on) { + always_publish_ = on; + if (on) device_plan_ = false; + } /// 0.1.43: the adaptive tier's overlap gate (see AdaptGate). Refused (false) with the device-planned layers (E-6), /// which never ask the host. The pointer must outlive the verifier's windows. bool set_adapt_gate(AdaptGate* g) { @@ -330,8 +335,23 @@ public: /// arena directly, 2 = a copy kernel stages it inside the graph (no API calls on the pool's thread; best when /// the CPU is RAM-bound, Q2_0). Set before the first `run`. void set_pcie_mode(int mode) { sink_.pcie_mode = mode; } + /// Called before every window this verifier launches (run, the batch and pipelined launches): the device's + /// residency table catches up with the host's (the adaptive tier's evictions while its copies are in flight). + /// It gets this verifier's stream; false (with the message in `err`) fails the launch. + void set_pre_launch(std::function f) { pre_launch_ = std::move(f); } /// the pool never plans a PCIe share (--pcie-frac 0): the window skips that path. Before the first run. + /// The PCIe count of each layer from measured costs (PcieModel) instead of a fixed share: the spin kernels stamp + /// each step's GPU work (the plan's arrival, the PCIe part's start, the wait for the CPU's rows; GPU clock), the host + /// times its pool, and after each window *model (the dispatch's) takes the costs. One GPU, no batch slots. Set + /// before `init` (the stamps are captured). `paused`: a request's own --pcie-frac holds meanwhile. + void set_pcie_balance(PcieModel* model) { bal_ = model; } + void pause_pcie_balance(bool paused) { + bal_paused_ = paused; + if (bal_ != nullptr && m_bal_ != nullptr) bal_->on = !paused; + } + bool pcie_balance_on() const { return bal_ != nullptr && m_bal_ != nullptr; } + double ms_wait = 0, ms_pool = 0, ms_host = 0, ms_commit = 0; int64_t windows = 0; /// STRATA_VERIFY_PROFILE=1 - GPU stage times of the windows since the last call (ms per @@ -538,6 +558,16 @@ private: uint32_t* h_flag_ = nullptr; uint32_t* m_flag_ = nullptr; uint32_t* h_flagA_ = nullptr; uint32_t* m_flagA_ = nullptr; // the GPU plan is in place uint32_t* h_flagB_ = nullptr; uint32_t* m_flagB_ = nullptr; // the PCIe share's DMA copies have landed + // set_pcie_balance: per step (layer x group, stride 2 groups) the GPU's clock as the plan arrives, as the PCIe + // part starts and as it waits for the CPU rows (4 words a step); the pool's ms, its experts, the PCIe ones, and + // whether the step had a plan + unsigned long long* h_bal_ = nullptr; unsigned long long* m_bal_ = nullptr; + std::vector bal_p_; + std::vector bal_nc_, bal_np_; + std::vector bal_ok_; + PcieModel* bal_ = nullptr; + bool bal_paused_ = false; + void pcie_balance_window(int64_t steps, int G); cudaEvent_t commit_done_ = nullptr; // recorded after an async commit (set_commit_async); see wait_commit bool commit_pending_ = false; cudaStream_t copy_ = nullptr; // the copy engine's stream (DMA of missed experts) @@ -552,6 +582,7 @@ private: static void publish_plan(void* ctx); void set_plan_slot(int grp); bool split_ = false; // opt-in (--spec-split): exact but slower, see the overlap study + std::function pre_launch_; // set_pre_launch int groups_[9] = {}; float* h_ymiss_ = nullptr; float* m_ymiss_ = nullptr; // T * k * n_embd diff --git a/include/strata/kernels/verify_kernels.hpp b/include/strata/kernels/verify_kernels.hpp index dab7c9fe..45bc70e1 100644 --- a/include/strata/kernels/verify_kernels.hpp +++ b/include/strata/kernels/verify_kernels.hpp @@ -85,6 +85,10 @@ void handoff_publish(float* dst, const float* a, int64_t na, const float* b, int /// The reading stage's hand-off wait, bounded: spin until *flag >= value, or after timeout_ns (0: no bound) set /// *err = 1 (mapped) and return, so the window's graph completes and the host fails the window cleanly. void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream); +/// wait_flag_ge, also writing the GPU's clock (ns, gpu_stamp's) as the kernel starts into *t_in and as it returns +/// into *t_out (either may be null): the verify window's PCIe-share balance, at no extra launch. +void wait_flag_ge_stamped(const uint32_t* flag, uint32_t value, unsigned long long* t_in, unsigned long long* t_out, + void* stream); /// the GPU's %globaltimer (ns) into buf[i] (a one-thread kernel: the verify window's stage profiler). Inside a PDL /// stretch (pdl.hpp) the stamp passes the early launch on, so a profiled window keeps the chain it measures. void gpu_stamp(unsigned long long* buf, int i, void* stream); @@ -126,6 +130,9 @@ void copy_indexed(float* dst, const float* src, int64_t stride, const int32_t* i /// into dst + k * blob_bytes with coalesced 16-byte loads - the PCIe share of a layer's missed experts, staged /// into VRAM before the grouped expert kernel reads them. Launched for a capacity of `cap` blobs. void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, int64_t blob_bytes, int cap, void* stream); +/// table[pairs[2k]] = pairs[2k + 1] for k < n, `pairs` in mapped host memory: a residency table's changed entries, +/// stream-ordered before the window that reads it, without the copy engine (where the tier's swaps may queue). +void res_patch(int32_t* table, const int32_t* pairs, int n, void* stream); /// ptr[k] = base + k * blob_bytes for k < *n (the staged copies `fetch_blobs` made). void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream); diff --git a/src/core/expert_source.cpp b/src/core/expert_source.cpp index 6547a2f1..4e116944 100644 --- a/src/core/expert_source.cpp +++ b/src/core/expert_source.cpp @@ -2687,6 +2687,7 @@ bool FileExpertSource::pin_cache_complement( } #endif const bool what_fits = budget_bytes == kResidentWhatFits; // #467: the soft mode's second try + int64_t budget_lent = 0, budget_lendable = 0; // the lend region's slots kept by a budget (below), and its size uint64_t budget_physical = 0; // #403: reuse the memory snapshot a budget was sized from uint64_t budget_commit = std::numeric_limits::max(); if (budget_bytes > 0) { @@ -2738,6 +2739,36 @@ bool FileExpertSource::pin_cache_complement( std::fprintf(stderr, "FileExpertSource: RAM budget %.2f GiB: %lld of the %.2f GiB of experts the GPU cache does " "not hold, by profile rank; the rest are read from the files\n", (double) budget_bytes / 1073741824.0, (long long) held, (double) bytes / 1073741824.0); + // The prompt path's lend region under a budget. Until now a budget turned the loan off (`lend_from_slot = -1` + // below), so every lent slot's expert was read from the pack during every prompt chunk and again when the slot + // was refilled after the prompt - even with room left in the budget. Measured on an RX 6900 XT 16 GB with + // --resident-budget-gib 71 and UD-Q4_K_XL: the copy kept all 63.47 GiB of the experts outside the cache, 7.5 + // GiB of the budget stayed unused, and every agent turn read 0.5-2.6 GB of the 1,231 lent slots' experts (3.6 + // GiB) from the GGUF (a fresh 17K-token prompt 24 GB). As the unbudgeted path does, take the lend region's + // experts from the last slot down (the order the borrowing takes them) while they fit in what the budget has + // left; the ones past it keep the file fallback, and `rank` keeps its precedence (the hottest experts first). + if (lend_from_slot >= 0 && lend_from_slot < n_slots && additional_gpu_pairs.empty()) { + budget_lendable = n_slots - lend_from_slot; + std::vector order; // the pairs in the lend region, highest slot first + for (size_t i = 0; i < primary_gpu_pairs.size(); ++i) + if (pair_slot[i] >= lend_from_slot && pair_slot[i] < n_slots) order.push_back(i); + std::sort(order.begin(), order.end(), [&](size_t a, size_t b) { return pair_slot[a] > pair_slot[b]; }); + const uint64_t at0 = at; + for (size_t i : order) { + const auto& pr = primary_gpu_pairs[i]; + const size_t idx = (size_t) pr.first * (size_t) n_expert_ + (size_t) pr.second; + const uint64_t b = layer_blob_bytes_[(size_t) pr.first]; + if (b > budget_bytes - at) break; // a contiguous tail of the region: a short prompt lends only the last few + if (ranked[idx] != kNoComplement) continue; + ranked[idx] = at; + at += b; + ++budget_lent; + } + std::fprintf(stderr, "FileExpertSource: the prompt path's lend region: %lld of its %lld slots keep their experts " + "in RAM too (%.2f GiB of the budget's remaining %.2f GiB)\n", + (long long) budget_lent, (long long) budget_lendable, (double) (at - at0) / 1073741824.0, + (double) (budget_bytes - at0) / 1073741824.0); + } offsets.swap(ranked); bytes = at; lend_from_slot = -1; @@ -3211,7 +3242,7 @@ bool FileExpertSource::pin_cache_complement( complement_partial_ = complement_registered_ && !(paced && partial_pin >= bytes); complement_locked_ = locked; complement_lock_off_ = lock_off; - complement_lent_slots_ = lend ? n_slots - keep_from : 0; + complement_lent_slots_ = lend ? n_slots - keep_from : budget_lent; // a budget keeps its own tail of the region complement_lent_slots_ += stage_lent; // and the split stages' regions: pairs the copy kept of them complement_ready_ = true; std::fprintf(stderr, "FileExpertSource: %s cache complement ready: resident %.2f GiB, pinned %.2f GiB in %.0f s%s%s\n", @@ -3219,21 +3250,24 @@ bool FileExpertSource::pin_cache_complement( (double) resident_bytes() / 1073741824.0, (double) pinned_bytes() / 1073741824.0, std::chrono::duration(std::chrono::steady_clock::now() - pin_t0).count(), note.empty() ? "" : "; ", note.c_str()); - if (lend) + const int64_t lendable_all = lend ? n_slots - lend_from_slot : budget_lendable; // 0: no lend region at all + if (lendable_all > 0) std::fprintf(stderr, "FileExpertSource: %lld of the prompt path's %lld lendable slots keep their experts in RAM " - "too%s\n", (long long) complement_lent_slots_, (long long) (n_slots - lend_from_slot), - complement_lent_slots_ < n_slots - lend_from_slot + "too%s\n", (long long) (lend ? n_slots - keep_from : budget_lent), (long long) lendable_all, + (lend ? n_slots - keep_from : budget_lent) < lendable_all ? " (the others are read from the file when lent: not enough RAM for them)" : ""); - if (lend && complement_lent_slots_ < n_slots - lend_from_slot) { + if (lendable_all > 0 && (lend ? n_slots - keep_from : budget_lent) < lendable_all) { // #1389: below full coverage the uncovered experts are read from the pack during a long prompt (a 74K prompt // routes through nearly all experts, so the misses repeat). The reporter measured 18% uncovered = -26% prompt // speed on a gfx1100; short prompts barely touch them. A warning, not a refusal. - const long long lendable = (long long) (n_slots - lend_from_slot); - const long long missing = lendable - (long long) complement_lent_slots_; + const long long lendable = (long long) lendable_all; + const long long missing = lendable - (long long) (lend ? n_slots - keep_from : budget_lent); std::fprintf(stderr, "FileExpertSource: WARNING: %lld of %lld lendable slots (%.0f%%) will read their experts from the pack " "during a long prompt; expect a slower prompt read on 50K+ token prompts (one measurement: 18%% uncovered " - "cost 26%%). Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start) and restart; " - "the line above should read N of N.\n", missing, lendable, 100.0 * (double) missing / (double) std::max(1, lendable)); + "cost 26%%). %s and restart; the line above should read N of N.\n", missing, lendable, + 100.0 * (double) missing / (double) std::max(1, lendable), + lend ? "Free RAM or lower STRATA_RESIDENT_HEADROOM_GIB (now the RAM left free at start)" + : "Raise --resident-budget-gib (the lend region comes after the ranked experts)"); } if (!stage_lend_regions_.empty()) { int64_t offered = 0; @@ -3262,7 +3296,7 @@ bool FileExpertSource::has_resident(int64_t layer, int64_t expert) const { return resident_blob(index) != nullptr; } -bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { +bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err, int64_t bounce) { err.clear(); if (n <= xstage_cap_) return true; if (!staged_.empty()) { err = "FileExpertSource: exchange buffers are in use"; return false; } @@ -3284,11 +3318,13 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { } 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_ && + // layers of several block sizes (a GGUF's mixed i-quants): spares of every size, see ExchangeStorage + bounce = std::max(0, std::min(bounce, n)); + const uint64_t rotate_total = detail::ExchangeStorage::exchange_bytes_needed(layer_blob_bytes_, (size_t) n, (size_t) bounce); + const bool eligible = requested && rotate_total != 0 && rotate_total <= std::numeric_limits::max() && + complement_pinned_ && !complement_partial_ && complement_host_ && complement_device_ && complement_bytes_ > 0; - const size_t total = (size_t) n * (size_t) blob; + const size_t total = eligible ? (size_t) rotate_total : (size_t) n * (size_t) blob; void* p = nullptr; if (cudaHostAlloc(&p, total, eligible ? cudaHostAllocMapped : cudaHostAllocDefault) == cudaSuccess && p != nullptr) { xstage_pinned_ = true; @@ -3302,14 +3338,21 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { xstage_cap_ = n; xstage_blob_ = blob; if (requested) { - std::string reason = "requires equal-size expert blocks and a fully mapped/pinned RAM complement"; + std::string reason = "requires 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); + std::vector sizes(complement_offsets_.size(), 0); + for (size_t i = 0; i < sizes.size(); ++i) { + const size_t layer = n_expert_ > 0 ? i / (size_t) n_expert_ : 0; + sizes[i] = layer < layer_blob_bytes_.size() ? layer_blob_bytes_[layer] : 0; + } + if (exchange_storage_.initialize_sized(complement_offsets_, sizes, (uint8_t*)complement_host_, complement_device_, + complement_bytes_, xstage_, (const uint8_t*)device, (uint64_t)total, (size_t)n, (size_t)bounce, reason)) { + std::fprintf(stderr, "FileExpertSource: exchange buffer rotation enabled: %lld buffers in %zu block sizes " + "(largest %llu bytes, %.2f GiB page-locked); no host commit memcpy\n", + (long long)n, exchange_storage_.block_sizes(), (unsigned long long)blob, + (double)total / 1073741824.0); } } catch (const std::bad_alloc&) { reason = "buffer metadata allocation failed"; } } else if (eligible) { @@ -3322,22 +3365,24 @@ bool FileExpertSource::reserve_exchanges(int64_t n, std::string& err) { return true; } -uint8_t* FileExpertSource::exchange_buffer(int64_t q) const { +uint8_t* FileExpertSource::exchange_buffer(int64_t q, int64_t layer) const { if (xstage_ == nullptr || q < 0 || q >= xstage_cap_) return nullptr; - if (exchange_storage_.active()) return exchange_storage_.spare((size_t)q).host; + if (exchange_storage_.active()) + return layer >= 0 && layer < n_layers_ ? exchange_storage_.spare((size_t)q, (size_t)layer_blob_bytes_[(size_t)layer]).host + : 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 (out < 0 || out >= n_expert_ || !has_resident(layer, in) || has_resident(layer, out) || - exchange_buffer(q) == nullptr) return false; + exchange_buffer(q, layer) == 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); if (override_[i_out] != nullptr) return false; for (const Exchange& x : staged_) if (x.in == i_in || x.q == q) return false; - override_[i_out] = exchange_buffer(q); + override_[i_out] = exchange_buffer(q, layer); staged_.push_back({i_in, i_out, q, layer_blob_bytes_[(size_t) layer]}); return true; } @@ -3399,6 +3444,35 @@ int64_t FileExpertSource::commit_exchanges() { return n; } +bool FileExpertSource::replace_resident(int64_t layer, int64_t in, int64_t out) { + if (!complement_ready_ || complement_host_ == nullptr || exchange_storage_.active() || !staged_.empty() || + layer < 0 || layer >= n_layers_ || in < 0 || out < 0 || in >= n_expert_ || out >= n_expert_ || in == out) + 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 (i_in >= complement_offsets_.size() || i_out >= complement_offsets_.size()) return false; + if (!override_.empty() && (override_[i_in] != nullptr || override_[i_out] != nullptr)) return false; + const uint64_t at = complement_offsets_[i_out], bytes = layer_blob_bytes_[(size_t) layer]; + if (at == kNoComplement || complement_offsets_[i_in] != kNoComplement || at > complement_bytes_ || + bytes > complement_bytes_ - at) return false; + // read beside the copy first: a failed read leaves `out` where it was + if (ram_adapt_buf_.size() < (size_t) bytes) ram_adapt_buf_.resize((size_t) bytes); + const auto t0 = std::chrono::steady_clock::now(); + if (!copy_from_files(layer, in, ram_adapt_buf_.data())) return false; + file_us_.fetch_add((uint64_t) std::chrono::duration(std::chrono::steady_clock::now() - t0).count(), + std::memory_order_relaxed); + file_read_bytes_.fetch_add(bytes, std::memory_order_relaxed); + // #2134: a Foresight slot may be copying out of `out`'s place right now; it is dropped (never served) before the place is rewritten + ForesightSwap* fs = fs_swap_.load(std::memory_order_acquire); + if (fs != nullptr) fs->hold(layer, (int32_t) out); + std::memcpy((uint8_t*) complement_host_ + (size_t) at, ram_adapt_buf_.data(), (size_t) bytes); + const bool moved = detail::exchange_cache_complement(complement_offsets_, i_out, i_in); + if (fs != nullptr) fs->unhold(layer, (int32_t) out); + if (!moved) return false; + ++ram_adapts_; + return true; +} + void FileExpertSource::commit_copies() { fs_hold_staged(true); // #2134: held until commit_flip has pointed `out` at its new place if (exchange_storage_.active()) return; // STRATA_EXCHANGE_ROTATE: ownership moves in commit_flip, nothing to copy @@ -3767,8 +3841,9 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 ++d.tail_experts; } } - const bool pcie_ok = d.pcie_num > 0 && d.src->pcie_layer(d.layers); - int m = pcie_ok ? (nmiss * d.pcie_num) >> 8 : 0; + // STRATA_PCIE_BALANCE (opt-in, #1548): the count comes from the measured CPU and GPU costs instead of the share + const bool pcie_ok = (d.pcie_num > 0 || d.pcie_model.on) && d.src->pcie_layer(d.layers); + int m = pcie_ok ? d.pcie_model.pick(nmiss, (nmiss * d.pcie_num) >> 8) : 0; // STRATA_PCIE_MIN1 (opt-in): the share rounds to 0 for 1-2 misses per layer, so the PCIe lane idles on the typical // decode step; with >= 2 misses give it at least one (the last in routing order). It only flies if its blob is // pinned (the fetch below checks), else it stays a CPU miss exactly as before. Read once. @@ -3886,6 +3961,13 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 bool any_cpu = false; for (int64_t i = 0; i < n; ++i) if (kind[i] == -1) { any_cpu = true; break; } // -2: skipped (STRATA_ROUTE_TAIL_SKIP), no work + if (d.dres_check != nullptr && any_cpu) { // STRATA_ADAPT_CHECKRES + bool published = false; + for (int64_t i = 0; i < n && !published; ++i) + published = ids[i] < 0 || ids[i] >= d.n_expert || + d.dres_check[(size_t) d.layers * (size_t) d.n_expert + (size_t) ids[i]] < 0; + if (!published) ++d.stale_x; + } const auto c1 = std::chrono::steady_clock::now(); if (any_cpu) { // #578 --remote-expert-opt: a token whose experts all run on a GPU (CUDA0 or a helper) needs no CPU activation @@ -3964,6 +4046,7 @@ void expert_pool_dispatch_multi(ExpertDispatch& d, const float* x_f, const int32 ++d.multi_entries; } const auto c3 = std::chrono::steady_clock::now(); + if (d.plan != nullptr) d.plan->cpu_jobs = njobs; pt("run", njobs); if (njobs > 0) { if (native) d.pool->run_split_multi_native(lay.fmt[(size_t) d.layers], d.jobs_multi.data(), njobs); diff --git a/src/core/layer.cpp b/src/core/layer.cpp index 7eeb8a0a..701ef22e 100644 --- a/src/core/layer.cpp +++ b/src/core/layer.cpp @@ -34,11 +34,15 @@ #include #include #include +#include #include #include #include #include #include +#ifndef _WIN32 +#include +#endif #include #include namespace strata::core { @@ -516,6 +520,53 @@ namespace { int64_t g_kv_resident = 0; uint64_t g_kv_host_bytes = 0; +// The KV host copy: pinned and device-mapped. cudaHostAlloc is the default, but under WSL2 the driver caps what +// cudaHostAlloc(Mapped) may pin at about 1 GiB in all, while cudaHostRegister of ordinary memory is not capped there: +// the expert arena registers tens of GiB the same way (pinned.cu). So under WSL2, detected as generate.cpp's +// under_wddm() does (/dev/dxg, the device its GPU goes through to the Windows driver), the copy is anonymous memory +// registered Portable|Mapped before any page is touched, which also leaves WSL's small cudaHostAlloc budget to the +// staging buffers. Elsewhere cudaHostAlloc stays first. Either way the other method is the fallback when the first +// is refused. STRATA_KV_HOST_REGISTER=1/0 forces registering first or cudaHostAlloc first. Like the cudaHostAlloc +// copy it lives as long as the process. +uint8_t* kv_host_alloc(uint64_t bytes) { + auto host_alloc = [](uint64_t n) -> uint8_t* { + uint8_t* h = nullptr; + if (cudaHostAlloc((void**) &h, n, cudaHostAllocMapped | cudaHostAllocPortable) == cudaSuccess) return h; + (void) cudaGetLastError(); + return nullptr; + }; +#ifdef _WIN32 + return host_alloc(bytes); +#else + static const bool register_first = [] { + const char* e = std::getenv("STRATA_KV_HOST_REGISTER"); + if (e != nullptr && (e[0] == '0' || e[0] == '1')) return e[0] == '1'; + return std::filesystem::exists("/dev/dxg"); + }(); + auto register_anon = [](uint64_t n) -> uint8_t* { + void* m = mmap(nullptr, (size_t) n, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); + if (m == MAP_FAILED) return nullptr; + if (cudaHostRegister(m, (size_t) n, cudaHostRegisterPortable | cudaHostRegisterMapped) != cudaSuccess) { + (void) cudaGetLastError(); + munmap(m, (size_t) n); + return nullptr; + } + static bool said = false; + if (!said) { + std::fprintf(stderr, "strata: KV streaming: the host copy is pinned with cudaHostRegister\n"); + said = true; + } + return (uint8_t*) m; + }; + if (register_first) { + if (uint8_t* m = register_anon(bytes)) return m; + return host_alloc(bytes); + } + if (uint8_t* h = host_alloc(bytes)) return h; + return register_anon(bytes); +#endif +} + // ---- the elastic K/V (--kv-grow): one VMM range per state, each pool array at a chunk boundary in it bool g_kv_elastic = false; int64_t g_kv_elastic_init = 16384; @@ -802,12 +853,12 @@ uint64_t qsa_state_init(const ModelGeometry& g, int64_t max_cells, void* base, Q const uint64_t bytes = (uint64_t) pages * strata::kernels::kv_block_bytes(s, qsa_kv_format(st)) + 4 * 256; uint8_t* h = nullptr; uint8_t* d = nullptr; - if (cudaHostAlloc((void**) &h, bytes, cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess || + if ((h = kv_host_alloc(bytes)) == nullptr || cudaHostGetDevicePointer((void**) &d, h, 0) != cudaSuccess) { - // under WSL the NVIDIA driver pins only ~1 GiB in all, which is less than 128K of 8-bit KV needs + // both cudaHostRegister and cudaHostAlloc were refused (kv_host_alloc): usually not enough free RAM if (p.mode == 1) std::fprintf(stderr, "strata: KV streaming: cannot pin %.2f GiB of RAM for a layer's KV copy " - "(%.2f GiB pinned so far) - lower the context, or run without --kv-resident (under " - "WSL the driver pins only about 1 GiB in all)\n", (double) bytes / 1073741824.0, + "(%.2f GiB pinned so far): RAM or the driver refused to pin it - lower the context, " + "or run without --kv-resident\n", (double) bytes / 1073741824.0, (double) g_kv_host_bytes / 1073741824.0); return 0; } diff --git a/src/core/verify.cpp b/src/core/verify.cpp index 6c1c1e3e..24c29a0a 100644 --- a/src/core/verify.cpp +++ b/src/core/verify.cpp @@ -573,7 +573,7 @@ Verifier::~Verifier() { if (arena_) cudaFree(arena_); if (hcount_d_) cudaFree(hcount_d_); void* hosts[] = {h_tok_, h_step_, h_pos_, h_commit_, h_ple_, h_out_, h_x_, h_ids_, h_w_, h_seq_, h_flag_, h_ymiss_, - h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_}; + h_flagA_, h_plan_, h_flagB_, h_plan_err_, h_nf_, herr_h_, hdrop_h_, h_bal_}; for (void* h : hosts) if (h) cudaFreeHost(h); } @@ -686,6 +686,17 @@ bool Verifier::init(const WeightTable& wt, const ModelGeometry& g, SessionState& mapped(64, (void**) &h_plan_err_, (void**) &m_plan_err_) && mapped(T * K * N * 4, (void**) &h_ymiss_, (void**) &m_ymiss_); if (!ok) { err = "verify: mapped staging allocation failed"; return false; } + if (bal_ != nullptr) { // set_pcie_balance: four stamp words per (layer, group) + if (!mapped((size_t) g.n_layers * 2 * 4 * 8, (void**) &h_bal_, (void**) &m_bal_)) { + err = "verify: mapped balance stamps allocation failed"; + return false; + } + bal_p_.assign((size_t) g.n_layers * 2, 0.0); + bal_nc_.assign((size_t) g.n_layers * 2, 0); + bal_np_.assign((size_t) g.n_layers * 2, 0); + bal_ok_.assign((size_t) g.n_layers * 2, 0); + bal_->on = true; + } // the GPU plan: counts(4) | start(cap+1) | dst(cap) | tok(cap) | pad | ptr(cap u64) | ptr2(cap u64) | start2(cap+1) { const int64_t cap = (int64_t) (T * K); @@ -1919,10 +1930,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { wait_flag_ge_or(m_flagA_, ring, skip_ + grp, cs); copy_i32_from_mapped_unless(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, skip_ + grp, ring, cs); } else { - if (fuse_wait_on() && !prof_on_) { // 143-amdk: one launch for the wait and the copy + if (fuse_wait_on() && !prof_on_ && m_bal_ == nullptr) { // 143-amdk: one launch for the wait and the copy wait_copy_i32_from_mapped(m_flagA_, ring, pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs); } else { - wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan + if (m_bal_ != nullptr) // set_pcie_balance: the GPU's share starts as the plan arrives + wait_flag_ge_stamped(m_flagA_, ring, nullptr, m_bal_ + ((l - lb_) * 2 + grp) * 4, cs); + else + wait_flag_ge(m_flagA_, ring, cs); // the pool published this group's GPU plan copy_i32_from_mapped(pl, m_plan_ + (size_t) grp * (size_t) plan_i32_, plan_i32_, cs); } } @@ -1930,6 +1944,8 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { grouped(p_ptr, p_start, p_counts, 0, hit_out); stamp(l, 20, grp); if (device_plan_) wait_flag_ge_or(m_flagB_, ring, skip_ + grp, cs); + else if (m_bal_ != nullptr) // set_pcie_balance: the PCIe part starts + wait_flag_ge_stamped(m_flagB_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 1, nullptr, cs); else wait_flag_ge(m_flagB_, ring, cs); // the PCIe share is in staging (DMA) or mapped if (sink_.pcie_mode == 2) { // stage it with a copy kernel, then point at staging const int64_t per = G == 2 ? kStagingBlobs / 2 : kStagingBlobs; @@ -1947,8 +1963,13 @@ bool Verifier::record_window(int T, cudaStream_t cs, std::string& err) { copy_or_zero_from_mapped(parts_out, m_ymiss_ + (size_t) tb * K * N, (long long) n * K * N, skip_ + grp, ring, cs); } else { - const bool fuse_rows = fuse_wait_on() && !prof_on_ && !remote_opt_ && dec_batch; // 143-amdk - if (!fuse_rows) wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows + const bool fuse_rows = fuse_wait_on() && !prof_on_ && !remote_opt_ && dec_batch && m_bal_ == nullptr; // 143-amdk + if (!fuse_rows) { + if (m_bal_ != nullptr) // set_pcie_balance: ... and ends as it waits for the CPU's rows + wait_flag_ge_stamped(m_flag_, ring, m_bal_ + ((l - lb_) * 2 + grp) * 4 + 2, nullptr, cs); + else + wait_flag_ge(m_flag_, ring, cs); // the CPU's share is in the mapped rows + } stamp(l, 23, grp); if (remote_opt_) // #578: the helper's rows come back reduced; skip them as well remote_opt_->copy_rows(parts_out, m_ymiss_ + (size_t) tb * K * N, tb, n, p_dst, p_counts + 1, cs); @@ -2557,6 +2578,7 @@ bool Verifier::prelaunch(int T, const int32_t* tokens, int64_t pos0, std::string std::atomic_thread_fence(std::memory_order_seq_cst); trace_ev("WINDOW-PRE", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); + if (h_bal_ != nullptr) std::memset(h_bal_, 0, (size_t) bal_p_.size() * 4 * 8); // this window's stamps only if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; // 0.1.43: the same gate run() applies before it launches (the adaptive tier's copies land first) if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && @@ -2588,6 +2610,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, // or this thread would serve the window as the other variant const bool pre = prelaunched_ == T; prelaunched_ = 0; + if (!pre && pre_launch_ && !pre_launch_(cs_, err)) return false; // (a prelaunched window's was served with the first stage's) if (!pre) refresh_ar(); if (!capture(T, err) || !capture_commit(err)) return false; const bool chain = chain_overlap(); @@ -2620,6 +2643,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, trace_ev("WINDOW", -1, -1, pos0 * 16 + T); ms_host += ms_since(t0); VDBG("staged; launching\n"); + if (h_bal_ != nullptr) std::memset(h_bal_, 0, (size_t) bal_p_.size() * 4 * 8); // this window's stamps only if (ar_on() && h_plan_err_ != nullptr) *(volatile uint32_t*) h_plan_err_ = 0; // 0.1.43: with the all-resident graph the host serves no layer, so nothing can hold a layer back: every copy first if (adapt_gate_ != nullptr && adapt_gate_->active.load(std::memory_order_acquire) && ar_on() && @@ -2753,6 +2777,13 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, progress_tick(); std::atomic_thread_fence(std::memory_order_seq_cst); _mm_sfence(); + if (h_bal_ != nullptr) { // set_pcie_balance: the step's plan, its CPU and its PCIe experts + const size_t bi = (size_t) ((k / G) * 2 + grp); + bal_ok_[bi] = *(volatile uint32_t*) h_flagA_ == want; + bal_nc_[bi] = bal_ok_[bi] ? sink_.cpu_jobs : 0; + bal_np_[bi] = bal_ok_[bi] ? sink_.counts[2] : 0; + sink_.cpu_jobs = 0; + } 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; @@ -2775,6 +2806,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, ms_host += ms_since(tp); } if (!(test_stall && k + 1 == steps)) *flag = want; + if (h_bal_ != nullptr) bal_p_[(size_t) ((k / G) * 2 + grp)] = ms_since(b); ms_wait += std::chrono::duration(b - a).count(); ms_pool += ms_since(b); } @@ -2833,6 +2865,7 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, cudaStreamSynchronize(copy_); // no host function of this window may raise flag B in the next one copy_used_ = false; } + if (h_bal_ != nullptr && !all_resident_ && !bal_paused_) pcie_balance_window(steps, G); if (prof_on_ && G == 1) collect_profile(); // the window's GPU stage stamps // ---- a sampled or penalized request: the head's sampling again, host-side so its parameters are this call's // own (a captured kernel would replay the same draws forever). Row t's draw is Philox(seed, pos0 + t): tied to @@ -2900,6 +2933,20 @@ bool Verifier::run(int T, const int32_t* tokens, int64_t pos0, PoolMultiFn pool, return true; } +// set_pcie_balance: each stamped step's times into the model's fits (PcieModel::sample), solved once a window. +void Verifier::pcie_balance_window(int64_t steps, int G) { + const volatile unsigned long long* st = h_bal_; + PcieModel& M = *bal_; + for (int64_t k = 0; k < steps; ++k) { + const size_t i = (size_t) ((k / G) * 2 + k % G); + if (!bal_ok_[i]) continue; + const unsigned long long ta = st[4 * i], tb = st[4 * i + 1], tw = st[4 * i + 2]; + if (ta == 0 || tb < ta || tw < tb || tw - ta > 1000000000ull) continue; // not stamped in this window + M.sample(bal_nc_[i], bal_np_[i], bal_p_[i], (double) (tw - ta) * 1e-6); + } + M.solve(); +} + void Verifier::set_plan_slot(int grp) { const int64_t cap = sink_.cap; int32_t* base = h_plan_ + (size_t) grp * (size_t) plan_i32_; @@ -3446,6 +3493,7 @@ bool Verifier::run_slot_rows(const int* rows, int S, const int32_t* tokens, cons using namespace strata::kernels; const OnDevice on_device(device_); const ModelGeometry& g = *g_; + if (pre_launch_ && !pre_launch_(cs_, err)) return false; if (!stage_batch(rows, S, 0, tokens, pos, err)) return false; const cudaError_t le = cudaGraphLaunch(exec_bm_[bkey(rows, S, 0)], cs_); if (le != cudaSuccess) { err = std::string("verify: batch launch: ") + cudaGetErrorString(le); return false; } @@ -3613,6 +3661,7 @@ bool Verifier::batch_launch(int base, int S, const int32_t* tokens, const int64_ if (b_running_) { err = "verify: batch_launch while this stage is busy"; return false; } int rows[8] = {}; for (int t = 0; t < S && t < 8; ++t) rows[t] = base + t; + if (pre_launch_ && !pre_launch_(cs_, err)) return false; 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 && !batch_self_commits(rows, S)) // (else the window has kept its rows itself) @@ -3899,6 +3948,7 @@ bool Verifier::pl_launch(int T, const int32_t* tokens, int64_t pos0, std::string err = "verify: pipelined window not prepared (capture_all)"; return false; } + if (pre_launch_ && !pre_launch_(cs_, err)) return false; const Clock::time_point t0 = Clock::now(); last_batch_ = false; bool staged = pl_prestaged_ && last_t_ == T && last_pos0_ == pos0; diff --git a/src/kernels/cuda/verify_kernels.cu b/src/kernels/cuda/verify_kernels.cu index 0928c731..854f375f 100644 --- a/src/kernels/cuda/verify_kernels.cu +++ b/src/kernels/cuda/verify_kernels.cu @@ -598,6 +598,10 @@ __global__ void fetch_blobs_kernel(const unsigned long long* __restrict__ src, c } } +__global__ void res_patch_kernel(int32_t* __restrict__ table, const volatile int32_t* pairs, int n) { + for (int k = blockIdx.x * blockDim.x + threadIdx.x; k < n; k += gridDim.x * blockDim.x) table[pairs[2 * k]] = pairs[2 * k + 1]; +} + __global__ void rebase_ptrs_kernel(unsigned long long* ptr, const int32_t* n, unsigned long long base, long long bytes) { const int k = threadIdx.x; if (k < *n) ptr[k] = base + (unsigned long long) k * (unsigned long long) bytes; @@ -693,6 +697,12 @@ void fetch_blobs(const unsigned long long* src, const int32_t* n, uint8_t* dst, check("fetch_blobs"); } +void res_patch(int32_t* table, const int32_t* pairs, int n, void* stream) { + if (n <= 0) return; + res_patch_kernel<<<(n + 255) / 256 < 64 ? (n + 255) / 256 : 64, 256, 0, (cudaStream_t) stream>>>(table, pairs, n); + check("res_patch"); +} + void rebase_ptrs(unsigned long long* ptr, const int32_t* n, uint8_t* base, int64_t blob_bytes, void* stream) { rebase_ptrs_kernel<<<1, 128, 0, (cudaStream_t) stream>>>(ptr, n, (unsigned long long) base, (long long) blob_bytes); check("rebase_ptrs"); @@ -1208,6 +1218,15 @@ __global__ void handoff_publish_kernel(float* dst, const float* __restrict__ a, } } } + +// wait_flag_ge, with the GPU's clock as it arrives (t_in) and as it leaves (t_out), either may be null +__global__ void wait_flag_ge_stamped_kernel(const volatile uint32_t* flag, uint32_t value, volatile unsigned long long* t_in, + volatile unsigned long long* t_out) { + if (t_in != nullptr) *t_in = strata_now_ns(); + while (*flag < value) strata_spin_pause(); + __threadfence_system(); + if (t_out != nullptr) *t_out = strata_now_ns(); +} } // namespace void wait_handoff(const uint32_t* flag, uint32_t value, uint32_t* err, unsigned long long timeout_ns, void* stream) { @@ -1470,6 +1489,12 @@ void wait_flag_ge(const uint32_t* flag, uint32_t value, void* stream) { check("wait_flag_ge"); } +void wait_flag_ge_stamped(const uint32_t* flag, uint32_t value, unsigned long long* t_in, unsigned long long* t_out, + void* stream) { + wait_flag_ge_stamped_kernel<<<1, 1, 0, (cudaStream_t) stream>>>(flag, value, t_in, t_out); + check("wait_flag_ge_stamped"); +} + void embedding_gather_dev(const uint8_t* codes, const float* scales, const float* offsets, const int32_t* tokens, int n_tok, int64_t n, int code_bits, int code_bias, int group_elems, uint64_t row_codes, uint64_t row_groups, float* out, void* stream) { diff --git a/src/program/generate.cpp b/src/program/generate.cpp index 2c7f9492..a183866f 100644 --- a/src/program/generate.cpp +++ b/src/program/generate.cpp @@ -372,7 +372,7 @@ bool resident_stage_swaps(strata::core::FileExpertSource& src, const std::vector if (slot < 0) continue; const SwapHome home = locate(s.layer); const strata::core::OnDevice on(home.dev); - if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q), home.cache->device_slot(slot), + if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(q, s.layer), home.cache->device_slot(slot), (size_t) strata::kernels::cpu::expert_layout().blob_bytes(s.layer), cudaMemcpyDeviceToHost, home.stream); e != cudaSuccess) { std::fprintf(stderr, "strata: copy back of layer %d slot %d (device %d) failed: %s\n", (int) s.layer, @@ -1504,6 +1504,67 @@ bool adapt_overlap() { return v; } +/// ExpertDispatch::evict_sync where the tier does not wait for its copies; STRATA_ADAPT_EVICT_SYNC=0 turns it off. +bool adapt_evict_sync() { + static const bool v = [] { const char* e = std::getenv("STRATA_ADAPT_EVICT_SYNC"); return e == nullptr || std::atoi(e) != 0; }(); + return v; +} + +/// STRATA_ADAPT_CHECKRES=1: before a verify window, the device's residency table read back into `back` and +/// compared with the host's (the pool's plan); the mismatched entries, the first ones reported. +int64_t res_check(const int32_t* d_res, const std::vector& host_res, std::vector& back, + int64_t n_expert, int64_t window) { + if (cudaMemcpy(back.data(), d_res, host_res.size() * sizeof(int32_t), cudaMemcpyDeviceToHost) != cudaSuccess) { + std::fprintf(stderr, "strata: res check: the read-back failed: %s\n", cudaGetErrorString(cudaGetLastError())); + return 0; + } + static int printed = 0; + int64_t bad = 0; + for (size_t i = 0; i < host_res.size(); ++i) + if (back[i] != host_res[i]) { + ++bad; + if (printed < 20) { + ++printed; + std::fprintf(stderr, "strata: res check: window %lld layer %lld expert %lld: host %d, device %d\n", + (long long) window, (long long) (i / (size_t) n_expert), (long long) (i % (size_t) n_expert), + (int) host_res[i], (int) back[i]); + } + } + return bad; +} + +/// The pre-launch hook's patch: the changed entries of the host's residency table (`idx`) as (index, entry) pairs into +/// the mapped `pairs` (room for `cap`); their count, or -1 when they do not fit (then the whole table goes up). +int64_t res_patch_pairs(const std::vector& idx, const std::vector& host_res, int32_t* pairs, size_t cap) { + if (pairs == nullptr || idx.size() > cap) return -1; + for (size_t k = 0; k < idx.size(); ++k) { + pairs[2 * k] = idx[k]; + pairs[2 * k + 1] = host_res[(size_t) idx[k]]; + } + std::atomic_thread_fence(std::memory_order_seq_cst); + return (int64_t) idx.size(); +} + +/// Mapped host memory for res_patch_pairs (portable: every card of a layer split reads it), or null. The kernels read +/// it at the host's address: each of `devs` (-1: the current device) must map it there, else the whole table goes up. +int32_t* res_pairs_alloc(size_t cap, const std::vector& devs) { + void* p = nullptr; + if (cudaHostAlloc(&p, cap * 2 * sizeof(int32_t), cudaHostAllocMapped | cudaHostAllocPortable) != cudaSuccess) { + (void) cudaGetLastError(); + return nullptr; + } + for (int dev : devs) { + const strata::core::OnDevice on(dev); + void* d = nullptr; + if (cudaHostGetDevicePointer(&d, p, 0) != cudaSuccess || d != p) { + (void) cudaGetLastError(); + cudaFreeHost(p); + return nullptr; + } + } + return (int32_t*) p; +} + /// --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 { @@ -3220,6 +3281,14 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata generate: PCIe probe failed -> pcie_frac default %.2f\n", base); } } + // STRATA_PCIE_BALANCE=1 (opt-in): each verify layer's PCIe count from measured costs (Verifier::set_pcie_balance) + // instead of the probe's fixed share above - the CPU's speed sets the right share as much as the link's. IQ2_XS, + // one AVX2 pool worker (emulated on an RTX 5090 + 9950X3D): 16.8-17.2 -> 12.8-13.0 ms a round; the 9950X3D's own + // 16 workers: 12.2 either way. One GPU, no batch slots, no --pcie-frac. + auto pcie_balance = [&]() { + const char* e = std::getenv("STRATA_PCIE_BALANCE"); + return !pcie_given && native_pack && !multi_gpu && o.batch <= 0 && e != nullptr && std::strcmp(e, "1") == 0; + }; // the canonical Q2_0 pack's CPU kernels are AVX-512 only; a native pack runs on AVX2 CPUs as well if (!native_pack) { // #2347: an NVFP4 / i-quant / Unsloth pack IS a native pack and runs on an AVX2 CPU (its rows have AVX2 @@ -7578,18 +7647,23 @@ int main(int argc, char** argv) { // #669 / #765: a big chunk lends many cache slots to the prompt path, and each lent slot's expert is read back // from the SSD whenever the RAM could not keep its copy (31 GB: auto:32768 read prompts ~3x slower than auto). // Said, never capped: --prefill is the user's, and with the RAM for them it is the faster one (+21-35%). - if (resident_ok && lend_from >= 0 && o.prefill_chunk > 8192 && xcache.slots() > lend_from && + // #1683: with a RAM budget the lend region is kept after the ranked experts, as far as the budget reaches, so + // the advice there is a larger budget, not a smaller chunk (the budget used to keep none of it whatever the chunk) + if (resident_ok && lend_from >= 0 && (o.prefill_chunk > 8192 || o.resident_budget > 0) && xcache.slots() > lend_from && src.resident_lent_slots() < xcache.slots() - lend_from) std::fprintf(stderr, "strata generate: WARNING: a prompt chunk of %lld tokens lends %lld cache slots to the " "prompt path, but only %lld of their experts fit in RAM: the others are read from the " "SSD on every chunk, and prompts can read ~3x slower than with --prefill auto (#669). " - "A smaller --prefill, or auto, keeps them all in RAM\n", + "%s keeps them all in RAM\n", (long long) o.prefill_chunk, (long long) (xcache.slots() - lend_from), - (long long) src.resident_lent_slots()); + (long long) src.resident_lent_slots(), + o.resident_budget > 0 ? "A larger --resident-budget-gib (the lend region comes after the ranked experts), or a smaller --prefill," + : "A smaller --prefill, or auto,"); 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)) + if (o.adapt_async && !src.reserve_exchanges(2 * std::min(o.adapt_swaps, 96), err, + std::min(o.adapt_swaps, 96))) 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 @@ -8433,6 +8507,7 @@ int main(int argc, char** argv) { for (int st = 0; st + 1 < n_stages; ++st) stage_ver_p(st, 1).set_next(&stage_ver_p(st + 1, 1), &split_drive_b); } ver.set_remote_expert_opt(remote_opt.get()); + if (pcie_balance() && n_stages == 1) ver.set_pcie_balance(&drive.d.pcie_model); 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() || prefill_head_alias_bound ? &native_head : nullptr, batch_mtp ? strata::kernels::kVerifyMaxT : std::max(o.spec, std::min(o.batch, (int) strata::kernels::kVerifyMaxT)), err) || @@ -9404,13 +9479,14 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: adaptive overlap: off%s%s\n", aov_why ? ": " : " (STRATA_ADAPT_OVERLAP=1 turns it on)", aov_why ? aov_why : ""); // a layer split's later stages keep a copy of the residency table on their devices, and swap on their own - auto res_upload = [&]() { - if (d_res != nullptr) - res_put(d_res); + auto res_upload = [&]() -> cudaError_t { // the first error, every table tried + cudaError_t r = d_res != nullptr ? res_put(d_res) : cudaSuccess; for (auto& st : stages) { const strata::core::OnDevice on(st->dev); - res_put(st->d_res); + const cudaError_t e = res_put(st->d_res); + if (r == cudaSuccess) r = e; } + return r; }; auto apply_pending = [&](bool wait) { if (peer.valid()) peer.apply_pending(wait); @@ -9429,12 +9505,118 @@ int main(int argc, char** argv) { host_res[(size_t) i] = slot; srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed } + if (drive.d.evict_sync) { // a failed upload leaves them to the pre-launch hook + for (const auto& pr : pending) drive.d.res_dirty_idx.push_back(pr.first); + drive.d.res_dirty = true; + } pending.clear(); pending_age = 0; agate.active.store(false, std::memory_order_release); // 0.1.43: the copies have landed (STRATA_ADAPT_OVERLAP) aflipped = false; - res_upload(); + if (res_upload() == cudaSuccess) { // the whole table: the hook has nothing left + drive.d.res_dirty = false; + drive.d.res_dirty_idx.clear(); + } }; + // Where the tier does not wait for its copies (STRATA_ADAPT_NOWAIT=1, STRATA_ADAPT_LAG > 1), its evictions reach + // the device's tables before the next window: adapt() marks them non-resident at once, apply_pending uploads + // only when the round's copies land - a window or more later, and until then doorbell_publish_res skips the + // activation of a layer whose routed experts all look resident, while the pool computes an evicted one from the + // activation published before. The hook runs at each verifier's launch; the serial windows (one at a time, + // the batch windows included, a layer split's stages one after another) take it. + // --batch-groups with a layer split launches a group while another is in flight on the other stage, which + // waits on this thread: a synchronous upload there could wait on that window, so those verifiers publish + // every activation instead (set_always_publish; the device table then decides nothing a stale entry breaks). + // --pipeline-windows is exempt: its verifiers always publish, and the tier fences the windows in flight + // before it overwrites a slot (adapt_fence). --adapt-async uploads at each of its steps. + // STRATA_ADAPT_CHECKRES=1 reads the tables back at each launch and compares them with the host's. + const bool piped_groups = o.batch > 0 && o.batch_groups > 1 && !stages.empty(); + const bool serial_windows = !pipe && !piped_groups; + const bool tier_lags = !drive.d.usage.empty() && (adapt_nowait() || adapt_lag() > 1); + drive.d.evict_sync = serial_windows && tier_lags && adapt_evict_sync(); + if (piped_groups && tier_lags && adapt_evict_sync()) { + ver.set_always_publish(true); + for (auto& st : stages) st->ver.set_always_publish(true); + } + const bool res_checking = std::getenv("STRATA_ADAPT_CHECKRES") != nullptr && serial_windows; + std::vector res_back; + int64_t res_windows = 0, res_bad = 0, res_bad_windows = 0; + if (res_checking) { + res_back.assign(host_res.size(), 0); + drive.d.dres_check = res_back.data(); + } + // The changed entries go up by a kernel on each card's verifier stream, reading them from mapped memory: a + // synchronous upload waits for the copy engine, which the tier's swaps of the round before still hold (~4 ms + // on 33 swaps; measured +0.9 ms a chat round). Too many changes, or no mapped memory: the whole table. + constexpr size_t kResPatchCap = 16384; + std::vector res_devs{-1}; + for (auto& st : stages) res_devs.push_back(st->dev); + int32_t* res_pairs = drive.d.evict_sync ? res_pairs_alloc(kResPatchCap, res_devs) : nullptr; + auto res_sync = [&](bool check, std::string& e) -> bool { + if (drive.d.res_dirty) { + const int64_t n = res_patch_pairs(drive.d.res_dirty_idx, host_res, res_pairs, kResPatchCap); + cudaError_t r = cudaSuccess; + if (n >= 0) { + if (d_res != nullptr) { + strata::kernels::res_patch(d_res, res_pairs, (int) n, ver.stream()); + r = cudaGetLastError(); + } + for (size_t k = 0; k < stages.size() && r == cudaSuccess; ++k) { + const strata::core::OnDevice on(stages[k]->dev); + strata::kernels::res_patch(stages[k]->d_res, res_pairs, (int) n, stages[k]->ver.stream()); + r = cudaGetLastError(); + } + } else { + r = res_upload(); + } + if (r != cudaSuccess) { + e = std::string("the residency table update failed: ") + cudaGetErrorString(r); + return false; + } + drive.d.res_dirty = false; + drive.d.res_dirty_idx.clear(); + } + if (!check) return true; + cudaStreamSynchronize(ver.stream()); // the patches landed (the verifier streams do not block the read) + for (auto& st : stages) { + const strata::core::OnDevice on(st->dev); + cudaStreamSynchronize(st->ver.stream()); + } + int64_t bad = 0; + for (auto& st : stages) { // the later stages' copies first: res_back ends with CUDA0's (the pool's check) + const strata::core::OnDevice on(st->dev); + bad += res_check(st->d_res, host_res, res_back, g.n_expert, res_windows); + } + bad += res_check(d_res, host_res, res_back, g.n_expert, res_windows); + ++res_windows; + res_bad += bad; + res_bad_windows += bad > 0; + if ((res_windows & 255) == 0 || (bad > 0 && res_bad_windows <= 4)) + std::fprintf(stderr, "strata serve: res check: %lld windows, %lld with mismatches (%lld entries), " + "%lld layer-windows with CPU experts and no activation published\n", + (long long) res_windows, (long long) res_bad_windows, (long long) res_bad, + (long long) drive.d.stale_x); + return true; + }; + struct PreLaunchOff { // the hooks' captures die before the verifiers + strata::core::Verifier& v; + std::vector>& stages; + strata::core::ExpertDispatch& d; + int32_t* pairs; + ~PreLaunchOff() { + v.set_pre_launch(nullptr); + for (auto& st : stages) st->ver.set_pre_launch(nullptr); + d.dres_check = nullptr; + if (pairs != nullptr) cudaFreeHost(pairs); + } + } pre_launch_off{ver, stages, drive.d, res_pairs}; + if (drive.d.evict_sync || res_checking) { + ver.set_pre_launch([&](cudaStream_t, std::string& e) { return res_sync(res_checking, e); }); + for (auto& st : stages) st->ver.set_pre_launch([&](cudaStream_t, std::string& e) { return res_sync(false, e); }); + if (drive.d.evict_sync) + std::fprintf(stderr, "strata serve: the adaptive tier's evictions reach the device's table before the next " + "window (STRATA_ADAPT_EVICT_SYNC=0: when its copies land)\n"); + } // --pipeline-windows: set while the tier adapts beside windows in flight (see its use in adapt) std::function adapt_fence; int64_t adapt_nswaps = 0; // the blocking tier's swaps chosen, cumulative (the decode timing line's swaps/window) @@ -9563,6 +9745,10 @@ int main(int argc, char** argv) { agate.landed.store((int32_t) g.n_layers, std::memory_order_release); } } + if (drive.d.evict_sync && !swaps.empty()) { // the evicted ones are misses now (see the pre-launch hook) + for (const Swap& s : swaps) drive.d.res_dirty_idx.push_back((int32_t) (s.layer * g.n_expert + s.out)); + drive.d.res_dirty = true; + } if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), adapt_stream, dma_mode) != cudaSuccess) { std::fprintf(stderr, "strata serve: adaptive swap copy failed (batched): %s\n", @@ -9744,7 +9930,7 @@ int main(int argc, char** argv) { const strata::core::OnDevice on(h.dev); for (const ASwap& w : aswaps) { if (w.home != hi || !w.exchange) continue; - if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j), h.cache->device_slot(w.slot), + if (const cudaError_t e = cudaMemcpyAsync(src.exchange_buffer(w.j, w.layer), 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", @@ -9974,8 +10160,9 @@ int main(int argc, char** argv) { for (size_t hi = 0; hi < ahomes.size(); ++hi) if (a_ram_due[hi] && a_gap_seq[hi] <= a_ram_mark[hi]) return true; std::fill(a_ram_due.begin(), a_ram_due.end(), (uint8_t) 0); - ajob->post([&] { src.commit_copies(); }); astate = AState::Commit; + if (src.exchange_rotation()) continue; // STRATA_EXCHANGE_ROTATE: no bytes move, the flip is all there is + ajob->post([&] { src.commit_copies(); }); if (!drain) return true; continue; case AState::Commit: // step 4 @@ -11394,6 +11581,7 @@ int main(int argc, char** argv) { // in prompt order. With them the conversation cache matches a picture by its key and grid, not by its // embedding floats, so a picture encoded again with other bits still matches. Absent: the embeddings' hash. std::vector req_img_keys; + bool req_pcie_set = false; // the request names its own share (the measured one holds meanwhile) if (endp != nullptr) { // GENI takes the same keys (#75: image requests were always greedy); its // embedding file path is the first token without an = for (;;) { @@ -11419,7 +11607,7 @@ int main(int argc, char** argv) { else if (key == "penalty_freq") req_penalty_freq = fv; else if (key == "penalty_present") req_penalty_present = fv; else if (key == "seed") req_seed = std::strtoull(tok.c_str() + eq + 1, nullptr, 10); - else if (key == "pcie_frac") req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); + else if (key == "pcie_frac") { req_pcie_frac = std::clamp((double) fv, 0.0, 1.0); req_pcie_set = true; } else if (key == "spec_min_p") req_spec_min_p = std::clamp((double) fv, 0.0, 1.0); else if (key == "pipe") req_pipe = std::max(0.0, (double) fv); else if (key == "aux_cpus") req_aux_cpus = std::atoi(tok.c_str() + eq + 1) != 0 ? 1 : 0; @@ -13009,6 +13197,7 @@ int main(int argc, char** argv) { std::fprintf(stderr, "strata serve: aux cpus %s for this request%s\n", strata::aux_cpus::enabled() ? "ON" : "off", want && !strata::aux_cpus::enabled() ? " (asked for, but no CPU is spare: see the start-up line)" : ""); } + ver.pause_pcie_balance(req_pcie_set); // the measured costs keep across requests 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) @@ -13993,6 +14182,40 @@ int main(int argc, char** argv) { } } else if (pending.empty() || ++pending_age >= adapt_lag()) apply_pending(true); + // STRATA_RAM_ADAPT= (opt-in, the resident RAM mode on one GPU): the RAM copy is chosen once, at + // start, so an expert it does not hold is read from the file every time the conversation routes to + // it. With this, before a window and while no adaptive round is in flight, up to n experts the windows + // keep routing to (the adaptive tier's decayed count, at least its own candidate floor of 2) take the + // RAM places of experts of their layer that are not routed to (count below 0.5), one pair per layer, + // the largest difference first. One blob read each, on this thread; the RAM stays the same size, and + // the routing, the weights and the VRAM tier's own rule are untouched. + static const int ram_adapt_n = [] { + const char* e = std::getenv("STRATA_RAM_ADAPT"); + return e != nullptr ? std::max(0, std::atoi(e)) : 0; + }(); + if (ram_adapt_n > 0 && !first_window && !drive.d.usage.empty() && pending.empty() && + (!ajob || astate == AState::Idle) && src.complement_ready() && !multi_gpu && !peer.valid() && + !remote_opt && o.batch == 0) { + constexpr float kRamAdaptRouted = 2.0f, kRamAdaptUnused = 0.5f; + struct RamSwap { float gain; int32_t layer, in, out; }; + std::vector swaps; + for (int64_t l = 0; l < g.n_layers; ++l) { + const float* u = drive.d.usage.data() + l * g.n_expert; + const int32_t* r = host_res.data() + l * g.n_expert; + int32_t in = -1, out = -1; + for (int32_t e = 0; e < (int32_t) g.n_expert; ++e) { + if (r[e] >= 0) continue; // in VRAM: the RAM copy does not hold it + if (src.has_resident(l, e)) { if (out < 0 || u[e] < u[out]) out = e; } + else if (u[e] >= kRamAdaptRouted && (in < 0 || u[e] > u[in])) in = e; + } + if (in >= 0 && out >= 0 && u[out] < kRamAdaptUnused) + swaps.push_back({u[in] - u[out], (int32_t) l, in, out}); + } + std::sort(swaps.begin(), swaps.end(), + [](const RamSwap& a, const RamSwap& b) { return a.gain > b.gain; }); + if ((int) swaps.size() > ram_adapt_n) swaps.resize((size_t) ram_adapt_n); + for (const RamSwap& x : swaps) src.replace_resident(x.layer, x.in, x.out); + } 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; @@ -14457,6 +14680,9 @@ 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 (src.ram_adapts() > 0) // STRATA_RAM_ADAPT, cumulative + std::fprintf(stderr, "strata serve: resident RAM: %lld experts moved in from the file in place of " + "unused ones (STRATA_RAM_ADAPT)\n", (long long) src.ram_adapts()); 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)", @@ -14981,6 +15207,7 @@ int main(int argc, char** argv) { vh.blob = thits.blob; vh.slot_off = xcache.slot_offsets(); // E-6: the device plan's pointers vh.n_slots = xcache.slots(); + if (pcie_balance()) ver.set_pcie_balance(&drive.d.pcie_model); if (!ver.init(wt, g, ss, vh, native_head.loaded() ? &native_head : nullptr, o.spec, err)) { std::fprintf(stderr, "strata generate: %s\n", err.c_str()); return 1; @@ -15009,6 +15236,57 @@ int main(int argc, char** argv) { const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes(); const double fms0 = src.file_ms(); if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f); + // before every window: the device's table follows the host's (the tier's evictions while its copies are in + // flight - see the serve path); the hook's captures live in this block, so it is taken off the verifier when the + // block ends + const bool res_checking = std::getenv("STRATA_ADAPT_CHECKRES") != nullptr && d_res != nullptr; + std::vector res_back; + int64_t res_windows = 0, res_bad = 0, res_bad_windows = 0; + if (res_checking) { + res_back.assign(host_res.size(), 0); + drive.d.dres_check = res_back.data(); + } + drive.d.evict_sync = d_res != nullptr && !drive.d.usage.empty() && (adapt_nowait() || adapt_lag() > 1) && + adapt_evict_sync(); + // the changed entries by a kernel on the verifier's stream (see the serve path) + constexpr size_t kResPatchCap = 16384; + int32_t* res_pairs = drive.d.evict_sync ? res_pairs_alloc(kResPatchCap, {-1}) : nullptr; + struct PreLaunchOff { + strata::core::Verifier& v; + strata::core::ExpertDispatch& d; + int32_t* pairs; + ~PreLaunchOff() { + v.set_pre_launch(nullptr); + d.dres_check = nullptr; + if (pairs != nullptr) cudaFreeHost(pairs); + } + } pre_launch_off{ver, drive.d, res_pairs}; + if (drive.d.evict_sync || res_checking) + ver.set_pre_launch([&](cudaStream_t cs, std::string& e) -> bool { + if (drive.d.res_dirty) { + const int64_t n = res_patch_pairs(drive.d.res_dirty_idx, host_res, res_pairs, kResPatchCap); + cudaError_t r; + if (n >= 0) { + strata::kernels::res_patch(d_res, res_pairs, (int) n, cs); + r = cudaGetLastError(); + } else { + r = res_put(d_res); + } + if (r != cudaSuccess) { + e = std::string("the residency table update failed: ") + cudaGetErrorString(r); + return false; + } + drive.d.res_dirty = false; + drive.d.res_dirty_idx.clear(); + } + if (!res_checking) return true; + cudaStreamSynchronize(cs); // the patch landed + const int64_t bad = res_check(d_res, host_res, res_back, g.n_expert, res_windows); + ++res_windows; + res_bad += bad; + res_bad_windows += bad > 0; + return true; + }); int64_t swaps_total = 0; double ms_adapt = 0; cudaStream_t adapt_stream = nullptr; @@ -15042,10 +15320,16 @@ int main(int argc, char** argv) { host_res[(size_t) i] = slot; srcp->release((int64_t) i / g.n_expert, (int64_t) i % g.n_expert); // in VRAM now: RAM not needed } + if (drive.d.evict_sync) { // a failed upload leaves them to the pre-launch hook + for (const auto& pr : pending) drive.d.res_dirty_idx.push_back(pr.first); + drive.d.res_dirty = true; + } pending.clear(); pending_age = 0; - if (d_res != nullptr) - res_put(d_res); + if (d_res != nullptr && res_put(d_res) == cudaSuccess) { // the whole table: the hook has nothing left + drive.d.res_dirty = false; + drive.d.res_dirty_idx.clear(); + } }; // Plan v0.3 P6: the VRAM tier follows the conversation. Candidates are missing experts routed at least // twice (decayed); each is paired with its layer's least-routed resident expert and swapped when it was @@ -15129,6 +15413,10 @@ int main(int argc, char** argv) { srcp->prefetch(s.layer, s.out); // a file-backed arena released its pages: read them back ahead pending.emplace_back((int32_t) in, slot); // resident once the copy has landed } + if (drive.d.evict_sync && !swaps.empty()) { // the evicted ones are misses now (see the pre-launch hook) + for (const Swap& s : swaps) drive.d.res_dirty_idx.push_back((int32_t) (s.layer * g.n_expert + s.out)); + drive.d.res_dirty = true; + } if (!cp_dst.empty() && strata::core::copy_blobs(cp_dst.data(), cp_src.data(), cp_bytes.data(), cp_dst.size(), adapt_stream, dma_mode) != cudaSuccess) { std::fprintf(stderr, "strata generate: an adaptive refill failed\n"); @@ -15389,6 +15677,10 @@ int main(int argc, char** argv) { if (rounds > 0 && !drive.d.usage.empty()) std::printf("%-24s %lld experts swapped into the VRAM tier (every %d rounds, %.3f ms/round)\n", "adaptive tier", (long long) swaps_total, o.adapt_every, ms_adapt / rounds); + if (res_checking) + std::printf("%-24s %lld windows, %lld with mismatches (%lld entries), %lld layer-windows with CPU experts and " + "no activation published\n", "residency check", (long long) res_windows, + (long long) res_bad_windows, (long long) res_bad, (long long) drive.d.stale_x); if (src.complement_ready()) std::printf("%-24s %.2f GiB of experts in RAM, %lld exchanged with the VRAM tier, %lld blob reads from " "the file\n", "resident RAM", (double) src.resident_bytes() / 1073741824.0, @@ -15425,6 +15717,12 @@ int main(int argc, char** argv) { std::printf("%-24s %.2f distinct experts per layer read over PCIe (share %d/256 of the misses)\n", "pcie experts", (double) (drive.d.pcie_experts - pcie0) / (double) (rounds * g.n_layers), drive.d.pcie_num); + if (rounds > 0 && ver.pcie_balance_on()) { + const strata::core::PcieModel& pm = drive.d.pcie_model; + std::printf("%-24s CPU %.0f us + %.0f an expert + %.0f a PCIe one, GPU %.0f us + %.0f a PCIe expert (the " + "PCIe count per layer from these)\n", "pcie model", 1000 * pm.a, 1000 * pm.c, 1000 * pm.d, + 1000 * pm.g0, 1000 * pm.g); + } (void) pool_ms0; if (use_mtp && rounds > 0) std::printf("%-24s %.3f ms/round drafting (%lld rounds), MTP prompt %.1f ms, %.0f MiB of VRAM\n", "mtp", diff --git a/tests/core/exchange_storage_test.cpp b/tests/core/exchange_storage_test.cpp index b790b4f2..019a3380 100644 --- a/tests/core/exchange_storage_test.cpp +++ b/tests/core/exchange_storage_test.cpp @@ -110,6 +110,101 @@ void exercise(size_t bytes, size_t rounds) { !storage.exchanges() && !storage.avoided_bytes(), "clear retained state"); } +// Layers of different block sizes: the spares are kept per size, and a swap (two experts of one layer) hands back a +// buffer of the size it took. +void exercise_sized(size_t rounds) { + const size_t layer_bytes[3] = {33, 4097, 64}; + constexpr size_t per_layer = 10, resident_per_layer = 6, n = 3 * per_layer, count = 4, bounce = 1, guard = 19; + std::vector sizes(n), offsets(n, absent); + uint64_t resident_bytes = 0; + for (size_t i = 0; i < n; ++i) { + sizes[i] = layer_bytes[i / per_layer]; + if (i % per_layer < resident_per_layer) { offsets[i] = resident_bytes; resident_bytes += sizes[i]; } + } + const uint64_t need = ExchangeStorage::exchange_bytes_needed(sizes, count, bounce); + require(need == (count - bounce) * (33 + 64 + 4097) + bounce * 4097, "wrong exchange allocation size"); + std::vector arena(guard + resident_bytes + guard, 0xcd), spare(guard + need + guard, 0xef); + std::vector aliases(resident_bytes), spare_aliases(need); + std::vector> reference(n); + std::mt19937 random(603); + for (size_t i = 0; i < n; ++i) { + reference[i].resize(sizes[i]); + for (auto& v : reference[i]) v = (uint8_t)random(); + if (offsets[i] != absent) std::memcpy(arena.data() + guard + offsets[i], reference[i].data(), sizes[i]); + } + ExchangeStorage storage; + std::string error; + require(!storage.initialize_sized(offsets, sizes, arena.data() + guard, aliases.data(), resident_bytes, + spare.data() + guard, spare_aliases.data(), need - 1, count, bounce, error), "short exchange allocation accepted"); + require(storage.initialize_sized(offsets, sizes, arena.data() + guard, aliases.data(), resident_bytes, + spare.data() + guard, spare_aliases.data(), need, count, bounce, error), error.c_str()); + require(storage.block_sizes() == 3, "wrong number of block sizes"); + // the bounce ordinal exists in the largest size only; the others in every size + require(storage.spare(count - 1, 4097).host && !storage.spare(count - 1, 33).host && !storage.spare(count - 1, 64).host, + "bounce buffers of a smaller size"); + require(storage.spare(count - 1).host == storage.spare(count - 1, 4097).host, "the size-less spare is not the largest"); + require(!storage.spare(0, 34).host && !storage.spare(count, 33).host, "a spare of no size or ordinal"); + std::set original; + for (size_t i = 0; i < n; ++i) if (auto q = storage.resident(i).host) original.insert(q); + for (size_t c = 0; c < 3; ++c) + for (size_t q = 0; q < count; ++q) if (auto b = storage.spare(q, layer_bytes[c]).host) original.insert(b); + uint64_t exchanges = 0, bytes_moved = 0; + for (size_t round = 0; round < rounds; ++round) { + size_t used[3] = {0, 0, 0}; // the ordinal is the swap's number in the round, whatever its layer + size_t ordinal = 0; + std::vector order = {0, 1, 2, 0, 1, 2}; + std::shuffle(order.begin(), order.end(), random); + for (const size_t layer : order) { + if (ordinal >= count - bounce) break; + const size_t bytes = layer_bytes[layer], q = ordinal++; + std::vector ins, outs; + for (size_t i = layer * per_layer; i < (layer + 1) * per_layer; ++i) (storage.resident(i).host ? ins : outs).push_back(i); + std::shuffle(ins.begin(), ins.end(), random); + std::shuffle(outs.begin(), outs.end(), random); + const size_t in = ins[0], out = outs[0]; + const ExchangeStorage::View before = storage.resident(in), staged = storage.spare(q, bytes); + require(staged.host != nullptr, "no spare of the layer's size"); + std::memcpy(staged.host, reference[out].data(), bytes); + const size_t other = layer_bytes[(layer + 1) % 3]; + require(!storage.commit(in, out, q, staged.host, other), "another size's commit accepted"); + size_t stranger = ((layer + 1) % 3) * per_layer; // an expert of another layer that RAM does not hold + while (storage.resident(stranger).host) ++stranger; + require(!storage.commit(in, stranger, q, staged.host, bytes), "another layer's expert accepted"); + require(storage.commit(in, out, q, staged.host, bytes), "valid sized swap rejected"); + require(storage.resident(out).host == staged.host && storage.resident(out).device == staged.device, + "evicted buffer was not adopted with its alias"); + require(storage.spare(q, bytes).host == before.host && storage.spare(q, bytes).device == before.device, + "old RAM input was not recycled with its alias"); + ++used[layer]; ++exchanges; bytes_moved += bytes; + } + std::set live; + for (size_t i = 0; i < n; ++i) if (auto q = storage.resident(i).host) { + require(live.insert(q).second, "two experts share storage"); + require(!std::memcmp(q, reference[i].data(), sizes[i]), "resident bytes corrupted"); + } + for (size_t c = 0; c < 3; ++c) + for (size_t q = 0; q < count; ++q) if (auto b = storage.spare(q, layer_bytes[c]).host) + require(live.insert(b).second, "spare aliases live expert"); + require(live == original, "storage leaked or duplicated"); + for (size_t layer = 0; layer < 3; ++layer) { + size_t held = 0; + for (size_t i = layer * per_layer; i < (layer + 1) * per_layer; ++i) held += storage.resident(i).host != nullptr; + require(held == resident_per_layer, "a layer's resident count changed"); + } + } + require(storage.exchanges() == exchanges && storage.avoided_bytes() == bytes_moved, "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"); + // overlapping resident blocks are refused + std::vector bad = offsets; + bad[1] = offsets[0] + 1; + ExchangeStorage t; + require(!t.initialize_sized(bad, sizes, arena.data() + guard, aliases.data(), resident_bytes, + spare.data() + guard, spare_aliases.data(), need, count, bounce, error) && !t.active(), "overlapping blocks accepted"); +} + void invalid_geometry() { uint8_t h[64]{}, d[64]{}, x[64]{}, xd[64]{}; ExchangeStorage s; std::string e; @@ -128,6 +223,7 @@ int main() { 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"; + exercise_sized(2048); + std::cout << "exchange_storage_test: PASS (byte/alias/ownership checks, 12304 exchanges; several block sizes)\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 51a4ee1e..c4586c87 100644 --- a/tests/core/file_expert_source_test.cpp +++ b/tests/core/file_expert_source_test.cpp @@ -830,6 +830,84 @@ void test_foresight_exchange(bool two_phase) { src.close(); } +// STRATA_RAM_ADAPT: an expert read from the file takes the RAM place of another of its layer. +void test_replace_resident(bool pin) { + using namespace strata::core; + using namespace strata::kernels::cpu; +#if defined(_WIN32) + _putenv_s("STRATA_EXCHANGE_ROTATE", "0"); +#else + setenv("STRATA_EXCHANGE_ROTATE", "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}}; + // experts 2 and 3 are in VRAM, the RAM budget holds 0 and 1, expert 4 stays on the file tier + require(src.pin_cache_complement(cache, err, pin, {}, -1, 0, 2 * bytes, &rank), err); + require(src.reserve_exchanges(1, err), err); + require(src.has_resident(0, 0) && src.has_resident(0, 1) && !src.has_resident(0, 4), "fixture residency wrong"); + std::vector actual(bytes); + auto holds = [&](int e) { + const uint8_t* b = src.blob(0, e); + return b != nullptr && !std::memcmp(b, truth[(size_t)e].data(), bytes); + }; + require(!src.replace_resident(0, 1, 0), "an expert already in RAM accepted"); + require(!src.replace_resident(0, 4, 2), "a place the RAM does not hold accepted"); + require(!src.replace_resident(0, 4, 4) && !src.replace_resident(0, 5, 0) && !src.replace_resident(1, 4, 0), + "invalid arguments accepted"); + require(src.ram_adapts() == 0 && holds(0) && holds(1) && holds(4), "a refused call changed the copy"); + // a staged exchange owns the tables until it commits + require(cudaMemcpy(src.exchange_buffer(0), cache.device_slot(0), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, + "D2H eviction failed"); + require(src.stage_exchange(0, 0, 2, 0), "stage rejected"); + require(!src.replace_resident(0, 4, 1), "accepted beside a staged exchange"); + require(cache.fill_slot_blocking(0, truth[0].data(), err), err); + require(src.commit_exchanges() == 1, "commit count wrong"); // RAM: 2 (in 0's place) and 1; VRAM: 0 and 3 + const uint8_t* place = src.blob(0, 1); + require(src.replace_resident(0, 4, 1), "replace rejected"); + require(src.ram_adapts() == 1 && src.has_resident(0, 4) && !src.has_resident(0, 1), "residency wrong"); + require(src.blob(0, 4) == place && holds(4), "the incoming expert is not in the outgoing one's place"); + require(holds(1) && holds(2), "another expert's bytes changed"); + require(src.copy_blob(0, 1, actual.data()) && actual == truth[1], "the outgoing expert is not read from the file"); + require(!src.transient(0, 4), "resident became transient"); + if (pin) { + require(src.pinned(0, 4) && src.device_alias(0, 4), "mapping lost"); + require(cudaMemcpy(actual.data(), src.device_alias(0, 4), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, + "device alias read failed"); + require(actual == truth[4], "CUDA alias points at the old expert"); + } + // and back, then an exchange with the VRAM tier still works on the moved place + require(src.replace_resident(0, 1, 4) && holds(1) && src.blob(0, 1) == place && !src.has_resident(0, 4), + "replace back wrong"); + require(cudaMemcpy(src.exchange_buffer(0), cache.device_slot(1), bytes, cudaMemcpyDeviceToHost) == cudaSuccess, + "D2H eviction failed"); + require(src.stage_exchange(0, 1, 3, 0), "stage after replace rejected"); + require(cache.fill_slot_blocking(1, truth[1].data(), err), err); + require(src.commit_exchanges() == 1 && src.has_resident(0, 3) && holds(3) && !src.has_resident(0, 1), + "exchange after replace wrong"); + require(src.ram_adapts() == 2, "accounting wrong"); + std::cout << "replace_resident: pinned=" << pin << " exact_bytes=PASS\n"; +} + } // namespace int main(int argc, char** argv) { @@ -854,6 +932,8 @@ int main(int argc, char** argv) { test_rotating_source(true, false); test_foresight_exchange(false); test_foresight_exchange(true); + test_replace_resident(true); + test_replace_resident(false); } std::cout << "file_expert_source_test: PASS\n"; return 0;