BigMoeOnEdge/core/src/config.cpp
Helldez bea5a0b99e
feat(moe): --drop-cold-experts — spend quality only where it buys I/O (#95)
* feat(moe): --drop-cold-experts, spend quality only where it buys I/O

Turbo top-k drops the tail of a routing whether or not those experts were
already in RAM. A resident expert costs no flash read, so that trade pays
quality for nothing on the ~80% of decode routings that are cache hits.

This skips a routed expert only when it is a cache MISS and the router
weighted it below frac x (1/top-k). Replayed over the committed route
traces at frac 1.0, decode phase, that avoids 66% of flash reads for 9.5%
of the router's weight mass, where --n-expert-used 5 avoids 23% for a
comparable 10.6% -- about 3x the reads at the same quality cost.

Implementation. The decision needs the FINAL router weights, which arrive
several nodes after the topk where the streamer normally loads, so
load_layer() is deferred to the terminal node of the layer's weight chain.
Which node that is depends on the model's gating, so the hook learns it
from the graph rather than carrying an architecture table; if it fails to
arrive the hook forgets it and re-learns rather than re-betting. A dropped
slot has its weight zeroed and its expert id repointed at the routing's
top-weighted expert: an unread expert can sit in reserved-but-uncommitted
VM and mul_mat_id would touch it anyway, so the kernel is given memory
that is certainly resident and multiplies it by exactly zero.

Requires the LRU cache -- with --cache-mb 0 residency reads all-miss and
the policy would silently degenerate into an unconditional weight cut.
Prefill is excluded by default. The top expert is always pinned, so no
routing can be emptied at any threshold.

Gates: G8a/G8a' prove the deferral and the learned terminal node are
transparent (byte-identical output, zero drops, at a threshold below any
producible weight); G8b that full strength against a constantly-evicting
cache never reaches an unloaded slot; G8c that at top-k 1 dropping is a
no-op, pinning both the top-expert guarantee and the threshold tracking
the effective top-k.

Three existing metrics shift meaning under dropping and the docs now say
so: cache_hit_pct rises without the cache serving more (a dropped routing
is a miss that is never looked up), and token/layer_demand measure what
was staged rather than routed. prefetch.md's "cannot change output" is
scoped, limitations.md gains the non-reproducibility entry, and
benchmark-method.md warns that reversing the run order cannot distinguish
a moved drop rate from a contaminated cell.

Off by default in the CLI and in the app. The output is not reproducible
-- what gets dropped depends on what the cache held -- so it carries no
rows in the README tables, and switching it on by default waits on a
published on-device A/B rather than on the replay argument alone.

* feat(app): default cache-aware dropping to 75%, measured on device

Qwen3.6-35B-A3B (top-k 8 of 256), in-app, cache 3000, one variable
changed: 2.549 tok/s off, 3.938 at F=0.75 (+55%), 4.702 at F=1.0 (+84%),
with flash reads falling 248 -> 163 -> 48 GiB. Per-token bootstrap
intervals separate every pair except off vs 0.50, which overlaps -- at
half the uniform share the policy drops 2.7% of routings and buys
nothing, which doubles as a negative control that the machinery is free
when it does not fire.

Run order was 1.0, off, 0.5, 0.75, so the two fastest cells are the first
and the LAST; thermal drift would have made the last the worst. The
mechanism orders by threshold even though the run order does not.

The replay turned out conservative rather than optimistic. It is
documented as an upper bound because it cannot model the cache changing
in response to dropping: at F=0.75 it was accurate (37% predicted, 34%
measured), at F=1.0 it understated (66% predicted, 81% measured). Avoided
reads free cache capacity, which raises the hit rate, which leaves fewer
misses to drop.

75% rather than 100% is deliberate: it takes the larger part of the win
for half the discarded routings (14% against 28%). Quality is still
unquantified -- no perplexity number and no side-by-side exists -- so the
conservative end of a measured range is the defensible default. The CLI
stays off; the byte-identity gates need a deterministic default.

Also records cache_hit_pct rising 67.8 -> 90.7% as the documented
accounting artefact rather than the cache serving more, and majflt/token
as dominated by each run's starting memory state, not by the threshold.
2026-07-22 17:21:55 +02:00

104 lines
4.8 KiB
C++

#include "bmoe/config.h"
#include <utility>
namespace bmoe {
ValidationResult validate(const RunConfig & cfg) {
ValidationResult r;
auto fail = [&](std::string msg) {
r.ok = false;
r.error = std::move(msg);
return r;
};
if (cfg.model_path.empty()) {
return fail("model_path is required");
}
if (cfg.n_predict <= 0) {
return fail("n_predict must be positive");
}
if (cfg.n_threads <= 0) {
return fail("n_threads must be positive");
}
if (cfg.n_ctx <= 0) {
return fail("n_ctx must be positive");
}
// Lower bound only: 0 means "use the model default". The upper bound (<= the model's
// real expert count) needs the loaded gguf, so it is deferred to run() where the model
// is available — same rationale as the streaming checks that stay out of this pure path.
if (cfg.n_expert_used < 0) {
return fail("n_expert_used must be >= 0 (0 = model default)");
}
// Sampling ranges are enforced only when sampling is actually on (temp > 0). With temp <= 0
// the engine takes the argmax path and the other knobs are inert, so a caller that leaves them
// at any value still describes a valid greedy run — today's default stays valid untouched.
if (cfg.sampling.temp > 0.0f) {
if (cfg.sampling.top_k < 0) {
return fail("sampling.top_k must be >= 0 (0 disables the top-k stage)");
}
if (cfg.sampling.top_p <= 0.0f || cfg.sampling.top_p > 1.0f) {
return fail("sampling.top_p must be in (0, 1]");
}
}
// overlap is meaningless without streaming (it gates the streamer's own reads). The
// hook-availability check is deferred to run(): validate() stays pure (no native).
if (cfg.moe.overlap && !cfg.moe.enabled) {
return fail("moe.overlap requires moe.enabled");
}
if (cfg.moe.enabled) {
const MoeStreamConfig & m = cfg.moe;
if (m.io_threads < 1 || m.io_threads > MoeStreamConfig::io_threads_max) {
return fail("moe.io_threads must be in [1, " + std::to_string(MoeStreamConfig::io_threads_max) + "]");
}
if (m.cache_mb < 0) {
return fail("moe.cache_mb must be >= 0");
}
if (m.cache_mb > 0 && m.cache_mb < MoeStreamConfig::cache_min_mb && !m.force_cache) {
return fail("moe.cache_mb=" + std::to_string(m.cache_mb) + " is in the pathological band (< " +
std::to_string(MoeStreamConfig::cache_min_mb) +
" MiB): a cache smaller than one token's routed working set thrashes and is "
"slower than no cache. Use 0 to disable the cache, a value >= " +
std::to_string(MoeStreamConfig::cache_min_mb) + ", or set force_cache to override.");
}
if (m.prefetch_layers < 0 || m.prefetch_layers > MoeStreamConfig::prefetch_layers_max) {
return fail("moe.prefetch_layers must be in [0, " + std::to_string(MoeStreamConfig::prefetch_layers_max) +
"]");
}
if (m.cache_auto && m.cache_mb > 0) {
return fail("moe.cache_auto and an explicit moe.cache_mb are mutually exclusive: choose "
"auto-sizing (cache_mb = 0, cache_auto) or a fixed budget (cache_mb > 0).");
}
if (m.cache_floor_mb < 0) {
return fail("moe.cache_floor_mb must be >= 0");
}
if (m.cache_ceil_mb < 0) {
return fail("moe.cache_ceil_mb must be >= 0 (0 = no explicit ceiling)");
}
// "The LRU cache is on" means a fixed budget OR auto-sizing (which sizes a real LRU cache).
const bool cache_on = m.cache_mb > 0 || m.cache_auto;
if (m.prefetch_layers > 0 && !cache_on) {
return fail("moe.prefetch_layers requires the LRU cache (cache_mb > 0 or cache_auto): "
"speculative reads land in the per-layer cache buffers, which do not exist "
"with the cache off.");
}
if (m.drop_cold_frac > 0.0f && !cache_on) {
return fail("moe.drop_cold_frac requires the LRU cache (cache_mb > 0 or cache_auto): with the "
"cache off every expert is a miss, so the policy stops being cache-aware and "
"degenerates into an unconditional weight cut — which is what n_expert_used already "
"does, without pretending to consult residency.");
}
if (m.drop_cold_frac < 0.0f || m.drop_cold_frac > 1.0f) {
return fail("moe.drop_cold_frac must be in [0, 1] (0 = off). Above 1.0 the threshold can "
"exceed the largest weight in a routing, which would discard every expert of a "
"layer; 1.0 is the uniform share 1/n_expert_used and the useful maximum.");
}
}
return r;
}
} // namespace bmoe