Skip to content

Qwen3.8-Flash-Next on any consumer hardware: one-click install for Windows / Linux. Strata inference engine, OpenAI/Anthropic API on localhost, optional image input.

C++

calibrate: measure the adaptive expert tier (--adapt-every / --adapt-swaps / --adapt-decay), with 512-token answers (#907)

18721833167e2864a3fc66
diff --git a/docs/DETAILS.md b/docs/DETAILS.md
index 580937d9f..cd52b2720 100644
--- a/docs/DETAILS.md
+++ b/docs/DETAILS.md
@@ -414,11 +414,15 @@ START-HERE.bat --calibrate tune the engine for this PC (abo
With more than one model installed, it asks which one to start. `run-<model>.bat` starts a model directly.
-**Tuning for your PC (`--calibrate`, engine 0.1.19).** Three engine settings depend on the PC more than on the model:
+**Tuning for your PC (`--calibrate`, engine 0.1.19).** Four engine settings depend on the PC more than on the model:
- the share of the experts missing from VRAM that are copied to the GPU instead of computed by the CPU
(`--pcie-frac`: a fast PCIe link and a slower CPU want more, a laptop's narrower link less);
- how sure the draft layer must be to add another guess to a check (`--spec-min-p`);
-- how many CPU threads compute experts (`--pool-workers`: on CPUs with efficiency cores, fewer can be faster).
+- how many CPU threads compute experts (`--pool-workers`: on CPUs with efficiency cores, fewer can be faster);
+- how busily the VRAM expert cache follows the conversation (`--adapt-every`, `--adapt-swaps`, `--adapt-decay`): a PC
+ whose CPU reads the missed experts slowly (DDR3 or DDR4 in few channels) gains from swapping more. On a Xeon
+ E5-2673 v3 with DDR3 and an RTX 4060 Ti on PCIe 3.0 x8, 160 swaps every window measured +7.9% over the default
+ (Q2_0, with the swaps taking effect a window later, #764); see #906.
The defaults were measured on a Ryzen 5 7600 with an RTX 5070. Setup offers to measure them on your PC after an
install; `START-HERE.bat --calibrate` (Linux: `./setup.sh --calibrate`) does it any time. It measures the output
diff --git a/setup.py b/setup.py
index c64503330..ed441d76d 100644
--- a/setup.py
+++ b/setup.py
@@ -3441,7 +3441,7 @@ def calibrate_config(cfg_path: Path) -> bool:
cfg = json.loads(cfg_path.read_text(encoding="utf-8-sig"))
say()
say(" Tuning Strata for this PC: the output speed is measured with a few engine settings (the PCIe share, the")
- say(" draft depth, the CPU threads). It takes about 5-10 minutes; the PC is busy meanwhile.")
+ say(" draft depth, the CPU threads, the expert cache). It takes about 10 minutes; the PC is busy meanwhile.")
try:
since = os.path.getsize(cfg["log"]) if cfg.get("log") and os.path.isfile(cfg["log"]) else 0
except OSError:
diff --git a/tools/calibrate.py b/tools/calibrate.py
index 48d79c1ee..186604beb 100644
--- a/tools/calibrate.py
+++ b/tools/calibrate.py
@@ -8,8 +8,13 @@ measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5):
per extra window row (more experts per window), so it wants a higher floor.
--pool-workers the CPU threads that compute experts. Every physical core is not always best: on hybrid CPUs the
efficiency cores can make the whole window wait for them.
-The first two are measured through one engine (per-request `strata_tune` keys); the worker count needs a restart
-per value. Decode speed only: the prompt path streams every expert whatever these settings say.
+ --adapt-every / --adapt-swaps / --adapt-decay
+ how the VRAM expert tier follows the conversation: how often, how many experts it swaps in, how fast
+ its use counts fade. A PC whose CPU reads the missed experts slowly (DDR3, ~24 GB/s) gains from
+ swapping more: 160 swaps every window measured +7.9% over the default tier on a Xeon E5-2673 v3 (DDR3) with an
+ RTX 4060 Ti on PCIe 3.0 x8 (Q2_0; with the swaps taking effect a window later, #764).
+The first two are measured through one engine (per-request `strata_tune` keys); the worker count and the adaptive
+tier need a restart per value. Decode speed only: the prompt path streams every expert whatever these settings say.
A setting is kept only when it beats the default by more than MIN_GAIN in an interleaved re-measurement - the
adaptive expert tier and the OS make single measurements noisy by a few percent.
@@ -32,7 +37,14 @@ sys.path.insert(0, str(ROOT))
MIN_GAIN = 0.03 # a setting must beat the default by this much to be kept
PCIE_FRACS = (0.0, 0.2, 0.35, 0.55, 0.75)
SPEC_MIN_PS = (0.3, 0.5, 0.7)
+# the adaptive tier's candidates (every, swaps, decay) against the engine's own (None): swapping more and remembering
+# longer, the rest of the set as the engine has it
+ADAPT_CANDIDATES = (None, ("1", "80", "0.97"), ("1", "160", "0.97"))
+ADAPT_FLAGS = ("--adapt-every", "--adapt-swaps", "--adapt-decay")
MAX_NEW = 128
+# the expert tier follows a text over some windows: 128-token answers end before it shows (on a Xeon E5-2673 v3 with
+# DDR3, every 1 / 160 / 0.97 measured +0.7% with 128 tokens and +7.9% with 512-token answers), so its step uses these
+TIER_MAX_NEW = 512
PROMPTS = (
"Write a Python function that merges two sorted lists into one sorted list, with a docstring and two tests.",
"Explain in two paragraphs how a refrigerator moves heat from inside to outside.",
@@ -102,13 +114,14 @@ class Session:
self.engine = engine
self.ids_list = ids_list
- def rate(self, tune: dict | None = None) -> float:
+ def rate(self, tune: dict | None = None, max_new: int | None = None) -> float:
rates = []
for ids in self.ids_list:
sampling = {"temperature": 0}
if tune:
sampling["strata_tune"] = tune
- n = sum(1 for t in self.engine.generate(ids, MAX_NEW, sampling, threading.Event()) if t is not None)
+ n = sum(1 for t in self.engine.generate(ids, max_new or MAX_NEW, sampling, threading.Event())
+ if t is not None)
ms = (self.engine.last or {}).get("decode_ms") or 0.0
if n > 8 and ms > 0:
rates.append(n / (ms / 1000.0))
@@ -227,6 +240,31 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
base_rate = statistics.median(by_workers[w_best])
elif by_workers.get(d_workers):
base_rate = statistics.median(by_workers[d_workers])
+ # 5. the adaptive expert tier (a restart each), with everything chosen so far
+ tuned = apply(base_args, settings)
+ by_adapt = {}
+ for cand in ADAPT_CANDIDATES:
+ key = "default" if cand is None else "/".join(cand)
+ args = tuned
+ for flag, v in zip(ADAPT_FLAGS, cand or (None,) * len(ADAPT_FLAGS)):
+ args = with_arg(args, flag, v)
+ say(f" Measuring the expert tier {'(the engine default)' if cand is None else 'every ' + cand[0] + ', ' + cand[1] + ' swaps, decay ' + cand[2]} (restarts the engine) ...")
+ e = start_engine(args)
+ try:
+ sa = Session(e, ids_list)
+ sa.warm_up(1)
+ by_adapt[key] = [sa.rate(max_new=TIER_MAX_NEW), sa.rate(max_new=TIER_MAX_NEW)]
+ say(f" {statistics.median(by_adapt[key]):.1f} tok/s")
+ finally:
+ close(e)
+ a_best = pick(by_adapt, "default")
+ report["adapt"] = by_adapt
+ if a_best != "default":
+ for flag, v in zip(ADAPT_FLAGS, a_best.split("/")):
+ settings[flag] = v
+ base_rate = statistics.median(by_adapt[a_best])
+ elif by_adapt.get("default"):
+ base_rate = statistics.median(by_adapt["default"])
report["seconds"] = round(time.time() - t0)
report["tok_s"] = round(base_rate, 1) if base_rate else None
return {"settings": settings, "report": report}
@@ -245,7 +283,8 @@ def close(eng):
proc.kill()
-DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None} # None: the engine's own choice
+DEFAULTS = {"--pcie-frac": None, "--spec-min-p": "0.5", "--pool-workers": None, # None: the engine's own choice
+ "--adapt-every": None, "--adapt-swaps": None, "--adapt-decay": None}
def apply(args: list[str], settings: dict) -> list[str]:
diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py
index 61adf0ca4..6922d78b2 100644
--- a/tools/test_calibrate.py
+++ b/tools/test_calibrate.py
@@ -22,8 +22,9 @@ import calibrate as CAL # noqa: E402
class FakeEngine:
"""Speed = f(pcie_frac, spec_min_p, workers): the GEN line's tune keys arrive as `strata_tune`."""
- def __init__(self, args, speed, info_workers=6, starts=None):
+ def __init__(self, args, speed, info_workers=6, starts=None, adapt=None):
self.args = list(args)
+ self.adapt_bonus = (adapt or {}).get(CAL.arg_value(args, "--adapt-swaps"), 1.0)
w = CAL.arg_value(args, "--pool-workers")
self.workers = int(w) if w else info_workers
self.info = {"pool_workers": info_workers, "pcie_frac": 0.55, "spec_min_p": float(CAL.arg_value(args, "--spec-min-p") or 0)}
@@ -36,6 +37,7 @@ class FakeEngine:
def generate(self, ids, max_new, sampling, cancel):
tune = sampling.get("strata_tune") or {}
rate = self.speed(tune.get("pcie_frac", 0.55), tune.get("spec_min_p", self.info["spec_min_p"]), self.workers)
+ rate *= self.adapt_bonus
for _ in range(max_new):
yield 1
self.last = {"generated": max_new, "decode_ms": max_new / rate * 1000.0}
@@ -45,9 +47,10 @@ BASE = ["--pack", "p", "--spec", "4", "--spec-min-p", "0.5", "--max-context", "8
class Calibrate(unittest.TestCase):
- def run_with(self, speed, workers=6, base=BASE):
+ def run_with(self, speed, workers=6, base=BASE, adapt=None):
starts = []
- res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts), say=lambda *_: None)
+ res = CAL.measure(base, [[1, 2, 3]] * 3, lambda a: FakeEngine(a, speed, workers, starts, adapt),
+ say=lambda *_: None)
return res, starts
def test_defaults_kept_when_flat(self):
@@ -71,9 +74,24 @@ class Calibrate(unittest.TestCase):
# a hybrid CPU: half the workers is 20% faster
res, starts = self.run_with(lambda f, p, w: 60.0 if w == 3 else 50.0, workers=6)
self.assertEqual(res["settings"].get("--pool-workers"), "3")
- self.assertEqual(len(starts), 1 + len(CAL.worker_candidates(6))) # one start per worker count, plus the sweep
+ # one start per worker count and per expert-tier candidate, plus the sweep
+ self.assertEqual(len(starts), 1 + len(CAL.worker_candidates(6)) + len(CAL.ADAPT_CANDIDATES))
self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5") # measured against the product default
+ def test_adaptive_tier(self):
+ # a slow-RAM PC: swapping 160 experts per round is 10% faster, 80 is 2% (noise)
+ res, starts = self.run_with(lambda f, p, w: 50.0, adapt={"160": 1.10, "80": 1.02})
+ self.assertEqual([res["settings"].get(f) for f in CAL.ADAPT_FLAGS], ["1", "160", "0.97"])
+ flat, _ = self.run_with(lambda f, p, w: 50.0, adapt={"160": 1.02})
+ self.assertFalse(any(f in flat["settings"] for f in CAL.ADAPT_FLAGS))
+ # the candidates are measured with the worker count chosen before
+ res, starts = self.run_with(lambda f, p, w: 60.0 if w == 3 else 50.0, workers=6, adapt={"160": 1.10})
+ self.assertEqual(res["settings"].get("--pool-workers"), "3")
+ self.assertTrue(all(CAL.arg_value(a, "--pool-workers") == "3" for a in starts[-len(CAL.ADAPT_CANDIDATES):]))
+ a = CAL.apply(BASE, res["settings"])
+ self.assertEqual(CAL.arg_value(a, "--adapt-swaps"), "160")
+ self.assertIsNone(CAL.arg_value(CAL.apply(a, {}), "--adapt-swaps")) # an old calibration's tier goes
+
def test_old_calibration_is_the_baseline_reset(self):
# a config tuned earlier: the measurement starts from the product defaults, not from those values
base = CAL.apply(BASE, {"--pcie-frac": "0.20", "--pool-workers": "3", "--spec-min-p": "0.70"})