Merge batch 15 (d6f9f68f9) into f-i8-share

prefill.cpp: the two adjacent inserts (share_keeps_own_kernels and the switch-point globals) are both kept.
Settings register and docs/SETTINGS.md regenerated (the way-back count is 71).
This commit is contained in:
Niko1221 committed 2026-11-13 17:03:33 +01:00
commit 1ce91c84c4
17 files changed
+2574 -474

No files matched your search

+5
View File
@@ -444,6 +444,11 @@ if(STRATA_BUILD_TESTS)
target_include_directories(fp16_rows_rule_test PRIVATE include)
add_test(NAME fp16_rows_rule_test COMMAND fp16_rows_rule_test)
# STRATA_SWITCH_POINT (on by default for NVIDIA sm_86, one GPU): the floor from the card's share of non-resident experts, a cost estimate of the staged and the streamed walk (header-only, no GPU)
add_executable(switch_point_rule_test tests/prefill/switch_point_rule_test.cpp)
target_include_directories(switch_point_rule_test PRIVATE include)
add_test(NAME switch_point_rule_test COMMAND switch_point_rule_test)
# whether the CUDA fused prompt kernels take the Gyro trellis experts by default (STRATA_PF_FUSED_TQ unset: the sm_86 cards with 80+ SMs; =1 any card; =0 off): the pure
# rule, pinned for every card class (header-only, no GPU)
add_executable(fused_tq_default_test tests/prefill/fused_tq_default_test.cpp)
File diff suppressed because it is too large. Load diff
+3 -1
View File
@@ -289,7 +289,7 @@ Off unless you set them. The last column says where each one is described.
| `STRATA_WDDM_BUDGET` | number | AMD, Intel Arc | [AMD_HIP.md](AMD_HIP.md) |
| `STRATA_WS_FAST` | number | NVIDIA and AMD | [OLDER_GPUS.md](OLDER_GPUS.md) |
## Switches that go back to earlier behaviour (69)
## Switches that go back to earlier behaviour (71)
These behaviours are on by default. Setting the switch returns the earlier behaviour; the notes in the register say which
version made it the default.
@@ -341,6 +341,7 @@ version made it the default.
| `STRATA_PLE_AUTO_MMAP` | number | NVIDIA and AMD, Intel Arc | v0.1.43.1 | [DETAILS.md](DETAILS.md) |
| `STRATA_PREFILL_LOAN_WALK` | on / off | NVIDIA and AMD | - | - |
| `STRATA_PREFILL_STREAM_MIN` | number | NVIDIA and AMD, Intel Arc | v0.1.40.1 | [AMD_HIP.md](AMD_HIP.md), [STRIX_HALO.md](STRIX_HALO.md) |
| `STRATA_PREFILL_TAIL_LOAN` | on / off | NVIDIA and AMD | - | - |
| `STRATA_PROMPT_ATTN_ESIMD` | number | Intel Arc | v0.2.9 | - |
| `STRATA_PROMPT_ATTN_OLD` | on / off | NVIDIA and AMD, Intel Arc | v0.1.40.1 | [NVIDIA_V100.md](NVIDIA_V100.md), [OLDER_GPUS.md](OLDER_GPUS.md) |
| `STRATA_Q2_WARP` | on / off | NVIDIA and AMD | v0.1.45 | [DETAILS.md](DETAILS.md) |
@@ -357,6 +358,7 @@ version made it the default.
| `STRATA_SM60_TABLE` | number | NVIDIA and AMD | v0.1.43 | [OLDER_GPUS.md](OLDER_GPUS.md) |
| `STRATA_SPLIT_CHUNK16K` | number | NVIDIA and AMD | v0.1.44 | [MULTI_GPU.md](MULTI_GPU.md) |
| `STRATA_SPLIT_OWN` | on / off | NVIDIA and AMD, Intel Arc | v0.1.40.1 | [MULTI_GPU.md](MULTI_GPU.md) |
| `STRATA_SWITCH_POINT` | on / off | NVIDIA and AMD | - | - |
| `STRATA_SYCL_BF16_DET` | number | Intel Arc | v0.2.13 | - |
| `STRATA_TOPK_SAMPLE` | number | NVIDIA and AMD | v0.1.45 | [DETAILS.md](DETAILS.md) |
| `STRATA_TOPK_SPLIT` | number | NVIDIA and AMD | v0.1.45 | [DETAILS.md](DETAILS.md) |
+48
View File
@@ -24,4 +24,52 @@ constexpr int64_t walk_chunk(int64_t tokens, int64_t chunk, int64_t floor) {
return (tokens > 0 && chunk > 0 && tokens < floor && chunk >= floor) ? floor - 1 : chunk;
}
// The tail of a lent fused layout. A layout laid out for chunks at or above the floor (the fused MoE buffers) also
// holds MMQ's rows for a chunk BELOW the floor, which runs staged in the same buffers. Sizing that for floor - 1
// tokens costs expert slots on every prompt, whatever its own chunks are (a floor of 3,584 against 1,024: about 289 MB,
// 92 slots of an RTX A6000). A segment of `tokens` read in chunks of `chunk` has a chunk below the floor only at its
// end, so that is all the tail it needs.
/// The most MMQ rows (in tokens) a segment of `tokens` read in chunks of `chunk` puts into the fused layout's buffers:
/// the last chunk when it is below `floor`, else 0 (every other chunk is a full one, at or above the floor, and runs
/// the fused kernels). A layout whose chunk is itself below the floor is not a fused layout: min(chunk, tokens).
constexpr int64_t tail_need(int64_t tokens, int64_t chunk, int64_t floor) {
if (tokens <= 0 || chunk <= 0) return 0;
if (chunk < floor) return tokens < chunk ? tokens : chunk;
const int64_t last = tokens > chunk ? tokens - ((tokens - 1) / chunk) * chunk : tokens;
return last < floor ? last : 0;
}
/// The tail a layout is carved with for that need: on the 256-token grid (so that two requests with nearly the same tail
/// keep one layout), at most floor - 1 (today's size), 0 for no need.
constexpr int64_t tail_layout(int64_t need, int64_t floor) {
if (need <= 0 || floor <= 1) return 0;
const int64_t grid = (need + 255) / 256 * 256;
return grid < floor - 1 ? grid : floor - 1;
}
/// The tail a layout for a segment is carved with (what lend asks the layout for).
constexpr int64_t segment_tail(int64_t tokens, int64_t chunk, int64_t floor) {
return tail_layout(tail_need(tokens, chunk, floor), floor);
}
/// The tail a lend carves a layout with, given the layout that is in place: GROW-ONLY while the layout's chunk stays.
/// `layout_chunk` / `layout_tail`: the layout now laid out (a tail of -1: carved with today's floor - 1, i.e. never sized
/// by a segment: the start-up layout, or the way-back switch); `want`: the chunk this segment's loan is for; `need`: its
/// segment_tail(). A layout of the same chunk that is tail-sized keeps its tail when it covers the need (no relayout
/// for a smaller follow-up) and otherwise goes straight to today's size: floor - 1, so a sequence of segments costs at
/// most ONE relayout more than today's sizing, then runs on today's bytes. Any other case (another chunk: a relayout
/// today as well; a start-up layout) starts again from the need of that moment.
constexpr int64_t next_tail(int64_t layout_chunk, int64_t layout_tail, int64_t want, int64_t need, int64_t floor) {
if (layout_tail >= 0 && layout_chunk == want) return layout_tail >= need ? layout_tail : (floor > 1 ? floor - 1 : 0);
return need;
}
/// A loan carved for `lent_chunk` with room for `lent_tail` MMQ tokens serves a later segment of `tokens` (wanting
/// chunks of `want`) without a new layout only if its chunk covers `want` AND the segment, read in the loan's own
/// chunks (a layout always reads in its own chunk), needs no more tail than the loan holds.
constexpr bool reuse_ok(int64_t want, int64_t tokens, int64_t lent_chunk, int64_t lent_tail, int64_t floor) {
return want <= lent_chunk && tail_need(tokens, lent_chunk, floor) <= lent_tail;
}
} // namespace strata::prefill::loan_rules
+14 -3
View File
@@ -85,8 +85,16 @@ public:
/// With borrowed buffers: lay them out again for chunks of `chunk` tokens (at most `init`'s) in `borrow` - a
/// request lends only the slots its prompt needs. The stream must be idle (between prompts).
bool relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err);
/// `tail` (>= 0, a fused layout only): the MMQ rows, in tokens, the layout holds for a chunk below the stream floor
/// (loan_rules.hpp: a lent layout is sized for its segment's own short last chunk, not for floor - 1); -1: floor - 1.
bool relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err, int64_t tail = -1);
int64_t chunk() const;
/// The tail the layout in place was carved with (-1: the default, floor - 1), and the MMQ tokens a chunk below the
/// floor may bring into it (a layout that is not fused takes any chunk it has: INT64_MAX).
int64_t layout_tail() const;
int64_t tail_room() const;
/// True when a layout for `chunk` is the fused one, whose MoE buffers carry a tail (see relayout).
static bool tail_matters(int64_t chunk, bool src);
/// The share of the streamed experts' bytes DMA-able straight from pinned RAM (1 = all). Sizes the streamed
/// ring (a big one only pays when the copy engine, not the host copies, is the limit); set before bytes_needed.
@@ -100,6 +108,9 @@ public:
/// (staged_fo_rule.hpp: Windows gfx1151, every layer without an MMQ tile and on the fused kernels, entry on), the measured crossing of the verify windows and that entry.
/// A `--short-read` given on the command line is not asked. Call once the expert layout is known.
static int64_t short_read_default(int64_t base);
/// STRATA_SWITCH_POINT (on by default for the class in switch_point_rule.hpp, =0 off): the expert cache's live slots and layers x experts of the single card's own model, before the first lend; the floor above is then
/// chosen from the share of experts the card does not hold, scaled by the cache's mean blob (MB), the start-up link probe (GB/s) and the card's SM count (switch_point_rule.hpp; 0 = unknown: the default floor). With STRATA_SWITCH_POINT=0 this changes nothing.
static void set_card_expert_share(int64_t resident_slots, int64_t total_pairs, double blob_mb = 0.0, double link_gbps = 0.0);
/// --prefill-pipe (opt-in): the chunk a layer split's first stage reads an `n`-token prompt in, for `stages`
/// stages, chunks of at most `cap` (the buffers' size) and a stage-chunk cost of b + a C with b/a = `ratio` tokens
/// (0: unknown - STRATA_PREFILL_EQUAL's rule: the same chunk count as `cap` gives, evened out when its last chunk
@@ -168,7 +179,7 @@ public:
/// Device bytes `init` needs for a chunk of `chunk` tokens (what a borrowed region must hold). `src`: init gets an
/// ExpertSource (carve picks the fused MoE layout only then).
static uint64_t bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
bool src = true);
bool src = true, int64_t tail = -1);
/// The same without the streamed ring: what the chunk's own buffers cost. The auto chunk scan sizes the chunk
/// first and hands the ring what the chunk leaves over, so it needs the chunk priced on its own.
@@ -331,7 +342,7 @@ public:
private:
static uint64_t bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
bool owned_pages, bool src);
bool owned_pages, bool src, int64_t tail = -1);
kernels::cpu::ExpertPool* cpu_pool_ = nullptr; ///< set_cpu_pool
// Layer-major prefill: the super-chunk's buffers for an n-token prompt (its size, 0 = not this prompt: `why`),
// the run, and the buffers given back after it. `cap` (> 0): at most that many tokens (a layer split's stages
@@ -0,0 +1,124 @@
// include/strata/prefill/switch_point_rule.hpp - the chunk size below which a prompt chunk takes the STAGED walk and from which it takes the STREAMED walk
// (src/prefill/prefill.cpp stream_all_min()), chosen by estimated cost from the card's share of non-resident experts instead of the fixed 1,024.
// ON BY DEFAULT for one class of card (enabled() below): CUDA, NVIDIA discrete card on PCIe, one GPU, the start-up link probe ran, compute capability 8.6 (RTX A6000 and
// RTX A4000 measured). STRATA_SWITCH_POINT=0 is the way back; STRATA_SWITCH_POINT=1 asks for the rule on any other CUDA card (not measured there).
// Pure: no GPU, no environment read here.
//
// The two walks (prefill.cpp):
// streamed: every expert the card does not hold is copied through a ring in layer order, whatever the chunk routes; the copy runs through the attention
// halves, so the chunk costs about its copy time: P(T) = c_p * X + a_p * T (X = non-resident experts, T = chunk tokens).
// staged: the routing is read back per layer and only the routed non-resident experts are staged; the copy cannot overlap the layer's own compute:
// S(T) = s0 + c_s * Xs(T) + a_s * T, with Xs(T) = X * (1 - u(T)) the routed ones. u(T) is the share of the non-resident experts NOT routed by T tokens.
// Fitted on an RTX A6000 (48 GB, 12 GB/s link) with Qwen3.8-Flash-Next UD-Q4_K_XL (111 GB set, 55% of the expert slots resident), K-quant fused kernels, CPU share off
// (par/RESULTS-SWITCH-POINT.md, par/switchpt/fit1.py): c_p = 0.2612 ms, a_p = 0.0566 ms/token (at X = 12,097), c_s = 0.2278, a_s = 0.2294, s0 = 202 ms,
// u(T) = (T / 391)^-0.702 (measured routed shares 51 / 70 / 80 / 88 % at 1,100 / 2,049 / 4,097 / 8,193 tokens; the uniform-routing formula says 100% at all of them).
// Staged wins while advantage(T) = P(T) - S(T) = (c_p - c_s) * X - s0 + c_s * X * u(T) - (a_s - a_p) * T is positive.
//
// The floor is ONE scalar for the card, decided before the first lend (the lent cache slots, ring_slots(T), fused_layout(T) and moe_bufs() all read stream_all_min()), so it
// depends on the card's counts and never on the chunk in hand. X = 0 (every expert resident) gives exactly the default 1,024.
#pragma once
#include <algorithm>
#include <cmath>
#include <cstdint>
namespace strata::prefill::switch_point {
inline constexpr int64_t kFloorDefault = 1024; // = kStreamFloorDefault (stream_floor_rule.hpp): the floor of every card the rule does not move
inline constexpr int64_t kGrid = 256; // the prompt path's chunk grid
inline constexpr int64_t kFloorMax = 8192; // never past the auto chunk's usual top: above it the streamed walk's one pass is cheaper on every card measured
struct Constants {
double c_p = 0.2612; // ms per non-resident expert, streamed walk (its copy-bound floor)
double c_s = 0.2278; // ms per streamed expert, staged walk
double a_p = 0.0566; // ms per token, streamed walk
double a_s = 0.2294; // ms per token, staged walk
double s0 = 201.75; // ms, staged walk's fixed part
double t0 = 391.0; // u(T) = (T / t0)^-gamma, 1 below t0
double gamma = 0.702;
double x_inflate = 1.0; // the streamed walk's lend: X as streamed / X as counted from the cache before the lend
};
/// Share of the non-resident experts no token of a chunk of T tokens routes to.
inline double uncovered(int64_t T, const Constants& k) {
if (T <= 0) return 1.0;
return std::min(1.0, std::pow((double) T / k.t0, -k.gamma));
}
/// Milliseconds the staged walk saves over the streamed walk for a chunk of T tokens on a card with X non-resident experts (negative: it costs).
inline double advantage_ms(int64_t T, double X, const Constants& k) {
return (k.c_p - k.c_s) * X - k.s0 + k.c_s * X * uncovered(T, k) - (k.a_s - k.a_p) * (double) T;
}
/// The floor for a card holding `resident_slots` of `total_pairs` (layers x experts): staged below it, streamed from it.
/// total_pairs <= 0 (unknown) or nothing non-resident: the default. A card that gains nothing at 1,024 keeps 1,024 (never lower).
inline int64_t floor_for(int64_t resident_slots, int64_t total_pairs, const Constants& k = Constants{}) {
if (total_pairs <= 0 || resident_slots < 0 || resident_slots >= total_pairs) return kFloorDefault;
const double X = (double) (total_pairs - resident_slots) * k.x_inflate;
int64_t T = kFloorDefault;
while (T < kFloorMax && advantage_ms(T, X, k) > 0.0) T += kGrid; // advantage falls with T: the first T where it is not positive is the floor
return T;
}
// ---- per-card scaling (SWITCH-POINT-2) ----
// The A6000 fit above does not transfer as it is (the A4000's crossing is about 1,930 tokens, the fit's 5,632), but its structure does: the copy terms scale with the cost of moving one expert
// (mean blob bytes / the link's GB/s) and the compute terms with 1 / the SM count (the A4000 streams at 0.63 ms a token against the A6000's 0.36: 84 / 48). s0 and u(T) stay as fitted.
// Measured crossings of the staged walk against the streamed one with the CPU share off (RTX A6000 3.8K, RTX A4000 1.9K) are matched to within one 256-token step by the real crossing
// rounded DOWN to the grid. The R9700 (HIP, 28.3 GB/s probe but 0.14 ms a streamed expert) is not matched (model 1.1K, measured 1.5K): CUDA builds only.
struct Card {
double blob_mb = 3.19; // mean expert blob of the cache (cache bytes / slots), MB: the A6000 fit's value
double link_gbps = 12.2; // the start-up host-to-device probe, GB/s
int sm = 84; // multiprocessor count
};
inline bool card_known(const Card& c) { return c.blob_mb > 0.0 && c.link_gbps > 0.0 && c.sm > 0; }
inline Constants constants_for(const Card& c) {
Constants k;
const double copy = (c.blob_mb / c.link_gbps) / (3.19 / 12.2);
const double comp = 84.0 / (double) c.sm;
k.c_p *= copy; k.c_s *= copy;
k.a_p *= comp; k.a_s *= comp;
return k;
}
/// The floor for this card with the CPU share off: the largest grid size at which the staged walk still wins (the first size where it does not, one step back), never below 1,024.
inline int64_t floor_for_card(int64_t resident_slots, int64_t total_pairs, const Card& c) {
if (!card_known(c)) return kFloorDefault;
const int64_t first = floor_for(resident_slots, total_pairs, constants_for(c));
return std::max<int64_t>(kFloorDefault, first - kGrid);
}
/// With the share on, the staged walk's limit is the floor times this ratio. Measured share-on break-even / share-off crossing: RTX A4000 2.9K / 1.93K = 1.50, RTX A6000 6.19K / 4.18K = 1.48,
/// R9700 2.5K / 1.5K = 1.67 (not covered by this rule). Against this rule's own floors as the engine printed them (A6000 3,584, A4000 2,048) the same break-evens are 1.73 and 1.42, so no single ratio
/// fits both: 1.6 gives limits 5,632 (A6000, 558 under its break-even: up to 6% left on the table at 5,633) and 3,072 (A4000, 172 over: up to 3% lost at 2,900-3,072); both are far better than the
/// fixed 3,072 on the A6000 (par/RESULTS-SWITCH-POINT.md, 06:12 block).
inline constexpr double kShareRatio = 1.6;
/// The share's limit for a card whose floor moved: floor x kShareRatio on the grid; 0 (the share's own default stays) when the floor is the default.
inline int64_t share_limit_for(int64_t floor) {
if (floor <= kFloorDefault) return 0;
return std::min<int64_t>(2 * kFloorMax, ((int64_t) ((double) floor * kShareRatio) / kGrid) * kGrid);
}
// ---- the class the rule is on for by default ----
// The device facts the engine reads once the card's expert cache is built (src/prefill/prefill.cpp, Prefill::set_card_expert_share).
struct DeviceClass {
bool cuda = false; // a CUDA build (HIP builds: never)
bool discrete = false; // a discrete card, not an integrated / shared-memory GPU
bool single_gpu = false; // the engine runs on one card: no layer split, no second card
bool link_probed = false; // the start-up host-to-device probe ran and gave a rate (the PCIe cost the rule scales with)
int cc_major = 0, cc_minor = 0; // compute capability
};
/// Measured: RTX A6000 (Boston) and RTX A4000 (z440), both 8.6. Every other compute capability (6.0, 7.0, 7.5, 8.0, 8.9, 12.0, 12.1) is outside the class until it is measured.
inline constexpr int kClassCcMajor = 8, kClassCcMinor = 6;
inline bool in_default_class(const DeviceClass& d) {
return d.cuda && d.discrete && d.single_gpu && d.link_probed && d.cc_major == kClassCcMajor && d.cc_minor == kClassCcMinor;
}
/// STRATA_SWITCH_POINT as the engine reads it: -1 unset (or empty), 1 for exactly "1", 0 for any other value.
inline int env_state(const char* v) {
if (v == nullptr || v[0] == '\0') return -1;
return (v[0] == '1' && v[1] == '\0') ? 1 : 0;
}
/// Whether the rule runs: HIP never; STRATA_SWITCH_POINT=0 (or any value but 1) never; =1 on every CUDA card; unset: the class above.
inline bool enabled(const DeviceClass& d, int env) {
if (!d.cuda || env == 0) return false;
return env == 1 || in_default_class(d);
}
} // namespace strata::prefill::switch_point
+148 -12
View File
@@ -35,25 +35,54 @@ namespace strata::spec {
/// The round times of a learning stretch, by context bucket and window size, for a fixed cost table. Keeps up to kKeep
/// samples per (bucket, size) in arrival order.
///
/// Which rounds count (measured, phaseA-tests/par/RESULTS-DRAFT-COSTS.md): on an Apple M5 Max a GPU that has been busy for more than about 7 s runs
/// slower, and unevenly by window size (after 75 s of continuous load 5 rows cost 27 % more and 1 row 14 % more, so 5 rows against 3 rows read 1.38
/// instead of 1.30), while a request that arrives after a pause of half a second runs in the fast state at once; the Radeon 780M shows no such
/// difference (round times within 1 % at any load time). The table is what requests after a pause cost. add() takes the busy age of the round
/// (`busy_age_s`: the seconds since the last pause of kIdleS or more) and keeps the rounds of the first kFreshS seconds ("fresh") apart from the later
/// ones ("late"); the table uses the fresh rounds only when the late ones differ from them by more than kStateTol in some size that has min_n of
/// both (a state effect), and all rounds otherwise (the engine does not need the split on a machine that has no such difference, and more rounds
/// measure the rare sizes better).
class CostLearner {
public:
static constexpr int kMaxT = 16;
static constexpr int kCtxBuckets = 3;
static constexpr int kKeep = 4096;
void add(int bucket, int t, double ms);
static constexpr double kFreshS = 6.0; ///< a round is fresh when the engine has been busy for at most this long (M5 Max: flat to 7.5 s, +3 % at 7.5-10 s)
static constexpr double kIdleS = 0.5; ///< a pause of this length (no request running) starts a new busy run; the caller measures it (M5 Max: 0.5 s restores the fast state)
static constexpr double kStateTol = 0.02; ///< late against fresh round times beyond this in some size = a state effect
static constexpr int kFallbackFactor = 3; ///< with a state effect, a stretch with this many times min_rounds timed rounds of any age ends with the fresh ones ...
static constexpr int kFallbackShare = 5; ///< ... when they are at least 1 / kFallbackShare of min_rounds
/// `busy_age_s` < 0: unknown (counts as fresh).
void add(int bucket, int t, double ms, double busy_age_s = -1.0);
void reset();
int64_t rounds() const { return rounds_; }
int samples(int bucket, int t) const;
/// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket; empty when the bucket has none):
/// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; the other
/// sizes are filled between measured neighbours (linear in the size) or, outside them, by the policy's prior shape.
std::vector<double> table(int bucket, int min_n) const;
int64_t rounds() const { return rounds_; } ///< the fresh rounds
int64_t late_rounds() const { return late_; } ///< the rounds after the engine had been busy for more than kFreshS
int samples(int bucket, int t) const; ///< fresh samples of a size
/// A state effect in `bucket`: some size has at least `min_n` fresh and `min_n` late samples and their trimmed means differ by more than kStateTol.
bool state_effect(int bucket, int min_n) const;
/// Some size of `bucket` has at least `min_n` fresh and `min_n` late samples: state_effect() says something (a fresh-only machine is told apart from one without effect).
bool state_known(int bucket, int min_n) const;
/// The samples of size `t` that table() would use now: the fresh ones when there is a state effect, fresh + late otherwise.
int usable(int bucket, int t, int min_n) const;
/// The table of `bucket` for windows 1..n (n = the largest size seen in that bucket, or `upto` when that is larger; empty when the bucket has none):
/// the trimmed mean (the lowest and highest kTrim share dropped) of each size with at least `min_n` samples; a size with kWeakN to min_n - 1
/// samples counts with its median when that is within [fill, kWeakMax x fill] (a rough measurement, never below the trend); a size in between two measured ones is linear in the size; a size above the
/// measured ones continues the straight line through them with the steeper of the last segment's slope and the slope over all measured sizes
/// (costs grow at least that fast: a fill never falls below the measured trend; one measured size: the policy's prior shape), below them the
/// prior shape; the table never falls from one size to the next.
std::vector<double> table(int bucket, int min_n, int upto = 0) const;
static constexpr int kWeakN = 5; ///< samples from which a size below min_n counts by its median ...
static constexpr double kWeakMax = 1.5; ///< ... when that median is not below the fill and at most this many times it (a stalled handful is not a measurement)
struct Verdict {
bool ready = false; ///< enough rounds, and every bucket with data has a size with min_n samples
bool disturbed = false; ///< the stretch looks disturbed: do not keep a table from it (start learning again)
std::string why; ///< what was seen (for the log)
};
/// Ready after `min_rounds` timed rounds. Disturbed (each check per size with at least 2 x min_n samples):
/// Ready after `min_rounds` usable rounds (fresh and late ones when no bucket has a state effect, the fresh ones when one has), or, with a state
/// effect, after kFallbackFactor x `min_rounds` rounds of any age when at least `min_rounds` / kFallbackShare of them are fresh (one long burst
/// keeps only its first kFreshS seconds). Disturbed (each check per size with at least 2 x min_n samples, on the samples the table uses):
/// (1) its trimmed means of the first and the second half of its samples differ by more than kDriftMax;
/// (2) more than kSpikeMax of its samples are above twice its median;
/// (3) a measured size is cheaper than a measured smaller one by more than kOrderSlack (a round of more rows cannot be cheaper).
@@ -64,23 +93,45 @@ public:
static constexpr double kOrderSlack = 0.10;
private:
std::array<std::array<std::vector<float>, kMaxT + 1>, kCtxBuckets> s_{};
/// The samples of every size of `bucket` that the table uses: the fresh ones, or fresh + late.
std::array<std::vector<float>, kMaxT + 1> sets(int bucket, bool pooled) const;
std::array<std::array<std::vector<float>, kMaxT + 1>, kCtxBuckets> s_{}; // fresh
std::array<std::array<std::vector<float>, kMaxT + 1>, kCtxBuckets> late_s_{}; // late
int64_t rounds_ = 0;
int64_t late_ = 0;
};
/// The per-machine table file of --draft-costs: text, one table per context bucket, valid only for the `key` it was learned under
/// (card, driver, engine, model, drafter and the settings that move a round's cost; the engine builds it).
/// strata-draft-costs 1
/// strata-draft-costs 2 (1: tables learned from every round of a stretch; they are learned again)
/// key <one line>
/// bucket <0..2> <ms of T1>,<ms of T2>,...
/// share <0..1> (optional: the CPU prompt share learned on this machine, src/prefill/prefill.cpp)
/// pcie <0..1> (optional: the decode PCIe share PcieAuto settled on, src/program/generate.cpp)
/// end
/// The real rounds of one size seen since the table was learned: n rounds, their sum in ms (each clamped to [kCalibLo, kCalibHi] x the learned cost), and the
/// rounds themselves (up to kVals): the size's real price is their MEDIAN (a cold or stalled round, a first use, another process, moves a mean but not a median).
/// A file line from before the values ("cal b t n sum" without them) has nv = 0: its price is the mean as before.
/// cal <bucket> <size> <n> <sum> [<ms of round 1> ... <ms of round n>]
struct CalAcc {
static constexpr int kVals = 16;
int n = 0;
double sum = 0.0;
int nv = 0; ///< how many of vals hold a round (== n when every round is kept)
std::array<double, kVals> vals{};
};
struct CostFile {
std::string key;
std::array<std::vector<double>, CostLearner::kCtxBuckets> tables{};
double cpu_share = -1.0; ///< < 0: none stored
double pcie_frac = -1.0; ///< the decode PCIe share PcieAuto settled on; < 0: none stored (a file from before it: refined, then written)
/// Calibration against real requests (see DraftPolicy::start_calibration); a file without these lines has none done.
int reqs = 0; ///< requests that ran while the table was held back (DraftPolicy::kCalibReqs ends the holding)
bool fresh = false; ///< a file with no table yet: the real rounds of the sizes are being collected while live costs decide (DraftPolicy::start_passive); no "bucket" lines
bool state_effect = false; ///< the learning stretch showed a load-time effect: only fresh real rounds are counted
std::array<unsigned, CostLearner::kCtxBuckets> real{}; ///< bit t-1: the cost of size t is a median of real rounds, no longer the learned one
std::array<std::array<CalAcc, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets> cal{}; ///< real rounds collected so far for the sizes not yet replaced
std::array<std::array<double, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets> real_cost{}; ///< the cost of a size marked real (the table lines keep the learned costs)
};
/// false (with `why` for the log) when the file is missing, unreadable, malformed or truncated, or was learned under another key: the caller
/// then learns a new table. Never throws.
@@ -99,11 +150,16 @@ public:
struct Pick {
bool lookup = false;
int t = 1; // window size (1 + drafts)
int pad = 0; // a learning stretch's window longer than the proposal: this many rows past it are filler (the caller fills them)
};
/// `t_mtp`: the MTP's window; `lookup_k`: the lookup proposal's length (0 = none); `match`: its match length.
Pick choose(int t_mtp, int lookup_k, int match) const;
/// pad_cap > 0 (learning, a deterministic proposal): a window may be longer than the proposal, up to pad_cap drafts, its extra rows filler
/// that the verifier will most likely reject; only a learning stretch asks for one (see explore below).
Pick choose(int t_mtp, int lookup_k, int match, int pad_cap = 0) const;
/// After the round: the window it used, the drafts accepted, and the round's time (verify + commit + draft).
void observe(bool lookup, int t, int accepted, int match, double round_ms);
/// The round of a window run for its size's sake (Pick::pad > 0): its time goes to the learner and the cost of that size, its outcome to no statistic.
void observe_forced(int t, double round_ms);
/// Gated proposals, inside one generation: a round's committed outcome only, never its time. `t` is the
/// lookup window chosen before the draws, or the configured MTP window; both are fixed by the history. A
/// lookup window counts as a probe of its size, so a size whose cost is still guessed is tried kProbes times,
@@ -150,6 +206,65 @@ public:
/// Learning a fixed table: every timed round also goes to learner() (raw round time, in its context bucket). Off by default.
void set_learning(bool on) { learning_ = on; }
bool learning() const { return learning_; }
/// Measuring the sizes the policy can pick (learning only): after kExploreAfter timed rounds, a lookup proposal (padded with filler rows up to
/// pad_cap when the caller allows it, else long enough as it is) takes the window of a size that has fewer than kExploreN samples in the
/// current context bucket instead (the smallest such size), at most kExplorePerSize times per size and kExploreBudget times in a stretch. The tokens of a learning stretch were never repeatable
/// (the windows follow the live costs); a window's size can change the batch the verifier runs, and with it the tokens. A size that
/// no proposal ever reaches keeps its filled-in cost (CostLearner::table).
static constexpr int kExploreAfter = 100;
static constexpr int kExploreN = 30;
static constexpr int kExplorePerSize = 40;
static constexpr int kExploreBudget = 300;
int forced_rounds() const { return forced_total_; }
/// The MTP / drafter window of a round that the caller has just decided (`t` rows, at most `cap` rows possible): the size to run instead when
/// a learning stretch wants to time one (rows past the drafts are the caller's filler), else 0. Same limits as for a lookup window. Forced
/// rounds happen only while they count: in the first kFreshS seconds of a busy run, or when the stretch has shown no state effect.
int explore_window(int t, int cap) const;
/// A round with no lookup proposal: the size of a lookup-type window (2..cap rows, every row after the first filler) a learning stretch wants to time, else 0.
int explore_lookup(int cap) const;
/// Start the learning stretch again: the learner's samples and the forced-round counts.
void reset_learning();
/// The largest allowed window size (the table is written up to it).
int top_size() const { return fit(max_t_); }
/// How long the engine has been busy (seconds since its last pause of CostLearner::kIdleS), as the caller measures it, for the round
/// observe() is about to be given; < 0 (the default): unknown. Only the learner reads it.
void set_busy_age(double s) { busy_age_ = s; }
/// Calibration of a fixed table against real requests. The learned costs come from a learning stretch (forced windows with filler rows, a burst of
/// prose), and a real round of the same size can cost a little more (measured on an M5 Max: 2 % on 2, 3 and 5 rows) - enough to flip a close choice
/// between a 4 and a 5 row window (JSON decode 6 % slower than live costs). After a table is fixed, every real round (never a forced one) of a size
/// whose cost is still the learned one is kept (clamped to [kCalibLo, kCalibHi] x the learned cost; only the first kFreshS seconds of a busy run when
/// the machine has a load-time effect), across starts through the table file (CostFile::cal). At kCalibN rounds the size's cost becomes their mean
/// (a result outside [kCalibOkLo, kCalibOkHi] x the learned cost means a disturbed stretch: the rounds are dropped and collected again) and the size
/// is marked real (CostFile::real) for good: no later change, so the windows of a repeated start are the same. A size that real requests never reach
/// keeps its learned cost. real, cal and real_cost come from the file (CostFile).
/// Until every size of the table is real the table is not used: the policy decides with live costs, exactly as without a table (a half-calibrated
/// table priced a JSON request 5 % slower than live costs), and only collects the real rounds; once the last size is calibrated the table
/// (the real costs) decides for good. A size that real requests do not reach (the long lookup sizes of a big GPU) would hold it back for good, so after
/// kCalibReqs requests the table is used anyway: such a size is priced at its learned cost x the mean (real / learned) of the real
/// sizes of 2 or more rows (a size 1 at its learned cost) until it has its own kCalibN rounds. The count is kept in the file (CostFile::reqs).
static constexpr int kCalibN = 16;
static constexpr int kCalibReqs = 100; // requests that may run while the table is held back; then a size not reached keeps a scaled learned cost
static constexpr double kCalibLo = 0.85, kCalibHi = 1.30, kCalibOkLo = 0.86, kCalibOkHi = 1.29;
void start_calibration(bool state_effect, const std::array<unsigned, kCtxBuckets>& real,
const std::array<std::array<CalAcc, kMaxT + 1>, kCtxBuckets>& cal,
const std::array<std::array<double, kMaxT + 1>, kCtxBuckets>& real_cost, int reqs = 0);
/// A machine without a table file builds one from the rounds its live-cost policy runs anyway, with no learning stretch and no forced window: from the
/// first request on the table is held back (live costs decide, exactly as without --draft-costs); only the first kFreshS seconds of a busy run are counted
/// (a machine without a load-time effect just gets fewer samples); a size is real at kCalibN own rounds (the file keeps the sums, so counts survive a
/// restart); when every size up to `n` is real, or after kCalibReqs requests, the table takes over: the real costs, and for a size never reached the live
/// cost at that moment (the policy's own prior when it never measured one); such a size keeps collecting like any size of a table that is in use.
/// cf: the file as read (or an empty one with only the key); n: the table length (top_size()).
void start_passive(const CostFile& cf, int n);
bool passive() const { return passive_; }
bool calibrating() const { return calib_on_; }
bool calib_dirty() const { return calib_dirty_; }
/// While a loaded table still has sizes that are not calibrated (calibrating()), the table is held back: the policy decides with live costs
/// exactly as without a table (fixed() is false), and the real rounds are collected meanwhile. Once the last size is calibrated (at a request's
/// end, calibrate()) the table takes over for good. table_held() is true in that stretch.
bool table_held() const { return held_table_; }
/// At a request's end: replaces the sizes that have kCalibN real rounds and puts the table, the real marks and the rounds collected so far into
/// cf (its other fields stay); report says which sizes changed (empty when none). True when cf should be written (something changed).
bool calibrate(CostFile& cf, std::string& report);
CostLearner& learner() { return learner_; }
const CostLearner& learner() const { return learner_; }
@@ -197,6 +312,27 @@ private:
bool robust_ = false;
bool fixed_ = false; // set_fixed_costs: no round time changes a cost
bool learning_ = false; // set_learning: round times also go to learner_
double busy_age_ = -1.0; // set_busy_age
bool calib_on_ = false, calib_dirty_ = false, calib_fresh_only_ = false;
std::array<int, kCtxBuckets> fixed_n_{}; // the length of each bucket's fixed table
std::array<unsigned, kCtxBuckets> real_{};
std::array<std::array<CalAcc, kMaxT + 1>, kCtxBuckets> cal_{};
std::array<std::array<double, kMaxT + 1>, kCtxBuckets> learned_{}, real_cost_{}; // the table as fixed (learned); the cost of each real size
int reqs_ = 0; // requests that ran while the table was held back (the file keeps it)
bool passive_ = false; // start_passive: no learned table until the take-over (learned_ is zero before it)
void take_over_passive(); // the learned cost of every size not real: the live cost now (a real one keeps its own); then use_table()
bool held_table_ = false; // a table is loaded but not used yet: live costs decide (see table_held())
bool live_saved_ = false;
std::array<std::array<double, kMaxT + 1>, kCtxBuckets> live_cost_{}, live_n_{}; // the live costs as they were when the table was set
void calib_add(int bucket, int t, double ms, double age);
void apply_table();
void hold_table(); // back to the live costs (fixed_ off) for the buckets that have a table
void use_table(); // all sizes calibrated: the table (real costs) decides, fixed_ on
int explore_size(int lookup_k, int pad_cap) const; // the size a learning stretch measures next, 0 = none (choose() counts it)
int explore_next(int reach, int skip) const; // the smallest size 2..reach (not `skip`) that still needs rounds; counts it; 0 = none
bool explore_ok() const; // a forced round counts now (fresh phase, or no state effect)
mutable int forced_total_ = 0; // windows taken for their size's sake, this stretch
mutable std::array<int, kMaxT + 1> forced_{}; // ... by size
CostLearner learner_;
double clamp_sample(int t, double ms) const;
static constexpr int kPBuckets = 8;
@@ -205,7 +341,7 @@ private:
// Gated proposals (observe_committed / defer_cost / apply_costs); all zero or empty on any other path.
std::array<std::array<double, kMaxT + 1>, kCtxBuckets> tried_{}; // lookup windows of that size run with no time yet
std::array<std::array<double, kMaxT + 1>, kCtxBuckets> delayed_n_{}; // of cost_n_: times applied by apply_costs (not new probes)
struct HeldCost { int64_t end; int bucket; int t; double ms; };
struct HeldCost { int64_t end; int bucket; int t; double ms; double age; };
std::vector<HeldCost> held_; // defer_cost, oldest first
};
+11 -1
View File
@@ -4063,7 +4063,17 @@ def learned_profile_args(cfg: dict, args: list[str]) -> list[str]:
return args
DRAFT_COSTS_DEFAULT = True # repeatable output: on by default (owner decision); "draft_costs": false in a config turns it off
DRAFT_COSTS_DEFAULT_PLATFORMS = ("darwin",) # Metal: the taken-over table measured above live costs there (M5 Max: Q2_0 code +2.6 %, chat +2.4 %, JSON +0.2 %; IQ3_S +0.2 / +0.6 / +0.7 %)
def draft_costs_default(platform: str | None = None) -> bool:
"""Repeatable output (owner decision) is the default only where the table was measured at or above live costs: Metal. On CUDA (RTX PRO 5000, IQ3_S: code
-1.5 %, chat -1.5 %, JSON +1.9 % against live costs) and HIP the engine keeps live costs, as an engine started without --draft-costs does. `"draft_costs": true`
in a config turns the table on anywhere (tests and A/Bs), `"draft_costs": false` turns it off."""
return (platform or sys.platform) in DRAFT_COSTS_DEFAULT_PLATFORMS
DRAFT_COSTS_DEFAULT = draft_costs_default() # "draft_costs": true / false in a config overrides it
_engine_texts: dict = {}
+19
View File
@@ -2564,6 +2564,25 @@ class DraftCosts(unittest.TestCase):
self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args)), args)
self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args), str(self.tmp / "missing")), args)
def test_default_is_on_only_on_metal(self):
# the taken-over table measured above live costs on Metal and below them on CUDA (l620, 11-13): live costs stay the default there and on HIP
self.assertTrue(server.draft_costs_default("darwin"))
for platform in ("linux", "win32", "cygwin", "freebsd14", "android"):
self.assertFalse(server.draft_costs_default(platform), platform)
self.assertEqual(server.DRAFT_COSTS_DEFAULT, sys.platform == "darwin")
def test_table_off_by_default_gives_no_flag_unless_the_config_asks(self):
args = ["--native", "x", "--spec", "6"]
new = self.tmp / "new-engine"
new.write_bytes(b"\x7fELF strata --spec --serve --draft-costs --draft-costs-key")
with mock.patch.object(server, "DRAFT_COSTS_DEFAULT", False): # CUDA / HIP class
self.assertEqual(server.draft_costs_args({"model_name": "m"}, list(args), str(new)), args)
self.assertIn("--draft-costs", server.draft_costs_args({"model_name": "m", "draft_costs": True}, list(args), str(new))) # the test switch
self.assertEqual(server.draft_costs_args({"model_name": "m", "draft_costs": False}, list(args), str(new)), args)
with mock.patch.object(server, "DRAFT_COSTS_DEFAULT", True): # Metal class
self.assertIn("--draft-costs", server.draft_costs_args({"model_name": "m"}, list(args), str(new)))
self.assertEqual(server.draft_costs_args({"model_name": "m", "draft_costs": False}, list(args), str(new)), args)
def test_on_gives_a_file_in_the_redirected_folder(self):
args = ["--native", "x", "--spec", "6"]
got = server.draft_costs_args({"model_name": "qwen3.8-flash-next-iq3_s", "draft_costs": True}, list(args))
+113 -14
View File
@@ -13,6 +13,7 @@
#include "strata/prefill/fp16_rows_rule.hpp"
#include "strata/prefill/own_only_line.hpp"
#include "strata/prefill/stream_floor_rule.hpp"
#include "strata/prefill/switch_point_rule.hpp"
#include "strata/kernels/gfx_arch.hpp"
#include "strata/prefill/fewrows.hpp"
#include "strata/prefill/gp100_prompt_default.hpp"
@@ -204,7 +205,10 @@ std::vector<std::string>& own_only_switches() {
const bool g_own_only_defaults = [] {
strata::kernels::native_expert_i8_set_mmq_free(); // the int8 expert kernels are the default prompt-expert kernels here (i8_expert_rule.hpp, i8_switch_effective)
#if defined(STRATA_USE_HIP) || defined(__HIPCC__)
static const char* const kOn[] = {"STRATA_PF_FUSED", "STRATA_PF_FUSED_Q50", "STRATA_PF_FUSED_KQ"};
// (gfx12 only: every one of these is read behind the device's own gfx12 check, moe_fused_iq.cu q8d_hip_requested .. q6k_hip_requested, so a gfx11
// card keeps the rules it has: its layers of those formats take the FP16 path here as before)
static const char* const kOn[] = {"STRATA_PF_FUSED", "STRATA_PF_FUSED_Q50", "STRATA_PF_FUSED_Q8D", "STRATA_PF_FUSED_Q8GU",
"STRATA_PF_FUSED_Q6K", "STRATA_PF_FUSED_KQ", "STRATA_PF_FUSED_TQ"};
#else
// (not STRATA_PF_FUSED_Q2N: the GGUF Q2_0 / Q2_0 pair on sm_80+ misses its worst-row bound against MMQ at 20K / 32K tokens on sm_86,
// not explained yet; those layers take the FP16 path here unless the user sets it)
@@ -416,6 +420,44 @@ inline bool share_keeps_own_kernels(int64_t rows_cpu) {
#endif
return strata::prefill::share_layer_keeps_own_kernels(own_only, env, rows_cpu);
}
// STRATA_SWITCH_POINT (CUDA builds only): the floor of a card that streams part of the experts comes from switch_point_rule.hpp's cost estimate. ON BY DEFAULT for the class
// in_default_class() names (NVIDIA discrete card on PCIe, one GPU, link probe ran, compute capability 8.6); STRATA_SWITCH_POINT=0 is the way back, =1 asks for it on any other CUDA card.
// The card's counts arrive from Prefill::set_card_expert_share (the cache's slots and layers x experts, known before the first lend); until then the default answers.
std::atomic<int64_t> g_sp_resident{-1}, g_sp_total{0};
double g_sp_blob_mb = 0.0, g_sp_link_gbps = 0.0; // the cache's mean blob (MB) and the start-up probe (GB/s), from Prefill::set_card_expert_share
int g_sp_sm = 0; // the card's multiprocessor count
int g_sp_cc_major = 0, g_sp_cc_minor = 0; // the card's compute capability
bool g_sp_integrated = true; // not known as discrete until the card answered
// STRATA_SWITCH_POINT as set: -1 unset, 1 for "1", 0 for any other value (the way back)
inline int switch_point_env() {
static const int e = [] {
const char* v = std::getenv("STRATA_SWITCH_POINT");
return v != nullptr && v[0] != '\0' ? strata::prefill::switch_point::env_state(v) : -1;
}();
return e;
}
// the card's counts have arrived (set_card_expert_share ran: a single card, no batch slots)
inline bool switch_point_known() { return g_sp_resident.load(std::memory_order_acquire) >= 0; }
inline bool switch_point_on() {
#if defined(STRATA_USE_HIP) || defined(__HIPCC__) || defined(STRATA_HIP_GFX906)
return false; // measured on CUDA only
#else
if (!switch_point_known()) return false;
strata::prefill::switch_point::DeviceClass d;
d.cuda = true;
d.discrete = !g_sp_integrated;
d.single_gpu = true; // set_card_expert_share is called from the single-card, no-batch paths only
d.link_probed = g_sp_link_gbps > 0.0;
d.cc_major = g_sp_cc_major; d.cc_minor = g_sp_cc_minor;
return strata::prefill::switch_point::enabled(d, switch_point_env());
#endif
}
// the card as the rule scales it; a field not set gives card_known() == false and the default floor
inline strata::prefill::switch_point::Card sp_card() {
strata::prefill::switch_point::Card c;
c.blob_mb = g_sp_blob_mb; c.link_gbps = g_sp_link_gbps; c.sm = g_sp_sm;
return c;
}
// The floor without STRATA_PREFILL_STREAM_MIN and the CPU share: stream_floor_rule.hpp's answer, decided once when the expert layout is known (a call before that gets the default and is not cached).
inline int64_t default_stream_floor() {
static std::atomic<int64_t> cached{-1};
@@ -424,7 +466,22 @@ inline int64_t default_stream_floor() {
const auto& lay = strata::kernels::cpu::expert_layout();
if (!lay.native || lay.fmt.empty()) return strata::prefill::kStreamFloorDefault;
const bool cls = stream_floor_class_measured();
const int64_t v = strata::prefill::stream_floor_default(cls, cls && layers_all_fused_only(), staged_fo_on());
int64_t v = strata::prefill::stream_floor_default(cls, cls && layers_all_fused_only(), staged_fo_on());
#if !defined(STRATA_USE_HIP) && !defined(__HIPCC__) && !defined(STRATA_HIP_GFX906)
// the card's counts are not known yet (set_card_expert_share has not run) and the rule is not switched off: the default, not cached
if (v == strata::prefill::kStreamFloorDefault && switch_point_env() != 0 && !switch_point_known()) return v;
#endif
if (v == strata::prefill::kStreamFloorDefault && switch_point_on()) {
const int64_t res = g_sp_resident.load(std::memory_order_acquire), tot = g_sp_total.load(std::memory_order_acquire);
const auto card = sp_card();
if (!strata::prefill::switch_point::card_known(card)) return v; // the link or the card is not known: the default, not cached
v = strata::prefill::switch_point::floor_for_card(res, tot, card);
if (v != strata::prefill::kStreamFloorDefault)
std::fprintf(stderr, "prefill: prompt chunks of %lld tokens or more stream every expert the card does not hold (%lld of %lld experts resident; %.2f MB experts, %.1f GB/s link, %d SMs); a shorter chunk stages only the routed ones. STRATA_SWITCH_POINT=0 keeps the fixed 1,024.\n",
(long long) v, (long long) res, (long long) tot, card.blob_mb, card.link_gbps, card.sm);
cached.store(v, std::memory_order_release);
return v;
}
cached.store(v, std::memory_order_release);
if (v != strata::prefill::kStreamFloorDefault)
std::fprintf(stderr, "prefill: prompt pieces of %lld tokens or more read on the fused kernels, as long prompts do. STRATA_PREFILL_STREAM_MIN=1024 keeps the old rule.\n", (long long) v);
@@ -1414,7 +1471,8 @@ struct Prefill::Impl {
// this layout's GU, H and Xq are the fused path's (moe_bufs' `fused`), so a layer that runs MMQ or the FP16 path may
// only write stream_all_min() - 1 of its rows into them; fused_layout() keeps the two in step (#583, #954)
bool fused_bufs = false;
std::unique_ptr<Stager> stager; // the unpinned experts' host copies (step 4)
int64_t tail_req = -1; // the MMQ tail (tokens) the fused layout was carved for: -1 = stream_all_min() - 1 (start-up, the way back); relayout's `tail`
std::unique_ptr<Stager> stager; // the unpinned experts' host copies (step 4)
std::unique_ptr<PrefillWarmer> warmer; // STRATA_PREFILL_WARM=1: the per-layer walk's page warming
std::vector<std::vector<int64_t>> warm_prev; // per layer: the file-tier experts of the previous chunk
cudaEvent_t copied[RING_MAX] = {}, used[RING_MAX] = {};
@@ -1984,21 +2042,24 @@ bool fused_layout(size_t T, bool src) {
// The MoE buffers MMQ and the fused path share: GU and H in floats, Xq and Hq in bytes. Without `fused` (the
// default): MMQ's, for T tokens.
struct MoeBufs { size_t gu, h, xq, hq; };
MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused) {
// `tail` (>= 0, fused only): the MMQ rows a chunk below the floor may bring, in tokens (a lent layout sized for its
// segment's own last chunk, loan_rules.hpp); -1: stream_all_min() - 1, as the start-up layout.
MoeBufs moe_bufs(size_t T, int64_t n_expert, bool fused, int64_t tail = -1) {
if (!fused && pf_group_scratch()) { // GU, H, Hq: one group's rows (Xq keeps every row: gate/up reads the layer's)
const size_t gc = (size_t) group_cap_rows(T, n_expert);
return {gc * kFF2, gc * kFF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) gc, kFF)};
}
if (!fused) return {T * K * kFF2, T * K * kFF, mmq::q8_bytes((int64_t) (T * K), N), mmq::q8_bytes((int64_t) (T * K), kFF)};
const size_t ts = (size_t) std::min<int64_t>((int64_t) T, stream_all_min() - 1); // MMQ's last small chunk
const int64_t tail_tokens = tail >= 0 ? std::min<int64_t>(tail, std::max<int64_t>(stream_all_min() - 1, 0)) : stream_all_min() - 1;
const size_t ts = (size_t) std::min<int64_t>((int64_t) T, tail_tokens); // MMQ's last small chunk
return {std::max<size_t>(ts * K * kFF2, (fused::group_bytes((int64_t) (T * K), (int) n_expert) + 3) / 4),
std::max<size_t>(ts * K * kFF, (fused::act_bytes((int64_t) (T * K), kFF) + 3) / 4),
std::max(mmq::q8_bytes((int64_t) (ts * K), N), fused::act_bytes((int64_t) T, N)),
mmq::q8_bytes((int64_t) (ts * K), kFF)};
}
uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused) {
uint64_t moe_set_bytes(size_t T, int64_t n_expert, bool fused, int64_t tail = -1) {
const MmqPlan& mp = mmq_plan();
const MoeBufs mb = moe_bufs(T, n_expert, fused);
const MoeBufs mb = moe_bufs(T, n_expert, fused, tail);
Alloc a; a.count_only = true; bool ok = true;
a.take<float>(T * n_expert, ok); a.take<float>(T * K, ok); a.take<int32_t>(T * K, ok); a.take<int32_t>(T * K, ok);
a.take<int32_t>(T * K, ok);
@@ -2362,9 +2423,9 @@ bool Prefill::carve(size_t T, void* alloc) {
// one region for the attention half's and the MoE half's scratch (see gdn_set_bytes)
const bool fz = fused_layout(T, m.src != nullptr);
m.fused_bufs = fz;
const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz);
const MoeBufs mb = moe_bufs(T, m.g->n_expert, fz, m.tail_req);
const uint64_t region = std::max({gdn_set_bytes(T), qsa_set_bytes(T, m.cap, m.max_blocks, m.sel_batch,
m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz),
m.attn_batch, s), moe_set_bytes(T, m.g->n_expert, fz, m.tail_req),
hcr ? hc_set_bytes(T, m.f16_io) : (uint64_t) 0});
uint8_t* base = o.take<uint8_t>((size_t) region, ok);
// No region: the sub-allocators below would each cudaMalloc their share (hundreds of MiB) on a card that has just
@@ -2495,8 +2556,9 @@ bool Prefill::carve(size_t T, void* alloc) {
return ok;
}
bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err) {
bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::string& err, int64_t tail) {
Impl& m = *impl_;
m.tail_req = tail; // read by carve (a failure leaves the layout unusable as before; the caller ends the request)
if (m.borrow_spill) {
err = "prefill: a hybrid borrowed/owned layout cannot be changed between requests";
return false;
@@ -2534,6 +2596,14 @@ bool Prefill::relayout(int64_t chunk, void* borrow, uint64_t borrow_bytes, std::
}
int64_t Prefill::chunk() const { return impl_->T; }
int64_t Prefill::layout_tail() const { return impl_->tail_req; }
int64_t Prefill::tail_room() const {
const Impl& m = *impl_;
if (!m.fused_bufs) return std::numeric_limits<int64_t>::max(); // MMQ-sized buffers: any chunk the layout has
const int64_t d = std::max<int64_t>(stream_all_min() - 1, 0);
return m.tail_req >= 0 ? std::min(m.tail_req, d) : d;
}
bool Prefill::tail_matters(int64_t chunk, bool src) { return chunk > 0 && fused_layout((size_t) chunk, src); }
void Prefill::set_ring_room_active(bool on) {
ring_room_active_ = on;
@@ -3087,6 +3157,21 @@ int64_t Prefill::short_read_default(int64_t base) {
const bool cls = stream_floor_class_measured();
return strata::prefill::short_read_default(base, cls, cls && layers_all_fused_only(), staged_fo_on());
}
void Prefill::set_card_expert_share(int64_t resident_slots, int64_t total_pairs, double blob_mb, double link_gbps) {
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
int dev = 0;
cudaDeviceProp prop;
const bool got = cudaGetDevice(&dev) == cudaSuccess && cudaGetDeviceProperties(&prop, dev) == cudaSuccess;
g_sp_sm = got ? prop.multiProcessorCount : 0;
g_sp_cc_major = got ? prop.major : 0;
g_sp_cc_minor = got ? prop.minor : 0;
g_sp_integrated = got ? prop.integrated != 0 : true;
#endif
g_sp_blob_mb = blob_mb;
g_sp_link_gbps = link_gbps;
g_sp_total.store(total_pairs, std::memory_order_release);
g_sp_resident.store(resident_slots, std::memory_order_release);
}
// --prefill-pipe (opt-in; STRATA_PREFILL_PIPE): a layer split reads a prompt as a pipeline - stage s reads chunk c while
// stage s+1 reads chunk c-1. A stage-chunk costs its layers x (b + a C): a fixed part per chunk (b: the pass over the
@@ -3187,8 +3272,8 @@ int64_t Prefill::chain_experts_streamed() const {
return sum;
}
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src) {
return bytes_needed_impl(g, ss, chunk, false, src);
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src, int64_t tail) {
return bytes_needed_impl(g, ss, chunk, false, src, tail);
}
// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB
@@ -3199,7 +3284,7 @@ uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::S
}
uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
bool owned_pages, bool src) {
bool owned_pages, bool src, int64_t tail) {
// the same allocation sequence as `init` (`carve`), counted - with the MoE layout `carve` picks for the same source
const size_t T = (size_t) chunk;
bool ok = true;
@@ -3234,7 +3319,7 @@ uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::Se
const int64_t cap = strata::kernels::qsa_selection_width(strata::kernels::kTopkMaxCells, s);
const int64_t max_blocks = ss.qsa_states[ss.qsa_primary()].max_cells / s.idx_block + 2;
o.take<uint8_t>((size_t) std::max({gdn_set_bytes(T), qsa_set_bytes(T, cap, max_blocks, 256, 32, s),
moe_set_bytes(T, g.n_expert, fused_layout(T, src)),
moe_set_bytes(T, g.n_expert, fused_layout(T, src), tail),
hcr ? hc_set_bytes(T, f16_io) : (uint64_t) 0}), ok);
for (int i = 0; i < DQ; ++i) { o.take<uint16_t>(kFF2 * kEmbd, ok); o.take<uint16_t>(kEmbd * kFF, ok); }
if (mmq_plan().any) {
@@ -3296,6 +3381,12 @@ void Prefill::arm_cpu_share(bool applies, bool by_default) {
#if !defined(STRATA_USE_HIP) && !defined(STRATA_HIP_GFX906)
if (applies && by_default && cpu_share_explicit() == -2.0 && !g_share_default) {
g_share_default = true;
if (switch_point_on() && g_sp_resident.load(std::memory_order_acquire) >= 0 && strata::prefill::switch_point::card_known(sp_card())) {
// STRATA_SWITCH_POINT (on by default for its class, 0 = off): the share's limit scales with the card's own floor (floor x kShareRatio), not the fixed 3,072
const int64_t lim = strata::prefill::switch_point::share_limit_for(strata::prefill::switch_point::floor_for_card(
g_sp_resident.load(std::memory_order_acquire), g_sp_total.load(std::memory_order_acquire), sp_card()));
if (lim > 0) g_share_limit_arch = lim;
}
std::fprintf(stderr, "prefill: the CPU share is ON by default for prompt chunks up to %lld tokens (the idle CPU "
"takes some of the experts the GPU would stream; answers can differ slightly from 0.1.40.3, "
"mean KL ~0.004 below 1024 tokens, ~0.011 at 1-3K). STRATA_PREFILL_CPU_SHARE=0 turns it off, "
@@ -3812,6 +3903,14 @@ bool Prefill::run_impl(const int64_t* tokens, int64_t n, int64_t pos0, std::stri
std::fflush(stderr);
}
const int64_t T = std::min(C, n - c0), p0 = pos0 + c0;
// A fused layout carved with a tail (relayout's `tail`, loan_rules.hpp) holds MMQ's rows for that many tokens of a
// chunk below the stream floor: a longer one would overrun GU / H / Xq / Hq (an illegal access, or a hang). The
// lend sizes the tail from the segment, so this is the clean error for anything that drifts from it.
if (m.fused_bufs && T < stream_all_min() && T > tail_room()) {
err = "prefill: a chunk of " + std::to_string((long long) T) + " tokens below the stream floor does not fit the fused layout's tail of " +
std::to_string((long long) tail_room()) + " tokens";
return false;
}
// STRATA_KVA: this chunk is approximated in the layers at and after the split when its last position is
// before the request's full-computation suffix; a chunk in the suffix runs the ordinary path everywhere.
const bool kva_approx = kva_run && (p0 + T <= kva_frontier);
+233 -28
View File
@@ -10165,6 +10165,13 @@ int main(int argc, char** argv) {
// tokens (RTX A6000). Applies to every piece within 255 tokens under the floor (769-1,023 at 1,024; 2,817-3,071 under the CPU
// share's 3,072). STRATA_PREFILL_LOAN_WALK=0 keeps the rounded chunk.
static const bool loan_by_walk = [] { const char* e = std::getenv("STRATA_PREFILL_LOAN_WALK"); return !(e != nullptr && e[0] == '0'); }();
// The lent fused layout's MMQ tail is sized from the segment's own last chunk, not from the stream floor (a floor of 3,584
// against 1,024 costs ~92 expert slots on an RTX A6000, streamed again by every chunk above the floor). One GPU, no peer, no
// --batch above one slot, no head alias; a layer split keeps the floor's tail. STRATA_PREFILL_TAIL_LOAN=0 keeps today's size.
static const bool tail_loan_on = [] { const char* e = std::getenv("STRATA_PREFILL_TAIL_LOAN"); return !(e != nullptr && e[0] == '0'); }();
// STRATA_DBG_TAIL_NOREUSE=1 (a test of the backstop): a loan is reused by chunk alone, as before the tail rule - a later short segment then
// overruns the tail and the chunk check in Prefill::run_impl must end the request with its error
static const bool dbg_tail_noreuse = [] { const char* e = std::getenv("STRATA_DBG_TAIL_NOREUSE"); return e != nullptr && e[0] == '1'; }();
auto loan_chunk = [&](int64_t tokens, int64_t chunk) -> int64_t {
return loan_by_walk ? strata::prefill::loan_rules::walk_chunk(tokens, chunk, strata::prefill::Prefill::stream_all_min_tokens())
: chunk;
@@ -11139,6 +11146,8 @@ int main(int argc, char** argv) {
"nothing to take, so it is not armed by default (STRATA_PREFILL_CPU_SHARE=auto forces it)\n",
(long long) xcache.slots(), (long long) (g.n_layers * g.n_expert));
if (share_pool && stages.empty() && !multi_gpu && share_has_work && !share_default_ok()) share_has_work = false; // H11
if (stages.empty() && !multi_gpu && o.batch <= 0) // STRATA_SWITCH_POINT: one card, no batch slots; before any bytes_needed, like the share
strata::prefill::Prefill::set_card_expert_share((int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert), xcache.slots() > 0 ? (double) xcache.bytes() / (double) xcache.slots() / 1e6 : 0.0, o.pcie_probe_gbps);
strata::prefill::Prefill::arm_cpu_share(share_pool, share_pool && stages.empty() && !multi_gpu && share_has_work);
void* borrow = nullptr;
uint64_t borrow_bytes = 0;
@@ -11171,9 +11180,10 @@ int main(int argc, char** argv) {
(uint64_t) strata::kernels::cpu::expert_layout().max_blob, need);
};
auto on_part_device = [](int dev) { return strata::core::OnDevice(dev); };
auto part_slots = [&](const PfPart& p, int64_t c) -> int64_t {
// `tail` (>= 0): the lent fused layout's MMQ tail in tokens (loan_rules.hpp); -1: today's floor - 1
auto part_slots = [&](const PfPart& p, int64_t c, int64_t tail = -1) -> int64_t {
return cache_slots_for(*p.cache, strata::program::split_part_figure(on_part_device, p.dev, [&] {
return strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr);
return strata::prefill::Prefill::bytes_needed(g, *p.ses, c, srcp != nullptr, tail);
}));
};
auto part_bytes = [&](const PfPart& p, int32_t first) -> uint64_t {
@@ -14670,6 +14680,43 @@ int main(int argc, char** argv) {
strata::core::pin_reserve_release_hard(); // the load is over: nothing else needs the headroom
strata::core::kfd_settle::settle_before_ready(); // integrated gfx11 under Linux: until the kernel has stopped moving the registered arena (nothing elsewhere)
strata::core::manifest::instance().write("ready"); // STRATA_MANIFEST (a no-op unless it is set)
// ---- window warm-up (lane DRAFT-COSTS): the first run of a window width builds its graph / pipeline (srv118 CUDA: a capture; Metal: the first execution), so a
// width that the policy first picks inside a long request pays it there (M5 Max, IQ3_S: +60 ms on the first five-row lookup round, in the timed code request in 5 of 8 launches
// with a table, because the release and the live costs happen to pay it in request 1). One dummy window per allowed width 1..S, once, before the first request is read; it
// changes nothing a request can see: the windows write K/V cells 0..T-1 and the recurrent state of the session, and session_zero() below zeroes the session exactly as a request
// that reuses nothing does (the engine's state after session_init); no checkpoint, conversation entry, RNG draw, policy sample or statistic is touched (the policy's observe_*
// calls live in the decode loop); the expert cache may page in what the dummy token routes to (speed only). STRATA_WINDOW_WARM=0: off (research switch).
{
static const bool warm_off = [] { const char* v = std::getenv("STRATA_WINDOW_WARM"); return v != nullptr && v[0] == '0'; }();
if (!warm_off && o.spec >= 2 && n_stages == 1 && o.batch <= 0) {
const Clock::time_point w0 = Clock::now();
std::vector<int32_t> wtok((size_t) o.spec, 1), wout((size_t) o.spec + 1, 0);
std::string werr, wlist;
bool wok = true;
for (int t = 1; t <= o.spec && wok; ++t) {
if (!((lookup_size_mask(o) >> t) & 1u)) continue;
bool no_vram = false;
if (!ver.prepare(t, no_vram, werr)) { if (no_vram) continue; wok = false; break; } // CUDA / HIP: the graph now (a size that finds no VRAM is left to the runtime rule); Metal: nothing to do
const Clock::time_point t0 = Clock::now();
drive.d.layers = 0;
drive.d.experts = 0;
drive.d.failed = false;
wok = ver.run(t, wtok.data(), 0, win_pool_fn, win_pool_user, wout.data(), werr) && !drive.d.failed;
char wb[48];
std::snprintf(wb, sizeof wb, "%s%d:%.0f", wlist.empty() ? "" : " ", t,
std::chrono::duration<double, std::milli>(Clock::now() - t0).count());
wlist += wb;
}
strata::core::session_zero(ss, g, nullptr, main_cs);
cudaStreamSynchronize(main_stream);
drive.d.layers = 0;
drive.d.experts = 0;
drive.d.failed = false;
std::fprintf(stderr, "strata serve: window warm-up: ms per width %s, total %.0f ms%s%s\n", wlist.c_str(),
std::chrono::duration<double, std::milli>(Clock::now() - w0).count(), wok ? "" : "; a window failed: ",
wok ? "" : werr.c_str());
}
}
g_gpu_pause_idle.idle(gpu_pause_now()); // AMD on Linux: the gap before the first request starts here (the start-up's own pauses are not a "between")
std::printf("READY %lld stop hold holdb\n", (long long) o.max_context); // "stop": this engine honours STOP; "hold": GEN hold=N:ID; "holdb": the --batch slots end at the hold too (BDONE hold)
std::fflush(stdout);
@@ -14711,31 +14758,74 @@ int main(int argc, char** argv) {
constexpr int kDraftCostMinN = 20; // a window size needs this many rounds to be measured (fewer: filled in)
std::string dc_key;
bool dc_learning = false;
bool dc_calib = false; // a table is used and its sizes are being calibrated against real rounds (DraftPolicy::start_calibration)
// how long the engine has been busy: the learner keeps only the rounds of the first seconds of a busy run (CostLearner::kFreshS); a busy run
// starts at a request that begins CostLearner::kIdleS or more after the last one ended (the GPU runs slower and steeper after a long load)
Clock::time_point dc_busy_since = Clock::now(), dc_last_end = Clock::now();
bool dc_seen_request = false;
bool dc_pcie_pending = false; // a loaded table without a PCIe share: written into it once PcieAuto has settled
strata::spec::CostFile dc_file; // that table, as loaded
bool dc_shares_due = false; // the table is held back (live costs): its stored CPU prompt share / PCIe share are fixed when it takes over
auto dc_apply_shares = [&](const strata::spec::CostFile& cf) {
if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share);
if (dc_pcie_ok && cf.pcie_frac >= 0.0) fix_pcie_share(cf.pcie_frac);
};
if (!o.draft_costs.empty() && !policy.fixed()) {
dc_key = draft_costs_key(argc, argv, o.draft_costs_key, spec_cost);
strata::spec::CostFile cf;
std::string why;
if (strata::spec::read_cost_file(o.draft_costs, dc_key, cf, why)) {
// a machine with no table (a new engine, driver, model or setting discards the file) builds one from the rounds of its normal requests, with live
// costs deciding meanwhile: no learning stretch. The old one-start stretch (forced filler windows, a burst of requests) runs only for the test
// harnesses that set STRATA_DRAFT_COSTS_LEARN=1; the server and the launcher never do.
const char* dc_lv = std::getenv("STRATA_DRAFT_COSTS_LEARN");
const bool dc_force_learn = dc_lv != nullptr && dc_lv[0] == '1';
const bool dc_read_ok = strata::spec::read_cost_file(o.draft_costs, dc_key, cf, why);
if (dc_read_ok && cf.fresh) { // a file of the passive stretch: the real rounds collected so far
dc_file = cf;
policy.start_passive(cf, policy.top_size());
dc_calib = true;
std::fprintf(stderr, "strata serve: draft costs: this machine's table is being built from real requests (%s; %d requests so far): live costs "
"decide until every window size has %d own rounds or %d requests have run\n",
o.draft_costs.c_str(), cf.reqs, strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs);
} else if (!dc_read_ok && !dc_force_learn) { // no table yet
cf.key = dc_key;
cf.fresh = true;
dc_file = cf;
policy.start_passive(cf, policy.top_size());
dc_calib = true;
std::fprintf(stderr, "strata serve: draft costs: no table for this machine yet (%s: %s): it is built from real requests, live costs decide "
"until every window size has %d own rounds or %d requests have run\n",
o.draft_costs.c_str(), why.c_str(), strata::spec::DraftPolicy::kCalibN, strata::spec::DraftPolicy::kCalibReqs);
} else if (dc_read_ok) {
std::string sizes;
for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k)
if (!cf.tables[(size_t) k].empty()) {
policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k);
sizes += (sizes.empty() ? "" : ", ") + std::to_string(cf.tables[(size_t) k].size());
}
if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share);
dc_file = cf;
policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs);
dc_calib = policy.calibrating();
if (policy.table_held()) dc_shares_due = true; // a held table leaves the shares live too: they are fixed when the table takes over
else dc_apply_shares(cf);
std::string extra = cf.cpu_share >= 0.0 ? "; CPU prompt share " + std::to_string(cf.cpu_share).substr(0, 4) : "";
if (dc_pcie_ok && cf.pcie_frac >= 0.0) { // PcieAuto's settled share: fixed, no refinement in this run
fix_pcie_share(cf.pcie_frac);
extra += "; PCIe share " + std::to_string(cf.pcie_frac).substr(0, 4);
} else if (dc_pcie_ok) { // a file from before the stored PCIe share: refined as before, then written into the file
dc_pcie_pending = true;
dc_file = cf;
extra += "; PCIe share: refined in this run, then stored";
}
std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request "
"gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str());
if (dc_calib && policy.table_held())
std::fprintf(stderr, "strata serve: draft costs: this machine's table is loaded (%s; window sizes %s%s), not used yet: the "
"windows follow live costs until every size is calibrated against real requests (or 100 requests have run)\n",
o.draft_costs.c_str(), sizes.c_str(), extra.c_str());
else if (dc_calib)
std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s); sizes real requests have not "
"reached yet keep collecting rounds and change the table once when they have their own\n",
o.draft_costs.c_str(), sizes.c_str(), extra.c_str());
else
std::fprintf(stderr, "strata serve: draft costs: this machine's table is used (%s; window sizes %s%s): the same request "
"gives the same tokens on every start\n", o.draft_costs.c_str(), sizes.c_str(), extra.c_str());
} else {
policy.set_learning(true);
dc_learning = true;
@@ -16436,7 +16526,14 @@ int main(int argc, char** argv) {
continue;
}
const bool geni = line.rfind("GENI ", 0) == 0;
if (geni || line.rfind("GEN ", 0) == 0) refresh_file_tier();
if (geni || line.rfind("GEN ", 0) == 0) {
refresh_file_tier();
if (dc_learning || dc_calib) { // the request's arrival, before its prompt is read: a pause since the last one ended starts a new busy run
const Clock::time_point dc_now = Clock::now();
if (!dc_seen_request || std::chrono::duration<double>(dc_now - dc_last_end).count() >= strata::spec::CostLearner::kIdleS) dc_busy_since = dc_now;
dc_seen_request = true;
}
}
if (!geni && line.rfind("GEN ", 0) != 0) {
std::printf("ERR expected: GEN <max_new> <id,id,...> or GENI <max_new> <file> <id,id,...>\n");
continue;
@@ -17802,10 +17899,18 @@ int main(int argc, char** argv) {
return false;
}
bool any = false;
namespace lr = strata::prefill::loan_rules;
using strata::prefill::Prefill;
const int64_t floor_t = Prefill::stream_all_min_tokens();
const bool tail_ok = tail_loan_on && pf_parts.size() == 1 && stages.empty() && !multi_gpu && !peer.valid() &&
!o.prefill_head_alias && o.batch <= 1;
for (PfPart& p : pf_parts) {
if (p.first < 0) continue;
if (!p.lent.empty()) {
if (want <= p.lent_chunk) continue; // its current loan already covers this
// its current loan already covers this: the chunk, and (a fused layout) the tail the segment's last
// chunk needs when it is read in the loan's own chunks
if (tail_ok && !dbg_tail_noreuse ? lr::reuse_ok(want, tokens, p.lent_chunk, p.sp->tail_room(), floor_t)
: want <= p.lent_chunk) continue;
// ONLY this participant's loan goes back: `refill` would return the other participants'
// loans too, and their buffers are still laid out in their caches - marking those slots
// resident again would hand the next window a prompt buffer in place of an expert
@@ -17813,6 +17918,7 @@ int main(int argc, char** argv) {
}
const strata::core::OnDevice on(p.dev);
int64_t want_p = want;
int64_t tail_p = -1; // the tail the layout is laid out with (-1: floor - 1)
int32_t first = p.first_now;
// --prefill-head-alias: the loan laid out at start (slot 1 on) is kept; a hybrid layout cannot relayout.
// (STRATA_MTP_ROOM_MIN's room is not one: its slots are the drafter's own bytes, so a roomed
@@ -17823,10 +17929,18 @@ int main(int argc, char** argv) {
// a request's smaller chunk can need MORE slots than the auto chunk's region (p.first) holds. The
// loan starts where the chunk itself needs it (the 128-slot floor aside); a chunk that cannot be
// lent even then is halved until it can, instead of ending the engine.
int64_t need_p = part_slots(p, want_p);
// the tail this layout is carved with for chunks of `w` (-1: today's floor - 1): grow-only while the layout's
// chunk stays (loan_rules::next_tail), the need of the moment otherwise
auto tail_for = [&](int64_t w) -> int64_t {
if (!tail_ok || !Prefill::tail_matters(w, srcp != nullptr)) return -1;
return lr::next_tail(p.sp->chunk(), p.sp->layout_tail(), w, lr::segment_tail(tokens, w, floor_t), floor_t);
};
tail_p = tail_for(want_p);
int64_t need_p = part_slots(p, want_p, tail_p);
while ((need_p <= 0 || need_p + g_lend_keep > p.cache->slots()) && want_p > 256) {
want_p = std::max<int64_t>(256, want_p / 2 / 256 * 256);
need_p = part_slots(p, want_p);
tail_p = tail_for(want_p);
need_p = part_slots(p, want_p, tail_p);
}
if (need_p <= 0 || need_p + g_lend_keep > p.cache->slots()) {
e = "prefill: no chunk of this request fits the slots that can be lent (#2090)";
@@ -17842,9 +17956,23 @@ int main(int argc, char** argv) {
(long long) need_p, (long long) (p.cache->slots() - p.first));
first = (int32_t) (p.cache->slots() - need_p);
}
if (want_p != p.sp->chunk() || first != p.first_now) {
if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e)) return false;
if (want_p != p.sp->chunk() || first != p.first_now || (tail_p >= 0 && tail_p != p.sp->layout_tail())) {
const auto t_rl = Clock::now();
if (!p.sp->relayout(want_p, p.cache->device_slot(first), part_bytes(p, first), e, tail_p)) return false;
p.first_now = first;
if (tail_p >= 0) {
static bool said = false;
if (!said) {
said = true;
std::fprintf(stderr, "strata serve: the lent prompt buffers are sized for the request's own short last chunk "
"(tail %lld tokens, not the stream floor's %lld); STRATA_PREFILL_TAIL_LOAN=0 keeps the floor's\n",
(long long) tail_p, (long long) (floor_t - 1));
}
if (trace)
std::fprintf(stderr, "strata trace: relayout for %lld tokens, tail %lld, first slot %d: %.1f ms\n", (long long) want_p,
(long long) tail_p, (int) first,
std::chrono::duration<double, std::milli>(Clock::now() - t_rl).count());
}
}
for (int64_t l = p.lb; l < p.le; ++l) // THIS participant's layers only
for (int64_t ex = 0; ex < g.n_expert; ++ex) {
@@ -19641,6 +19769,7 @@ int main(int argc, char** argv) {
policy.set_context(p);
const bool merged = first_window && merge_T > 0; // the prompt's last tokens and the first token
bool from_sfx = false;
int sfx_pad = 0; // a learning stretch's lookup window longer than the proposal: the filler rows (DraftPolicy::Pick::pad)
int sfx_match = 0;
bool dfr_lookup = false;
int dfr_T = 0, dfr_match = 0;
@@ -19696,14 +19825,35 @@ int main(int argc, char** argv) {
// chooses, and the lookup is taken without asking whether the MTP's first guess agrees
const bool probabilistic = use_mtp && !req_df2 && mtp.prob(); // DFlash2's candidates are not draws from the MTP's q
if (k > 0 && (probabilistic || !draft_on || sbuf[0] == drafts[0])) {
// a learning stretch may run a longer window than the proposal to time that size: the extra rows repeat the proposal's last
// token, which the verifier rejects (a deterministic proposal only: a probabilistic window keeps its own draws)
const strata::spec::DraftPolicy::Pick pk = probabilistic
? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match);
if (pk.lookup && !trace_nopick) { T = pk.t; from_sfx = true; }
? source_policy.choose(S_mtp, k, sfx_match) : policy.choose(T, k, sfx_match, dc_learning ? S_look - 1 : 0);
if (pk.lookup && !trace_nopick && pk.t - 1 <= (int) sbuf.size()) {
T = pk.t; from_sfx = true;
if (pk.pad > 0) {
sfx_pad = pk.pad;
for (int i = k; i < k + pk.pad; ++i) sbuf[(size_t) i] = sbuf[(size_t) k - 1];
}
}
if (pk.lookup && !trace_nopick && o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits
const int t = graph_fits(T);
if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; }
T = t;
}
} else if (k == 0 && dc_learning && draft_on && !probabilistic && !trace_nopick) {
// no proposal at all: a learning stretch may still time a lookup-type window size (every row after the first is filler,
// the MTP's own first guess repeated; the verifier rejects them), so that sizes only lookups reach get measured
const int s = policy.explore_lookup(std::min<int>(S_look, (int) sbuf.size() + 1));
if (s > 0) {
T = s; from_sfx = true; sfx_pad = s - 1; sfx_match = 0;
for (int i = 0; i < s - 1; ++i) sbuf[(size_t) i] = drafts[0];
if (o.lookup_max_t > 0) { // --lookup-max-t: a size whose window graph fits
const int t = graph_fits(T);
if (t < 0) { std::printf("ERR %s\n", err.c_str()); return 1; }
T = t;
}
}
}
}
}
@@ -19738,6 +19888,14 @@ int main(int argc, char** argv) {
chain_n = std::max(0, t - T);
}
}
// a learning stretch times the window sizes the round's own rule does not reach: the MTP / drafter window of a round with no lookup and no
// chain is run at another size (the rows past the real drafts are whatever the drafts array holds: valid ids that the verifier rejects);
// a deterministic window only, and only the learning stretch (DraftPolicy::explore_window)
bool win_forced = false;
if (dc_learning && draft_on && !first_window && !merged && !from_sfx && chain_n == 0 && !gated_proposal && !(use_mtp && !req_df2 && mtp.prob())) {
const int sx = policy.explore_window(T, std::min<int>(S_mtp, (int) drafts.size() + 1));
if (sx > 0 && p + sx <= o.max_context) { T = sx; win_forced = true; }
}
const int T_mtp = T;
T += chain_n;
const bool timed_round = !first_window;
@@ -20141,8 +20299,11 @@ int main(int argc, char** argv) {
std::fprintf(df2_trace, "\n");
tr_k = 0;
}
if (spec_cost && use_mtp && timed_round && !from_sfx) policy.observe_probs(dwin_s.data(), T_mtp - 1, a);
if (timed_round && !eos && chain_n == 0)
if (spec_cost && use_mtp && timed_round && !from_sfx && !win_forced) policy.observe_probs(dwin_s.data(), T_mtp - 1, a);
if (dc_learning || dc_calib) policy.set_busy_age(std::chrono::duration<double>(Clock::now() - dc_busy_since).count());
if (timed_round && !eos && chain_n == 0 && ((sfx_pad > 0 && from_sfx) || win_forced)) // a window run for its size's sake: its time only
policy.observe_forced(T, std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
else if (timed_round && !eos && chain_n == 0)
policy.observe(from_sfx, T, a, sfx_match,
std::chrono::duration<double, std::milli>(Clock::now() - round0).count());
else if (timed_round && !eos) // a chained window: its MTP part, its chain, its cost
@@ -20158,6 +20319,7 @@ int main(int argc, char** argv) {
if (hold_on && std::strcmp(finish, "length") == 0 && produced_n >= req_hold_n && (produced_n < max_new || admit_slot >= 0)) finish = "hold";
if (!keep_sync()) { std::printf("ERR %s\n", err.c_str()); return 1; }
const double decode_ms = std::chrono::duration<double, std::milli>(Clock::now() - d0).count();
dc_last_end = Clock::now(); // the busy run goes on when the next request starts within CostLearner::kIdleS of this
if (use_df2 && o.draft_auto && bandit_key != 0 && produced_n >= 48 && decode_ms > 0.0) {
DraftBandit& b = bandit[bandit_key];
const int w = req_df2 ? 1 : 0;
@@ -20175,12 +20337,13 @@ int main(int argc, char** argv) {
const strata::spec::CostLearner::Verdict v = policy.learner().check(kDraftCostRounds, kDraftCostMinN);
if (v.ready && v.disturbed) {
std::fprintf(stderr, "strata serve: draft costs: the learning stretch looks disturbed (%s): it is learned again\n", v.why.c_str());
policy.learner().reset();
policy.reset_learning();
} else if (v.ready) {
strata::spec::CostFile cf;
cf.key = dc_key;
for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k)
cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN);
cf.tables[(size_t) k] = policy.learner().table(k, kDraftCostMinN, policy.top_size());
cf.state_effect = policy.learner().state_effect(0, kDraftCostMinN); // real rounds are counted by the same rule (fresh only, or all)
// the CPU prompt share, when it is on and balancing from measured times: its balance as measured so far, to a 0.05
// step (0.5 when no short prompt has measured it yet: on an RTX A6000 a fixed 0.5 read a 981-token chunk as fast as the
// balancing share, 1,001-1,009 against 995-997 ms); fixed from now on like the table
@@ -20194,14 +20357,17 @@ int main(int argc, char** argv) {
if (dc_pcie_ok) cf.pcie_frac = o.pcie_frac;
std::string why;
const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why);
if (cf.cpu_share >= 0.0) strata::prefill::Prefill::fix_cpu_share(cf.cpu_share);
if (cf.pcie_frac >= 0.0) fix_pcie_share(cf.pcie_frac);
for (int k = 0; k < strata::spec::CostLearner::kCtxBuckets; ++k)
if (!cf.tables[(size_t) k].empty())
policy.set_fixed_costs(cf.tables[(size_t) k].data(), (int) cf.tables[(size_t) k].size(), k);
policy.set_learning(false);
policy.learner().reset();
policy.reset_learning();
dc_learning = false;
dc_file = cf;
policy.start_calibration(cf.state_effect, cf.real, cf.cal, cf.real_cost, cf.reqs);
dc_calib = policy.calibrating();
if (policy.table_held()) dc_shares_due = true; // the shares stay live until the table takes over
else dc_apply_shares(cf);
std::string t0;
char b[24];
for (size_t i = 0; i < cf.tables[0].size(); ++i) {
@@ -20216,8 +20382,42 @@ int main(int argc, char** argv) {
std::snprintf(b, sizeof b, "; PCIe share %.2f", cf.pcie_frac);
t0 += b;
}
std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); it is fixed from the next request "
"on%s%s\n", t0.c_str(), saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str());
std::fprintf(stderr, "strata serve: draft costs: this machine's table is learned (%s); %s%s%s\n", t0.c_str(),
dc_calib ? "live costs decide until every size is calibrated against real requests (or 100 requests have run), then it is fixed"
: "it is fixed from the next request on",
saved ? "" : " (not saved: ", saved ? "" : (why + "; the next start learns again)").c_str());
}
}
// --draft-costs, calibration: the real rounds of this request that the sizes still at their learned cost have collected; a size with
// kCalibN of them takes their mean (the file is rewritten whole, the new cost applies from the next request on, no later change)
if (dc_calib && (policy.calib_dirty() || policy.table_held())) {
const bool dc_was_held = policy.table_held(), dc_was_passive = policy.passive();
strata::spec::CostFile cc = dc_file;
std::string rep, why;
if (policy.calibrate(cc, rep)) {
if (dc_was_passive && !policy.passive()) { // the table is made: the shares go in with it, the CPU share only when a short prompt has measured it
if (strata::prefill::Prefill::cpu_share_balancing() && sp.stats().cpu_share_readings > 0)
cc.cpu_share = std::clamp(std::round(sp.stats().cpu_share_balanced * 20.0) / 20.0, 0.05, 0.9);
if (dc_pcie_ok) {
if (!pcie_auto.on) cc.pcie_frac = o.pcie_frac;
else dc_pcie_pending = true;
}
dc_shares_due = true;
}
const bool saved = strata::spec::write_cost_file(o.draft_costs, cc, why);
dc_file = cc;
if (!rep.empty())
std::fprintf(stderr, "strata serve: draft costs: calibrated against real requests: %s%s\n", rep.c_str(),
saved ? "" : (" (not saved: " + why + ")").c_str());
}
dc_calib = policy.calibrating();
if (dc_was_held && policy.fixed()) { // the table takes over: the stored shares are fixed with it
if (dc_shares_due) dc_apply_shares(dc_file);
dc_shares_due = false;
std::fprintf(stderr, "strata serve: draft costs: %s; this machine's table decides the windows from the next request on%s\n",
dc_calib ? "100 requests have run, sizes real requests did not reach keep a scaled learned cost until they have their own rounds"
: "every size is calibrated",
dc_file.cpu_share >= 0.0 || dc_file.pcie_frac >= 0.0 ? " (the stored shares are fixed with it)" : "");
}
}
// --draft-costs with a table from before the stored PCIe share: once PcieAuto has settled (three readings, or it gave up), its
@@ -20229,9 +20429,12 @@ int main(int argc, char** argv) {
cf.pcie_frac = o.pcie_frac;
std::string why;
const bool saved = strata::spec::write_cost_file(o.draft_costs, cf, why);
fix_pcie_share(cf.pcie_frac);
std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed from the next request on\n",
cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str());
dc_file = cf;
if (policy.table_held()) dc_shares_due = true; // held back: fixed when the table takes over
else fix_pcie_share(cf.pcie_frac);
std::fprintf(stderr, "strata serve: draft costs: the PCIe share settled at %.2f; it is %s and fixed %s\n",
cf.pcie_frac, saved ? "stored with this machine's table" : ("not stored (" + why + ")").c_str(),
policy.table_held() ? "when the table takes over" : "from the next request on");
}
// the last commit (set_commit_async): the session is complete before anything reads or copies it
if (!ver.wait_commit(err)) {
@@ -20810,6 +21013,8 @@ int main(int argc, char** argv) {
int64_t pos_start = 0;
int64_t spec_pos = strata::spec::kSpecNotStarted; // plan v0.3 P6: where the speculative loop starts (0 is a real position: a 1-token prompt on a native pack)
strata::prefill::Prefill prefill;
if (!multi_gpu && o.batch <= 0) // STRATA_SWITCH_POINT: before any bytes_needed, like the share
strata::prefill::Prefill::set_card_expert_share((int64_t) xcache.slots(), (int64_t) (g.n_layers * g.n_expert), xcache.slots() > 0 ? (double) xcache.bytes() / (double) xcache.slots() / 1e6 : 0.0, o.pcie_probe_gbps);
// #1595: not by default when the cache holds every expert (nothing to take)
strata::prefill::Prefill::arm_cpu_share(!multi_gpu && !o.no_pool,
!multi_gpu && !o.no_pool && o.batch <= 0 &&
+13
View File
@@ -3919,6 +3919,19 @@ int strata::qwen35::run(int argc, char** argv) {
if (std::getenv(v) == nullptr) _putenv_s(v, "1");
#endif
}
#if !defined(__HIPCC__)
// A build without llama.cpp's MMQ (MMQ::built() false: strata_pf_own with mmq_absent.cpp) has no MMQ tile for any layer, so a layer takes the fused kernels or the
// whole prompt takes the grouped kernels. `strata` already sets STRATA_PF_FUSED=1 before main in such a build (prefill.cpp, g_own_only_defaults), which makes every
// sm_80+ card whose kernels cover a layer's pair take them (fused_tile::q36_takes); this standalone engine does not link that code, so it does the same here: the same
// behaviour on both entry points. A value you set is kept (=0 keeps every layer on the grouped kernels). A build with MMQ is unchanged.
if (!MMQ::built()) {
#if !defined(_WIN32)
setenv("STRATA_PF_FUSED", "1", 0);
#else
if (std::getenv("STRATA_PF_FUSED") == nullptr) _putenv_s("STRATA_PF_FUSED", "1");
#endif
}
#endif
if (mtp_d < 0 || mtp_d > 7) { std::fprintf(stderr, "strata-q36: --mtp takes 0 .. 7 drafts\n"); return 2; }
if (chunk < 0 || chunk > 4096 || ctx < 256) { std::fprintf(stderr, "strata-q36: bad --chunk / --max-context\n"); return 2; }
Model m;
+462 -25
View File
@@ -79,19 +79,60 @@ double median_of(std::vector<float> v) {
static_assert(CostLearner::kMaxT == DraftPolicy::kMaxT && CostLearner::kCtxBuckets == DraftPolicy::kCtxBuckets, "one table shape");
void CostLearner::add(int bucket, int t, double ms) {
void CostLearner::add(int bucket, int t, double ms, double busy_age_s) {
if (!(ms > 0.0) || !std::isfinite(ms)) return;
bucket = std::clamp(bucket, 0, kCtxBuckets - 1);
t = std::clamp(t, 1, kMaxT);
++rounds_;
auto& v = s_[(size_t) bucket][(size_t) t];
const bool late = busy_age_s > kFreshS; // a GPU that has been busy for long can run in another state than a request after a pause finds it
++(late ? late_ : rounds_);
auto& v = (late ? late_s_ : s_)[(size_t) bucket][(size_t) t];
if ((int) v.size() < kKeep) v.push_back((float) ms);
}
void CostLearner::reset() {
for (auto& b : s_)
for (auto& v : b) v.clear();
for (auto& b : late_s_)
for (auto& v : b) v.clear();
rounds_ = 0;
late_ = 0;
}
bool CostLearner::state_effect(int bucket, int min_n) const {
if (bucket < 0 || bucket >= kCtxBuckets) return false;
const int need = std::max(1, min_n);
for (int t = 1; t <= kMaxT; ++t) {
const auto& f = s_[(size_t) bucket][(size_t) t];
const auto& l = late_s_[(size_t) bucket][(size_t) t];
if ((int) f.size() < need || (int) l.size() < need) continue;
const double tf = trimmed_mean(f), tl = trimmed_mean(l);
if (tf > 0.0 && std::fabs(tl - tf) / tf > kStateTol) return true;
}
return false;
}
std::array<std::vector<float>, CostLearner::kMaxT + 1> CostLearner::sets(int bucket, bool pooled) const {
std::array<std::vector<float>, kMaxT + 1> out;
for (int t = 1; t <= kMaxT; ++t) {
out[(size_t) t] = s_[(size_t) bucket][(size_t) t];
if (pooled) out[(size_t) t].insert(out[(size_t) t].end(), late_s_[(size_t) bucket][(size_t) t].begin(), late_s_[(size_t) bucket][(size_t) t].end());
}
return out;
}
bool CostLearner::state_known(int bucket, int min_n) const {
if (bucket < 0 || bucket >= kCtxBuckets) return false;
const int need = std::max(1, min_n);
for (int t = 1; t <= kMaxT; ++t)
if ((int) s_[(size_t) bucket][(size_t) t].size() >= need && (int) late_s_[(size_t) bucket][(size_t) t].size() >= need) return true;
return false;
}
int CostLearner::usable(int bucket, int t, int min_n) const {
if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > kMaxT) return 0;
int n = (int) s_[(size_t) bucket][(size_t) t].size();
if (!state_effect(bucket, min_n)) n += (int) late_s_[(size_t) bucket][(size_t) t].size();
return n;
}
int CostLearner::samples(int bucket, int t) const {
@@ -99,13 +140,13 @@ int CostLearner::samples(int bucket, int t) const {
return (int) s_[(size_t) bucket][(size_t) t].size();
}
std::vector<double> CostLearner::table(int bucket, int min_n) const {
std::vector<double> CostLearner::table(int bucket, int min_n, int upto) const {
std::vector<double> out;
if (bucket < 0 || bucket >= kCtxBuckets) return out;
const auto& b = s_[(size_t) bucket];
const std::array<std::vector<float>, kMaxT + 1> b = sets(bucket, !state_effect(bucket, min_n));
int top = 0;
std::array<double, kMaxT + 1> got{};
std::vector<int> seen;
std::vector<int> seen; // the measured sizes (min_n samples), ascending; a rough one (kWeakN samples) joins when it is accepted below
for (int t = 1; t <= kMaxT; ++t) {
if (!b[(size_t) t].empty()) top = t;
if ((int) b[(size_t) t].size() >= std::max(1, min_n)) {
@@ -114,35 +155,58 @@ std::vector<double> CostLearner::table(int bucket, int min_n) const {
}
}
if (top == 0 || seen.empty()) return out;
for (int t = 1; t <= top; ++t) {
if (got[(size_t) t] > 0.0) {
out.push_back(got[(size_t) t]);
continue;
}
top = std::max(top, std::min(upto, kMaxT));
// the cost of an unmeasured size from the measured ones: linear between two, the prior shape below them, above them the straight line with the
// steeper of the last segment's slope and the slope over all measured sizes (never flatter than the measured trend)
const auto fill = [&](int t) {
int lo = 0, hi = 0;
for (const int u : seen) {
if (u < t) lo = u;
if (u > t && hi == 0) hi = u;
}
if (lo > 0 && hi > 0) out.push_back(got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo));
else {
const int u = hi > 0 ? hi : lo;
out.push_back(got[(size_t) u] * kShape[t] / kShape[u]);
if (lo > 0 && hi > 0) return got[(size_t) lo] + (got[(size_t) hi] - got[(size_t) lo]) * (t - lo) / (double) (hi - lo);
if (hi > 0) return got[(size_t) hi] * kShape[t] / kShape[hi];
if (seen.size() < 2) return got[(size_t) lo] * kShape[t] / kShape[lo];
const int u2 = seen.back(), u1 = seen[seen.size() - 2], u0 = seen.front();
const double slope = std::max({0.0, (got[(size_t) u2] - got[(size_t) u1]) / (double) (u2 - u1), (got[(size_t) u2] - got[(size_t) u0]) / (double) (u2 - u0)});
return got[(size_t) u2] + slope * (t - u2);
};
for (int t = 1; t <= top; ++t) {
if (got[(size_t) t] > 0.0) {
out.push_back(got[(size_t) t]);
continue;
}
double v = fill(t);
const int n = (int) b[(size_t) t].size();
if (n >= kWeakN) { // a few rounds: their median counts when it is not below the trend and not far above it (a stalled handful does not)
std::vector<float> s = b[(size_t) t];
std::sort(s.begin(), s.end());
const double med = n % 2 ? (double) s[(size_t) n / 2] : 0.5 * ((double) s[(size_t) n / 2 - 1] + (double) s[(size_t) n / 2]);
if (med >= v && med <= kWeakMax * v) {
v = med;
got[(size_t) t] = med;
seen.insert(std::upper_bound(seen.begin(), seen.end(), t), t);
}
}
out.push_back(v);
}
for (size_t i = 1; i < out.size(); ++i) out[i] = std::max(out[i], out[i - 1]); // more rows never cost less
return out;
}
CostLearner::Verdict CostLearner::check(int64_t min_rounds, int min_n) const {
Verdict v;
char b[160];
bool any = false, every_bucket_ok = true;
bool any = false, every_bucket_ok = true, effect = false;
for (int k = 0; k < kCtxBuckets; ++k) {
bool has = false, measured = false;
double prev_ms = 0.0;
int prev_t = 0;
const bool eff = state_effect(k, min_n);
effect = effect || eff;
const std::array<std::vector<float>, kMaxT + 1> use = sets(k, !eff);
for (int t = 1; t <= kMaxT; ++t) {
const auto& s = s_[(size_t) k][(size_t) t];
const auto& s = use[(size_t) t];
has = has || !s.empty();
if ((int) s.size() < std::max(1, min_n)) continue;
measured = true;
@@ -175,14 +239,18 @@ CostLearner::Verdict CostLearner::check(int64_t min_rounds, int min_n) const {
any = any || measured;
if (has && !measured) every_bucket_ok = false;
}
v.ready = rounds_ >= min_rounds && any && every_bucket_ok;
// no state effect: every round counts. With one: the fresh rounds, or, for a stretch that never paused (one long burst keeps only its first kFreshS
// seconds), kFallbackFactor x the quota in rounds of any age when the fresh ones are at least 1 / kFallbackShare of the quota
const bool enough = effect ? (rounds_ >= min_rounds || (rounds_ + late_ >= kFallbackFactor * min_rounds && rounds_ * kFallbackShare >= min_rounds))
: rounds_ + late_ >= min_rounds;
v.ready = enough && any && every_bucket_ok;
return v;
}
// ---------------------------------------------------------------------------------------------------- the table file
namespace {
constexpr const char* kCostFileHead = "strata-draft-costs 1";
constexpr const char* kCostFileHead = "strata-draft-costs 2"; // 2: learned from the rounds of the first seconds of a busy run; a version 1 file is learned again
// the path as UTF-8 (the server passes it so); on Windows a plain std::string would be read in the ANSI code page
std::filesystem::path utf8_path(const std::string& s) { return std::filesystem::path(std::u8string(s.begin(), s.end())); }
std::string one_line(std::string s) {
@@ -217,6 +285,63 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o
out.pcie_frac = s;
continue;
}
if (line.rfind("state ", 0) == 0) { // calibration lines (DraftPolicy::start_calibration); a file without them has no calibration done
if (line != "state 0" && line != "state 1") { why = "a malformed state"; return false; }
out.state_effect = line == "state 1";
continue;
}
if (line == "fresh 1") { out.fresh = true; continue; }
if (line.rfind("reqs ", 0) == 0) {
int rq = -1;
if (std::sscanf(line.c_str(), "reqs %d", &rq) != 1 || rq < 0 || rq > 1000000) { why = "a malformed request count"; return false; }
out.reqs = rq;
continue;
}
if (line.rfind("real ", 0) == 0) {
int rb = -1;
unsigned m = 0;
if (std::sscanf(line.c_str(), "real %d %u", &rb, &m) != 2 || rb < 0 || rb >= CostLearner::kCtxBuckets) { why = "a malformed real mark"; return false; }
out.real[(size_t) rb] = m;
continue;
}
if (line.rfind("cal ", 0) == 0) {
int cb = -1, ct = -1, cn = -1, used = 0;
double cs = -1.0;
if (std::sscanf(line.c_str(), "cal %d %d %d %lf%n", &cb, &ct, &cn, &cs, &used) != 4 || cb < 0 || cb >= CostLearner::kCtxBuckets || ct < 1 || ct > CostLearner::kMaxT
|| cn < 0 || cn > 100000 || !(cs >= 0.0) || !(cs < 1e9)) {
why = "a malformed calibration line";
return false;
}
CalAcc ca;
ca.n = cn;
ca.sum = cs;
{ // the rounds themselves (a line from before them: none, the mean decides as it did)
const char* p = line.c_str() + used;
int k = 0;
bool ok = true;
while (k < CalAcc::kVals) {
char* e = nullptr;
const double v = std::strtod(p, &e);
if (e == p) break;
if (!(v > 0.0) || !(v < 1e6)) { ok = false; break; }
ca.vals[(size_t) k++] = v;
p = e;
}
ca.nv = ok && k == cn && cn <= CalAcc::kVals ? k : 0;
}
out.cal[(size_t) cb][(size_t) ct] = ca;
continue;
}
if (line.rfind("rc ", 0) == 0) {
int rb = -1, rt = -1;
double rv = -1.0;
if (std::sscanf(line.c_str(), "rc %d %d %lf", &rb, &rt, &rv) != 3 || rb < 0 || rb >= CostLearner::kCtxBuckets || rt < 1 || rt > CostLearner::kMaxT || !(rv > 0.0) || !(rv < 1e5)) {
why = "a malformed real cost";
return false;
}
out.real_cost[(size_t) rb][(size_t) rt] = rv;
continue;
}
int b = -1, used = 0;
if (std::sscanf(line.c_str(), "bucket %d %n", &b, &used) < 1 || used == 0 || b < 0 || b >= CostLearner::kCtxBuckets) {
why = "a malformed line";
@@ -237,7 +362,7 @@ bool read_cost_file(const std::string& path, const std::string& key, CostFile& o
out.tables[(size_t) b] = std::move(v);
any = true;
}
if (!ended || !any) { why = "the file is cut short"; return false; }
if (!ended || (!any && !out.fresh) || (any && out.fresh)) { why = "the file is cut short"; return false; }
out.key = key;
return true;
}
@@ -264,6 +389,29 @@ bool write_cost_file(const std::string& path, const CostFile& c, std::string& wh
}
f << "\n";
}
if (c.state_effect) f << "state 1\n";
if (c.reqs > 0) f << "reqs " << c.reqs << "\n";
if (c.fresh) f << "fresh 1\n";
for (int k = 0; k < CostLearner::kCtxBuckets; ++k) {
if (c.real[(size_t) k] != 0u) f << "real " << k << " " << c.real[(size_t) k] << "\n";
for (int t = 1; t <= CostLearner::kMaxT; ++t)
if ((c.real[(size_t) k] >> (t - 1) & 1u) && c.real_cost[(size_t) k][(size_t) t] > 0.0) {
std::snprintf(b, sizeof b, "%.4f", c.real_cost[(size_t) k][(size_t) t]);
f << "rc " << k << " " << t << " " << b << "\n";
}
for (int t = 1; t <= CostLearner::kMaxT; ++t) {
const CalAcc& a = c.cal[(size_t) k][(size_t) t];
if (a.n <= 0 || (c.real[(size_t) k] >> (t - 1) & 1u)) continue;
std::snprintf(b, sizeof b, "%.4f", a.sum);
f << "cal " << k << " " << t << " " << a.n << " " << b;
if (a.nv == a.n)
for (int i = 0; i < a.nv; ++i) {
std::snprintf(b, sizeof b, "%.4f", (double) a.vals[(size_t) i]);
f << " " << b;
}
f << "\n";
}
}
if (c.cpu_share >= 0.0) {
std::snprintf(b, sizeof b, "share %.3f\n", std::min(c.cpu_share, 1.0));
f << b;
@@ -291,14 +439,22 @@ DraftPolicy::DraftPolicy(int max_t, double margin)
}
void DraftPolicy::set_fixed_costs(const double* ms, int n, int bucket) {
if (!fixed_ && !live_saved_) { // the live costs at this point: start_calibration() may hand them back
live_cost_ = cost_;
live_n_ = cost_n_;
live_saved_ = true;
}
fixed_ = true;
held_table_ = false;
held_.clear();
if (ms == nullptr || n <= 0) return;
bucket = std::clamp(bucket, 0, kCtxBuckets - 1);
fixed_n_[(size_t) bucket] = std::min(n, kMaxT);
for (int t = 1; t <= kMaxT; ++t) { // the table replaces what was measured; sizes past its end scale from it (cost_ms)
const bool in = t <= n && ms[t - 1] > 0.0;
cost_[bucket][t] = in ? ms[t - 1] : 0.0;
cost_n_[bucket][t] = in ? 1e6 : 0.0;
learned_[(size_t) bucket][(size_t) t] = cost_[bucket][t];
}
}
@@ -405,10 +561,19 @@ double DraftPolicy::mtp_tokens(int t) const {
return 1.0 + 0.7 * (t - 1); // before any MTP window of this size: a typical acceptance
}
DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const {
DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match, int pad_cap) const {
Pick p;
p.t = std::clamp(t_mtp, 1, max_t_);
if (lookup_k <= 0) return p;
if (learning_ && !fixed_) { // a learning stretch measures the sizes it has too few rounds of, when a proposal is long enough for one
const int s = explore_size(lookup_k, pad_cap);
if (s > 0) {
p.lookup = true;
p.t = s;
p.pad = std::max(0, s - 1 - lookup_k);
return p;
}
}
const double base = mtp_tokens(p.t) / cost_ms(p.t);
const double q = lookup_rate(match);
double e = 1.0, qi = 1.0, best = 0.0;
@@ -437,9 +602,60 @@ DraftPolicy::Pick DraftPolicy::choose(int t_mtp, int lookup_k, int match) const
return p;
}
bool DraftPolicy::explore_ok() const {
const double age = busy_age_ < 0.0 ? 0.0 : busy_age_;
if (age <= CostLearner::kFreshS) return true; // a fresh round: it counts on every machine
return learner_.state_known(bk_, 20) && !learner_.state_effect(bk_, 20); // a late round counts only where the stretch has shown no state effect
}
int DraftPolicy::explore_next(int reach, int skip) const {
if (learner_.rounds() + learner_.late_rounds() < kExploreAfter || forced_total_ >= kExploreBudget || !explore_ok()) return 0;
for (int s = 2; s <= std::min(reach, max_t_); ++s) {
if (s == skip || !allowed(s) || forced_[(size_t) s] >= kExplorePerSize || learner_.usable(bk_, s, 20) >= kExploreN) continue;
++forced_[(size_t) s];
++forced_total_;
return s;
}
return 0;
}
int DraftPolicy::explore_size(int lookup_k, int pad_cap) const {
return explore_next(std::max(lookup_k, pad_cap) + 1, 0);
}
int DraftPolicy::explore_lookup(int cap) const {
if (!learning_ || fixed_) return 0;
return explore_next(cap, 0);
}
int DraftPolicy::explore_window(int t, int cap) const {
if (!learning_ || fixed_) return 0;
return explore_next(cap, t);
}
void DraftPolicy::observe_forced(int t, double round_ms) {
t = std::clamp(t, 1, kMaxT);
if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
if (round_ms > 0 && !fixed_) {
round_ms = clamp_sample(t, round_ms);
const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha;
cost_[bk_][t] = cost_n_[bk_][t] > 0 ? (1.0 - alpha) * cost_[bk_][t] + alpha * round_ms : round_ms;
cost_n_[bk_][t] += 1.0;
last_[bk_][t] = rounds_;
}
rounds_ += 1.0;
}
void DraftPolicy::reset_learning() {
learner_.reset();
forced_total_ = 0;
forced_.fill(0);
}
void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double round_ms) {
t = std::clamp(t, 1, kMaxT);
if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms);
if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
if (calib_on_ && round_ms > 0) calib_add(bk_, t, round_ms, busy_age_);
if (round_ms > 0 && !fixed_) {
round_ms = clamp_sample(t, round_ms);
const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; // a running mean for the first samples
@@ -459,6 +675,226 @@ void DraftPolicy::observe(bool lookup, int t, int accepted, int match, double ro
}
}
// ---- calibration of a fixed table against real requests (see the header)
void DraftPolicy::apply_table() {
if (!fixed_) return; // a held table: cost_ is the live cost, not touched
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
if (n <= 0) continue;
// a size that is not real (real requests never reached it in kCalibReqs requests): its learned cost x the mean (real / learned) of the real sizes of
// 2 or more rows, so it is not left at a price that the sizes next to it have left (size 1 stays); no real size of 2+ rows: its learned cost
double sum = 0.0;
int cnt = 0;
for (int t = 2; t <= n; ++t)
if ((real_[(size_t) k] >> (t - 1) & 1u) && learned_[(size_t) k][(size_t) t] > 0.0) {
sum += real_cost_[(size_t) k][(size_t) t] / learned_[(size_t) k][(size_t) t];
++cnt;
}
const double r = cnt > 0 ? sum / cnt : 1.0;
for (int t = 1; t <= n; ++t) {
if (real_[(size_t) k] >> (t - 1) & 1u) cost_[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t];
else cost_[(size_t) k][(size_t) t] = learned_[(size_t) k][(size_t) t] * (t >= 2 ? r : 1.0);
}
// more rows never cost less. An inversion is repaired from the trusted side: a size that is only guessed (not real), or that sits below another real size, is
// LOWERED to the price of the next larger size first (a cold first-use round or a live value taken at take-over made it too high; raising every larger size to it,
// as a forward pass alone does, made one 20 ms 2-row price of the srv118 table the price of every size from 2 to 7 rows and the policy took 12-row windows);
// a real size above an unreached next size is left, and the forward pass then lifts that guess to it
for (int t = n - 1; t >= 1; --t) {
const bool real_t = real_[(size_t) k] >> (t - 1) & 1u, real_next = real_[(size_t) k] >> t & 1u;
if (cost_[(size_t) k][(size_t) t] > cost_[(size_t) k][(size_t) t + 1] && (!real_t || real_next))
cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t + 1];
}
for (int t = 2; t <= n; ++t)
if (cost_[(size_t) k][(size_t) t] < cost_[(size_t) k][(size_t) t - 1]) cost_[(size_t) k][(size_t) t] = cost_[(size_t) k][(size_t) t - 1];
}
}
void DraftPolicy::start_calibration(bool state_effect, const std::array<unsigned, kCtxBuckets>& real,
const std::array<std::array<CalAcc, kMaxT + 1>, kCtxBuckets>& cal,
const std::array<std::array<double, kMaxT + 1>, kCtxBuckets>& real_cost, int reqs) {
reqs_ = std::max(reqs, 0);
calib_fresh_only_ = state_effect;
real_ = real;
cal_ = cal;
real_cost_ = real_cost;
for (int k = 0; k < kCtxBuckets; ++k) // a mark without a cost (a damaged file) is no mark
for (int t = 1; t <= kMaxT; ++t)
if ((real_[(size_t) k] >> (t - 1) & 1u) && !(real_cost_[(size_t) k][(size_t) t] > 0.0)) real_[(size_t) k] &= ~(1u << (t - 1));
apply_table();
calib_dirty_ = false;
calib_on_ = false;
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
for (int t = 1; t <= n; ++t)
if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true;
}
// not calibrated: live costs decide, as without a table, until kCalibReqs requests have collected real rounds (a size real requests do not reach
// would hold the table back for good)
if (calib_on_ && reqs_ < kCalibReqs && fixed_ && live_saved_) hold_table();
}
void DraftPolicy::start_passive(const CostFile& cf, int n) {
passive_ = true;
calib_fresh_only_ = true; // see the header: only the first seconds of a busy run count, no detection of a load-time effect
real_ = {};
real_[0] = cf.real[0];
cal_ = {};
cal_[0] = cf.cal[0];
real_cost_ = {};
real_cost_[0] = cf.real_cost[0];
learned_ = {};
fixed_n_ = {};
fixed_n_[0] = std::clamp(n, 1, kMaxT);
for (int t = 1; t <= kMaxT; ++t) // a mark without a cost (a damaged file) is no mark; a size past the table length is none
if ((real_[0] >> (t - 1) & 1u) && (!(real_cost_[0][(size_t) t] > 0.0) || t > fixed_n_[0])) real_[0] &= ~(1u << (t - 1));
reqs_ = std::max(cf.reqs, 0);
held_table_ = true;
fixed_ = false;
calib_on_ = true;
calib_dirty_ = false;
}
void DraftPolicy::take_over_passive() {
const int bk_was = bk_;
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
for (int t = 1; t <= n; ++t) {
double v;
if (real_[(size_t) k] >> (t - 1) & 1u) v = real_cost_[(size_t) k][(size_t) t]; // a real size: its own cost
else if (cost_n_[k][t] > 0 && cost_[k][t] > 0.0) v = cost_[k][t]; // a size never reached 16 rounds: what the live estimator has now
else {
bk_ = k;
v = cost_ms(t); // never measured: the policy's own prior, as without a table
bk_ = bk_was;
}
if (!(v > 0.0)) v = t > 1 ? learned_[(size_t) k][(size_t) t - 1] : 1.0;
learned_[(size_t) k][(size_t) t] = v;
}
}
passive_ = false;
}
void DraftPolicy::hold_table() {
for (int k = 0; k < kCtxBuckets; ++k) {
if (fixed_n_[(size_t) k] <= 0) continue;
cost_[(size_t) k] = live_cost_[(size_t) k];
cost_n_[(size_t) k] = live_n_[(size_t) k];
}
fixed_ = false;
held_table_ = true;
held_.clear();
}
void DraftPolicy::use_table() {
fixed_ = true;
apply_table(); // every size is real: its real cost
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
if (n <= 0) continue;
for (int t = 1; t <= kMaxT; ++t) {
const bool in = t <= n && cost_[(size_t) k][(size_t) t] > 0.0;
if (!in) cost_[(size_t) k][(size_t) t] = 0.0;
cost_n_[(size_t) k][(size_t) t] = in ? 1e6 : 0.0;
}
}
fixed_ = true;
held_table_ = false;
held_.clear();
}
void DraftPolicy::calib_add(int bucket, int t, double ms, double age) {
static_assert(kCalibN <= CalAcc::kVals, "a size's rounds are all kept for the median");
if (bucket < 0 || bucket >= kCtxBuckets || t < 1 || t > fixed_n_[(size_t) bucket]) return;
if (real_[(size_t) bucket] >> (t - 1) & 1u) return;
if (calib_fresh_only_ && age > CostLearner::kFreshS) return; // the table is what rounds of the first seconds of a busy run cost
double base = learned_[(size_t) bucket][(size_t) t];
if (!(base > 0.0) && passive_) base = cost_n_[bucket][t] > 0 ? cost_[bucket][t] : 0.0; // no learned table: the live cost of the size is the reference
if (!(base > 0.0)) return;
CalAcc& a = cal_[(size_t) bucket][(size_t) t];
if (a.n >= kCalibN) return;
const double r = std::clamp(ms, kCalibLo * base, kCalibHi * base); // one stalled round moves the mean by at most (kCalibHi - 1) / kCalibN
a.sum += r;
if (a.nv == a.n && a.n < CalAcc::kVals) a.vals[(size_t) a.nv++] = r; // the rounds are kept: the price is their median
a.n += 1;
calib_dirty_ = true;
}
bool DraftPolicy::calibrate(CostFile& cf, std::string& report) {
report.clear();
if (!calib_on_ && !calib_dirty_) return false;
if (held_table_) ++reqs_; // a request that ran while the table is held back
char b[96];
bool changed = calib_dirty_ || held_table_, replaced = false; // a held table: the request count changed
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
for (int t = 1; t <= n; ++t) {
if (real_[(size_t) k] >> (t - 1) & 1u) continue;
CalAcc& a = cal_[(size_t) k][(size_t) t];
if (a.n < kCalibN) continue;
double v = a.sum / a.n; // a file from before the kept rounds: the mean
if (a.nv == a.n && a.n > 0) { // the median of the rounds: a cold first use, a stall, another process move a mean, not a median
std::array<double, CalAcc::kVals> s = a.vals;
std::sort(s.begin(), s.begin() + a.nv);
v = a.nv % 2 == 1 ? s[(size_t) a.nv / 2] : 0.5 * (s[(size_t) a.nv / 2 - 1] + s[(size_t) a.nv / 2]);
}
const double base = learned_[(size_t) k][(size_t) t];
if (!(base > 0.0) || (v >= kCalibOkLo * base && v <= kCalibOkHi * base)) { // no learned cost (passive): the clamped rounds are taken as they are
if (base > 0.0) std::snprintf(b, sizeof b, "%s%d rows %.2f -> %.2f", report.empty() ? "" : ", ", t, base, v);
else std::snprintf(b, sizeof b, "%s%d rows real %.2f", report.empty() ? "" : ", ", t, v);
report += b;
real_cost_[(size_t) k][(size_t) t] = v;
real_[(size_t) k] |= 1u << (t - 1);
replaced = true;
}
a = CalAcc{}; // replaced, or disturbed (rounds dropped, collected again)
}
}
if (replaced && fixed_) { // the table is in use with sizes that were not reached: their scaled costs follow the real sizes
std::array<std::array<double, kMaxT + 1>, kCtxBuckets> before = cost_;
apply_table();
for (int k = 0; k < kCtxBuckets; ++k)
for (int t = 1; t <= fixed_n_[(size_t) k]; ++t)
if (!(real_[(size_t) k] >> (t - 1) & 1u) && std::fabs(cost_[(size_t) k][(size_t) t] - before[(size_t) k][(size_t) t]) > 0.005) {
std::snprintf(b, sizeof b, "%s%d rows (not real yet) %.2f -> %.2f", report.empty() ? "" : ", ", t, before[(size_t) k][(size_t) t], cost_[(size_t) k][(size_t) t]);
report += b;
}
}
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
if (n <= 0) continue;
if (!(passive_ && !fixed_)) cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n); // the file keeps the learned costs
cf.real[(size_t) k] = real_[(size_t) k];
for (int t = 0; t <= kMaxT; ++t) {
cf.cal[(size_t) k][(size_t) t] = cal_[(size_t) k][(size_t) t];
cf.real_cost[(size_t) k][(size_t) t] = real_cost_[(size_t) k][(size_t) t];
}
}
cf.state_effect = calib_fresh_only_;
cf.reqs = reqs_;
cf.fresh = passive_;
calib_dirty_ = false;
calib_on_ = false;
for (int k = 0; k < kCtxBuckets; ++k)
for (int t = 1; t <= fixed_n_[(size_t) k]; ++t)
if (!(real_[(size_t) k] >> (t - 1) & 1u)) calib_on_ = true;
// the last size is calibrated, or kCalibReqs requests have not reached the rest: the table decides from the next round on
if (held_table_ && (!calib_on_ || reqs_ >= kCalibReqs)) {
if (passive_) {
take_over_passive();
for (int k = 0; k < kCtxBuckets; ++k) {
const int n = fixed_n_[(size_t) k];
if (n > 0) cf.tables[(size_t) k].assign(learned_[(size_t) k].begin() + 1, learned_[(size_t) k].begin() + 1 + n);
}
cf.fresh = false;
changed = true;
}
use_table();
if (calib_on_) report += std::string(report.empty() ? "" : ", ") + "table in use, sizes real requests did not reach keep a scaled learned cost";
}
return changed || replaced;
}
void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match) {
t = std::clamp(t, 1, kMaxT);
rounds_ += 1.0;
@@ -476,7 +912,7 @@ void DraftPolicy::observe_committed(bool lookup, int t, int accepted, int match)
}
void DraftPolicy::defer_cost(int64_t end, int t, double round_ms) {
if (round_ms > 0 && (learning_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms});
if (round_ms > 0 && (learning_ || calib_on_ || !fixed_)) held_.push_back({end, bk_, std::clamp(t, 1, kMaxT), round_ms, busy_age_});
}
void DraftPolicy::apply_costs(int64_t committed) {
@@ -484,7 +920,8 @@ void DraftPolicy::apply_costs(int64_t committed) {
const int bucket_now = bk_;
for (; n < held_.size() && held_[n].end < committed; ++n) {
const HeldCost& h = held_[n];
if (learning_) learner_.add(h.bucket, h.t, h.ms);
if (learning_) learner_.add(h.bucket, h.t, h.ms, h.age);
if (calib_on_) calib_add(h.bucket, h.t, h.ms, h.age);
if (fixed_) continue;
bk_ = h.bucket; // observe()'s update, in the bucket the round ran in
const double ms = clamp_sample(h.t, h.ms);
@@ -584,7 +1021,7 @@ int DraftPolicy::chain(int t_mtp, double p_mtp, int k_avail, int match) const {
void DraftPolicy::observe_chain(int t_mtp, int k, int accepted, int match, double round_ms) {
const int t = std::clamp(t_mtp + k, 1, kMaxT);
if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms);
if (learning_ && round_ms > 0) learner_.add(bk_, t, round_ms, busy_age_);
if (round_ms > 0 && !fixed_) {
round_ms = clamp_sample(t, round_ms);
const double alpha = robust_ ? std::max(kCostAlpha, 1.0 / (cost_n_[bk_][t] + 1.0)) : kCostAlpha; // a running mean for the first samples
+573 -6
View File
@@ -8,6 +8,7 @@
// 5. the policy never proposes a window beyond its cap.
#include "strata/spec/draft_policy.hpp"
#include <cmath>
#include <cstdint>
#include <cstdio>
#include <filesystem>
@@ -279,6 +280,89 @@ int main() {
check(p.learner().rounds() == 3 && p.learner().samples(0, 4) == 2 && p.learner().samples(0, 2) == 1,
"learning on: observe, observe_chain and held times are collected");
}
{
// The fixture of the Mac lane's fresh learning run (M5 Max, Q2_0, 30 requests of 256 tokens): sample counts and mean round ms per window size.
// 4 rows had 2 samples: its value comes from its neighbours, not from the two samples.
using strata::spec::CostLearner;
const auto fill = [](CostLearner& L, int t, int n, double ms, double age) { // n samples around ms (+-1 %, mean ms)
for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.005 * ((i % 5) - 2)), age);
};
CostLearner M;
fill(M, 1, 1193, 13.50, 2.0); fill(M, 2, 894, 15.74, 2.0); fill(M, 3, 1834, 18.40, 2.0); fill(M, 4, 2, 22.62, 2.0); fill(M, 5, 83, 24.95, 2.0);
const std::vector<double> t = M.table(0, 20);
check(t.size() == 5 && std::fabs(t[0] - 13.50) < 0.05 && std::fabs(t[2] - 18.40) < 0.05 && std::fabs(t[4] - 24.95) < 0.05, "fit: the well-sampled sizes are their trimmed means");
check(t.size() == 5 && std::fabs(t[3] - (18.40 + 24.95) / 2.0) < 0.05, "fit: 4 rows (2 samples) lie between its neighbours, not at its own 22.62");
check(M.rounds() == 4006 && M.late_rounds() == 0, "fit: all 4,006 rounds of the fixture were fresh");
// a size above the measured ones (5 rows with 8 samples): the straight line through the two largest measured sizes
CostLearner E;
fill(E, 1, 600, 12.5, 2.0); fill(E, 2, 400, 14.2, 2.0); fill(E, 3, 700, 16.2, 2.0); fill(E, 5, 8, 99.0, 2.0);
const std::vector<double> e = E.table(0, 20);
check(e.size() == 5 && std::fabs(e[3] - (16.2 + 2.0)) < 0.05 && std::fabs(e[4] - (16.2 + 4.0)) < 0.05,
"fit: 4 and 5 rows above the measured sizes continue the line through 2 and 3 rows (8 samples of 5 rows are not trusted)");
bool mono = true;
for (size_t i = 1; i < e.size(); ++i) mono &= e[i] >= e[i - 1];
CostLearner Dn; // a size measured cheaper than the one before it (noise): the table does not fall
fill(Dn, 1, 100, 20.0, 2.0); fill(Dn, 2, 100, 19.0, 2.0); fill(Dn, 3, 100, 25.0, 2.0);
const std::vector<double> d = Dn.table(0, 20);
mono &= d.size() == 3 && d[1] >= d[0] && d[2] >= d[1];
check(mono, "fit: the table never falls from one size to the next");
// busy age: a fast state for the first seconds of a run, a slow and steeper one later; only the first is kept
CostLearner B;
for (int i = 0; i < 1400; ++i) {
B.add(0, 1, 12.5, 4.0); B.add(0, 2, 14.2, 4.0); B.add(0, 3, 16.2, 4.0); // fresh (the first seconds of a run)
B.add(0, 1, 14.5, 60.0); B.add(0, 2, 17.1, 60.0); B.add(0, 3, 20.2, 60.0); // the same machine after a minute of load
if (i % 25 == 0) { B.add(0, 5, 21.3, 4.0); B.add(0, 5, 27.7, 60.0); }
}
const std::vector<double> b = B.table(0, 20);
check(B.rounds() == 4200 + 56 && B.late_rounds() == 4200 + 56, "busy age: late rounds are counted and not kept");
check(b.size() == 5 && std::fabs(b[2] - 16.2) < 0.05 && std::fabs(b[4] / b[2] - 21.3 / 16.2) < 0.01,
"busy age: the table is the fast state (5 rows against 3 rows 1.31, not 1.37 of the late rounds)");
CostLearner U; // an age that is not known counts as fresh
U.add(0, 3, 16.0);
check(U.rounds() == 1 && U.late_rounds() == 0, "busy age: an unknown age (none given) is kept");
// readiness: a stretch that never paused ends with its first seconds after 3 x the quota; one that is mid-way is not ready
CostLearner Bur;
for (int i = 0; i < 300; ++i) { Bur.add(0, 1, 12.5, 2.0); Bur.add(0, 2, 14.2, 2.0); Bur.add(0, 3, 16.2, 2.0); } // 900 fresh rounds
check(!Bur.check(1000, 20).ready, "ready: 900 fresh rounds and nothing else is not ready");
for (int i = 0; i < 700; ++i) Bur.add(0, 3, 20.2, 90.0);
check(!Bur.check(1000, 20).ready, "ready: late rounds below 3 x the quota do not end a short stretch");
CostLearner Bur2; // one long burst: 330 fresh rounds, then 2,700 late ones
for (int i = 0; i < 110; ++i) { Bur2.add(0, 1, 12.5, 2.0); Bur2.add(0, 2, 14.2, 2.0); Bur2.add(0, 3, 16.2, 2.0); }
for (int i = 0; i < 2000; ++i) Bur2.add(0, 3, 20.2, 90.0);
check(!Bur2.check(1000, 20).ready, "ready: 330 fresh + 2,000 late rounds (under 3 x the quota) is not ready");
for (int i = 0; i < 700; ++i) Bur2.add(0, 3, 20.2, 90.0);
const CostLearner::Verdict bv = Bur2.check(1000, 20);
const std::vector<double> bt = Bur2.table(0, 20);
check(bv.ready && !bv.disturbed && bt.size() == 3 && std::fabs(bt[2] - 16.2) < 0.05,
"ready: one burst that never paused ends after 3 x the quota, with the table of its first seconds");
CostLearner Few; // 150 fresh rounds only: not enough even after a very long burst
for (int i = 0; i < 50; ++i) { Few.add(0, 1, 12.5, 2.0); Few.add(0, 2, 14.2, 2.0); Few.add(0, 3, 16.2, 2.0); }
for (int i = 0; i < 5000; ++i) Few.add(0, 3, 20.2, 90.0);
check(!Few.check(1000, 20).ready, "ready: under a fifth of the quota kept is never ready");
// a machine without a state effect (the Radeon 780M: 75.5 ms for one row early, 76.0 late; windows of 1, 3 and 6 rows): every round counts, the rare sizes
// get all their samples (3 rows: 8 fresh + 100 late)
CostLearner R;
fill(R, 1, 80, 75.5, 2.0); fill(R, 3, 8, 111.0, 2.0); fill(R, 6, 3, 178.0, 2.0);
fill(R, 1, 1200, 76.0, 40.0); fill(R, 3, 100, 111.2, 40.0); fill(R, 6, 14, 178.1, 40.0);
const std::vector<double> rt = R.table(0, 20);
check(!R.state_effect(0, 20), "pooled: 0.7 % between early and late rounds is no state effect");
check(rt.size() == 6 && std::fabs(rt[2] - 111.1) < 0.2 && std::fabs(rt[0] - 76.0) < 0.2, "pooled: the table uses every round (3 rows from 108 samples)");
check(R.check(1000, 20).ready, "pooled: ready after the quota of rounds of any age");
check(B.state_effect(0, 20), "state effect: 16 % between early and late rounds is one");
// the policy hands the age to the learner, and a held (gated) time keeps the age it had
DraftPolicy pa(6);
pa.set_learning(true);
pa.set_busy_age(30.0);
pa.observe(false, 3, 1, 0, 20.0);
pa.set_busy_age(2.0);
pa.observe(false, 3, 1, 0, 16.0);
check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 1 && pa.learner().samples(0, 3) == 1, "policy: a round is kept by the busy age it ran at");
pa.set_busy_age(40.0);
pa.defer_cost(5, 3, 21.0);
pa.set_busy_age(1.0);
pa.apply_costs(100);
check(pa.learner().rounds() == 1 && pa.learner().late_rounds() == 2, "policy: a held time keeps the busy age of its round");
}
{
// The table file: a round trip, another key, a cut-short file, a missing file, a folder that does not exist yet.
namespace fs = std::filesystem;
@@ -298,9 +382,9 @@ int main() {
"file: read back with its key, every bucket as written");
check(!strata::spec::read_cost_file(path, "card B|engine 1|model m spec 6", r, why) && !why.empty(), "file: another key is not loaded");
check(!strata::spec::read_cost_file((dir / "none.costs").string(), c.key, r, why), "file: a missing file is not loaded");
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a cut-short file (no end line) is not loaded");
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,abc\nend\n"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,abc\nend\n"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed table is not loaded");
check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why), "file: a bad file is replaced whole");
check(!fs::exists(fs::path(path + ".tmp"), ec), "file: no temporary file is left");
@@ -308,23 +392,506 @@ int main() {
c.cpu_share = 0.45;
check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.cpu_share == 0.45,
"file: the CPU prompt share is stored and read back with the table");
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nshare 1.7\nend\n"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 1.7\nend\n"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a share outside 0..1 is not loaded");
// the decode PCIe share PcieAuto settled on (repeatable output): stored and read back; a file written before it has none, and
// still loads (the engine then refines the share as before and writes it)
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nshare 0.900\nend\n"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\nshare 0.900\nend\n"; }
check(strata::spec::read_cost_file(path, "x", r, why) && r.cpu_share == 0.9 && r.pcie_frac < 0.0,
"file: a file from before the PCIe share loads, with no PCIe share");
c.pcie_frac = 0.15;
check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && r.pcie_frac == 0.15 &&
r.cpu_share == 0.45 && r.tables[0].size() == 4,
"file: the PCIe share is stored and read back with the table and the prompt share");
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\npcie -0.2\nend\n"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie -0.2\nend\n"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a PCIe share outside 0..1 is not loaded");
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\npcie 0.15x\nend\n"; }
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18\npcie 0.15x\nend\n"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a malformed PCIe share is not loaded");
// version 1 (learned from every round, so from the slow state of a long burst): not loaded, learned again
{ std::ofstream f(path, std::ios::binary | std::ios::trunc); f << "strata-draft-costs 1\nkey x\nbucket 0 15.1,18\nend\n"; }
check(!strata::spec::read_cost_file(path, "x", r, why) && why.find("format") != std::string::npos, "file: a version 1 table is not loaded (learned again)");
// a start closed in the middle of learning leaves no table: nothing is written before the stretch is ready, and a half-written temporary file
// (the process died while writing) is never read as the table
fs::remove(fs::path(path), ec);
{ std::ofstream f(path + ".tmp", std::ios::binary | std::ios::trunc); f << "strata-draft-costs 2\nkey x\nbucket 0 15.1,18"; }
check(!strata::spec::read_cost_file(path, "x", r, why), "file: a half-written temporary file beside a missing table is not a table");
check(strata::spec::write_cost_file(path, c, why) && strata::spec::read_cost_file(path, c.key, r, why) && !fs::exists(fs::path(path + ".tmp"), ec),
"file: the next write replaces the leftover temporary file and the table loads");
fs::remove_all(dir, ec);
}
{
// sizes with too few samples: a rough measurement counts when it is not below the trend, a stalled handful does not, and a fill above the
// measured sizes never flattens the measured trend (Radeon 780M, 11-13: sizes 1 / 3 measured at 76.2 / 111.6 ms, size 4 with 6 rounds at 143)
using strata::spec::CostLearner;
const auto fill = [](CostLearner& L, int t, int n, double ms) {
for (int i = 0; i < n; ++i) L.add(0, t, ms * (1.0 + 0.004 * ((i % 5) - 2)));
};
CostLearner R;
fill(R, 1, 1279, 76.2); fill(R, 2, 2, 97.0); fill(R, 3, 126, 111.6); fill(R, 4, 6, 143.0);
const std::vector<double> t = R.table(0, 20);
check(t.size() == 4 && std::fabs(t[3] - 143.0) < 0.5, "sizes: 6 rounds of 4 rows (143 ms, above the line's 129) count by their median");
check(t.size() == 4 && std::fabs(t[1] - (76.2 + 111.6) / 2.0) < 0.2, "sizes: 2 rounds of 2 rows are filled in linearly");
const std::vector<double> u = R.table(0, 20, 6);
bool mono = u.size() == 6;
for (size_t i = 1; i < u.size(); ++i) mono &= u[i] >= u[i - 1];
check(u.size() == 6 && mono && u[4] >= 143.0 + 0.9 * (143.0 - 111.6) && u[5] > u[4], "sizes: 5 and 6 rows continue the steeper measured slope (32 ms a row), not the first segment's 18");
CostLearner S;
fill(S, 1, 600, 12.5); fill(S, 2, 400, 14.2); fill(S, 3, 700, 16.2); fill(S, 4, 6, 99.0);
const std::vector<double> s = S.table(0, 20);
check(s.size() == 4 && std::fabs(s[3] - 18.2) < 0.05, "sizes: a handful of rounds 5x above the trend (a stall) is not a measurement");
CostLearner Q; // costs 10 / 20 / 35: the fill goes on at 15 ms a row, not at 10
fill(Q, 1, 100, 10.0); fill(Q, 2, 100, 20.0); fill(Q, 3, 100, 35.0);
const std::vector<double> q = Q.table(0, 20, 5);
check(q.size() == 5 && q[3] >= 35.0 + 15.0 - 0.1 && q[4] >= 35.0 + 30.0 - 0.1, "sizes: a size above the measured ones never costs less than the last slope says");
check(Q.table(0, 20, 3).size() == 3 && Q.table(1, 20, 5).empty(), "sizes: upto adds nothing below the largest size seen, and an empty bucket stays empty");
// the learning stretch measures the sizes it has too few rounds of
const auto feed = [](DraftPolicy& p, int n) {
for (int i = 0; i < n; ++i) { p.observe(false, 1, 0, 0, 76.0); if (i % 4 == 0) p.observe(false, 3, 2, 0, 111.0); }
};
DraftPolicy y(8);
y.set_learning(true);
feed(y, 40);
y.choose(1, 5, 3);
check(y.forced_rounds() == 0, "explore: nothing is forced in the first rounds of a stretch");
feed(y, 300);
const DraftPolicy::Pick f1 = y.choose(1, 5, 3);
check(f1.lookup && f1.t == 2 && y.forced_rounds() == 1, "explore: after the first rounds the smallest size with few samples is taken, if a proposal reaches it");
const DraftPolicy::Pick f2 = y.choose(1, 1, 3);
check(y.forced_rounds() == 2 && f2.lookup && f2.t == 2, "explore: a proposal of one draft reaches 2 rows only");
DraftPolicy y16(16); // the budget: 14 sizes that need 30 rounds each are more than the stretch's budget
y16.set_learning(true);
feed(y16, 400);
for (int i = 0; i < 1200; ++i) {
const DraftPolicy::Pick pk = y16.choose(1, 15, 3);
y16.observe(pk.lookup, pk.t, pk.t > 1 ? pk.t - 1 : 0, 3, 76.0 + 17.0 * (pk.t - 1));
}
check(y16.forced_rounds() == DraftPolicy::kExploreBudget, "explore: the forced rounds stop at the stretch's budget");
const int before = y16.forced_rounds();
for (int i = 0; i < 50; ++i) y16.choose(1, 15, 3);
check(y16.forced_rounds() == before, "explore: nothing is forced once the budget is spent");
DraftPolicy z(8); // the cap per size: with a budget left over, one size is still not forced more than kExplorePerSize times
z.set_learning(true);
feed(z, 400);
for (int i = 0; i < 200; ++i) { const DraftPolicy::Pick pk = z.choose(1, 1, 3); z.observe(pk.lookup, pk.t, 0, 3, 0.0); } // no time, so no sample ever arrives
check(z.forced_rounds() == DraftPolicy::kExplorePerSize, "explore: a size is forced at most kExplorePerSize times");
z.reset_learning();
check(z.forced_rounds() == 0 && z.learner().rounds() == 0, "explore: a new stretch starts with a new budget");
DraftPolicy n(8); // not learning, or fixed: the policy never takes a window for its size's sake
feed(n, 400);
n.choose(1, 5, 3);
DraftPolicy x(8);
x.set_learning(true);
feed(x, 400);
const double ms[3] = {76.0, 95.0, 111.0};
x.set_fixed_costs(ms, 3);
for (int i = 0; i < 20; ++i) x.choose(1, 5, 3);
check(n.forced_rounds() == 0 && x.forced_rounds() == 0, "explore: not while learning is off, and not once the costs are fixed");
DraftPolicy w(8); // a size no proposal reaches stays filled in
w.set_learning(true);
feed(w, 600);
for (int i = 0; i < 100; ++i) { const DraftPolicy::Pick pk = w.choose(1, 1, 3); w.observe(pk.lookup, pk.t, 1, 3, 95.0); }
const std::vector<double> wt = w.learner().table(0, 20, 6);
check(w.learner().samples(0, 4) == 0 && wt.size() == 6 && wt[3] > wt[2] && wt[5] > wt[3], "explore: a size no proposal reaches is filled in above the measured ones");
// the window of a round that has no proposal: any undersampled size up to the cap, but not the size it already is
DraftPolicy m(8);
m.set_learning(true);
feed(m, 400);
check(m.explore_window(3, 6) == 2 && m.forced_rounds() == 1, "window: the smallest unmeasured size is run, not the one the round already has");
check(m.explore_window(2, 6) == 4, "window: a size with samples (3 rows) is skipped, the next unmeasured one is run");
check(m.explore_window(1, 1) == 0, "window: a cap of one row leaves nothing to run");
DraftPolicy m0(8);
feed(m0, 400);
check(m0.explore_window(3, 6) == 0, "window: nothing while learning is off");
DraftPolicy lk(8); // a round with no proposal at all: a lookup-type window of an unmeasured size
lk.set_learning(true);
feed(lk, 400);
check(lk.explore_lookup(5) == 2 && lk.explore_lookup(1) == 0 && m0.explore_lookup(5) == 0, "window: a round without a proposal can time a lookup-type size, only while learning");
// a late round counts only where the stretch has shown no state effect
DraftPolicy e1(8); // fresh 76 ms, late 80 ms: a state effect
e1.set_learning(true);
e1.set_busy_age(2.0);
for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 76.0);
e1.set_busy_age(100.0);
for (int i = 0; i < 60; ++i) e1.observe(false, 1, 0, 0, 80.0);
check(e1.explore_window(3, 6) == 0, "gate: a late round is not forced when the stretch has a state effect");
e1.set_busy_age(2.0);
check(e1.explore_window(3, 6) == 2, "gate: a fresh round is");
DraftPolicy e2(8); // fresh and late alike: no state effect
e2.set_learning(true);
e2.set_busy_age(2.0);
for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.0);
e2.set_busy_age(100.0);
for (int i = 0; i < 60; ++i) e2.observe(false, 1, 0, 0, 76.2);
check(e2.explore_window(3, 6) == 2, "gate: a late round is forced when the stretch shows no state effect");
DraftPolicy e3(8); // late rounds only so far: unknown, so not forced
e3.set_learning(true);
e3.set_busy_age(100.0);
for (int i = 0; i < 150; ++i) e3.observe(false, 1, 0, 0, 76.0);
check(e3.explore_window(3, 6) == 0, "gate: a late round is not forced while the stretch cannot tell yet");
// a padded window: a short proposal, a size past it that has no samples, the caller allows filler rows
DraftPolicy g(8);
g.set_learning(true);
feed(g, 400);
for (int i = 0; i < 40; ++i) g.observe_forced(2, 95.0); // size 2 measured (3 is fed already)
const DraftPolicy::Pick np = g.choose(1, 1, 3);
check(g.forced_rounds() == 0 || !np.lookup || np.pad == 0, "pad: without pad_cap a proposal of one draft never makes a longer window");
const DraftPolicy::Pick gp = g.choose(1, 1, 3, 7);
check(gp.lookup && gp.t == 4 && gp.pad == 2 && g.forced_rounds() == 1, "pad: with pad_cap the smallest unmeasured size is run, 2 filler rows past the proposal");
const double q0 = g.lookup_rate(3);
for (int i = 0; i < 30; ++i) g.observe_forced(4, 143.0);
check(g.lookup_rate(3) == q0 && g.learner().samples(0, 4) == 30, "pad: a forced round feeds the learner and no lookup statistic");
const DraftPolicy::Pick g5 = g.choose(1, 1, 3, 7);
check(g5.lookup && g5.t == 5 && g5.pad == 3, "pad: the next unmeasured size follows once one has its samples");
check(g.choose(1, 1, 3, 1).pad == 0, "pad: a pad_cap of one draft makes no filler");
}
{ // DRAFT-COSTS-5: a real price is the MEDIAN of its 16 rounds; the monotone guard repairs an inversion from the trusted side
namespace fs = std::filesystem;
using strata::spec::CalAcc;
using strata::spec::CostFile;
using strata::spec::CostLearner;
using Cal = std::array<std::array<CalAcc, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
using Rc = std::array<std::array<double, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
using Real = std::array<unsigned, CostLearner::kCtxBuckets>;
const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90};
const Cal cal0{};
const Rc rc0{};
{ // one cold round among 16 (the first use of a width): the real price is the median, a mean would be moved by it
DraftPolicy m(8);
m.set_fixed_costs(tab, 5, 0);
m.start_calibration(false, Real{}, cal0, rc0);
for (int i = 0; i < 15; ++i) m.observe(false, 2, 1, 0, 14.5);
m.observe(false, 2, 1, 0, 40.0);
CostFile cf;
std::string rep;
check(m.calibrate(cf, rep) && (cf.real[0] & 2u), "median: the 16th round marks the size real");
check(std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: one cold round among 16 does not move the real price");
}
{ // eight slow rounds in the first request, eight normal ones after: the median sits between (even count: mean of the two middle rounds)
DraftPolicy m(8);
m.set_fixed_costs(tab, 5, 0);
m.start_calibration(false, Real{}, cal0, rc0);
for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 15.0);
for (int i = 0; i < 8; ++i) m.observe(false, 2, 1, 0, 14.0);
CostFile cf;
std::string rep;
check(m.calibrate(cf, rep) && std::fabs(cf.real_cost[0][2] - 14.5) < 1e-9, "median: sixteen rounds of two values: the mean of the two middle ones");
}
{ // the rounds survive the file (a start collects part of them, the next start the rest) and a file line without them still loads (mean as before)
const fs::path dir = fs::temp_directory_path() / ("strata-dpt-med-" + std::to_string((unsigned long long) (uintptr_t) &tab));
const std::string path = (dir / "m.costs").string();
CostFile c;
c.key = "k";
c.tables[0] = {12.68, 14.30, 16.41};
c.cal[0][2] = CalAcc{};
c.cal[0][2].n = 3;
c.cal[0][2].sum = 43.5;
c.cal[0][2].nv = 3;
c.cal[0][2].vals = {14.5, 14.0, 15.0};
c.cal[0][3].n = 2; // no rounds kept (a file of an older build): only the sum
c.cal[0][3].sum = 33.0;
std::string why;
check(strata::spec::write_cost_file(path, c, why), "median file: written");
CostFile r;
check(strata::spec::read_cost_file(path, c.key, r, why), "median file: read back");
check(r.cal[0][2].n == 3 && r.cal[0][2].nv == 3 && std::fabs((double) r.cal[0][2].vals[1] - 14.0) < 1e-6 && std::fabs(r.cal[0][2].sum - 43.5) < 1e-3,
"median file: the kept rounds come back with their count and sum");
check(r.cal[0][3].n == 2 && r.cal[0][3].nv == 0 && std::fabs(r.cal[0][3].sum - 33.0) < 1e-3, "median file: a line without rounds keeps only n and sum (the mean decides)");
std::error_code ec;
fs::remove_all(dir, ec);
}
{ // fixture 1: the srv118 table as taken over (a real 2-row price of 20.08 ms, the sizes above it real or unreached): the outlier is lowered, 3-6 rows keep their prices
const double t12[12] = {7.928, 20.085, 9.577, 10.524, 12.136, 13.270, 19.223, 21.293, 23.659, 26.024, 28.390, 30.756};
Real real0{};
real0[0] = 63u;
Cal cal1{};
Rc rc1{};
const double rcv[7] = {0.0, 7.9276, 20.0847, 9.5771, 10.5245, 12.1355, 13.2695};
for (int t = 1; t <= 6; ++t) rc1[0][(size_t) t] = rcv[t];
DraftPolicy p(12);
p.set_fixed_costs(t12, 12, 0);
p.start_calibration(false, real0, cal1, rc1, 100);
bool mono = true;
for (int t = 2; t <= 12; ++t) mono = mono && p.cost_ms(t) >= p.cost_ms(t - 1) - 1e-12;
check(mono, "guard: the used table never costs less for more rows");
check(std::fabs(p.cost_ms(2) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(3) - 9.5771) < 1e-9 && std::fabs(p.cost_ms(4) - 10.5245) < 1e-9 && std::fabs(p.cost_ms(6) - 13.2695) < 1e-9,
"guard: the 20 ms 2-row outlier is lowered to the next real price, not raised into every larger size");
check(std::fabs(p.cost_ms(1) - 7.9276) < 1e-9, "guard: the 1-row price is untouched");
}
{ // fixture 2: the Q2_0 table at take-over: 4 rows an unreached live value above the real 5 rows
const double q[5] = {12.966, 14.482, 17.042, 21.796, 21.361};
Real real0{};
real0[0] = 23u; // sizes 1, 2, 3, 5
Cal cal1{};
Rc rc1{};
rc1[0][1] = 12.9665;
rc1[0][2] = 14.4821;
rc1[0][3] = 17.0419;
rc1[0][5] = 21.3610;
DraftPolicy p(8);
p.set_fixed_costs(q, 5, 0);
p.start_calibration(false, real0, cal1, rc1, 100);
check(std::fabs(p.cost_ms(4) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(5) - 21.3610) < 1e-9 && std::fabs(p.cost_ms(3) - 17.0419) < 1e-9,
"guard: an unreached 4 rows above the real 5 rows is lowered to it");
}
{ // fixture 3: the IQ3_S table at take-over: 4 rows 28.31 (a live value) above the real 5 rows 25.00
const double q[5] = {14.734, 16.967, 20.096, 28.312, 25.005};
Real real0{};
real0[0] = 23u;
Cal cal1{};
Rc rc1{};
rc1[0][1] = 14.7341;
rc1[0][2] = 16.9669;
rc1[0][3] = 20.0959;
rc1[0][5] = 25.0046;
DraftPolicy p(8);
p.set_fixed_costs(q, 5, 0);
p.start_calibration(false, real0, cal1, rc1, 100);
check(std::fabs(p.cost_ms(4) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(5) - 25.0046) < 1e-9 && std::fabs(p.cost_ms(2) - 16.9669) < 1e-9,
"guard: IQ3_S 4 rows 28.31 is lowered to the real 5 rows 25.00");
}
{ // a real size above an unreached next size is not lowered by the guess: the guess is lifted to it
const double q[5] = {12.0, 14.0, 20.0, 15.0, 16.0};
Real real0{};
real0[0] = 4u; // size 3 real at 20.0
Cal cal1{};
Rc rc1{};
rc1[0][3] = 20.0;
DraftPolicy p(8);
p.set_fixed_costs(q, 5, 0);
p.start_calibration(false, real0, cal1, rc1, 100);
check(std::fabs(p.cost_ms(3) - 20.0) < 1e-9 && p.cost_ms(4) >= 20.0 - 1e-9 && p.cost_ms(5) >= p.cost_ms(4) - 1e-12 && std::fabs(p.cost_ms(2) - 14.0) < 1e-9,
"guard: a real price is kept against a guessed larger size, which is lifted to it");
}
}
{ // calibration against real rounds
using strata::spec::CalAcc;
using strata::spec::CostFile;
using strata::spec::CostLearner;
using strata::spec::read_cost_file;
using strata::spec::write_cost_file;
using Cal = std::array<std::array<CalAcc, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
using Rc = std::array<std::array<double, CostLearner::kMaxT + 1>, CostLearner::kCtxBuckets>;
using Real = std::array<unsigned, CostLearner::kCtxBuckets>;
const double tab[5] = {12.68, 14.30, 16.41, 18.57, 20.90};
const Cal cal0{};
const Rc rc0{};
DraftPolicy c(8), live(8); // `live` has no table: a held table must decide exactly like it
c.set_fixed_costs(tab, 5, 0);
c.start_calibration(false, Real{}, cal0, rc0);
check(c.calibrating() && !c.calib_dirty() && c.table_held() && !c.fixed(), "calib: a table with uncalibrated sizes is held back: live costs, nothing collected yet");
bool same = true;
for (int i = 0; i < 15; ++i) {
const DraftPolicy::Pick pa = c.choose(i % 3 + 1, 5, 2), pb = live.choose(i % 3 + 1, 5, 2);
same = same && pa.lookup == pb.lookup && pa.t == pb.t && std::fabs(c.cost_ms(3) - live.cost_ms(3)) < 1e-12;
c.observe(false, 3, 2, 0, 16.70);
live.observe(false, 3, 2, 0, 16.70);
}
CostFile cf;
std::string rep;
check(same && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - live.cost_ms(4)) < 1e-12,
"calib: while held back, picks and costs equal those of a policy without a table (the live cost follows the rounds)");
check(c.calibrate(cf, rep) && rep.empty() && cf.cal[0][3].n == 15, "calib: 15 real rounds are kept, nothing replaced");
c.observe(false, 3, 2, 0, 16.70);
check(c.calibrate(cf, rep) && !rep.empty() && (cf.real[0] & 4u) && std::fabs(cf.real_cost[0][3] - 16.70) < 1e-9 && std::fabs(cf.tables[0][2] - 16.41) < 1e-9,
"calib: the 16th real round marks the size real; the file keeps the learned cost beside it");
check(c.table_held() && !c.fixed() && c.calibrating(), "calib: one real size is not enough: the table stays held back");
// the other four sizes get their 16 rounds: the table takes over at that request's end, at the real costs
const double rt[5] = {12.90, 14.60, 16.70, 19.90, 21.30};
for (int t = 1; t <= 5; ++t)
if (t != 3)
for (int i = 0; i < 16; ++i) c.observe(t == 4 || t == 5, t, 1, 0, rt[t - 1]);
check(c.calibrate(cf, rep) && c.fixed() && !c.table_held() && !c.calibrating(), "calib: with the last size calibrated the table is used");
check(std::fabs(c.cost_ms(1) - 12.90) < 1e-9 && std::fabs(c.cost_ms(3) - 16.70) < 1e-9 && std::fabs(c.cost_ms(4) - 19.90) < 1e-9 && std::fabs(c.cost_ms(5) - 21.30) < 1e-9,
"calib: the real costs decide");
for (int i = 0; i < 40; ++i) c.observe(false, 3, 2, 0, 15.0);
check(!c.calib_dirty() && std::fabs(c.cost_ms(3) - 16.70) < 1e-9, "calib: a real size never changes again");
// a lookup size reached once per request: its rounds come across starts through the file
CostFile cd;
cd.key = "k";
Cal cal1 = cal0;
Real real1{};
Rc rc1 = rc0;
for (int start = 0; start < 16; ++start) {
DraftPolicy e(8);
e.set_fixed_costs(tab, 5, 0);
e.start_calibration(false, real1, cal1, rc1);
e.observe(true, 4, 2, 0, 18.9);
std::string r2;
check(e.calibrate(cd, r2), "calib: a start with one real round of a size writes the file");
cal1 = cd.cal;
real1 = cd.real;
rc1 = cd.real_cost;
}
check((cd.real[0] & 8u) != 0 && std::fabs(cd.real_cost[0][4] - 18.9) < 1e-9 && cd.cal[0][4].n == 0 && std::fabs(cd.tables[0][3] - 18.57) < 1e-9,
"calib: 16 starts of one round each calibrate the size");
DraftPolicy again(8); // a start from that file: size 4 real, the others not: the table is held back
again.set_fixed_costs(tab, 5, 0);
again.start_calibration(false, real1, cal1, rc1);
check(again.table_held() && !again.fixed() && again.calibrating(), "calib: a restart with sizes still uncalibrated keeps the table held back");
{ // a file with every size real: the table is used from the first round, at the real costs
Real all{};
all[0] = 31u;
Rc rcall = rc0;
for (int t = 1; t <= 5; ++t) rcall[0][(size_t) t] = tab[t - 1] * 1.03;
DraftPolicy u(8);
u.set_fixed_costs(tab, 5, 0);
u.start_calibration(false, all, cal0, rcall);
check(u.fixed() && !u.table_held() && !u.calibrating() && std::fabs(u.cost_ms(4) - 18.57 * 1.03) < 1e-9 && std::fabs(u.cost_ms(1) - 12.68 * 1.03) < 1e-9,
"calib: a start from a fully calibrated file uses the table at the real costs");
}
{ // sizes that real requests never reach: after kCalibReqs requests the table is used anyway, those sizes at a scaled learned cost
DraftPolicy bd(8);
bd.set_fixed_costs(tab, 5, 0);
bd.start_calibration(false, Real{}, cal0, rc0, 0);
CostFile cb;
std::string rb;
for (int i = 0; i < 16; ++i) bd.observe(false, 2, 1, 0, 14.60);
bd.calibrate(cb, rb);
for (int rq = 2; rq < DraftPolicy::kCalibReqs; ++rq) {
bd.observe(false, 3, 2, 0, 16.70);
bd.calibrate(cb, rb);
}
check(bd.table_held() && !bd.fixed() && cb.reqs == DraftPolicy::kCalibReqs - 1, "budget: held back before the last request of the budget");
bd.observe(false, 3, 2, 0, 16.70);
const bool wr = bd.calibrate(cb, rb);
const double rr = (14.60 / 14.30 + 16.70 / 16.41) / 2.0;
check(wr && bd.fixed() && !bd.table_held() && cb.reqs == DraftPolicy::kCalibReqs && bd.calibrating(), "budget: after kCalibReqs requests the table is used, calibration goes on");
check(std::fabs(bd.cost_ms(2) - 14.60) < 1e-9 && std::fabs(bd.cost_ms(3) - 16.70) < 1e-9 && std::fabs(bd.cost_ms(1) - 12.68) < 1e-9 &&
std::fabs(bd.cost_ms(4) - 18.57 * rr) < 1e-6 && std::fabs(bd.cost_ms(5) - 20.90 * rr) < 1e-6,
"budget: real sizes at their real cost, sizes not reached at learned x the mean ratio, size 1 at its learned cost");
DraftPolicy bs(8); // a start from that file: used at once
bs.set_fixed_costs(tab, 5, 0);
bs.start_calibration(false, cb.real, cb.cal, cb.real_cost, cb.reqs);
check(bs.fixed() && !bs.table_held() && std::fabs(bs.cost_ms(4) - 18.57 * rr) < 1e-6, "budget: a start after the budget uses the table at once, same prices");
for (int i = 0; i < 16; ++i) bd.observe(true, 4, 2, 0, 19.90); // a size the policy now chooses collects its own rounds while the table is in use
check(bd.calibrate(cb, rb) && bd.fixed() && (cb.real[0] & 8u) && std::fabs(bd.cost_ms(4) - 19.90) < 1e-9 && cb.reqs == DraftPolicy::kCalibReqs,
"budget: in use, a size with its own kCalibN rounds becomes real");
}
{ // a machine with no table: built from the real rounds, no learning stretch, live costs decide until the take-over
CostFile c0;
c0.key = "k";
c0.fresh = true;
DraftPolicy p(8), lv(8);
p.start_passive(c0, 5);
check(p.passive() && p.table_held() && !p.fixed() && p.calibrating() && !p.learning(), "passive: held from the first request, no learning");
bool same = true;
for (int i = 0; i < 40; ++i) {
const DraftPolicy::Pick pa = p.choose(i % 3 + 1, 5, 2), pb = lv.choose(i % 3 + 1, 5, 2);
same = same && pa.lookup == pb.lookup && pa.t == pb.t && pa.pad == 0 && std::fabs(p.cost_ms(3) - lv.cost_ms(3)) < 1e-12;
p.set_busy_age(2.0);
p.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3));
lv.observe(i % 3 == 0, i % 3 + 1, 1, 0, 12.7 + 2.0 * (i % 3));
}
check(same && p.forced_rounds() == 0, "passive: picks and costs equal a policy without a table, no forced window");
CostFile cp;
std::string rp;
check(p.calibrate(cp, rp) && cp.fresh && cp.tables[0].empty() && cp.reqs == 1, "passive: the file has no table yet, one request counted");
// only the first seconds of a busy run are counted
DraftPolicy q(8);
q.start_passive(c0, 5);
q.set_busy_age(2.0);
for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6);
q.set_busy_age(50.0);
for (int i = 0; i < 10; ++i) q.observe(false, 2, 1, 0, 14.6);
CostFile cq;
q.calibrate(cq, rp);
check(cq.cal[0][2].n == 9 && cq.fresh, "passive: rounds late in a busy run are not counted; the first round of a size has no live cost to clamp to");
// the sums survive a restart: 9 + 7 more = 16 own rounds make the size real
cq.key = "k";
std::string wpath = "dp_passive_test.costs", wwhy;
check(write_cost_file(wpath, cq, wwhy), "passive: file written");
CostFile cr;
check(read_cost_file(wpath, "k", cr, wwhy) && cr.fresh && cr.tables[0].empty() && cr.cal[0][2].n == 9, "passive: a file with no table reads back");
std::remove(wpath.c_str());
DraftPolicy r(8);
r.start_passive(cr, 5);
r.set_busy_age(1.0);
for (int i = 0; i < 8; ++i) r.observe(false, 2, 1, 0, 14.6);
CostFile cs;
check(r.calibrate(cs, rp) && (cs.real[0] & 2u) && std::fabs(cs.real_cost[0][2] - 14.6) < 1e-9 && r.passive(), "passive: the size is real after 16 own rounds across a restart");
// take-over by every size real: the real costs, a table in the file
DraftPolicy a(8);
a.start_passive(c0, 5);
a.set_busy_age(1.0);
const double rt[5] = {12.9, 14.6, 16.7, 19.9, 21.3};
for (int t = 1; t <= 5; ++t)
for (int i = 0; i < 17; ++i) a.observe(t >= 4, t, 1, 0, rt[t - 1]);
CostFile ca;
check(a.calibrate(ca, rp) && a.fixed() && !a.passive() && !a.table_held() && !a.calibrating() && !ca.fresh && ca.tables[0].size() == 5, "passive: every size real: the table takes over, the file has a table");
check(std::fabs(a.cost_ms(1) - 12.9) < 1e-9 && std::fabs(a.cost_ms(4) - 19.9) < 1e-9 && std::fabs(ca.tables[0][2] - 16.7) < 1e-9, "passive: the real costs decide, the file keeps them as the table");
// take-over after kCalibReqs requests: a size never reached takes the live cost, a never measured one the policy's prior
DraftPolicy b(8), lb(8);
b.start_passive(c0, 5);
b.set_busy_age(1.0);
for (int i = 0; i < 17; ++i) {
b.observe(false, 2, 1, 0, 14.6);
lb.observe(false, 2, 1, 0, 14.6);
}
for (int i = 0; i < 6; ++i) {
b.observe(true, 4, 2, 0, 19.9);
lb.observe(true, 4, 2, 0, 19.9);
}
CostFile cb2;
for (int rq = 0; rq < DraftPolicy::kCalibReqs; ++rq) {
b.observe(false, 2, 1, 0, 14.6);
b.calibrate(cb2, rp);
}
check(b.fixed() && !b.passive() && cb2.reqs == DraftPolicy::kCalibReqs && cb2.tables[0].size() == 5, "passive: after kCalibReqs requests the table takes over");
check(std::fabs(cb2.tables[0][1] - 14.6) < 1e-9 && std::fabs(cb2.tables[0][3] - 19.9) < 1e-9 && std::fabs(cb2.tables[0][2] - lb.cost_ms(3)) < 0.1 && std::fabs(b.cost_ms(4) - 19.9) < 1e-9,
"passive: real size 2 at its real cost, size 4 at its live cost, size 3 (never measured) at the policy's prior");
for (int i = 0; i < 17; ++i) b.observe(true, 4, 2, 0, 20.1); // the unreached size keeps collecting
CostFile cb3 = cb2;
check(b.calibrate(cb3, rp) && (cb3.real[0] & 8u) && std::fabs(b.cost_ms(4) - 20.1) < 1e-9, "passive: after the take-over a size still collects and becomes real at 16 own rounds (its price the median: 5 rounds of 19.9, 11 of 20.1)");
}
// the file round trip: state, real, real cost, cal
CostFile w;
w.key = "k2";
w.tables[0].assign(tab, tab + 5);
w.state_effect = true;
w.reqs = 7;
w.real[0] = 6u;
w.real_cost[0][2] = 14.6;
w.real_cost[0][3] = 16.7;
w.cal[0][4] = CalAcc{7, 131.0};
const std::string path = "dp_calib_test.costs";
std::string why;
check(write_cost_file(path, w, why), "calib file: written");
CostFile r;
check(read_cost_file(path, "k2", r, why) && r.state_effect && r.reqs == 7 && r.real[0] == 6u && r.cal[0][4].n == 7 && std::fabs(r.cal[0][4].sum - 131.0) < 1e-3 && r.cal[0][2].n == 0 &&
std::fabs(r.real_cost[0][2] - 14.6) < 1e-9 && std::fabs(r.real_cost[0][3] - 16.7) < 1e-9,
"calib file: state, real marks, real costs and collected rounds come back");
std::remove(path.c_str());
// a machine with a load-time effect counts only the first kFreshS seconds of a busy run
DraftPolicy f(8);
f.set_fixed_costs(tab, 5, 0);
f.start_calibration(true, Real{}, cal0, rc0);
f.set_busy_age(2.0);
for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 14.6);
f.set_busy_age(50.0);
for (int i = 0; i < 10; ++i) f.observe(false, 2, 1, 0, 17.0);
CostFile cfz;
std::string rz;
f.calibrate(cfz, rz);
check(cfz.cal[0][2].n == 10, "calib: with a state effect only fresh rounds are counted");
// a disturbed stretch (a stalled machine) is dropped, not taken
DraftPolicy g(8);
g.set_fixed_costs(tab, 5, 0);
g.start_calibration(false, Real{}, cal0, rc0);
for (int i = 0; i < 16; ++i) g.observe(false, 2, 0, 0, 40.0);
CostFile cg;
std::string rg;
g.calibrate(cg, rg);
check(rg.empty() && g.table_held() && cg.cal[0][2].n == 0 && (cg.real[0] & 2u) == 0, "calib: rounds far above the learned cost are dropped");
// a size that real requests never reach, and a machine whose real sizes are all 1 row: nothing is scaled
DraftPolicy h(8);
h.set_fixed_costs(tab, 5, 0);
h.start_calibration(false, Real{}, cal0, rc0);
for (int i = 0; i < 16; ++i) h.observe(false, 1, 0, 0, 13.0);
CostFile ch;
std::string rh;
h.calibrate(ch, rh);
check((ch.real[0] & 1u) != 0 && h.table_held() && !h.fixed(), "calib: one real size does not bring the table into use");
}
std::printf(g_fail ? "FAIL\n" : "PASS\n");
return g_fail ? 1 : 0;
}
+10 -3
View File
@@ -1599,7 +1599,7 @@ bool Prefill::carve(size_t T, void* alloc) {
}
bool Prefill::relayout(int64_t chunk, void *borrow, uint64_t borrow_bytes,
std::string &err) try {
std::string &err, int64_t /*tail*/) try {
Impl& m = *impl_;
if (!m.borrowed || borrow == nullptr || chunk <= 0 || chunk > m.T_max) {
err = "prefill: relayout needs borrowed buffers and a chunk of at most " + std::to_string(m.T_max);
@@ -2197,9 +2197,16 @@ void Prefill::set_ring_budget(int slots, int64_t small_max) {
double Prefill::pinned_share() { return g_pinned_share; }
int64_t Prefill::stream_all_min_tokens() { return stream_all_min(); }
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src) {
uint64_t Prefill::bytes_needed(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk, bool src, int64_t /*tail*/) {
return bytes_needed_impl(g, ss, chunk, false, src);
}
// The shared header (include/strata/prefill/prefill.hpp) carries the lent layout's MMQ tail (loan_rules.hpp) and the card's expert share for the
// switch-point rule. The SYCL engine has no tail buffers (no MMQ), so these members answer "no tail" (-1, room for any chunk) and the parameters
// are accepted and ignored; the interface is kept in step with the header, the layouts behave as before the tail existed.
int64_t Prefill::layout_tail() const { return -1; }
int64_t Prefill::tail_room() const { return INT64_MAX; }
bool Prefill::tail_matters(int64_t, bool) { return false; }
void Prefill::set_card_expert_share(int64_t, int64_t, double, double) {}
// What `init` really allocates when the prompt path owns its buffers (no loan): every cudaMalloc rounds up to a 2 MiB
// page, and the ring is one allocation (carve). `bytes_needed` stays the borrowed region's sum.
@@ -2209,7 +2216,7 @@ uint64_t Prefill::bytes_needed_owned(const core::ModelGeometry& g, const core::S
}
uint64_t Prefill::bytes_needed_impl(const core::ModelGeometry& g, const core::SessionState& ss, int64_t chunk,
bool owned_pages, bool src) {
bool owned_pages, bool src, int64_t /*tail*/) {
// the same allocation sequence as `init`, counted
const size_t T = (size_t) chunk;
bool ok = true;
+89
View File
@@ -6,6 +6,11 @@
#include "strata/prefill/loan_rules.hpp"
using strata::prefill::loan_rules::walk_chunk;
using strata::prefill::loan_rules::tail_need;
using strata::prefill::loan_rules::tail_layout;
using strata::prefill::loan_rules::segment_tail;
using strata::prefill::loan_rules::reuse_ok;
using strata::prefill::loan_rules::next_tail;
static int failed = 0;
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); ++failed; } } while (0)
@@ -52,6 +57,90 @@ int main() {
// empty or negative requests are passed through
CHECK(walk_chunk(0, 256, 1024) == 256 && walk_chunk(10, 0, 1024) == 0);
static_assert(walk_chunk(999, 1024, 1024) == 1023, "constexpr");
// ---- the tail of a lent fused layout (tail_need / tail_layout / segment_tail / reuse_ok)
// one chunk at or above the floor: no MMQ rows at all
CHECK(tail_need(1024, 1024, 1024) == 0);
CHECK(tail_need(8192, 8192, 1024) == 0);
CHECK(tail_need(4096, 2048, 1024) == 0); // two full chunks
// a short last chunk is the whole need
CHECK(tail_need(4097, 2048, 1024) == 1);
CHECK(tail_need(5000, 2048, 1024) == 904);
CHECK(tail_need(5120 + 1023, 5120, 1024) == 1023);
CHECK(tail_need(5120 + 1024, 5120, 1024) == 0); // a last chunk at the floor streams: fused
// a floor of 3,584 (the rule on an RTX A6000): the same segments now have a tail up to 3,583
CHECK(tail_need(8193, 8192, 3584) == 1);
CHECK(tail_need(4097, 2048, 3584) == 2048); // a layout of 2,048-token chunks is below the floor: not fused, every chunk is MMQ's
CHECK(tail_need(8193 + 2000, 8192, 3584) == 2001);
CHECK(tail_need(8192 + 3584, 8192, 3584) == 0);
// a segment read in one chunk below the floor, in a layout whose chunk reaches it (a reused big loan)
CHECK(tail_need(2000, 8192, 3584) == 2000);
CHECK(tail_need(2000, 8192, 1024) == 0);
// a layout whose own chunk is below the floor is not fused: every chunk is MMQ's
CHECK(tail_need(5000, 1023, 1024) == 1023 && tail_need(500, 1023, 1024) == 500);
CHECK(tail_need(0, 4096, 1024) == 0 && tail_need(10, 0, 1024) == 0);
// never above floor - 1, never negative, last chunk exact for every size
for (int64_t floor : std::initializer_list<int64_t>{1, 64, 1024, 3072, 3584})
for (int64_t c : std::initializer_list<int64_t>{256, 1023, 1024, 2048, 4096, 8192})
for (int64_t t = 1; t <= 20000; t += 37) {
const int64_t need = tail_need(t, c, floor);
CHECK(need >= 0 && need <= (floor > 1 ? floor - 1 : 0));
int64_t worst = 0; // walk the chunks one by one
for (int64_t at = 0; at < t; at += c) {
const int64_t len = t - at < c ? t - at : c;
if (len < floor && len > worst) worst = len;
}
CHECK(need == worst);
const int64_t lay = tail_layout(need, floor);
CHECK(lay >= need && (need == 0 ? lay == 0 : lay % 256 == 0 || lay == floor - 1));
CHECK(lay <= (floor > 1 ? floor - 1 : 0));
CHECK(segment_tail(t, c, floor) == lay);
}
// the grid: 904 -> 1,024; clamped to today's floor - 1
CHECK(tail_layout(904, 3584) == 1024 && tail_layout(1, 3584) == 256 && tail_layout(1023, 1024) == 1023);
CHECK(tail_layout(0, 3584) == 0 && tail_layout(5, 1) == 0);
// the overflow case: a loan made for an 8,193+ segment whose last chunk is 1 token, then a 2,000-token segment
// (the 2,000 tokens read as ONE chunk of the loan's layout, staged under a 3,584 floor)
{
const int64_t floor = 3584, lent_chunk = 8192;
const int64_t lent_tail = segment_tail(8193, lent_chunk, floor); // 256: the last chunk is 1 token
CHECK(lent_tail == 256);
CHECK(!reuse_ok(2048, 2000, lent_chunk, lent_tail, floor)); // needs 2,000 (grid 2,048): relayout
CHECK(tail_need(2000, lent_chunk, floor) > lent_tail);
CHECK(reuse_ok(256, 100, lent_chunk, lent_tail, floor)); // 100 <= 256: reuse
CHECK(tail_need(4196, lent_chunk, floor) == 0); // one chunk of 4,196 >= floor: fused, no tail
CHECK(reuse_ok(2048, 4196, lent_chunk, lent_tail, floor)); // so it reuses
}
// a smaller want never reuses a smaller loan, a bigger tail never reuses a smaller one
CHECK(!reuse_ok(4096, 4096, 2048, 4095, 1024));
CHECK(reuse_ok(2048, 4096, 2048, 0, 1024));
CHECK(reuse_ok(2048, 4096, 4096, 0, 1024) && !reuse_ok(2048, 4097 + 4096, 4096, 0, 8192));
// ---- grow-only (next_tail): need grows, need shrinks, chunk grows
{
const int64_t floor = 3584;
CHECK(next_tail(8192, -1, 8192, 256, floor) == 256); // a start-up layout (default-sized): the need of the moment
CHECK(next_tail(8192, 1024, 8192, 256, floor) == 1024); // need shrinks: the tail stays (no relayout)
CHECK(next_tail(8192, 1024, 8192, 0, floor) == 1024);
CHECK(next_tail(8192, 1024, 8192, 1024, floor) == 1024); // equal: stays
CHECK(next_tail(8192, 1024, 8192, 1280, floor) == 3583); // need grows: today's size, once
CHECK(next_tail(8192, 3583, 8192, 3000, floor) == 3583); // and then it is today's: nothing grows past it
CHECK(next_tail(8192, 1024, 4096, 256, floor) == 256); // chunk shrinks: another layout, from its own need
CHECK(next_tail(4096, 1024, 8192, 2048, floor) == 2048); // chunk grows: from the need of that moment
CHECK(next_tail(8192, 0, 8192, 0, floor) == 0); // no tail needed, none carved
CHECK(next_tail(8192, 0, 8192, 256, floor) == 3583);
CHECK(next_tail(8192, 256, 8192, 256, 1) == 256 && next_tail(8192, 0, 8192, 5, 1) == 0);
// a sequence of needs on one chunk: at most one growth, every layout tail covers its segment, never shrinks
int64_t cap = -1, grown = 0;
for (int64_t need : std::initializer_list<int64_t>{256, 0, 1024, 256, 2048, 3583, 0, 512, 3000}) {
const int64_t t = next_tail(8192, cap, 8192, need, floor);
CHECK(t >= need);
if (cap >= 0) CHECK(t >= cap);
if (t != cap) ++grown;
cap = t;
}
CHECK(grown == 2); // the first carve (256), one growth (1024 > 256 -> today's 3583), then it stays
}
static_assert(tail_need(5000, 2048, 1024) == 904 && segment_tail(5000, 2048, 1024) == 1023, "constexpr");
if (failed != 0) return 1;
std::printf("loan_rules_test: all checks passed\n");
return 0;
+140
View File
@@ -0,0 +1,140 @@
// switch_point_rule.hpp: the floor from which a prompt chunk takes the streamed walk, from the card's share of non-resident experts. No GPU, no model.
#include <cmath>
#include <cstdio>
#include "strata/prefill/switch_point_rule.hpp"
namespace sp = strata::prefill::switch_point;
static int failed = 0;
#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "FAIL %s:%d: %s\n", __FILE__, __LINE__, #x); ++failed; } } while (0)
int main() {
static_assert(sp::kFloorDefault == 1024, "the default floor is 1,024");
const sp::Constants k;
const int64_t total = 24576; // 48 layers x 512 experts (Flash-Next)
// every expert resident (or an unknown card): exactly the default
CHECK(sp::floor_for(total, total) == 1024);
CHECK(sp::floor_for(total + 5, total) == 1024);
CHECK(sp::floor_for(0, 0) == 1024);
CHECK(sp::floor_for(-1, total) == 1024);
CHECK(sp::floor_for(5000, 0) == 1024);
// the floor is a multiple of the chunk grid, within [1024, kFloorMax], for every resident count
int64_t prev = 0;
bool seen_move = false;
for (int64_t res = 0; res <= total; res += 64) {
const int64_t f = sp::floor_for(res, total);
CHECK(f >= 1024 && f <= sp::kFloorMax);
CHECK((f - 1024) % sp::kGrid == 0);
if (f != 1024) seen_move = true;
(void) prev;
prev = f;
}
CHECK(seen_move);
// the A6000 / UD-Q4_K_XL card (55% resident): between the measured 2,049 (staged 1.28x faster) and 8,193 (staged 26% slower), about the measured crossing at 4,097
{
const int64_t res = (int64_t) (0.55 * (double) total);
const int64_t f = sp::floor_for(res, total);
CHECK(f > 2049 && f < 8193);
}
// the same card with the measured X (about 12,097 non-resident): the model's own crossing is 4,0xx
{
const int64_t f = sp::floor_for(total - 12097, total);
CHECK(f >= 3584 && f <= 4608);
CHECK(sp::advantage_ms(1100, 12097, k) > 1000.0); // measured 1,390 ms (3,236 against 1,838)
CHECK(sp::advantage_ms(2049, 12097, k) > 500.0); // measured 710 ms
CHECK(std::fabs(sp::advantage_ms(4097, 12097, k)) < 120.0); // measured 18 ms
CHECK(sp::advantage_ms(8193, 12097, k) < -700.0); // measured -950 ms
}
// a card with fewer non-resident experts stages less often: the floor does not rise as more experts are resident
{
int64_t last = sp::kFloorMax + 1;
for (int64_t res = total / 8; res <= total; res += 256) {
const int64_t f = sp::floor_for(res, total);
CHECK(f <= last);
last = f;
}
}
// the uncovered share: 1 below t0, falling, never above 1
CHECK(sp::uncovered(100, k) == 1.0);
CHECK(sp::uncovered(1100, k) > sp::uncovered(4097, k));
CHECK(sp::uncovered(8193, k) < 0.2);
CHECK(sp::uncovered(0, k) == 1.0);
// per-card scaling: the A6000 (3.19 MB experts, 12.2 GB/s, 84 SMs, 13,580 of 24,576 resident) and the A4000 (1.44 MB, 10.5 GB/s, 48 SMs, 7,836 resident), CPU share off:
// measured crossings about 3,840 and 1,930 tokens, the rule's floors are within one grid step of them
{
const sp::Card a6000{3.19, 12.2, 84}, a4000{1.44, 10.5, 48};
const int64_t f6 = sp::floor_for_card(13580, total, a6000);
const int64_t f4 = sp::floor_for_card(7836, total, a4000);
CHECK(f6 >= 3584 && f6 <= 4096);
CHECK(f4 >= 1792 && f4 <= 2048);
CHECK(f4 < f6); // the slower card of the two crosses earlier, as measured
CHECK((f6 - 1024) % sp::kGrid == 0 && (f4 - 1024) % sp::kGrid == 0);
// an unknown card (no probe, no SM count): the default
CHECK(sp::floor_for_card(13580, total, sp::Card{0.0, 12.2, 84}) == 1024);
CHECK(sp::floor_for_card(13580, total, sp::Card{3.19, 0.0, 84}) == 1024);
CHECK(sp::floor_for_card(13580, total, sp::Card{3.19, 12.2, 0}) == 1024);
// every expert resident: the default whatever the card
CHECK(sp::floor_for_card(total, total, a6000) == 1024);
// the A6000-class card's constants are the fit's own
const sp::Constants kc = sp::constants_for(sp::Card{});
CHECK(std::fabs(kc.c_p - 0.2612) < 1e-9 && std::fabs(kc.a_s - 0.2294) < 1e-9);
// faster link, same card: a smaller floor; more SMs, same link: a higher one
CHECK(sp::floor_for_card(13580, total, sp::Card{3.19, 24.0, 84}) <= f6);
CHECK(sp::floor_for_card(13580, total, sp::Card{3.19, 12.2, 120}) >= f6);
}
// the share's limit: the floor times the measured ratio on the grid, 0 (the share's own default stays) when the floor did not move
CHECK(sp::share_limit_for(1024) == 0);
CHECK(sp::share_limit_for(2048) == 3072); // A4000: measured break-even about 2,900
CHECK(sp::share_limit_for(3840) % sp::kGrid == 0 && sp::share_limit_for(3840) > 3840);
// the class the rule is on for by default: CUDA, discrete, one GPU, link probe ran, compute capability 8.6; STRATA_SWITCH_POINT=0 is the way back, =1 asks for it elsewhere
{
sp::DeviceClass in;
in.cuda = true; in.discrete = true; in.single_gpu = true; in.link_probed = true; in.cc_major = 8; in.cc_minor = 6;
CHECK(sp::in_default_class(in));
CHECK(sp::enabled(in, -1)); // nothing set: on
CHECK(!sp::enabled(in, 0)); // STRATA_SWITCH_POINT=0 (or any value but 1): the way back
CHECK(sp::enabled(in, 1)); // STRATA_SWITCH_POINT=1: on
// every other compute capability is out of the class with nothing set
const int other[][2] = {{6, 0}, {6, 1}, {7, 0}, {7, 5}, {8, 0}, {8, 7}, {8, 9}, {9, 0}, {10, 0}, {12, 0}, {12, 1}, {0, 0}};
for (const auto& cc : other) {
sp::DeviceClass d = in;
d.cc_major = cc[0]; d.cc_minor = cc[1];
CHECK(!sp::in_default_class(d));
CHECK(!sp::enabled(d, -1));
CHECK(sp::enabled(d, 1)); // the explicit opt-in still works on another CUDA card
CHECK(!sp::enabled(d, 0));
}
// each other condition on its own takes a card out of the class
{ sp::DeviceClass d = in; d.single_gpu = false; CHECK(!sp::enabled(d, -1)); CHECK(!sp::enabled(d, 0)); } // two cards / a layer split
{ sp::DeviceClass d = in; d.link_probed = false; CHECK(!sp::enabled(d, -1)); } // no probe
{ sp::DeviceClass d = in; d.discrete = false; CHECK(!sp::enabled(d, -1)); } // integrated / shared memory
{ sp::DeviceClass d = in; d.cuda = false; CHECK(!sp::enabled(d, -1)); CHECK(!sp::enabled(d, 1)); CHECK(!sp::enabled(d, 0)); } // HIP: never, whatever the cc says
{ sp::DeviceClass d; CHECK(!sp::enabled(d, -1)); CHECK(!sp::enabled(d, 1)); } // nothing known
// the variable: unset or empty = default, exactly "1" = on, anything else = off
CHECK(sp::env_state(nullptr) == -1);
CHECK(sp::env_state("") == -1);
CHECK(sp::env_state("1") == 1);
CHECK(sp::env_state("0") == 0);
CHECK(sp::env_state("off") == 0);
CHECK(sp::env_state("11") == 0);
// the class gives the measured floors: the A6000 and the A4000 are both 8.6
CHECK(sp::kClassCcMajor == 8 && sp::kClassCcMinor == 6);
CHECK(sp::floor_for_card(13580, total, sp::Card{3.14, 12.2, 84}) == 3584);
CHECK(sp::share_limit_for(3584) == 5632);
CHECK(sp::floor_for_card(7836, total, sp::Card{1.44, 11.0, 48}) == 2048);
CHECK(sp::share_limit_for(2048) == 3072);
}
if (failed) {
std::fprintf(stderr, "switch_point_rule_test: %d check(s) failed\n", failed);
return 1;
}
std::printf("switch_point_rule_test: OK\n");
return 0;
}