Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio diffusion: race the unlisted-arch int8 GEMM tiles held under load (RTX 3090 class: Qwen-Image-2.1 -10%, MiniMax-H3 -9%) (#17026)
Daniel Han682e73a7fb48
diff --git a/studio/backend/core/inference/diffusion_int8_gemm.py b/studio/backend/core/inference/diffusion_int8_gemm.pyindex 813b78278c9..c67e5fa61e3 100644--- a/studio/backend/core/inference/diffusion_int8_gemm.py+++ b/studio/backend/core/inference/diffusion_int8_gemm.py@@ -23,6 +23,7 @@ INT8_GEMM_TILES_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_TILES"INT8_SWIGLU_STREAMED_ENV = "UNSLOTH_DIFFUSION_INT8_SWIGLU_STREAMED"INT8_GEMM_UNLISTED_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_UNLISTED"INT8_GEMM_TMA_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_TMA"+INT8_GEMM_RACE_ENV = "UNSLOTH_DIFFUSION_INT8_GEMM_RACE"_MIN_TRITON = (3, 2)# torch._int_mm needs M > 16; below that the stock path (safe_int_mm padding) stays in charge._MIN_ROWS = 17@@ -59,6 +60,11 @@ _ARCH_CONFIG = {_FALLBACK_CONFIG = (128, 128, 64, 8, 4, 4)# Measured slower than cuBLAS: not probed unless forced._UNLISTED_SKIP = ((10, 0), (10, 3))+# Raced against the fallback on unlisted archs; a tile overflowing shared memory fails the probe and drops out.+_UNLISTED_RACE_TILES = (+ (128, 128, 128, 8, 4, 3),+ (256, 128, 128, 8, 8, 3),+)# First match wins, bounds inclusive. No L4 rule on purpose: power-capped clocks lose end to end.# (major, minor) -> ((N_lo, N_hi, K_lo, K_hi, tile), ...), M >= _SHAPE_MIN_M only.@@ -580,28 +586,57 @@ _UNLISTED_OK: dict = {}_UNLISTED_TIMING: dict = {}# (M, N, K): Qwen-Image-2.1 attention projection, MLP in, MLP down_UNLISTED_LATENCY_SHAPES = ((2048, 4096, 4096), (2048, 12288, 4096), (2048, 4096, 12288))+# Hold per tile (then as long timed): long enough for a power-capped part (L4: 72 W) to settle its clock.+_UNLISTED_RACE_SHAPES = tuple((4096, n, k) for _m, n, k in _UNLISTED_LATENCY_SHAPES)+_RACE_HOLD_S = 0.3def _unlisted_latency(index: int, cfg: tuple) -> dict:"""{"fused": us, "stock": us} summed over ``_UNLISTED_LATENCY_SHAPES``, each arm captured in a CUDA graph andreplayed, best of seven interleaved rounds. Stock = cuBLAS ``_int_mm``; its epilogue fuses into the consumer, soeach arm ends in one read of its output (int32 for stock, bf16 here) standing in for that consumer."""+ return _graph_latency(+ index,+ {+ "fused": lambda a, w, xs, ws: _launch(a, w, xs, ws, None, cfg).amax(),+ "stock": lambda a, w, xs, ws: _int_mm_stock(a, w).amax(),+ },+ )+++def _int_mm_stock(a: Any, w: Any) -> Any:+ import torch+ return torch._int_mm(a, w.t())+++def _unlisted_race(index: int, cfgs: tuple) -> dict:+ """{tile: us}, each held under load: a power-capped part clocks down under a tile that draws more, so a short+ burst would rank tiles by boost-clock speed, not render speed."""+ fns = {}+ for cfg in cfgs:+ fns[cfg] = lambda a, w, xs, ws, cfg = cfg: _launch(a, w, xs, ws, None, cfg).amax()+ return _graph_latency(index, fns, _UNLISTED_RACE_SHAPES, hold_s = _RACE_HOLD_S)+++def _graph_latency(+ index: int,+ fns: dict,+ shapes: tuple = _UNLISTED_LATENCY_SHAPES,+ hold_s: float = 0.0,+) -> dict:+ """{name: us} per CUDA-graph arm: best of seven interleaved rounds, or held ``hold_s`` then timed ``hold_s``."""import torchfrom .diffusion_cuda_graph import CAPTURE_MODE, _capturing, synchronize_outside_capturedev = torch.device("cuda", index)g = torch.Generator(device = "cpu").manual_seed(5)ops = []- for m, n, k in _UNLISTED_LATENCY_SHAPES:+ for m, n, k in shapes:a = torch.randint(-127, 128, (m, k), generator = g, dtype = torch.int8).to(dev)w = torch.randint(-127, 128, (n, k), generator = g, dtype = torch.int8).to(dev)xs = torch.full((m,), 1e-3, device = dev, dtype = torch.bfloat16)ws = torch.full((n,), 1e-3, device = dev, dtype = torch.bfloat16)ops.append((a, w, xs, ws))- fns = {- "fused": lambda a, w, xs, ws: _launch(a, w, xs, ws, None, cfg).amax(),- "stock": lambda a, w, xs, ws: torch._int_mm(a, w.t()).amax(),- }reps = 2graphs = {}with torch.cuda.device(dev):@@ -625,6 +660,11 @@ def _unlisted_latency(index: int, cfg: tuple) -> dict:synchronize_outside_capture(dev)start, end = torch.cuda.Event(enable_timing = True), torch.cuda.Event(enable_timing = True)best = {name: float("inf") for name in graphs}+ if hold_s > 0:+ for name, graph in graphs.items():+ best[name] = _held_us(graph, hold_s, start, end) / reps+ del graphs+ return bestfor _ in range(7):for name, graph in graphs.items():start.record()@@ -636,9 +676,32 @@ def _unlisted_latency(index: int, cfg: tuple) -> dict:return best+def _held_us(graph: Any, hold_s: float, start: Any, end: Any) -> float:+ """us per replay of ``graph`` after ``hold_s`` of back-to-back replays, averaged over ``hold_s`` more."""+ import time++ t0 = time.perf_counter()+ while time.perf_counter() - t0 < hold_s:+ graph.replay()+ end.record()+ end.synchronize()+ n = 0+ start.record()+ t0 = time.perf_counter()+ while n == 0 or time.perf_counter() - t0 < hold_s:+ graph.replay()+ n += 1+ if n % 2 == 0:+ end.record()+ end.synchronize()+ end.record()+ end.synchronize()+ return start.elapsed_time(end) * 1000.0 / n++def unlisted_config(index: int) -> Optional[tuple]:- """Unlisted sm80+ card: ``_FALLBACK_CONFIG`` when it passed the bit-exact probe (once per device) and the latency- check (once per (device, mode); skipped under force), else None. Outside any trace / capture."""+ """Unlisted sm80+ card: the race winner if the fallback passed the probe and the winner the latency check, else+ None. Force skips race and check and runs the fallback. Outside any trace / capture."""import torchmode = unlisted_mode()@@ -649,17 +712,19 @@ def unlisted_config(index: int) -> Optional[tuple]:_UNLISTED_PROBE[index] = _probe(index, _FALLBACK_CONFIG)if _UNLISTED_PROBE[index]:key = (index, mode)+ tile = _FALLBACK_CONFIG if mode == "force" else _unlisted_tile(index)if key not in _UNLISTED_OK:ok = Trueif mode != "force":try:- timing = _unlisted_latency(index, _FALLBACK_CONFIG)+ timing = _unlisted_latency(index, tile)_UNLISTED_TIMING[index] = {k: round(v, 1) for k, v in timing.items()}+ _UNLISTED_TIMING[index].update(_UNLISTED_RACE.get(index) or {})ok = timing["fused"] <= timing["stock"]except Exception: # noqa: BLE001 - main's path staysok = False_UNLISTED_OK[key] = ok- cfg = _FALLBACK_CONFIG if _UNLISTED_OK[key] else None+ cfg = tile if _UNLISTED_OK[key] else Noneexcept Exception: # noqa: BLE001cfg = None_DEVICE_TILES[index] = ()@@ -667,6 +732,115 @@ def unlisted_config(index: int) -> Optional[tuple]:return cfg+_UNLISTED_TILE: dict = {}+_UNLISTED_RACE: dict = {} # index -> {"tile": kept tile, "race": {tile: us}} for the log+_RACE_CACHE_NAME = "diffusion_int8_tile_race.json"+_RACE_CACHE_MAX = 16+++def race_enabled() -> bool:+ raw = (os.environ.get(INT8_GEMM_RACE_ENV) or "").strip().lower()+ return raw not in ("0", "off", "false", "no")+++def _race_cache_file() -> Optional[Any]:+ try:+ from pathlib import Path+ from utils.paths.storage_roots import cache_root+ return Path(cache_root()) / _RACE_CACHE_NAME+ except Exception: # noqa: BLE001 - no resolvable root: race every process+ return None+++def _race_key(index: int) -> Optional[str]:+ """Card, toolchain and this file's source: any change re-races."""+ try:+ import hashlib+ import torch+ import triton as _triton++ src = hashlib.sha256(open(__file__, "rb").read()).hexdigest()[:16]+ cap = torch.cuda.get_device_capability(index)+ return "|".join(+ (+ torch.cuda.get_device_name(index),+ f"{cap[0]}.{cap[1]}",+ torch.__version__,+ str(torch.version.cuda),+ _triton.__version__,+ src,+ )+ )+ except Exception: # noqa: BLE001+ return None+++def _race_cache_load(key: Optional[str]) -> Optional[tuple]:+ path = _race_cache_file() if key else None+ try:+ import json+ tile = (+ json.loads(path.read_text()).get(key) if path is not None and path.is_file() else None+ )+ except Exception: # noqa: BLE001 - unreadable or corrupt: a miss+ return None+ tile = tuple(tile) if isinstance(tile, list) else None+ return tile if tile == _FALLBACK_CONFIG or tile in _UNLISTED_RACE_TILES else None+++def _race_cache_store(key: Optional[str], tile: tuple) -> None:+ path = _race_cache_file() if key else None+ if path is None:+ return+ try:+ import json++ try:+ table = json.loads(path.read_text()) if path.is_file() else {}+ except Exception: # noqa: BLE001+ table = {}+ table = {k: v for k, v in table.items() if k != key and isinstance(v, list)}+ table = dict(list(table.items())[-(_RACE_CACHE_MAX - 1) :])+ table[key] = list(tile)+ path.parent.mkdir(parents = True, exist_ok = True)+ tmp = path.with_name(f"{path.name}.{os.getpid()}.tmp")+ tmp.write_text(json.dumps(table))+ os.replace(tmp, path)+ except Exception: # noqa: BLE001 - persistence is best-effort+ pass+++def _unlisted_tile(index: int) -> tuple:+ """Once per device: fastest probe-passing tile vs the fallback (ties keep the fallback), persisted per card and+ toolchain. Any failure, or UNSLOTH_DIFFUSION_INT8_GEMM_RACE=0, keeps the fallback."""+ if index not in _UNLISTED_TILE:+ best = _FALLBACK_CONFIG+ try:+ key = _race_key(index) if race_enabled() else None+ cached = _race_cache_load(key)+ if cached is not None and (cached == _FALLBACK_CONFIG or _probe(index, cached)):+ best = cached+ _UNLISTED_RACE[index] = {"tile": best}+ elif race_enabled():+ cands = tuple(+ t for t in _UNLISTED_RACE_TILES if t != _FALLBACK_CONFIG and _probe(index, t)+ )+ if cands:+ timing = _unlisted_race(index, (_FALLBACK_CONFIG,) + cands)+ for tile in cands:+ if timing[tile] < timing[best]:+ best = tile+ _UNLISTED_RACE[index] = {+ "tile": best,+ "race": {t: round(us, 1) for t, us in timing.items()},+ }+ _race_cache_store(key, best)+ except Exception: # noqa: BLE001 - the fallback stays+ best = _FALLBACK_CONFIG+ _UNLISTED_TILE[index] = best+ return _UNLISTED_TILE[index]++# (M, N, K, bias, fp32 scales). Ragged N / K stay on 16: an off-16 probe compiles the spilling variant (see ``_aligned``)._PROBE_SHAPES = ((257, 384, 512, False, False),@@ -1365,7 +1539,18 @@ def _swap_on(if gemmelse "keep cuBLAS",*torch.cuda.get_device_capability(index),- f" (latency check: {timing['fused']:.0f} vs {timing['stock']:.0f} us cuBLAS)"+ f" (latency check: {timing['fused']:.0f} vs {timing['stock']:.0f} us cuBLAS"+ + (f", tile {timing['tile']}" if timing.get("tile") else "")+ + (+ " of "+ + " / ".join(+ f"{t[0]}x{t[1]}x{t[2]} {us:.0f} us" for t, us in timing["race"].items()+ )+ + " held"+ if timing.get("race")+ else ""+ )+ + ")"if timingelse "",(diff --git a/studio/backend/tests/test_diffusion_int8_gemm_unlisted.py b/studio/backend/tests/test_diffusion_int8_gemm_unlisted.pyindex 323fb7c9613..1bdf4a7b274 100644--- a/studio/backend/tests/test_diffusion_int8_gemm_unlisted.py+++ b/studio/backend/tests/test_diffusion_int8_gemm_unlisted.py@@ -19,6 +19,7 @@ _ENVS = (g8.INT8_GEMM_ENV,g8.INT8_GEMM_UNLISTED_ENV,g8.INT8_GEMM_CONVROT_ENV,+ g8.INT8_GEMM_RACE_ENV,cq.INT8_ROTQUANT_ENV,)@@ -30,15 +31,19 @@ def _reset():g8._UNLISTED_PROBE,g8._UNLISTED_OK,g8._UNLISTED_TIMING,+ g8._UNLISTED_TILE,+ g8._UNLISTED_RACE,):d.clear()g8._UNLISTED_CARDS.clear()@pytest.fixture(autouse = True)-def _clean(monkeypatch):+def _clean(monkeypatch, tmp_path):for name in _ENVS:monkeypatch.delenv(name, raising = False)+ monkeypatch.setattr(g8, "_race_cache_file", lambda: tmp_path / g8._RACE_CACHE_NAME)+ monkeypatch.setattr(g8, "_race_key", lambda index: f"card{index}")_reset()yield_reset()@@ -51,17 +56,36 @@ class _Fake:cap,probe = True,timing = None,+ race = None,):- self.probes, self.timed = [], []+ self.probes, self.timed, self.raced = [], [], []self.timing = timing if timing is not None else {"fused": 10.0, "stock": 20.0}+ # None: every race tile fails its probe+ self.race = racemonkeypatch.setattr(torch.cuda, "is_available", lambda: True)monkeypatch.setattr(torch.cuda, "get_device_capability", lambda index = None: cap)monkeypatch.setattr(g8, "is_rocm_torch", lambda t: False)monkeypatch.setattr(g8, "_triton_version_ok", lambda version = None: True)monkeypatch.setattr(g8, "_kernels", lambda: object())monkeypatch.setattr(g8, "_op", lambda: "op")- monkeypatch.setattr(g8, "_probe", lambda index, cfg: self.probes.append(cfg) or probe)+ monkeypatch.setattr(g8, "_probe", self._probe_fn(probe))monkeypatch.setattr(g8, "_unlisted_latency", self._latency)+ monkeypatch.setattr(g8, "_unlisted_race", self._race)++ def _probe_fn(self, probe):+ def fn(index, cfg):+ self.probes.append(cfg)+ if cfg == g8._FALLBACK_CONFIG:+ return probe+ return self.race is not None and cfg in self.race++ return fn++ def _race(self, index, cfgs):+ self.raced.append(cfgs)+ if isinstance(self.race, Exception):+ raise self.race+ return {cfg: (self.race or {}).get(cfg, 10.0) for cfg in cfgs}def _latency(self, index, cfg):self.timed.append(cfg)@@ -117,7 +141,8 @@ def test_kill_switches(monkeypatch, env):def test_latency_gate(monkeypatch, timing, ok):fake = _Fake(monkeypatch, (8, 6), timing = timing)assert g8.device_config(0) == (g8._FALLBACK_CONFIG if ok else None)- assert fake.probes == [g8._FALLBACK_CONFIG] and fake.timed == [g8._FALLBACK_CONFIG]+ assert fake.probes[0] == g8._FALLBACK_CONFIG and fake.timed == [g8._FALLBACK_CONFIG]+ assert fake.probes[1:] == list(g8._UNLISTED_RACE_TILES)assert g8._DEVICE_TILES[0] == ()@@ -139,14 +164,15 @@ def test_decision_is_cached_per_device_and_the_switch_acts_between_loads(monkeypfake = _Fake(monkeypatch, (8, 6))assert g8.device_config(0) == g8._FALLBACK_CONFIGassert g8.device_config(0) == g8._FALLBACK_CONFIG- assert len(fake.probes) == 1 and len(fake.timed) == 1+ n = len(fake.probes)+ assert len(fake.timed) == 1monkeypatch.setenv(g8.INT8_GEMM_UNLISTED_ENV, "0")assert g8.device_config(0) is None and g8._DEVICE_CFG[0] is Nonemonkeypatch.delenv(g8.INT8_GEMM_UNLISTED_ENV)assert g8.device_config(0) == g8._FALLBACK_CONFIG- assert len(fake.probes) == 1 and len(fake.timed) == 1+ assert len(fake.probes) == n and len(fake.timed) == 1assert g8.device_config(1) == g8._FALLBACK_CONFIG # another card: its own probe and check- assert len(fake.probes) == 2 and len(fake.timed) == 2+ assert len(fake.probes) == 2 * n and len(fake.timed) == 2@pytest.mark.parametrize("cap", [(8, 9), (10, 0), (7, 5)])@@ -288,3 +314,197 @@ def test_switch_joins_the_compile_cache_key(monkeypatch):assert g8.INT8_GEMM_UNLISTED_ENV not in cc.graph_switches()monkeypatch.setenv(g8.INT8_GEMM_UNLISTED_ENV, "0")assert cc.graph_switches()[g8.INT8_GEMM_UNLISTED_ENV] == "off"+++_A100_TILE, _L4_TILE = g8._UNLISTED_RACE_TILES+++def test_race_tiles_fit_a_99kb_part_and_are_the_listed_tiles():+ # sm86 / sm87 parts have 99 KB of shared memory per block; a tile over it would only drop out at the probe+ for bm, bn, bk, _gm, _warps, stages in g8._UNLISTED_RACE_TILES:+ assert (bm * bk + bk * bn) * (stages - 1) <= 99 * 1024+ assert set(g8._UNLISTED_RACE_TILES) <= set(g8._ARCH_CONFIG.values())+++def test_race_keeps_the_fastest_probed_tile(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 9.0, _L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE+ assert fake.raced == [(g8._FALLBACK_CONFIG, _A100_TILE, _L4_TILE)]+ assert g8._UNLISTED_TIMING[0]["tile"] == _L4_TILE and g8._UNLISTED_TIMING[0]["fused"] == 10.0+ assert g8._UNLISTED_TIMING[0]["race"] == {+ g8._FALLBACK_CONFIG: 10.0,+ _A100_TILE: 9.0,+ _L4_TILE: 7.0,+ }+ assert g8.device_config(0) == _L4_TILE and len(fake.raced) == 1+++def test_race_tie_keeps_the_fallback(monkeypatch):+ _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 10.0, _L4_TILE: 10.0})+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+++def test_race_times_only_tiles_that_pass_their_probe(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 5.0})+ assert g8.device_config(0) == _A100_TILE+ assert fake.raced == [(g8._FALLBACK_CONFIG, _A100_TILE)]+++def test_no_probed_race_tile_never_races(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6))+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+ assert fake.raced == []+++def test_failed_race_keeps_the_fallback(monkeypatch):+ _Fake(monkeypatch, (8, 6), race = RuntimeError("capture failed"))+ monkeypatch.setattr(g8, "_probe", lambda index, cfg: True)+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+++def test_the_race_winner_still_needs_the_latency_check(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), timing = {"fused": 30.0, "stock": 20.0}, race = {_L4_TILE: 1.0})+ assert g8.device_config(0) is None+ assert fake.timed == [_L4_TILE]+++def test_a_faster_tile_can_pass_the_check_the_fallback_fails(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 8.0})+ # cuBLAS 20 us: the fallback (25 us) would keep it, the race winner (15 us) beats it+ monkeypatch.setattr(+ g8,+ "_unlisted_latency",+ lambda index, cfg: fake.timed.append(cfg)+ or {"fused": 15.0 if cfg == _A100_TILE else 25.0, "stock": 20.0},+ )+ assert g8.device_config(0) == _A100_TILE+ assert fake.timed == [_A100_TILE]+ assert g8._UNLISTED_TIMING[0]["tile"] == _A100_TILE and g8._UNLISTED_TIMING[0]["fused"] == 15.0++[email protected]("env", [g8.INT8_GEMM_UNLISTED_ENV, g8.INT8_GEMM_ENV])+def test_force_never_races(monkeypatch, env):+ monkeypatch.setenv(env, "1")+ fake = _Fake(monkeypatch, (8, 6), race = {_L4_TILE: 1.0})+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+ assert fake.raced == []++[email protected]("cap", [(8, 0), (8, 9), (12, 0)])+def test_listed_archs_never_race(monkeypatch, cap):+ fake = _Fake(monkeypatch, cap, race = {_A100_TILE: 1.0, _L4_TILE: 1.0})+ assert g8.device_config(0) == g8._ARCH_CONFIG[cap]+ assert fake.raced == [] and fake.timed == []+++def test_race_winner_is_reused_by_the_next_process(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 9.0, _L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE and len(fake.raced) == 1+ _reset() # a new process: in-memory verdicts gone, the file stays+ fake.probes.clear()+ assert g8.device_config(0) == _L4_TILE+ assert len(fake.raced) == 1 # no second race+ assert fake.probes == [g8._FALLBACK_CONFIG, _L4_TILE] # only the kept tile is probed again+++def test_a_kept_fallback_is_reused_without_probing_the_race_tiles(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 11.0, _L4_TILE: 12.0})+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+ _reset()+ fake.probes.clear()+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+ assert len(fake.raced) == 1 and fake.probes == [g8._FALLBACK_CONFIG]+++def test_another_card_or_toolchain_races_again(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_A100_TILE: 9.0, _L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE+ _reset()+ monkeypatch.setattr(g8, "_race_key", lambda index: "other-card")+ assert g8.device_config(0) == _L4_TILE and len(fake.raced) == 2+++def test_kept_tile_that_now_fails_its_probe_falls_back(monkeypatch):+ fake = _Fake(monkeypatch, (8, 6), race = {_L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE+ _reset()+ fake.race = {} # the kept tile no longer passes its probe+ assert g8.device_config(0) == g8._FALLBACK_CONFIG++[email protected]("raw", ["", "{not json", '{"card0": [1, 2, 3]}', '{"card0": "x"}'])+def test_unreadable_or_foreign_cache_entries_are_a_miss(monkeypatch, tmp_path, raw):+ (tmp_path / g8._RACE_CACHE_NAME).write_text(raw)+ fake = _Fake(monkeypatch, (8, 6), race = {_L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE and len(fake.raced) == 1++[email protected]("raw", ["0", "off"])+def test_race_switch_off_keeps_the_fallback_and_never_reads_the_file(monkeypatch, tmp_path, raw):+ (tmp_path / g8._RACE_CACHE_NAME).write_text('{"card0": [256, 128, 128, 8, 8, 3]}')+ monkeypatch.setenv(g8.INT8_GEMM_RACE_ENV, raw)+ fake = _Fake(monkeypatch, (8, 6), race = {_L4_TILE: 7.0})+ assert g8.device_config(0) == g8._FALLBACK_CONFIG+ assert fake.raced == [] and fake.probes == [g8._FALLBACK_CONFIG]+++def test_cache_keeps_a_bounded_number_of_cards(monkeypatch, tmp_path):+ import json++ path = tmp_path / g8._RACE_CACHE_NAME+ path.write_text(json.dumps({f"old{i}": list(g8._FALLBACK_CONFIG) for i in range(40)}))+ _Fake(monkeypatch, (8, 6), race = {_L4_TILE: 7.0})+ assert g8.device_config(0) == _L4_TILE+ table = json.loads(path.read_text())+ assert len(table) == g8._RACE_CACHE_MAX and table["card0"] == list(_L4_TILE)+++def test_race_holds_each_tile_under_load_at_render_rows(monkeypatch):+ seen = {}++ def fake_graph_latency(+ index,+ fns,+ shapes = g8._UNLISTED_LATENCY_SHAPES,+ hold_s = 0.0,+ ):+ seen.update(shapes = shapes, hold_s = hold_s, arms = tuple(fns))+ return {k: 1.0 for k in fns}++ monkeypatch.setattr(g8, "_graph_latency", fake_graph_latency)+ g8._unlisted_race(0, (g8._FALLBACK_CONFIG, _L4_TILE))+ assert seen["hold_s"] == g8._RACE_HOLD_S > 0+ assert all(m == 4096 for m, _n, _k in seen["shapes"]) and len(seen["shapes"]) == 3+ assert seen["arms"] == (g8._FALLBACK_CONFIG, _L4_TILE)+++class _Ev:+ def __init__(self, clock):+ self.clock, self.t = clock, None++ def record(self):+ self.t = self.clock[0]++ def synchronize(self):+ pass++ def elapsed_time(self, other):+ return (other.t - self.t) / 1000.0 # ms+++def test_held_timing_skips_the_settle_window(monkeypatch):+ # a part that runs 1 us per replay for the first 50 ms, then 2 us (clocked down): the held time is the slow one+ import time++ clock = [0.0]+ wall = [0.0]+ monkeypatch.setattr(time, "perf_counter", lambda: wall[0])++ class _G:+ def replay(self):+ dt = 1.0 if wall[0] < 0.05 else 2.0+ clock[0] += dt+ wall[0] += 0.001++ us = g8._held_us(_G(), 0.1, _Ev(clock), _Ev(clock))+ assert us == pytest.approx(2.0)