Files
Strata/engine/include/strata/program/split_rules.hpp
T
Niko1221 4285678952 feat(engine): layer split auto says when fewer cards would be faster, and names the setting to use (#6758)
From PR #6768 by @D-Ogi: after the auto layer-split search the engine asks the same
cost model for the chosen placement without its first stages. When the predicted
decode window is at least STRATA_SPLIT_FEWER_PCT percent (default 20, 0 = off) shorter,
it prints one FEWER CARDS line. The placement and the tokens do not change; the model
predicts decode only. (RTX 4090 x16 + RTX 3060 x4: K=10 predicted 27.0 ms, the 4090
alone 17.5 ms; measured 62 tok/s alone against 25-44% less with the split.)

Added here: the line is built by split_rules::fewer_cards_advice and names the exact
setting to try: `--gpu N` without `--layer-split` for one kept card; for several, the
other cards hidden (CUDA_VISIBLE_DEVICES=...) with `--layer-split auto` kept; and in the
Terminal the card roles (`strata launch --gpu-roles`). Nothing is dropped for the user.
split_rules_test checks both wordings. The settings register has the new name
(status rollback) and docs/SETTINGS.md and docs/MULTI_GPU.md are regenerated / extended.

Compile-checked as the Qwen engine target on CUDA sm_86 (z440).
2026-11-23 11:17:51 +01:00

280 lines
16 KiB
C++

// include/strata/program/split_rules.hpp - rules for the automatic layer split that do not need a GPU to check.
//
// A stage that owns one or two layers holds a handful of expert slots (a 12 GB 3060 with one layer held 512), and
// the prompt chunk of the whole pipeline is clamped to what the smallest cache can lend (#448): 576 -> 347 tok/s in
// #1616. So the search first looks for a placement in which every stage owns at least kMinStageLayers layers, and
// only falls back to the unrestricted best when no such placement can start the prompt path.
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <string>
#include <vector>
namespace strata::program::split_rules {
constexpr int64_t kMinStageLayers = 3;
/// The restriction only makes sense when the model has the layers for it.
inline bool restriction_possible(int64_t n_layers, int stages) {
return stages >= 2 && n_layers >= kMinStageLayers * stages;
}
/// cuts: the first layer of each later stage (stages - 1 of them); n_layers: the model's layers.
/// Returns the size of the smallest stage.
inline int64_t smallest_stage(const std::vector<int64_t>& cuts, int64_t n_layers) {
int64_t lo = n_layers, prev = 0;
for (const int64_t c : cuts) {
if (c - prev < lo) lo = c - prev;
prev = c;
}
if (n_layers - prev < lo) lo = n_layers - prev;
return lo;
}
/// True when some stage owns fewer than kMinStageLayers layers.
inline bool has_tiny_stage(const std::vector<int64_t>& cuts, int64_t n_layers) {
return smallest_stage(cuts, n_layers) < kMinStageLayers;
}
// ---- the trim's credit in the auto search (PR #4522). At the moment the search runs, CUDA0 holds the dense weights of ALL layers
// (its arena is built before the split is known) and gives back everything outside its own layers when it reloads trimmed, so its room
// for experts may count what the trim frees. A later stage's weights are not loaded yet: its free memory has no full copy in it, and the
// search already prices its trimmed weights (carve_bytes), so crediting it the same bytes again counts them twice and hands its cache room
// it does not have.
inline int64_t trim_credit(int stage, int64_t freed_by_trim) {
return stage == 0 && freed_by_trim > 0 ? freed_by_trim : 0;
}
// ---- #2644: the #1616 floor must not starve a card. On an asymmetric pair (RTX 4060 Ti 16 GB + RTX 3060 12 GB, 48
// layers, IQ3_S) the predicted decode window prefers almost every layer on the faster card, the first pick was K=2, and the
// #1616 retry (every stage at least kMinStageLayers) landed on the edge of that restriction: K=3, the 3060 with 3 layers,
// 12 GB idle, 452 tok/s of prefill against 802 at 28 layers (the prompt flows through the stages as a pipeline, so one
// busy card is the whole rig). So before that retry, a two-stage rig is asked for a placement in which each stage owns at
// least its share of the layers by its room for experts; the three-layer rule stays the second try, and the first pick
// the last.
/// Per stage, the fewest layers the share-of-room retry accepts: floor(n_layers x room_i / sum of rooms), at least
/// kMinStageLayers, and (when the floors would not fit) trimmed from the largest back toward kMinStageLayers until
/// they do. Rooms <= 0 count as 0; no room anywhere gives every stage kMinStageLayers.
inline std::vector<int64_t> share_floors(const std::vector<int64_t>& room, int64_t n_layers) {
std::vector<int64_t> floors(room.size(), kMinStageLayers);
double total = 0.0;
for (const int64_t r : room) total += r > 0 ? (double) r : 0.0;
if (total <= 0.0) return floors;
int64_t sum = 0;
for (size_t i = 0; i < room.size(); ++i) {
const double share = (room[i] > 0 ? (double) room[i] : 0.0) / total * (double) n_layers;
floors[i] = std::max<int64_t>(kMinStageLayers, (int64_t) share); // truncated: the floors sum to <= n_layers
sum += floors[i];
}
while (sum > n_layers) { // only through the kMinStageLayers lift of a small share
size_t big = 0;
for (size_t i = 1; i < floors.size(); ++i)
if (floors[i] > floors[big]) big = i;
if (floors[big] <= kMinStageLayers) break;
--floors[big];
--sum;
}
return floors;
}
/// True when some stage of `cuts` owns fewer layers than its floor.
inline bool below_floors(const std::vector<int64_t>& cuts, int64_t n_layers, const std::vector<int64_t>& floors) {
int64_t prev = 0;
for (size_t i = 0; i <= cuts.size() && i < floors.size(); ++i) {
const int64_t end = i < cuts.size() ? cuts[i] : n_layers;
if (end - prev < floors[i]) return true;
prev = end;
}
return false;
}
/// The share-of-room retry is worth running when some floor is above the plain three-layer rule's.
inline bool floors_exceed_minimum(const std::vector<int64_t>& floors) {
for (const int64_t f : floors)
if (f > kMinStageLayers) return true;
return false;
}
// ---- #1440: headroom among (near-)ties. The search scores a placement by its predicted window time alone, so on two
// equal cards every K whose caches hold all the profiled pairs ties, and the first one tried wins: the smallest K, which
// gives the LAST stage (the one that also carries the MTP drafter) the most layers and lets its cache fill the card to
// the reserve. On Linux xe a card that runs out of VRAM does not fail an allocation, the driver moves buffers to system
// memory: 2x Arc Pro B70, IQ3_S, auto picked K=24 with CUDA1 at 31.8 of 31.9 GiB and decoded ~11 tok/s, against ~54 with
// --layer-split 30. So among the placements within `tol` of the best predicted time, the one whose tightest stage
// keeps the most VRAM beyond all of its layers' experts wins (ties on that: the faster, then the first).
/// One scored placement: its cuts, its predicted window time and the smallest spare room over its stages (bytes; a
/// stage's room after its session minus every expert of its layers; negative when its cache cannot hold them all).
struct Placement {
std::vector<int64_t> cuts;
double ms = 0.0;
int64_t min_spare = 0;
};
/// The index of the plain pick (the first with the lowest time) in `c`, or 0 when `c` is empty.
inline size_t fastest(const std::vector<Placement>& c) {
size_t best = 0;
for (size_t i = 1; i < c.size(); ++i)
if (c[i].ms < c[best].ms) best = i;
return best;
}
/// The index of the pick with headroom: of the placements within `tol` (a fraction) of the fastest, the one with the
/// largest `min_spare`. tol <= 0 still breaks exact ties. 0 when `c` is empty.
inline size_t pick_with_headroom(const std::vector<Placement>& c, double tol) {
if (c.empty()) return 0;
const size_t best = fastest(c);
const double limit = c[best].ms + c[best].ms * (tol > 0.0 ? tol : 0.0);
size_t pick = best;
for (size_t i = 0; i < c.size(); ++i) {
if (c[i].ms > limit) continue;
if (c[i].min_spare > c[pick].min_spare || (c[i].min_spare == c[pick].min_spare && c[i].ms < c[pick].ms))
pick = i;
}
return pick;
}
// ---- #2007: the miss cost of a stage on a narrower link. 0.1.41 scaled each stage's miss term by 20 GB/s / its probed
// link (clamped to 1..64), for 2x 4090 D with CUDA1 on a physical x1 link (1.6 GB/s: x12, auto K 22 -> 38, prompt
// ~350 -> ~1400 tok/s). The same scale moved 2x Tesla T10 from K=23 to K=14: prompt -23%, decode -15% (xiake-1).
// So the scale is now relative to the stage with the fastest link (a symmetric rig keeps the fitted formula, whatever
// its link speed) and applies only from kLinkScaleMin on (a narrow riser or a chipset x1/x4 slot against an x16 one);
// below that the probe's noise and the formula's fit are the larger effects.
constexpr double kLinkScaleMin = 4.0;
/// STRATA_SPLIT_LINK_MIN (BW-MG, opt-in): the gap (the fastest stage's link / this stage's) from which the miss term is scaled; unset, empty or anything that is not a number >= 1 keeps kLinkScaleMin.
/// 2x RTX 5090 on a PCIe 4.0 x8 + x2 board (14.1 and 3.6 GB/s probed, a gap of 3.92): auto K=24 reads a 4K prompt in 5,950 ms against 4,270 on the x8 card alone; with the gap read as 3 the split
/// puts fewer layers on the x2 card (RESULTS-BW-E.md).
inline double link_scale_min_resolve(const char* env) {
if (env == nullptr || env[0] == '\0') return kLinkScaleMin;
char* end = nullptr;
const double v = std::strtod(env, &end);
return end != env && v >= 1.0 ? v : kLinkScaleMin;
}
/// Per stage: the factor on its miss term, from the probed H2D GB/s of each stage (<= 0: not probed -> 1.0).
inline std::vector<double> link_miss_scale(const std::vector<double>& gbps, double min_ratio = kLinkScaleMin) {
double fastest = 0.0;
for (const double b : gbps) fastest = b > fastest ? b : fastest;
std::vector<double> s(gbps.size(), 1.0);
if (fastest <= 0.0) return s;
for (size_t i = 0; i < gbps.size(); ++i) {
if (gbps[i] <= 0.0) continue;
const double r = fastest / gbps[i];
s[i] = r >= min_ratio ? (r > 64.0 ? 64.0 : r) : 1.0;
}
return s;
}
// ---- the gate-off fallback must still load. When no placement can start the prompt path the search chooses by decode speed
// alone, and nothing checked that a later stage's cache can hold anything; a later stage with no room for one expert slot ends
// the start ("layer split, CUDA1 expert cache: no room"). 2x 8 GB (RTX 3060 Ti + RTX 3070 Ti) with DFlash2 on CUDA1: the PCIe
// probe put the link gap at 3.66-4.33, on both sides of kLinkScaleMin, and the K=45 it picked below the step could not load.
// So the fallback first keeps to placements in which every later stage holds at least one slot; with none, it picks as before.
/// held[i]: the expert slots stage i's cache holds in the search's fill. True when a stage after the first holds none.
inline bool later_stage_empty(const std::vector<int64_t>& held) {
for (size_t i = 1; i < held.size(); ++i)
if (held[i] <= 0) return true;
return false;
}
/// The smallest spare room over the stages of `cuts`: room[i] - session(lb, le) - need(lb, le), where `need_prefix[l]`
/// is the bytes of every expert of layers [0, l) (n_layers + 1 entries).
template <class Session>
inline int64_t min_spare(const std::vector<int64_t>& cuts, int64_t n_layers, const std::vector<int64_t>& room,
const std::vector<int64_t>& need_prefix, Session&& session) {
int64_t lo = INT64_MAX;
for (size_t i = 0; i <= cuts.size(); ++i) {
const int64_t lb = i == 0 ? 0 : cuts[i - 1];
const int64_t le = i < cuts.size() ? cuts[i] : n_layers;
const int64_t spare = room[i] - session(lb, le) - (need_prefix[(size_t) le] - need_prefix[(size_t) lb]);
if (spare < lo) lo = spare;
}
return lo;
}
// ---- #6758: fewer cards. The search predicts the decode time only for placements of all the cards. A decode window
// passes each stage in turn. Thus each card adds the time of its layers to each window. The only gain is that its expert
// cache decreases the misses. A much slower card can cost more time than its cache saves.
//
// The example of #6758 is an RTX 4090 (PCIe x16) with an RTX 3060 (PCIe x4), IQ3_S and 48 layers. The search chose K=10
// at a predicted 27.0 ms per decode window. The best split run decoded at 34.6 tok/s. The RTX 4090 alone decoded at
// 62 to 74 tok/s.
//
// The same model thus also predicts the chosen placement without its first stages, down to the last card alone. The
// layers of a removed stage go to the next stage. The last stage always stays, because it holds the head. The engine
// prints one line when fewer cards are much faster. The line is advice only. The model predicts decode, and a split
// can read a prompt faster than one card (docs/MULTI_GPU.md).
constexpr double kFewerCardsPct = 20.0; // This is the default threshold in percent. No sweep supports this value (#6758).
/// Returns the threshold in percent from STRATA_SPLIT_FEWER_PCT. The engine prints the line only when the predicted
/// time of fewer cards is at least this much less. 0 disables the line. An unset, empty or invalid value (not a
/// number >= 0) gives kFewerCardsPct.
inline double fewer_cards_pct_resolve(const char* env) {
if (env == nullptr || env[0] == '\0') return kFewerCardsPct;
char* end = nullptr;
const double v = std::strtod(env, &end);
return end != env && v >= 0.0 ? v : kFewerCardsPct;
}
/// Returns `cuts` without its first `drop` stages. Each removed stage gets a cut of 0, thus its layers go to the next
/// stage. With drop >= cuts.size(), only the last card stays. With drop <= 0, the result is `cuts`.
inline std::vector<int64_t> without_first(const std::vector<int64_t>& cuts, int drop) {
std::vector<int64_t> out = cuts;
for (size_t i = 0; i < out.size() && (int) i < drop; ++i) out[i] = 0;
return out;
}
/// Returns the number of first stages to remove (0 keeps each card). ms_all is the predicted window time of the chosen
/// placement. ms_without[j] is the predicted time without the first j + 1 stages (a value <= 0 has no prediction).
/// The rule selects the lowest time if it is at least `pct` percent below ms_all. For equal times, it keeps more cards.
inline int fewer_cards(double ms_all, const std::vector<double>& ms_without, double pct) {
if (!(pct > 0.0) || !(ms_all > 0.0)) return 0;
const double limit = ms_all * (1.0 - pct / 100.0) + ms_all * 1e-9;
int pick = 0;
double pick_ms = 0.0;
for (size_t j = 0; j < ms_without.size(); ++j) {
const double ms = ms_without[j];
if (!(ms > 0.0) || ms > limit) continue;
if (pick == 0 || ms < pick_ms) {
pick = (int) j + 1;
pick_ms = ms;
}
}
return pick;
}
/// The text of the FEWER CARDS line (#6758). `gone` / `kept` name the cards ("CUDA0 (NVIDIA ...)"), `kept_devs` are the engine numbers of the cards
/// that stay, `ms` / `ms_all` the predicted decode windows without and with all cards, `ks` the chosen K. It names the exact setting that starts the
/// engine on the kept card(s): `--gpu N` without `--layer-split` for one card, the other cards hidden (CUDA_VISIBLE_DEVICES) for several; and in the
/// Terminal the card roles (the cards to leave out set to Off: `strata launch --gpu-roles`, docs/MULTI_GPU.md). Advice only: nothing changes.
inline std::string fewer_cards_advice(const std::string& gone, const std::string& kept, const std::vector<int>& kept_devs, double ms, double ms_all,
const std::string& ks) {
char head[512];
std::snprintf(head, sizeof head,
"strata generate: layer split auto: FEWER CARDS - without %s, the same model predicts %.1f ms per decode window. This is %.0f%% less than K=%s "
"(%.1f ms). A decode window passes each card in turn, so a much slower card can cost more time than its expert cache saves. The model predicts "
"decode only, not the prompt read: measure both before you leave a card out. ",
gone.c_str(), ms, ms_all > 0.0 ? 100.0 * (1.0 - ms / ms_all) : 0.0, ks.c_str(), ms_all);
std::string how;
if (kept_devs.size() == 1) {
how = "To try it, start the engine on " + kept + " alone: `--gpu " + std::to_string(kept_devs[0]) + "` and no `--layer-split`";
} else {
std::string vis;
for (const int d : kept_devs) vis += (vis.empty() ? "" : ",") + std::to_string(d);
how = "To try it, start the engine on " + kept + " only: hide the other cards (CUDA_VISIBLE_DEVICES=" + vis + ") and keep `--layer-split auto`";
}
how += ". In the Terminal set the card(s) named above as left out to Off in the card roles (`strata launch --gpu-roles`, docs/MULTI_GPU.md). "
"The CUDA numbers follow the card order of this start. STRATA_SPLIT_FEWER_PCT=0 turns this line off.";
return std::string(head) + how;
}
} // namespace strata::program::split_rules