From 7030c070f16541cd0f7abb50aaf2ef5b49570c9a Mon Sep 17 00:00:00 2001 From: Shogo Okada <33060490+okada-shogo@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:09:27 +0900 Subject: [PATCH 1/2] poly: Inkling 2's expert cache follows an answer with a half-life of 32 tokens follow() halves an expert's recent uses every kSwapHalf (128) tokens. A family hook, swap_half(), gives Inkling 2 32; every other family keeps kSwapHalf, so their paths do not change. STRATA_SWAP_HALF=N (1 to 65536) sets Inkling 2's, 128 being main's; a set value is logged at start and an invalid one is refused with a line. The 2x+2 rule for a trade is unchanged. The setting is in the settings register (opt-in) and docs/SETTINGS.md. Offline replay of routing traces (STRATA_ROUTE_TRACE, 18 answers: code, chat and prose after 2K-32K prompts, 512 tokens each, RTX 2070 8 GB), with a replica of follow() that matches the engine's hit counter within 0.2 points: IQ4_NL experts found in VRAM 80.7% -> 82.3% at 1.95 swaps a token (main 0.63); UD-Q2_K_XL 96.8% -> 97.2%. As before, the half-life counts evaluated rows (follow(written)), so with a drafter or batch slots a step of several rows decays several tokens' worth. Class: placement (which experts are in VRAM; routing unchanged). Same bits under STRATA_FREEZE_EXPERTS by construction: follow() returns before the decay and asks no trade. The decayed-count idea is merbanan's (Strata inkling2-turing, 0.95 a token). Co-Authored-By: Claude Opus 5.5 --- docs/SETTINGS.md | 3 ++- engine/src/poly/engine.cpp | 4 +++- engine/src/poly/engine.hpp | 4 +++- engine/src/poly/inkling2.cpp | 15 +++++++++++++ engine/src/poly/inkling2.hpp | 5 +++++ engine/src/poly/runtime.hpp | 3 ++- terminal/data/settings-register.json | 33 ++++++++++++++++++++++++++++ 7 files changed, 63 insertions(+), 4 deletions(-) diff --git a/docs/SETTINGS.md b/docs/SETTINGS.md index bb8fe28061..3152421fbe 100644 --- a/docs/SETTINGS.md +++ b/docs/SETTINGS.md @@ -11,7 +11,7 @@ A number or a word is set like any environment variable, for example `STRATA_KVA (`terminal/strata-.json`), which the server passes to the engine. The Strata project's Terminal writes it there with `strata launch --set NAME=value`. -## Switches you can turn on (347) +## Switches you can turn on (348) Off unless you set them. The last column says where each one is described. @@ -344,6 +344,7 @@ Off unless you set them. The last column says where each one is described. | `STRATA_STAGER_SSD` | on / off | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_STAGE_PIN` | number | NVIDIA and AMD | [DETAILS.md](DETAILS.md) | | `STRATA_STATE_HASH` | on / off | NVIDIA and AMD, Intel Arc | [SPLIT_SERVE.md](SPLIT_SERVE.md) | +| `STRATA_SWAP_HALF` | number | NVIDIA and AMD | - | | `STRATA_SYCL_BMG_EXPERT_WINDOW` | on / off | Intel Arc | [INTEL.md](INTEL.md) | | `STRATA_SYCL_GEMM_STAGE` | on / off | Intel Arc | [INTEL.md](INTEL.md) | | `STRATA_TEST_BELL_SLEEP_US` | number | NVIDIA and AMD | [BATCHING.md](BATCHING.md) | diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 35005b37ed..730fd0e9ab 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -3012,6 +3012,8 @@ void Engine::follow_loop() { } } +int Engine::swap_half() const { return kSwapHalf; } + // The cache follows what is written. Called at the start of an eval, where nothing queued reads the cache, with // the number of tokens the eval writes (0 for a prompt batch). The experts whose upload has arrived get their // slots. Then, for written tokens, the experts used lately that the cache lacks start on their way, each to the @@ -3091,7 +3093,7 @@ void Engine::follow(int written) { n_free += s.at.load() == Swap::kFree; } if (written <= 0) return; - const float keep = std::exp2(-(float) written / (float) kSwapHalf); + const float keep = std::exp2(-(float) written / (float) swap_half()); for (float& r : recent_) r *= keep; const auto from_pool = [&](Swap& s) { // the slot follow_loop() copies s from, held until s arrives s.from = -1; diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index ab0e274541..1370a13c17 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -543,6 +543,8 @@ class Engine { /// A token's experts outside VRAM may go to the host's threads through the doorbell (h_bell_): the architecture /// routes on the card (route_card()) and sums a token's experts in moe_card() when moe_sum_later() is false. virtual bool bells() const { return false; } + /// follow(): the tokens over which an expert's recent uses halve (kSwapHalf for every family but Inkling 2). + virtual int swap_half() const; /// What save_layer() writes of layer il that its run under way changes: all of it where a layer runs once a token. virtual void save_run(int il, int64_t pos, uint8_t* dst) { save_layer(il, pos, dst); } /// Optional host hook called before layer_head (including when layer_head is graph-replayed). @@ -1371,7 +1373,7 @@ class Engine { std::condition_variable swap_cv_; bool swap_quit_ = false; std::string swap_error_; ///< why the thread stopped; follow() throws it - std::vector recent_; ///< per (layer, expert): its uses by written tokens, halved every kSwapHalf + std::vector recent_; ///< per (layer, expert): its uses by written tokens, halved every swap_half() std::vector coming_; ///< per (layer, expert): on its way into the cache std::vector in_, out_; ///< per trade number: the experts to bring in, and the ones to give up std::vector trade_at_; ///< per trade number: how many of its pairs follow() has taken diff --git a/engine/src/poly/inkling2.cpp b/engine/src/poly/inkling2.cpp index c20d374044..d0b6291df5 100644 --- a/engine/src/poly/inkling2.cpp +++ b/engine/src/poly/inkling2.cpp @@ -1622,6 +1622,21 @@ void Inkling2::tail_rows(int il, int n) { axpy(fc_, 1.f, r_, n * n_embd_, true, st_); } +int Inkling2::swap_half() const { + static const int half = [] { + const char* v = std::getenv("STRATA_SWAP_HALF"); + if (!v || !v[0]) return 32; + const int n = std::atoi(v); + if (n < 1 || n > 65536) { + std::fprintf(stderr, "strata-poly: STRATA_SWAP_HALF=%s is not 1 to 65536 tokens: the default, 32\n", v); + return 32; + } + std::fprintf(stderr, "strata-poly: the expert cache's uses halve every %d tokens (STRATA_SWAP_HALF)\n", n); + return n; + }(); + return half; +} + // After the core's last layer, its first again, until the passes are done. Called for every layer a call runs, // replayed or not, so the pass is right for the recordings' keys. int Inkling2::next_layer(int il) { diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 9b3b442939..424cbf9698 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -144,6 +144,11 @@ class Inkling2 final : public Engine { // experts' sum comes in after the card's bool moe_sum_later(int n) const override { return n == 1 && whole_rec_ && !bell_; } bool bells() const override { return true; } + // follow()'s half-life: 32 tokens, not 128. Replayed on routing traces of 18 answers (code, chat and prose + // after 2K-32K prompts, 512 tokens each, IQ4_NL on an 8 GB RTX 2070), the experts found in VRAM went from 80.7% + // to 82.3% at 2 swaps a token instead of 0.6: an answer moves from topic to topic faster than 128 tokens follow. + // STRATA_SWAP_HALF=N sets it (128 is main's). + int swap_half() const override; #if defined(STRATA_USE_HIP) // the shared expert is one memset (moe_shared()), and a graph launch a layer for it cost an RX 9070 XT's host // more than the memset: with experts on the CPU (no doorbell on HIP) a token's layers are launched one by one diff --git a/engine/src/poly/runtime.hpp b/engine/src/poly/runtime.hpp index 7e2b362a01..ccc2c4044f 100644 --- a/engine/src/poly/runtime.hpp +++ b/engine/src/poly/runtime.hpp @@ -40,7 +40,8 @@ constexpr size_t kChunkBytes = size_t(64) << 20; // one upload, and each of th // Zero bytes behind every matrix the batched kernels may multiply (Mmq::fits): they read up to a step of 256 // columns past a row that ends inside one, which is at most 7 blocks of 34 bytes. constexpr size_t kTail = 256; -// follow(): an expert's recent use is the count of its uses, halved every kSwapHalf tokens. An expert takes a +// follow(): an expert's recent use is the count of its uses, halved every kSwapHalf tokens (a family may set its +// own: Engine::swap_half(), Inkling 2's 32). An expert takes a // cached one's slot when it was used twice lately and more than twice as much as that one. Counts this small are // noisy, and an upload gets in the way of the work: a slot goes to an expert that will clearly be used more. constexpr float kSwapMin = 2.f; diff --git a/terminal/data/settings-register.json b/terminal/data/settings-register.json index 1b115a1705..4d80a5c202 100644 --- a/terminal/data/settings-register.json +++ b/terminal/data/settings-register.json @@ -47293,6 +47293,39 @@ "retire_after": "", "retired_in": "" }, + { + "name": "STRATA_SWAP_HALF", + "backends": [ + "cuda-hip" + ], + "reads": [ + { + "file": "engine/src/poly/inkling2.cpp", + "line": 1627, + "backend": "cuda-hip", + "fn": "getenv" + } + ], + "parse": "int", + "default_state": null, + "code_default": null, + "engine_sets": [], + "engine_defaults": [], + "launch_files": [], + "launch_sets": [], + "launch_reads": [], + "doc_mentions": [], + "first_commit": "c1a69e3ccb", + "first_date": "2026-11-24", + "since": null, + "last_commit": "c1a69e3ccb", + "last_date": "2026-11-24", + "status": "opt-in", + "owner": "poly", + "note": "Inkling 2 only: the tokens over which follow()'s recent expert uses halve (Engine::swap_half(); default 32, kSwapHalf 128 for every other family). STRATA_SWAP_HALF=N, 1 to 65536, sets it (128 = the old behaviour); logged at start. Placement only: which experts sit in VRAM, not the arithmetic of either path. Measured: routing-trace replay and end-to-end runs on an RTX 2070 8 GB (the PR that added it)", + "retire_after": "", + "retired_in": "" + }, { "name": "STRATA_SWITCH_POINT", "backends": [ From 31b77bc1596d10b8b8e537949492f567998169ff Mon Sep 17 00:00:00 2001 From: Shogo Okada <33060490+okada-shogo@users.noreply.github.com> Date: Tue, 24 Nov 2026 04:09:56 +0900 Subject: [PATCH 2/2] poly: Inkling 2 refills its expert cache after a read 128 experts a token After a read, the cache has the slots the read's buffers gave back, empty, and follow() fills them first, as many a token as uploads are free (Options::expert_swaps, 64 by default). A family hook, default_swaps(), gives Inkling 2 128 when --expert-swaps is not given (64 on Metal, whose arena holds back the bytes of every upload at a time); every other family keeps 64. --expert-swaps N still sets it, now up to 256 (was 64). Trades stay at most kSwapTrades (64) a token whatever the number of uploads, as before: each takes one of the mirror's spares (build_mirror(), sized by the same constant) for the expert that goes out. So more uploads only fill a read's empty slots sooner. The next token waits for every upload asked (settle_swaps()): 128 experts of IQ4_NL are ~0.6 GB, ~50 ms over PCIe 3.0 x16, which only the tokens right after a read pay. Offline replay of routing traces (STRATA_ROUTE_TRACE, RTX 2070 8 GB; the engine's own cache at the first answer token): after 32K tokens, IQ4_NL found 40% -> 50% of its experts in VRAM over the first 16 tokens (about 67 ms less CPU-expert time over the first 64); UD-Q2_K_XL 47% -> 69% (about 91 ms). At 64 a token the refill used about half the bus. Measured on an RTX 2070: the first 64 tokens after a 32K prompt 5% faster (15% over the first 16), on IQ4_NL and UD-Q2_K_XL. Class: placement. Same bits under STRATA_FREEZE_EXPERTS by construction: grow_cache() and follow() move nothing there. Co-Authored-By: Claude Opus 5.5 --- docs/models/inkling.md | 2 +- engine/src/poly/engine.cpp | 13 ++++++++----- engine/src/poly/engine.hpp | 4 +++- engine/src/poly/inkling2.hpp | 9 +++++++++ engine/src/poly/main.cpp | 4 ++-- engine/src/poly/runtime.hpp | 1 + 6 files changed, 24 insertions(+), 9 deletions(-) diff --git a/docs/models/inkling.md b/docs/models/inkling.md index 8157465201..0cf1888117 100644 --- a/docs/models/inkling.md +++ b/docs/models/inkling.md @@ -150,7 +150,7 @@ the group ranks it fifth or lower. | --- | --- | --- | | `--attn-requant q5_0` | the attention's matrices in 5 bits instead of 8: fewer bytes a token, and more VRAM for experts | rounding | | `--loop-bf16` | the loop controllers in BF16 instead of F32 | rounding | -| `--expert-swaps 0` | no expert moves into VRAM while an answer is written (default 64 on their way at a time) | rounding: the same experts, but more of them on the CPU, which rounds a little differently | +| `--expert-swaps 0` | no expert moves into VRAM while an answer is written (default 128 on their way at a time for Inkling 2, 64 on Metal) | rounding: the same experts, but more of them on the CPU, which rounds a little differently | | `--tail-skip 4` | a token's experts ranked 5th to 8th that are not on the card are left out | **skips computation** | Measured on main d1f711e11, one setting at a time and all four, with ggml-org's IQ4_NL file and with UD-Q2_K_XL diff --git a/engine/src/poly/engine.cpp b/engine/src/poly/engine.cpp index 730fd0e9ab..22b8908477 100644 --- a/engine/src/poly/engine.cpp +++ b/engine/src/poly/engine.cpp @@ -2402,7 +2402,7 @@ void Engine::fill_expert_cache() { if (arena < all) { if (mmq_ && !stage_) metal_stage_need += stage_bytes_ + 256 + kTail + 2 * chunk_bytes_; if (!swap_ && opt_.expert_swaps != 0) // -1 is decided after the cache is filled: as many as it can be - metal_stage_need += (size_t) (opt_.expert_swaps < 0 ? 64 : opt_.expert_swaps) * slot_max_; + metal_stage_need += (size_t) (opt_.expert_swaps < 0 ? default_swaps() : opt_.expert_swaps) * slot_max_; if (metal_cache_limit_ == SIZE_MAX && !recorded_) metal_stage_need += size_t(scratch_at_) * sizeof(float) + state_n_ * sizeof(float) + (size_t(512) << 20); else if (arena > (size_t(512) << 20)) @@ -3126,6 +3126,9 @@ void Engine::follow(int written) { // forced, 16 a window took the mirror's spares faster than arrivals gave them back, and calls fell back to the // host; 1 a window kept the cache from following the answer. if (card_far_) n_free = std::max(0, std::min(n_free, kFarTrades)); + // Trades take a mirror spare each for the expert that goes out (build_mirror() keeps about kSwapTrades): more + // uploads at a time (Inkling 2's default_swaps()) only fill a read's empty slots sooner, trades stay as many. + n_free = std::min(n_free, kSwapTrades); if (n_free == 0) { if (asked) { { std::lock_guard l(swap_m_); } @@ -3254,8 +3257,8 @@ void Engine::load(const Options& o) { throw std::runtime_error("a prompt batch is 1 to 4096 tokens"); if (opt_.stage_mib < 0) throw std::runtime_error("the staging buffer must be at least 1 MiB (0: the default)"); if (opt_.stage_ahead < 0) throw std::runtime_error("the batch size to stage ahead from cannot be negative"); - if (opt_.expert_swaps < -1 || opt_.expert_swaps > 64) - throw std::runtime_error("0 to 64 experts can be on their way into the cache at a time (-1: the default)"); + if (opt_.expert_swaps < -1 || opt_.expert_swaps > 256) + throw std::runtime_error("0 to 256 experts can be on their way into the cache at a time (-1: the default)"); if (opt_.window < 0 || opt_.window > 8) throw std::runtime_error("a window is 1 to 8 tokens, or 0 for the model's own"); if (opt_.lock_experts && opt_.ram_experts_mib >= 0) @@ -3571,7 +3574,7 @@ void Engine::load(const Options& o) { // and 5,120 MiB 87 and 98, UD-Q4_K_M there 31 and 38, Gemma 4 UD-Q6_K_XL with 5,120 MiB under 11 GiB at 6.9 GB // 100 and 137, at 2.9 GB 42 and 78. In unified memory a swap is a copy within RAM: on the M5 Ultra held to 6-7 // GiB, 64 of them wrote 3-5% faster. - if (opt_.expert_swaps < 0) opt_.expert_swaps = 64; + if (opt_.expert_swaps < 0) opt_.expert_swaps = default_swaps(); if (opt_.ram_experts_mib >= 0) { // each size of slot takes the share of the budget its experts outside VRAM have of all of those pool_size_of_.assign(layers_.size(), 0); @@ -5903,7 +5906,7 @@ void Engine::build_mirror() { size_t total = 0; for (size_t c = 0; c < (size_t) n_trade_; ++c) { if (!stride[c]) continue; - spares[c] = 1 + (size_t) (64.0 * (cached_all ? (double) cached[c] / (double) cached_all : 1.0)); + spares[c] = 1 + (size_t) ((double) kSwapTrades * (cached_all ? (double) cached[c] / (double) cached_all : 1.0)); total += (want[c].size() + spares[c]) * stride[c]; } constexpr size_t kHeadroom = size_t(4) << 30; // as the RAM budget's (load()) diff --git a/engine/src/poly/engine.hpp b/engine/src/poly/engine.hpp index 1370a13c17..e3e2867484 100644 --- a/engine/src/poly/engine.hpp +++ b/engine/src/poly/engine.hpp @@ -93,7 +93,7 @@ struct Options { ///< below 0: as the two took the time between them; 0: none int expert_swaps = -1; ///< experts on their way into the cache at a time while an answer is written, each ///< to the slot of one the answer uses less; 0: the cache stays as it was loaded; - ///< -1: 64 + ///< -1: Engine::default_swaps() (64; Inkling 2: 128 on CUDA/HIP) int64_t ram_experts_mib = -2; ///< the memory this process holds for the experts outside VRAM, answer or not: ///< the ones used most lately are read into it from the files; the others are left ///< to the file cache, which gives them to whatever needs the memory, and come back @@ -545,6 +545,8 @@ class Engine { virtual bool bells() const { return false; } /// follow(): the tokens over which an expert's recent uses halve (kSwapHalf for every family but Inkling 2). virtual int swap_half() const; + /// Options::expert_swaps when it is not given (-1): the uploads on their way into the cache at a time. + virtual int default_swaps() const { return 64; } /// What save_layer() writes of layer il that its run under way changes: all of it where a layer runs once a token. virtual void save_run(int il, int64_t pos, uint8_t* dst) { save_layer(il, pos, dst); } /// Optional host hook called before layer_head (including when layer_head is graph-replayed). diff --git a/engine/src/poly/inkling2.hpp b/engine/src/poly/inkling2.hpp index 424cbf9698..c5cd634533 100644 --- a/engine/src/poly/inkling2.hpp +++ b/engine/src/poly/inkling2.hpp @@ -149,6 +149,15 @@ class Inkling2 final : public Engine { // to 82.3% at 2 swaps a token instead of 0.6: an answer moves from topic to topic faster than 128 tokens follow. // STRATA_SWAP_HALF=N sets it (128 is main's). int swap_half() const override; + // 128 uploads at a time, not 64. After a long read the cache has hundreds of empty slots (740 of 860 after + // 32K tokens of IQ4_NL on an 8 GB card), which follow() fills first, as many a token as uploads are free: 64 a + // token used about half the bus while the first tokens ran mostly on the CPU. Trades in an answer stay at 1-2 a + // token, so this only fills the cache sooner after a read. --expert-swaps N sets it. +#if defined(STRATA_GPU_METAL) + int default_swaps() const override { return 64; } // Metal's arena holds back their bytes (fill_expert_cache()) +#else + int default_swaps() const override { return 128; } +#endif #if defined(STRATA_USE_HIP) // the shared expert is one memset (moe_shared()), and a graph launch a layer for it cost an RX 9070 XT's host // more than the memset: with experts on the CPU (no doorbell on HIP) a token's layers are launched one by one diff --git a/engine/src/poly/main.cpp b/engine/src/poly/main.cpp index e7eff913c3..0548fa0db6 100644 --- a/engine/src/poly/main.cpp +++ b/engine/src/poly/main.cpp @@ -1689,8 +1689,8 @@ void usage() { " Metal default: q8_0 for a compatible Qwen35MoE geometry, else fp16\n" #endif " --expert-swaps N while an answer is written, up to N experts it keeps using are on their way\n" - " into VRAM, in place of cached ones it uses less (default 64, 0 = the cache\n" - " stays as it was loaded)\n" + " into VRAM, in place of cached ones it uses less (default 64, Inkling 2: 128;\n" + " up to 256; 0 = the cache stays as it was loaded)\n" " --ram-experts-mib N hold N MiB of RAM for the experts outside VRAM, during answers too: the ones\n" " used most lately; the rest stay in the file cache for other programs to take,\n" " and are read back when a token needs them (default: all of them when they\n" diff --git a/engine/src/poly/runtime.hpp b/engine/src/poly/runtime.hpp index ccc2c4044f..0eb4c18b7e 100644 --- a/engine/src/poly/runtime.hpp +++ b/engine/src/poly/runtime.hpp @@ -46,6 +46,7 @@ constexpr size_t kTail = 256; // noisy, and an upload gets in the way of the work: a slot goes to an expert that will clearly be used more. constexpr float kSwapMin = 2.f; constexpr int kSwapHalf = 128; +constexpr int kSwapTrades = 64; // trades follow() asks a token at most, whatever Options::expert_swaps constexpr int kFarTrades = 4; // card_far_: trades a window asks (Engine::follow()) // Engine::pick_way(): each way of a window is timed this many times before the faster one is taken. What a way // takes moves, most in an answer's first windows, while the cache comes to hold the answer's experts, so the way