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 ROCm: keep stored flash-attention verdicts from recompiling per bucket, and gate the CFG replica too (#14869)
Daniel Han1f557674773a
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.pyindex 8d5b15bf001..1f3caf1a787 100644--- a/studio/backend/core/inference/diffusion_attention.py+++ b/studio/backend/core/inference/diffusion_attention.py@@ -39,6 +39,7 @@ import functoolsimport osimport reimport threading+import weakreffrom typing import Any, OptionalATTN_AUTO = "auto"@@ -846,6 +847,7 @@ def _sync_rocm_flash_baseline() -> None:if current != _ROCM_FLASH_BASELINE[0]:ROCM_FLASH_ADMISSIONS.clear()_ROCM_FLASH_BUCKETS.clear()+ _ROCM_FLASH_STORED_MISSES.clear()_ROCM_FLASH_BASELINE[0] = current@@ -901,7 +903,7 @@ def _rocm_flash_length_reason(query: Any, key: Any) -> Optional[str]:return Noneif traced:# Nothing here may graph-break: the device index, the verdict tables and any probe are read in plain Python- # by the constant-marked helper, called with constants only (the gate's own key, never a traced size).+ # by the constant-marked helpers, called with constants only (the gate's own key, never a traced size).match = Nonefor shape, found in gate.items():if shape[1] == dtype_name and heads == shape[2] and head_dim == shape[3]:@@ -909,15 +911,38 @@ def _rocm_flash_length_reason(query: Any, key: Any) -> Optional[str]:breakif match is None:return None+ h, d, geometries = match[0][2], match[0][3], tuple(sorted(match[1]))+ b_bucket = _rocm_flash_batch_bucket(batch)+ joint = kv == seq # self / joint attention: one symbol, so no guard+ kv_bucket = None if joint else _rocm_flash_bucket(kv)+ # Guard only where the route changes, so neighbouring same-verdict buckets reuse this graph.+ segments = _rocm_flash_traced_segments(+ raw_device, dtype_name, h, d, geometries, kv_bucket, b_bucket+ )+ for end, bucket, known, reason in segments:+ if seq < end:+ if known:+ return reason+ return _rocm_flash_traced_reason(+ raw_device,+ dtype_name,+ h,+ d,+ geometries,+ bucket,+ bucket if joint else kv_bucket,+ b_bucket,+ )+ q_bucket = _rocm_flash_bucket(seq)return _rocm_flash_traced_reason(raw_device,dtype_name,- match[0][2],- match[0][3],- tuple(sorted(match[1])),- _rocm_flash_bucket(seq),- _rocm_flash_bucket(kv),- _rocm_flash_batch_bucket(batch),+ h,+ d,+ geometries,+ q_bucket,+ q_bucket if joint else kv_bucket,+ b_bucket,)device = _indexed_cuda_device(raw_device)try:@@ -964,6 +989,85 @@ def _rocm_flash_traced_reason(return "compiled or captured"+# Traced query lengths are routed by segments up to this many tokens; longer ones guard on their own bucket.+_ROCM_FLASH_SEGMENT_LIMIT = 1 << 22+# Admission keys with no stored verdict at first stored-only lookup (later verdicts reach the per-bucket route).+_ROCM_FLASH_STORED_MISSES: set = set()+_ROCM_FLASH_SLOWER = "slower or inexact at this size"+++def _rocm_flash_bucket_known(+ device: str, dtype: Any, geometries: tuple, q_bucket: int, kv_bucket: int, b_bucket: int+) -> Optional[bool]:+ """This bucket's verdict if already known (in memory, this load's admissions or the stored timings), never+ probing: True flash, False native, None untimed or deferred."""+ deferred = getattr(_ROCM_FLASH_LOCAL, "deferred", None)+ verdict: Optional[bool] = True+ for g in geometries:+ k = (device, str(dtype), *g, q_bucket, kv_bucket, b_bucket)+ ok = _ROCM_FLASH_BUCKETS.get(k)+ if ok is None and not (isinstance(deferred, set) and k in deferred):+ ok = _rocm_flash_geometry_admitted(+ device,+ dtype,+ g,+ tokens = q_bucket,+ batch = b_bucket,+ stored_only = True,+ **({} if kv_bucket == q_bucket else {"kv_tokens": kv_bucket}),+ )+ if ok is not None:+ _ROCM_FLASH_BUCKETS[k] = ok+ if ok is False:+ return False+ if ok is None:+ verdict = None+ return verdict+++def _rocm_flash_traced_segments(+ raw_device: str,+ dtype_name: str,+ heads: int,+ head_dim: int,+ geometries: tuple,+ kv_bucket: Optional[int],+ b_bucket: int,+) -> tuple:+ """The query-length axis of a traced call as ascending ``(end, bucket, known, reason)`` segments: a run of+ neighbouring buckets whose known verdict matches is one segment (``reason`` its route), an untimed bucket is its+ own (``known`` False). ``kv_bucket`` None means keys are as long as queries. Run in plain Python while Dynamo+ traces (constant-marked like ``_rocm_flash_traced_reason``); ``()`` when anything is odd (the caller falls back+ to the per-bucket route)."""+ try:+ import torch++ device = _indexed_cuda_device(raw_device)+ gate = _active_rocm_flash_gate()+ if gate and (device, dtype_name, heads, head_dim) not in gate:+ return ()+ dtype = getattr(torch, dtype_name.rpartition(".")[2], None)+ if not isinstance(dtype, torch.dtype):+ return ()+ _sync_rocm_flash_baseline()+ segments: list = []+ bucket = ROCM_FLASH_MIN_BUCKET+ with _ROCM_FLASH_GATE_LOCK:+ while bucket < _ROCM_FLASH_SEGMENT_LIMIT:+ ok = _rocm_flash_bucket_known(+ device, dtype, geometries, bucket, kv_bucket or bucket, b_bucket+ )+ reason = None if ok else _ROCM_FLASH_SLOWER+ if ok is not None and segments and segments[-1][2] and segments[-1][3] == reason:+ segments[-1] = (bucket * 2, segments[-1][1], True, reason)+ else:+ segments.append((bucket * 2, bucket, ok is not None, reason))+ bucket *= 2+ return tuple(segments)+ except Exception: # noqa: BLE001+ return ()++def _rocm_flash_bucket_reason(device: str, dtype: Any, geometries: tuple, q_bucket: int, kv_bucket: int, b_bucket: int) -> Optional[str]:@@ -972,7 +1076,7 @@ def _rocm_flash_bucket_reason(if all(_ROCM_FLASH_BUCKETS.get(k) is True for k in keys):return Noneif any(_ROCM_FLASH_BUCKETS.get(k) is False for k in keys):- return "slower or inexact at this size"+ return _ROCM_FLASH_SLOWERdeferred = getattr(_ROCM_FLASH_LOCAL, "deferred", None)if not isinstance(deferred, set):deferred = set() # no owning DiT: nothing to remember the deferral on@@ -997,7 +1101,7 @@ def _rocm_flash_bucket_reason(return "timing deferred"_ROCM_FLASH_BUCKETS[k] = okverdict = verdict and ok- return None if verdict else "slower or inexact at this size"+ return None if verdict else _ROCM_FLASH_SLOWERdef _native_sdpa_fused_serves(@@ -1080,10 +1184,12 @@ def _rocm_flash_geometry_admitted(kv_tokens: Optional[int] = None,batch: int = 1,live: bool = False,+ stored_only: bool = False,) -> Optional[bool]:"""Whether flash is admitted for ``geometry`` (hidden, heads, head_dim[, context width]) at ``batch`` x ``tokens``queries x ``kv_tokens`` keys (default square, batch 1). None when the probe could not run (it raised, or ``live``,- inside a running forward, and there is no room for it beside that forward's tensors): nothing is cached."""+ inside a running forward, and there is no room for it beside that forward's tensors): nothing is cached.+ ``stored_only``: None instead of probing when no verdict is known yet."""kv = tokens if kv_tokens is None else int(kv_tokens)# Geometry, lengths and batch as separate fields: a flat tuple aliases (h, H, d, ctx) at n with (h, H, d) at ctx x n.key = (device, str(dtype), tuple(geometry), tokens, kv, batch)@@ -1091,6 +1197,10 @@ def _rocm_flash_geometry_admitted(cached = ROCM_FLASH_ADMISSIONS.get(key)if cached is not None:return bool(cached.get("admitted"))+ if stored_only and key in _ROCM_FLASH_STORED_MISSES:+ return (+ None # traced segments ask for every bucket on every call: read the store once per slot+ )toolchain = _rocm_flash_toolchain_key(device)path = _rocm_flash_cache_path(toolchain)size = (str(tokens) if kv == tokens else f"{tokens}x{kv}") + ("" if batch == 1 else f"b{batch}")@@ -1107,6 +1217,9 @@ def _rocm_flash_geometry_admitted(ROCM_FLASH_ADMISSIONS[key] = rec_log_rocm_flash_verdict(logger, device, geometry, rec, "cached")return rec["admitted"]+ if stored_only:+ _ROCM_FLASH_STORED_MISSES.add(key)+ return Noneif live:need = _rocm_flash_probe_bytes(geometry, tokens, kv, batch, dtype, device)if not _rocm_flash_probe_fits(device, need):@@ -1144,6 +1257,7 @@ def _rocm_flash_geometry_admitted(valid = _rocm_flash_record_ok(rec)rec["admitted"] = valid and _rocm_flash_wins(rec)ROCM_FLASH_ADMISSIONS[key] = rec+ _ROCM_FLASH_STORED_MISSES.discard(key)if valid: # an implausible timing is not stored, so it cannot pin a verdict_save_rocm_flash_verdict(path, toolchain, slot, rec)_log_rocm_flash_verdict(logger, device, geometry, rec, "probe")@@ -1935,6 +2049,7 @@ def _install_rocm_flash_dispatch_guard() -> bool:try:import torchtorch.compiler.assume_constant_result(_rocm_flash_traced_reason)+ torch.compiler.assume_constant_result(_rocm_flash_traced_segments)except Exception: # noqa: BLE001 - torch without it: a traced call graph-breaks into the helper, still correctpassreturn _install_dispatch_guard(@@ -1957,6 +2072,8 @@ _ROCM_FLASH_HOOKS_ATTR = "_unsloth_rocm_flash_hooks"# On the pipe: every DiT the hooks went on, whatever attribute holds it (a MiniMax-H3 view hooks transformer_ref, which# _attention_dits does not enumerate). Reset, report and the memory guard iterate this._ROCM_FLASH_DITS_ATTR = "_unsloth_rocm_flash_dits"+# On a hooked DiT: its live CFG replicas (weak refs), reset by begin_attention_run with the source.+_ROCM_FLASH_REPLICAS_ATTR = "_unsloth_rocm_flash_replicas"def _rocm_flash_dits(pipe: Any) -> list:@@ -1969,6 +2086,16 @@ def _rocm_flash_dits(pipe: Any) -> list:return found+def _with_rocm_flash_replicas(dits: list) -> list:+ """``dits`` followed by their live CFG replicas (``track_rocm_flash_replica``)."""+ out = list(dits)+ for source in dits:+ replicas = getattr(source, _ROCM_FLASH_REPLICAS_ATTR, None)+ if isinstance(replicas, weakref.WeakSet):+ out.extend(r for r in list(replicas) if not any(r is d for d in out))+ return out++def _compiling() -> bool:try:import torch@@ -2003,53 +2130,81 @@ def _track_rocm_flash_calls(pipe: Any) -> None:registry.append(dit)except Exception: # noqa: BLE001pass- register_pre = getattr(dit, "register_forward_pre_hook", None)- register_post = getattr(dit, "register_forward_hook", None)- if not callable(register_pre) or not callable(register_post):- continue- if getattr(dit, _ROCM_FLASH_HOOKS_ATTR, None):- continue+ _hook_rocm_flash_dit(dit)- # Also while Dynamo traces a compiled DiT (it replays these threading.local writes), so a traced call sees the- # gate and runs native.- def pre(- _module,- _args,- dit = dit,- ) -> None:- outer = getattr(_ROCM_FLASH_LOCAL, "stack", None)- if outer is None:- outer = _ROCM_FLASH_LOCAL.stack = []- outer.append(- (- getattr(_ROCM_FLASH_LOCAL, "gate", None),- getattr(_ROCM_FLASH_LOCAL, "tally", None),- getattr(_ROCM_FLASH_LOCAL, "deferred", None),- )++def _hook_rocm_flash_dit(dit: Any) -> None:+ register_pre = getattr(dit, "register_forward_pre_hook", None)+ register_post = getattr(dit, "register_forward_hook", None)+ if not callable(register_pre) or not callable(register_post):+ return+ if getattr(dit, _ROCM_FLASH_HOOKS_ATTR, None):+ return++ # Dynamo replays these threading.local writes, so traced calls see the gate too.+ # Use the hook's ``dit`` arg, never a closure: that cycle pins a dropped CFG replica's weights on its card.+ def pre(dit, _args) -> None:+ outer = getattr(_ROCM_FLASH_LOCAL, "stack", None)+ if outer is None:+ outer = _ROCM_FLASH_LOCAL.stack = []+ outer.append(+ (+ getattr(_ROCM_FLASH_LOCAL, "gate", None),+ getattr(_ROCM_FLASH_LOCAL, "tally", None),+ getattr(_ROCM_FLASH_LOCAL, "deferred", None),)- _ROCM_FLASH_LOCAL.gate = getattr(dit, ROCM_FLASH_GATE_ATTR, None) or None- tally = getattr(dit, ROCM_FLASH_TALLY_ATTR, None)- _ROCM_FLASH_LOCAL.tally = tally if isinstance(tally, dict) else None- deferred = getattr(dit, ROCM_FLASH_DEFERRED_ATTR, None)- _ROCM_FLASH_LOCAL.deferred = deferred if isinstance(deferred, set) else None-- def post(_module, _args, _output) -> None:- stack = getattr(_ROCM_FLASH_LOCAL, "stack", None)- gate, tally, deferred = stack.pop() if stack else (None, None, None)- _ROCM_FLASH_LOCAL.gate, _ROCM_FLASH_LOCAL.tally = gate, tally- _ROCM_FLASH_LOCAL.deferred = deferred+ )+ _ROCM_FLASH_LOCAL.gate = getattr(dit, ROCM_FLASH_GATE_ATTR, None) or None+ tally = getattr(dit, ROCM_FLASH_TALLY_ATTR, None)+ _ROCM_FLASH_LOCAL.tally = tally if isinstance(tally, dict) else None+ deferred = getattr(dit, ROCM_FLASH_DEFERRED_ATTR, None)+ _ROCM_FLASH_LOCAL.deferred = deferred if isinstance(deferred, set) else None++ def post(_module, _args, _output) -> None:+ stack = getattr(_ROCM_FLASH_LOCAL, "stack", None)+ gate, tally, deferred = stack.pop() if stack else (None, None, None)+ _ROCM_FLASH_LOCAL.gate, _ROCM_FLASH_LOCAL.tally = gate, tally+ _ROCM_FLASH_LOCAL.deferred = deferred++ try:+ try: # also after a forward that raised, so a failed run never leaves its gate active+ post_handle = register_post(post, always_call = True)+ except TypeError:+ post_handle = register_post(post)+ handles = [register_pre(pre), post_handle]+ setattr(dit, _ROCM_FLASH_HOOKS_ATTR, handles)+ setattr(dit, ROCM_FLASH_TALLY_ATTR, {})+ setattr(dit, ROCM_FLASH_DEFERRED_ATTR, set())+ except Exception: # noqa: BLE001+ pass- try:- try: # also after a forward that raised, so a failed run never leaves its gate active- post_handle = register_post(post, always_call = True)- except TypeError:- post_handle = register_post(post)- handles = [register_pre(pre), post_handle]- setattr(dit, _ROCM_FLASH_HOOKS_ATTR, handles)- setattr(dit, ROCM_FLASH_TALLY_ATTR, {})- setattr(dit, ROCM_FLASH_DEFERRED_ATTR, set())- except Exception: # noqa: BLE001- pass++def track_rocm_flash_replica(source: Any, replica: Any, device: Any) -> None:+ """A CFG replica (``diffusion_multigpu.build_replica``, root hooks cleared) runs its forward on its own worker+ thread, where the source's hooks never set the gate: give it its own hooks and the source's gate keyed to its+ card, so its calls are gated (and their buckets timed) on that card exactly as the source's are."""+ if not getattr(source, _ROCM_FLASH_HOOKS_ATTR, None):+ return+ gate = getattr(source, ROCM_FLASH_GATE_ATTR, None)+ try:+ if gate:+ card = _indexed_cuda_device(str(device))+ gate = {(card, *shape[1:]): found for shape, found in gate.items()}+ setattr(replica, ROCM_FLASH_GATE_ATTR, gate or None)+ setattr(+ replica, _ROCM_FLASH_HOOKS_ATTR, None+ ) # the copied handles point at the source's hooks+ except Exception: # noqa: BLE001+ return+ _hook_rocm_flash_dit(replica)+ try: # the replica outlives a generation: its deferred buckets must be retried at the next one as the source's are+ replicas = getattr(source, _ROCM_FLASH_REPLICAS_ATTR, None)+ if not isinstance(replicas, weakref.WeakSet):+ replicas = weakref.WeakSet()+ setattr(source, _ROCM_FLASH_REPLICAS_ATTR, replicas)+ replicas.add(replica)+ except Exception: # noqa: BLE001+ passdef _untrack_rocm_flash_calls(pipe: Any) -> None:@@ -2090,7 +2245,7 @@ def rocm_flash_ran(pipe: Any) -> Optional[tuple[str, str]]:if not dits:return Nonetotal: dict[str, int] = {}- for dit in dits:+ for dit in _with_rocm_flash_replicas(dits): # a CFG replica's calls are this generation's tootally = getattr(dit, ROCM_FLASH_TALLY_ATTR, None)if isinstance(tally, dict):for name, count in tally.items():@@ -2120,7 +2275,7 @@ def rocm_flash_ran(pipe: Any) -> Optional[tuple[str, str]]:def begin_attention_run(state: Any) -> None:"""A generation boundary: the per-DiT route tallies restart, so the report after it describes this run alone, andthis run's DiTs retry buckets whose probe could not run."""- for dit in _rocm_flash_dits(getattr(state, "pipe", None)):+ for dit in _with_rocm_flash_replicas(_rocm_flash_dits(getattr(state, "pipe", None))):if isinstance(getattr(dit, ROCM_FLASH_TALLY_ATTR, None), dict):try:setattr(dit, ROCM_FLASH_TALLY_ATTR, {})diff --git a/studio/backend/core/inference/diffusion_multigpu.py b/studio/backend/core/inference/diffusion_multigpu.pyindex 861e9f4a6ff..f97a37dd2d5 100644--- a/studio/backend/core/inference/diffusion_multigpu.py+++ b/studio/backend/core/inference/diffusion_multigpu.py@@ -1614,6 +1614,10 @@ def build_replica(module: Any, device: Any) -> Any:)if stray:raise RuntimeError(f"replica weights stayed on {', '.join(stray)}, not {device}")+ # The ROCm flash gate is thread-local state its root hooks set; the copy runs on its own worker thread.+ from .diffusion_attention import track_rocm_flash_replica++ track_rocm_flash_replica(module, replica, device)return replica@@ -1719,7 +1723,7 @@ def _copy_module(module: Any, device: Any) -> Any:_SHARED_STATE_TYPES = frozenset({"NVFP4StepController"})# Caches only the source's own hooks fill and clear: the FLUX.3 conditioning blocks reach the copy through the# forwarded call (diffusion_cond_blocks), so a copied cache would only pin source-card tensors that no render clears.-_SOURCE_ONLY_ATTRS = frozenset({"_unsloth_cond_cache"})+_SOURCE_ONLY_ATTRS = frozenset({"_unsloth_cond_cache", "_unsloth_rocm_flash_replicas"})def _rewrap_compiled(source: Any, replica: Any) -> None:diff --git a/studio/backend/tests/test_diffusion_attention_rocm_flash.py b/studio/backend/tests/test_diffusion_attention_rocm_flash.pyindex 3669c344530..d7aec268eea 100644--- a/studio/backend/tests/test_diffusion_attention_rocm_flash.py+++ b/studio/backend/tests/test_diffusion_attention_rocm_flash.py@@ -39,6 +39,7 @@ def _clean(monkeypatch, tmp_path):monkeypatch.setattr(att, "_INSTALL_ATTEMPTED", set())monkeypatch.setattr(att, "_ROCM_FLASH_LOCAL", __import__("threading").local(), raising = False)monkeypatch.setattr(att, "_ROCM_FLASH_BUCKETS", {}, raising = False)+ monkeypatch.setattr(att, "_ROCM_FLASH_STORED_MISSES", set(), raising = False)monkeypatch.setattr(att, "_ROCM_FLASH_BASELINE", [None], raising = False)monkeypatch.setattr(att, "_rocm_flash_probe_fits", lambda device, need: True, raising = False)monkeypatch.setattr(att, "_ROCM_FLASH_ROUTED", {})@@ -1333,6 +1334,78 @@ def test_deferral_belongs_to_its_dit_not_to_other_generations(monkeypatch):assert timed == [4096, 32768] and ran[-1] == "flash"+def test_cfg_replica_retries_its_deferred_bucket_at_the_next_generation(monkeypatch):+ dit, guarded, ran, timed = _length_env(monkeypatch, {4096: 70.0, 32768: 60.0})+ replica = _Dit()+ att.track_rocm_flash_replica(dit, replica, "cpu")+ pipe = types.SimpleNamespace(transformer = dit)+ monkeypatch.setattr(att, "_rocm_flash_probe_fits", lambda device, need: False)+ att.begin_attention_run(types.SimpleNamespace(pipe = pipe))+ replica.run(guarded, [(40000, None)])+ assert timed == [4096] and ran == ["native"]+ assert len(getattr(replica, att.ROCM_FLASH_DEFERRED_ATTR)) == 1+ # Room on the replica card at the next generation: the same (kept) replica times the bucket again.+ monkeypatch.setattr(att, "_rocm_flash_probe_fits", lambda device, need: True)+ att.begin_attention_run(types.SimpleNamespace(pipe = pipe))+ replica.run(guarded, [(40000, None)])+ assert timed == [4096, 32768] and ran[-1] == "flash"+++def test_cfg_replica_routes_count_in_the_generation_report(monkeypatch):+ dit, guarded, ran, timed = _length_env(monkeypatch, {4096: 70.0, 32768: 90.0})+ replica = _Dit()+ att.track_rocm_flash_replica(dit, replica, "cpu")+ pipe = types.SimpleNamespace(transformer = dit)+ att.begin_attention_run(types.SimpleNamespace(pipe = pipe))+ dit.run(guarded, [(5000, None)])+ replica.run(guarded, [(40000, None)])+ assert ran == ["flash", "native"]+ value, reason = att.rocm_flash_ran(pipe)+ assert value == "flash" and "on 1 of 2 attention calls" in reason+ att.begin_attention_run(types.SimpleNamespace(pipe = pipe))+ replica.run(guarded, [(40000, None)])+ assert att.rocm_flash_ran(pipe)[0] == "native"+++def test_a_hooked_replica_is_freed_without_a_cycle_collection():+ import gc+ import weakref++ torch = pytest.importorskip("torch")+ module = torch.nn.Linear(4, 4)+ att._hook_rocm_flash_dit(module)+ assert getattr(module, att._ROCM_FLASH_HOOKS_ATTR)+ ref = weakref.ref(module)+ enabled = gc.isenabled()+ gc.disable()+ try:+ del module+ assert (+ ref() is None+ ) # no hook -> module cycle: a dropped CFG replica frees its card memory at once+ finally:+ if enabled:+ gc.enable()+++def test_traced_segments_read_the_stored_verdicts_once_per_absent_bucket(monkeypatch, tmp_path):+ torch = pytest.importorskip("torch")+ loads = []+ real_load = att._load_rocm_flash_verdicts+ monkeypatch.setattr(att, "_rocm_flash_toolchain_key", lambda device: "tc")+ monkeypatch.setattr(att, "_rocm_flash_cache_path", lambda tc: str(tmp_path / "probe.json"))+ monkeypatch.setattr(+ att, "_load_rocm_flash_verdicts", lambda *a: loads.append(a) or real_load(*a)+ )+ g = ((3072, 24, 128),)+ args = ("cuda:0", torch.bfloat16, g, 4096, 4096, 1)+ assert att._rocm_flash_bucket_known(*args) is None+ first = len(loads)+ assert first == 1+ assert att._rocm_flash_bucket_known(*args) is None+ assert len(loads) == first # an absent slot is not re-read on every traced call++def test_a_moved_sdpa_baseline_drops_the_in_memory_verdicts(monkeypatch):baseline = ["sdpafem,aotriton-exp1"]monkeypatch.setattr(att, "_native_sdpa_baseline", lambda: baseline[0])@@ -1981,6 +2054,62 @@ def test_compiled_dynamic_lengths_recompile_per_bucket_not_per_length(monkeypatctorch._dynamo.reset()[email protected]("native_8192", [False, True])+def test_compiled_lengths_across_known_buckets_guard_only_where_the_route_changes(+ monkeypatch, native_8192+):+ # every bucket already timed (persisted, read back after a restart): neighbouring buckets with the same verdict+ # share one graph; a bucket whose verdict differs still gets its own+ flash_ms = {4096: 70.0, 8192: 90.0 if native_8192 else 70.0, 16384: 70.0}+ torch, dit, timed = _compiled_env(monkeypatch, True, flash_ms)+ bf16 = torch.bfloat16+ lengths = (4352, 9000, 17000, 5000, 9500)+ eager = [float(dit(torch.zeros(1, n, 2, 16, dtype = bf16)).flatten()[0]) for n in lengths]+ att._ROCM_FLASH_BUCKETS.clear()+ att.ROCM_FLASH_ADMISSIONS.clear()+ att._ROCM_FLASH_STORED_MISSES.clear()+ torch._dynamo.reset()+ frames = []+ compiled = torch.compile(+ dit,+ backend = lambda gm, inputs: frames.append(gm) or gm.forward,+ dynamic = True,+ fullgraph = True,+ )+ out, counts = [], []+ for n in lengths:+ out.append(float(compiled(torch.zeros(1, n, 2, 16, dtype = bf16)).flatten()[0]))+ counts.append(len(frames))+ assert out == eager == ([1.0, -1.0, 1.0, 1.0, -1.0] if native_8192 else [1.0] * 5)+ assert counts == ([1, 2, 3, 3, 3] if native_8192 else [1, 1, 1, 1, 1])+ assert timed == [4096, 8192, 16384] # read back, never re-timed+ torch._dynamo.reset()+++def test_cfg_replica_keeps_the_rocm_flash_gate_on_its_worker_thread(monkeypatch):+ mg = pytest.importorskip("core.inference.diffusion_multigpu")+ torch, dit, timed = _compiled_env(monkeypatch, True, {4096: 70.0, 8192: 110.0})+ q = torch.zeros(1, 9000, 2, 16, dtype = torch.bfloat16)+ assert float(dit(q).flatten()[0]) == -1.0 # 8192 lost its timing: native on the source+ replica = mg.build_replica(dit, "cpu")+ worker = mg._ReplicaWorker(torch.device("cpu"))+ try:+ out = worker.call(mg._replica_call(replica, (q,), {}))+ finally:+ worker.close()+ assert float(out.flatten()[0]) == -1.0 and timed == [4096, 8192]+ assert getattr(att._ROCM_FLASH_LOCAL, "gate", None) is None+ # a rebuilt replica (weights changed) is tracked too; the copy carries no replica set of its own+ again = mg.build_replica(dit, "cpu")+ assert att._ROCM_FLASH_REPLICAS_ATTR not in again.__dict__+ assert set(getattr(dit, att._ROCM_FLASH_REPLICAS_ATTR)) == {replica, again}+ # on another card the gate is that card's, so its buckets are timed there+ copy = torch.nn.Module()+ att.track_rocm_flash_replica(dit, copy, "cuda:1")+ gate = getattr(copy, att.ROCM_FLASH_GATE_ATTR)+ assert {k[0] for k in gate} == {"cuda:1"} and len(copy._forward_pre_hooks) == 1++def test_traced_call_with_no_room_for_its_probe_runs_native(monkeypatch):torch, dit, timed = _compiled_env(monkeypatch, True, {4096: 70.0, 8192: 70.0})monkeypatch.setattr(att, "_rocm_flash_probe_fits", lambda device, need: False)