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 shared-expert stream fork on AMD (STRATA_SH_STREAM, off against on) and keep it per PC

Vop3peb6e0f1e4d7b
diff --git a/docs/AMD_HIP.md b/docs/AMD_HIP.md
index 2b443dd36..3f9782083 100644
--- a/docs/AMD_HIP.md
+++ b/docs/AMD_HIP.md
@@ -216,7 +216,10 @@ machine). Windows HIP: the doorbell kernels fence their store (#697), and the sh
that default stays. The measurements disagree by platform. 2x RX 6900 XT on Linux (#1272): turning it off costs 5-13%
of decode (one card 47.5 / 46.9 / 48.3 -> 50.5 / 48.5 / 51.3 tok/s with it on). RX 6800 on Windows (#816,
`bench/results/2026-10-04-community-rx-6800-windows`): on was 12-22% slower. 4x R9700: fork off was 13-45% faster.
-Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way.
+Linux RX 6000 users can try `STRATA_SH_STREAM=1`; the output is identical either way. Since the same card goes
+both ways on different PCs, `./setup.sh --calibrate` measures it on yours (off against on, a restart each) and writes
+`STRATA_SH_STREAM=1` into the config's `"env"` only when it wins by more than 3%; a later calibration that finds it no
+longer faster removes it again.
**The draft's side stream (`STRATA_MTP_SIDE_STREAM`):** HIP does not use the MTP drafter's branch stream, and since
0.1.40.2 it does not create it (#1240: an R9700 lost prompt speed with it). gfx103x is the exception and creates it: on
diff --git a/setup.py b/setup.py
index 79d0a819f..6e28ec906 100644
--- a/setup.py
+++ b/setup.py
@@ -4766,13 +4766,17 @@ def calibrate_config(cfg_path: Path) -> bool:
say(f" the engine said: {why}")
return False
cfg["args"] = CAL.apply(cfg["args"], res["settings"])
+ if "env" in res: # HIP: the engine variables it measured (STRATA_SH_STREAM)
+ cfg["env"] = CAL.apply_env(cfg.get("env"), res["env"])
write_config(cfg_path, cfg)
st = load_settings()
- st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "tok_s": res["report"].get("tok_s"),
+ st.setdefault("calibration", {})[hardware_key(cfg)] = {"settings": res["settings"], "env": res.get("env") or {},
+ "tok_s": res["report"].get("tok_s"),
"date": time.strftime("%Y-%m-%d")}
save_settings(st)
- if res["settings"]:
- ok("tuned for this PC: " + ", ".join(f"{k} {v}" for k, v in res["settings"].items())
+ chosen = {**res["settings"], **(res.get("env") or {})}
+ if chosen:
+ ok("tuned for this PC: " + ", ".join(f"{k} {v}" if k.startswith("--") else f"{k}={v}" for k, v in chosen.items())
+ (f" ({res['report']['tok_s']} tok/s)" if res["report"].get("tok_s") else ""))
else:
ok("tuned for this PC: the default settings are already the fastest here"
@@ -6812,6 +6816,8 @@ def main() -> int:
sys.path.insert(0, str(ROOT / "tools"))
import calibrate as CAL
cfg["args"] = CAL.apply(cfg["args"], cal.get("settings") or {})
+ if "env" in cal: # a calibration from before the env step leaves "env" as it is
+ cfg["env"] = CAL.apply_env(cfg.get("env"), cal["env"])
ok("the settings tuned for this PC earlier are used" + (f" ({cal['date']})" if cal.get("date") else ""))
else: # #642: measured counts (a calibration) win over the rule
cfg["args"] = recommend_pool_workers(cfg["args"])
diff --git a/tools/calibrate.py b/tools/calibrate.py
index 3ed6a4c85..52dda9dbc 100644
--- a/tools/calibrate.py
+++ b/tools/calibrate.py
@@ -13,6 +13,11 @@ measured on (a Ryzen 5 7600 + RTX 5070 on PCIe 5):
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).
+ STRATA_SH_STREAM (AMD only)
+ the shared expert on its own stream. Off by default on HIP (#816: an RX 6800 on Windows and 4x R9700
+ decode 12-45% faster without it), but the same card family on another PC goes the other way (#1272:
+ 2x RX 6900 XT on Linux, 6-11% faster with it), so it is measured here, per PC, and written into the
+ config's "env" only when it wins. The output is identical either way (same token ids).
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.
@@ -40,6 +45,8 @@ SPEC_MIN_PS = (0.3, 0.5, 0.7)
SWEEP_ROUNDS = 3 # how many times the sweep visits each value (see `sweep`)
# 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
+# HIP: the shared-expert stream fork, off (the HIP default) against on; an engine environment variable, not an argument
+SH_STREAM = "STRATA_SH_STREAM"
ADAPT_CANDIDATES = (None, ("1", "80", "0.97"), ("1", "160", "0.97"))
ADAPT_FLAGS = ("--adapt-every", "--adapt-swaps", "--adapt-decay")
MAX_NEW = 128
@@ -139,8 +146,10 @@ def run(cfg: dict, say=print, start_engine=None) -> dict:
if start_engine is None:
from serve.server import StrataEngine, child_env
- def start_engine(args):
- return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=child_env(cfg))
+ def start_engine(args, env=None):
+ e = child_env(cfg)
+ e.update(env or {})
+ return StrataEngine(cfg["exe"], args, cwd=cfg.get("cwd"), log=cfg.get("log"), env=e)
import strata_tokenizer as ST
tpath = Path(cfg["tokenizer"])
vocab = json.loads((tpath / "vocab.json").read_text(encoding="utf-8"))
@@ -150,7 +159,7 @@ def run(cfg: dict, say=print, start_engine=None) -> dict:
tok = ST.Tokenizer(toks, (tpath / "merges.txt").read_text(encoding="utf-8").split("\n"),
json.loads((tpath / "token_type.json").read_text()))
ids_list = [chat_ids(tok, p) for p in PROMPTS]
- return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras())
+ return measure(engine_args(cfg), ids_list, start_engine, say, host_worker_extras(), hip=cfg.get("backend") == "hip")
def engine_args(cfg: dict) -> list[str]:
@@ -199,7 +208,7 @@ def sweep(s, values: list, base_tune: dict, key: str, label: str, say) -> dict:
return out
-def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=()) -> dict:
+def measure(base_args: list[str], ids_list, start_engine, say=print, extra_workers=(), hip: bool = False) -> dict:
t0 = time.time()
report: dict = {}
say(" Loading the model for the measurements ...")
@@ -290,9 +299,34 @@ def measure(base_args: list[str], ids_list, start_engine, say=print, extra_worke
base_rate = statistics.median(by_adapt[a_best])
elif by_adapt.get("default"):
base_rate = statistics.median(by_adapt["default"])
+ # 6. HIP: the shared-expert stream fork (a restart each), with everything chosen so far. Both values are set
+ # explicitly, so a value the config carried before does not decide the baseline.
+ env = {}
+ if hip:
+ tuned = apply(base_args, settings)
+ by_fork = {}
+ for v in ("0", "1"):
+ say(f" Measuring the shared expert {'on its own stream' if v == '1' else 'on the main stream (the AMD default)'}"
+ " (restarts the engine) ...")
+ e = restart(lambda a: start_engine(a, {SH_STREAM: v}), tuned, f"{SH_STREAM}={v}", say, report)
+ if e is None:
+ continue
+ try:
+ sf = Session(e, ids_list)
+ sf.warm_up(1)
+ by_fork[v] = [sf.rate(), sf.rate()]
+ say(f" {statistics.median(by_fork[v]):.1f} tok/s")
+ finally:
+ close(e)
+ report["sh_stream"] = by_fork
+ if pick(by_fork, "0") == "1":
+ env[SH_STREAM] = "1"
+ base_rate = statistics.median(by_fork["1"])
+ elif by_fork.get("0"):
+ base_rate = statistics.median(by_fork["0"])
report["seconds"] = round(time.time() - t0)
report["tok_s"] = round(base_rate, 1) if base_rate else None
- return {"settings": settings, "report": report}
+ return {"settings": settings, "env": env, "report": report}
def restart(start_engine, args, what, say, report):
@@ -336,6 +370,17 @@ def apply(args: list[str], settings: dict) -> list[str]:
return out
+ENV_KEYS = (SH_STREAM,)
+
+
+def apply_env(env: dict | None, calibrated: dict | None) -> dict:
+ """The config's "env" with a calibration's engine variables: the ones it chose are set, the others in ENV_KEYS are
+ removed (back to the engine's default), so an older calibration's choice never lingers."""
+ out = {k: v for k, v in (env or {}).items() if k not in ENV_KEYS}
+ out.update(calibrated or {})
+ return out
+
+
if __name__ == "__main__":
if len(sys.argv) != 2:
sys.exit("usage: calibrate.py <strata-*.json>")
diff --git a/tools/test_calibrate.py b/tools/test_calibrate.py
index 7ce1bdd0f..3fb4804a2 100644
--- a/tools/test_calibrate.py
+++ b/tools/test_calibrate.py
@@ -126,6 +126,48 @@ class Calibrate(unittest.TestCase):
self.assertIsNone(CAL.arg_value(starts[0], "--pool-workers"))
self.assertEqual(CAL.arg_value(starts[0], "--spec-min-p"), "0.5")
+ def test_sh_stream_is_measured_on_hip_only(self):
+ # #1272 / #816: the shared-expert fork is measured off (the HIP default) against on, each with a restart and
+ # the engine variable set explicitly; it is kept only when it wins by more than MIN_GAIN
+ def run(bonus, hip=True):
+ starts, envs = [], []
+
+ def start(args, env=None):
+ envs.append(dict(env or {}))
+ fork = (env or {}).get(CAL.SH_STREAM) == "1"
+ return FakeEngine(args, lambda f, p, w: 50.0 * (bonus if fork else 1.0), 6, starts)
+ res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=hip)
+ return res, starts, envs
+ res, starts, envs = run(1.08)
+ self.assertEqual(res["env"], {CAL.SH_STREAM: "1"})
+ self.assertEqual(envs[-2:], [{CAL.SH_STREAM: "0"}, {CAL.SH_STREAM: "1"}])
+ self.assertEqual(starts[-1], starts[-2]) # the same args for both: only the variable differs
+ self.assertGreater(res["report"]["tok_s"], 52.0) # the reported speed is the fork's
+ flat, _, _ = run(1.02) # within noise: the default stays
+ self.assertEqual(flat["env"], {})
+ self.assertEqual(set(flat["report"]["sh_stream"]), {"0", "1"})
+ slower, _, _ = run(0.80)
+ self.assertEqual(slower["env"], {})
+ cuda, _, envs = run(1.50, hip=False) # not AMD: no step, no engine variable
+ self.assertEqual(cuda["env"], {})
+ self.assertNotIn("sh_stream", cuda["report"])
+ self.assertTrue(all(e == {} for e in envs))
+
+ def test_a_failed_fork_start_keeps_the_default(self):
+ def start(args, env=None):
+ if (env or {}).get(CAL.SH_STREAM) == "1":
+ raise RuntimeError("out of memory")
+ return FakeEngine(args, lambda f, p, w: 50.0, 6)
+ res = CAL.measure(BASE, [[1, 2, 3]] * 3, start, say=lambda *_: None, hip=True)
+ self.assertEqual(res["env"], {})
+ self.assertIn(f"{CAL.SH_STREAM}=1", res["report"]["failed_starts"])
+
+ def test_apply_env(self):
+ old = {"STRATA_ROCBLAS_TUNING": "tools/hip", CAL.SH_STREAM: "1"}
+ self.assertEqual(CAL.apply_env(old, {}), {"STRATA_ROCBLAS_TUNING": "tools/hip"}) # an older choice goes
+ self.assertEqual(CAL.apply_env({"X": "1"}, {CAL.SH_STREAM: "1"}), {"X": "1", CAL.SH_STREAM: "1"})
+ self.assertEqual(CAL.apply_env(None, None), {})
+
def test_apply(self):
a = CAL.apply(BASE, {"--pcie-frac": "0.35", "--pool-workers": "4"})
self.assertEqual(CAL.arg_value(a, "--pcie-frac"), "0.35")
@@ -157,14 +199,15 @@ class Calibrate(unittest.TestCase):
(tok / "token_type.json").write_text(json.dumps([1, 1]))
seen = []
saved = CAL.measure
- CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(): seen.append(args) or {}
+ CAL.measure = lambda args, ids_list, start_engine, say=print, extra=(), hip=False: seen.append((args, hip)) or {}
fake = type("ST", (), {"Tokenizer": lambda *a: type("T", (), {"encode": lambda s, t, **k: [0]})()})
try:
with mock.patch.dict(sys.modules, {"strata_tokenizer": fake}):
CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0]}, start_engine=lambda a: None)
+ CAL.run({"tokenizer": d, "args": list(BASE), "gpu": [0], "backend": "hip"}, start_engine=lambda a: None)
finally:
CAL.measure = saved
- self.assertEqual(seen, [BASE])
+ self.assertEqual(seen, [(BASE, False), (BASE, True)]) # the shared-expert step runs on AMD only
def test_engine_error(self):
with tempfile.TemporaryDirectory() as d:
@@ -236,6 +279,21 @@ class SetupIntegration(unittest.TestCase):
other = dict(written, args=CAL.with_arg(written["args"], "--max-context", "131072"))
self.assertIsNone(self.S.saved_calibration(other))
+ def test_calibrate_config_writes_the_env_choice(self):
+ # HIP: the measured engine variable goes into the config's "env" and the settings file; a re-run that finds it
+ # no longer faster removes it again, and leaves the config's other variables alone
+ cfg_path = Path(self.tmp.name) / "strata-iq3_s.json"
+ cfg = {"exe": "x", "args": list(BASE), "model_name": "m", "backend": "hip", "env": {"STRATA_ROCBLAS_TUNING": "t"}}
+ cfg_path.write_text(json.dumps(cfg))
+ CAL.run = lambda c, say=print, start_engine=None: {"settings": {}, "env": {CAL.SH_STREAM: "1"}, "report": {"tok_s": 70.1}}
+ self.assertTrue(self.S.calibrate_config(cfg_path))
+ written = json.loads(cfg_path.read_text())
+ self.assertEqual(written["env"], {"STRATA_ROCBLAS_TUNING": "t", CAL.SH_STREAM: "1"})
+ self.assertEqual(self.S.saved_calibration(written)["env"], {CAL.SH_STREAM: "1"})
+ CAL.run = lambda c, say=print, start_engine=None: {"settings": {}, "env": {}, "report": {"tok_s": 65.0}}
+ self.assertTrue(self.S.calibrate_config(cfg_path))
+ self.assertEqual(json.loads(cfg_path.read_text())["env"], {"STRATA_ROCBLAS_TUNING": "t"})
+
def test_failed_calibration_keeps_defaults(self):
cfg_path = Path(self.tmp.name) / "strata-q2_0.json"
cfg_path.write_text(json.dumps({"exe": "x", "args": list(BASE), "model_name": "m"}))