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 installer: drop a flash-attn built for a torch that is gone, and pair torch 2.9 with torchao 0.15.0 (#13247)
alkinun6d7c6e962dcf
diff --git a/studio/backend/core/_torchao_stub.py b/studio/backend/core/_torchao_stub.pyindex 54943908fbe..add31323a6d 100644--- a/studio/backend/core/_torchao_stub.py+++ b/studio/backend/core/_torchao_stub.py@@ -249,15 +249,13 @@ _TORCHAO_EXPORT_MIN = (0, 15)def torchao_export_loadable() -> bool:- """Whether an export worker can get real torchao: always off Windows ROCm; there, torchao must- be installed and unsloth must ship the shim. Searches sys.path, so a stub already in- sys.modules does not count, and imports nothing."""+ """checks Windows ROCm for torchao and unsloth's shim without imports; true elsewhere."""if not _is_windows_rocm():return Truetry:if importlib.machinery.PathFinder.find_spec("torchao") is None:return False- # transformers 5's TorchAoConfig minimum; torch <= 2.9 is paired with torchao 0.14.+ # TorchAoConfig requires torchao 0.15; torch <= 2.8 is paired with torchao 0.14found = re.match(r"(\d+)\.(\d+)", importlib.metadata.version("torchao"))if not found or (int(found[1]), int(found[2])) < _TORCHAO_EXPORT_MIN:return False@@ -272,8 +270,7 @@ _STUB_CONSUMERS = ("transformers", "peft", "diffusers", "accelerate", "unsloth",def install_torchao_windows_rocm_real_or_stub() -> bool:- """Export worker: real torchao on Windows ROCm when it is installed and unsloth can import it- without torch.distributed, else the stub. True iff real torchao is loaded. No-op elsewhere."""+ """load real torchao on Windows ROCm when its no-distributed shim works; return true iff loaded."""if not _is_windows_rocm():return False# A spawn child re-runs run.py as __mp_main__, which stubs torchao first. Drop that stubdiff --git a/studio/backend/core/inference/diffusion_precision.py b/studio/backend/core/inference/diffusion_precision.pyindex 9a229d9990c..efc6f959037 100644--- a/studio/backend/core/inference/diffusion_precision.py+++ b/studio/backend/core/inference/diffusion_precision.py@@ -178,13 +178,12 @@ _TE_QUANT_REQUIREMENTS = {def te_quant_unsupported_reason(mode: str) -> str:- """Why ``te_quant_supported`` declined ``mode``, naming what that mode needs."""return f"text-encoder '{mode}' needs {_TE_QUANT_REQUIREMENTS[mode]}, which this host does not provide"@lru_cache(maxsize = 1)def nvfp4_weight_only_importable() -> bool:- """Whether torchao ships a usable ``NVFP4WeightOnlyConfig`` (0.15+; Studio pins 0.14 on torch <= 2.9)."""+ """requires torchao 0.15+; Studio pins 0.14 with torch <= 2.8."""try:from torchao.prototype.mx_formats import NVFP4WeightOnlyConfigfrom .diffusion_transformer_quant import _quiet_config@@ -195,9 +194,7 @@ def nvfp4_weight_only_importable() -> bool:def te_quant_supported(target: Any, mode: str) -> bool:- """Whether ``mode`` is usable for ``target``: a CUDA bf16 device plus what each backend- needs -- fp8 dtype (fp8, nvfp4 block scales), fp8 GEMM sm_89+ (fp8_dynamic), int8 sm_80+- (int8). nvfp4 is weight-only, so it has no FP4 tensor-core requirement."""+ """CUDA bf16: e4m3 for fp8/nvfp4, sm_89+ for dynamic fp8, sm_80+ for int8; no FP4 cores."""if getattr(target, "device", None) != "cuda":return Falseif nvfp4_blocked(mode):diff --git a/studio/backend/tests/test_diffusion_measured_placement.py b/studio/backend/tests/test_diffusion_measured_placement.pyindex bf52c75023a..f8a0271beb5 100644--- a/studio/backend/tests/test_diffusion_measured_placement.py+++ b/studio/backend/tests/test_diffusion_measured_placement.py@@ -759,13 +759,13 @@ def test_torchao_groups_stay_on_device_after_release_and_restore(monkeypatch):assert torch.equal(net(x), ref)restore()for lin in net[1]:- # torchao 0.14 (torch <= 2.9) keeps the v1 layout, nesting its int8 data one subclass deeper+ # torchao 0.14 with torch <= 2.8 uses v1 layout, nesting int8 data one subclass deeperassert set(_inner_devices(lin.weight)) == {"cuda"}assert torch.equal(net(x), ref)def _encode_release_pipe(monkeypatch):- """A real group-offloaded denoiser pinned whole; the encoder records which blocks are on the device."""+ """a whole-pinned group-offloaded denoiser whose encoder records block device placement."""torch, net = _cuda_offload_model()from diffusers.hooks import apply_group_offloadingdiff --git a/studio/backend/tests/test_diffusion_precision.py b/studio/backend/tests/test_diffusion_precision.pyindex 85b46df2026..f7a1bb0fb8f 100644--- a/studio/backend/tests/test_diffusion_precision.py+++ b/studio/backend/tests/test_diffusion_precision.py@@ -127,14 +127,14 @@ def test_nvfp4_supported_without_fp4_cores(monkeypatch, cc):def test_nvfp4_supported_requires_cuda_bf16_and_fp8_dtype(monkeypatch):_stub_torch(monkeypatch, cc = (8, 6))assert te_quant_supported(_target(device = "cpu"), TE_QUANT_NVFP4) is False- # pre-ampere resolves float16, which torchao's nvfp4 quantiser rejects+ # pre-Ampere resolves float16, which torchao's nvfp4 quantizer rejectsassert te_quant_supported(_target(dtype = "float16"), TE_QUANT_NVFP4) is False_stub_torch(monkeypatch, with_fp8 = False, cc = (8, 6))assert te_quant_supported(_target(), TE_QUANT_NVFP4) is Falsedef test_nvfp4_unsupported_when_torchao_lacks_the_weight_only_config(monkeypatch):- # studio pins torchao 0.14 for torch 2.9 and older, which has no NVFP4WeightOnlyConfig+ # Studio pins torchao 0.14 for torch <= 2.8, which lacks NVFP4WeightOnlyConfig_stub_torch(monkeypatch, cc = (8, 6), nvfp4_config = False)assert te_quant_supported(_target(cc = (8, 6)), TE_QUANT_NVFP4) is Falseassert te_quant_supported(_target(cc = (8, 6)), TE_QUANT_INT8) is True@@ -146,7 +146,7 @@ def test_int8_supported_requires_sm80(monkeypatch):assert te_quant_supported(_target(), TE_QUANT_INT8) is True_stub_torch(monkeypatch, cc = (7, 5))assert te_quant_supported(_target(), TE_QUANT_INT8) is False- # Still needs CUDA + bf16 like every mode.+ # all modes also require CUDA and bf16_stub_torch(monkeypatch, cc = (8, 0))assert te_quant_supported(_target(device = "cpu"), TE_QUANT_INT8) is Falsediff --git a/studio/backend/tests/test_torchao_select.py b/studio/backend/tests/test_torchao_select.pyindex 550ab85f152..4b4de2431d2 100644--- a/studio/backend/tests/test_torchao_select.py+++ b/studio/backend/tests/test_torchao_select.py@@ -53,27 +53,29 @@ def _load_module(monkeypatch):("2.10.0.dev20250804+cu130", "torchao==0.17.0"),("2.10.0.dev20250804+cu128", "torchao==0.16.0"),("2.10rc1", "torchao==0.16.0"),- # 2.11 -> 0.17.0, whose cpp is built for it.+ # torchao 0.17.0 cpp is built for torch 2.11.("2.11.0+cu130", "torchao==0.17.0"),("2.11.0", "torchao==0.17.0"),("2.11.1+cu126", "torchao==0.17.0"),- # 2.12+ -> 0.18.0, whose release CI is pinned to 2.13. 0.17.0's upstream table stops- # at 2.11, so leaving this range there ran it outside its declared window.+ # torchao 0.18.0 CI targets torch 2.13; torchao 0.17.0 supports only through torch 2.11.("2.12.0", "torchao==0.18.0"),("2.12.1+cu130", "torchao==0.18.0"),("2.13.0+cu132", "torchao==0.18.0"),("2.14.0+cu130", "torchao==0.18.0"),("2.14.0+xpu", "torchao==0.18.0"),("2.99.0", "torchao==0.18.0"),- # The CUDA-13 branch belongs to 2.10 alone; it must not leak upward.+ # CUDA 13 selection applies only to torch 2.10.("2.12.0+cu126", "torchao==0.18.0"),("2.12.0.dev20260801+cu132", "torchao==0.18.0"),- # torch <=2.9 keeps today's pin (already a correct match for 2.9.0).- ("2.9.0+cu128", "torchao==0.14.0"),- ("2.9.1", "torchao==0.14.0"),+ # torchao 0.15.0 is the floor for diffusers 0.41's unconditional import (#13244).+ ("2.9.0+cu126", "torchao==0.15.0"),+ ("2.9.0+cu128", "torchao==0.15.0"),+ ("2.9.1", "torchao==0.15.0"),+ ("2.9.1+rocm6.4", "torchao==0.15.0"),+ # torch <= 2.8 retains the 0.14.0 pin.("2.8.0", "torchao==0.14.0"),("2.4.0", "torchao==0.14.0"),- # Unparseable / missing / non-2.x major -> conservative default.+ # malformed, missing, and non-2.x versions use the conservative default.(None, "torchao==0.14.0"),("", "torchao==0.14.0"),("garbage", "torchao==0.14.0"),@@ -87,10 +89,10 @@ def test_select_torchao_spec(monkeypatch, torch_version, expected):def test_default_spec_matches_table(monkeypatch):- """The default/floor stays the historical pin so older torch is unchanged."""+ """the historical default keeps older torch versions unchanged."""mod = _load_module(monkeypatch)assert mod._TORCHAO_DEFAULT_SPEC == "torchao==0.14.0"- assert mod._select_torchao_spec("2.9.0") == mod._TORCHAO_DEFAULT_SPEC+ assert mod._select_torchao_spec("2.8.0") == mod._TORCHAO_DEFAULT_SPECdef test_matching_torchao_pin_does_not_need_force_reinstall(monkeypatch):@@ -130,8 +132,7 @@ def test_the_torchao_index_follows_the_resident_torch_build(monkeypatch, torch_vassert got == (f"https://download.pytorch.org/whl/{leaf}" if leaf else None)-# torchao per leaf, from the live listings. Only leaves that do NOT cover every release this-# selector can ask for; everything absent serves its whole range.+# only leaves missing a selected release are listed; omitted leaves cover their whole range._TORCHAO_INDEX_GAPS = {"cu118": ({m: f"0.{m}.0" for m in range(3, 12)}, range(5, 8)),"cu129": (@@ -143,15 +144,7 @@ _TORCHAO_INDEX_GAPS = {def test_the_index_pin_starves_only_where_the_retry_covers_it(monkeypatch):- """A pin that could not be served would fail an install, because this step is fatal.-- Four cells cannot be served, and none of them is predictable from a rule: cu118 stops at- torchao 0.11.0, rocm7.0 carries 0.16.0 alone, and cu129 has 0.14.1 where the 2.9 row asks- for 0.14.0 exactly -- a hole in the MIDDLE of its range, which no floor could describe.- All four resolve from the default index, which is where they came from before this step- pinned anything, so the retry makes them identical to today rather than broken. Recording- them here means a fifth cannot appear unnoticed.- """+ """the default-index retry must cover every leaf missing its selected torchao release."""mod = _load_module(monkeypatch)starved = set()for leaf, (published, torch_minors) in _TORCHAO_INDEX_GAPS.items():@@ -162,17 +155,16 @@ def test_the_index_pin_starves_only_where_the_retry_covers_it(monkeypatch):if wanted not in published.values():starved.add((leaf, minor, wanted))assert starved == {- # cu118 tops out at torchao 0.11.0, so every torch it serves wants more than it has.+ # cu118 lacks every selected torchao release for torch 2.5 through 2.7.("cu118", 5, "0.14.0"),("cu118", 6, "0.14.0"),("cu118", 7, "0.14.0"),- # cu129 publishes 0.14.1, not 0.14.0, and stops at 0.17.0.+ # cu129 lacks torchao 0.14.0 and releases after 0.17.0.("cu129", 8, "0.14.0"),- ("cu129", 9, "0.14.0"),("cu129", 12, "0.18.0"),("cu129", 13, "0.18.0"),- # rocm7.0 publishes 0.16.0 alone, which is what its torch 2.10 row already wants.- ("rocm7.0", 9, "0.14.0"),+ # rocm7.0 provides only torchao 0.16.0.+ ("rocm7.0", 9, "0.15.0"),}, sorted(starved)@@ -183,9 +175,7 @@ def _torchao_installer_source():def test_the_torchao_step_pins_the_index_and_retries_without_it():- """cu129 serves torch to 2.13 but stops at torchao 0.17.0, and a leaf added upstream- after this ships can lag a release, so the pin must not be able to fail an install.- Unlike torchcodec the retry stays FATAL if it also fails: torchao is not optional."""+ """a lagging accelerator leaf retries the default index, but failure there remains fatal."""body = _torchao_installer_source()assert "index = None if default_index else _torch_accelerator_index_url(torch_version)" in bodyassert '"--index-url", index, spec' in body@@ -688,7 +678,7 @@ def test_real_or_stub_replaces_a_stub_inherited_from_run_py(monkeypatch, consumedef test_real_or_stub_keeps_the_stub_when_torchao_is_not_loadable(monkeypatch):- """torch <= 2.9 pairs with torchao 0.14, which transformers 5 rejects: never load it."""+ """torch <= 2.8 pairs with torchao 0.14, which transformers 5 rejects; never load it."""monkeypatch.setattr(_stub, "_is_windows_rocm", lambda: True)monkeypatch.setattr(_stub, "torchao_export_loadable", lambda: False)monkeypatch.delitem(sys.modules, "torchao", raising = False)diff --git a/studio/install_python_stack.py b/studio/install_python_stack.pyindex d92185f1d4e..92eed171c02 100644--- a/studio/install_python_stack.py+++ b/studio/install_python_stack.py@@ -690,52 +690,38 @@ class _FreezeNewTorchForCoreUpdate:return False-# torchao's cpp is built for ONE torch release AND CUDA major. Either mismatch costs the-# kernels, never the import: torchao/__init__.py has caught the dlopen failure since 0.12 and-# import_fixes.py filters that warning. Match torchao to the installed torch (pytorch/ao#2919):-# 2.9.x -> 0.14.0-# 2.10.x, CUDA<=12 -> 0.16.0 (cpp built for 2.10, loads via the CUDA-12 wheel)-# 2.10.x, CUDA>=13 -> 0.17.0 (cu130: 0.16.0's CUDA-12 cpp crashes on load; 0.17.0-# targets torch 2.11 so its cpp is cleanly skipped, not crashed)-# 2.11.x -> 0.17.0 (cpp built for 2.11)-# 2.12.x and up -> 0.18.0 (dropped torch <2.11; release CI pinned to 2.13)-# Unknown/older torch keeps the conservative default.-#-# The version alone is not enough: torchao ships per accelerator under /whl/<tag>, and PyPI's-# single default tracks whatever major PyTorch currently ships (13 as of 0.18.0), so it cannot-# be treated as a fixed fallback major. The caller pins the index to the resident torch.+# torchao cpp extensions match one torch and CUDA release; mismatches disable kernels or crash.+# torch 2.9 needs 0.15 because 0.14 breaks supported Diffusers and Transformers (#13244).+# use the resident accelerator index because PyPI follows the latest PyTorch CUDA major._TORCHAO_DEFAULT_SPEC = "torchao==0.14.0"+_TORCHAO_TORCH_29_SPEC = "torchao==0.15.0"_TORCHAO_TORCH_210_SPEC = "torchao==0.16.0"_TORCHAO_TORCH_210_CUDA13_SPEC = "torchao==0.17.0"_TORCHAO_TORCH_211_SPEC = "torchao==0.17.0"_TORCHAO_TORCH_212_PLUS_SPEC = "torchao==0.18.0"-# torch 2.10 built against CUDA >= this major can't load 0.16.0's CUDA-12 cpp.+# torch 2.10 cannot load 0.16's CUDA 12 cpp on this major or newer._TORCHAO_CUDA13_MIN_MAJOR = 13def _cuda_major_from_torch_version(torch_version: str) -> int | None:- """Extract the CUDA major from a torch local version tag, e.g. '2.10.0+cu130'- -> 13, '2.10.0+cu128' -> 12. Returns None for rocm/cpu/tagless builds."""+ """return the CUDA major from a torch local tag, or None for rocm, cpu, and tagless builds."""local = str(torch_version).split("+", 1)if len(local) < 2 or not local[1].startswith("cu"):return None- digits = re.sub(r"[^0-9].*", "", local[1][2:]) # 'cu130' -> '130'+ digits = re.sub(r"[^0-9].*", "", local[1][2:])if not digits:return None- return int(digits) // 10 # '130' -> 13, '128' -> 12, '118' -> 11+ return int(digits) // 10def _select_torchao_spec(torch_version: str | None) -> str:- """Map an installed torch version string (e.g. '2.10.0+cu130') to the torchao- pip spec whose cpp extensions match it. Falls back to _TORCHAO_DEFAULT_SPEC for- torch <=2.9, a non-2.x major, or an unparseable/missing version. Pure function.- """+ """select the torchao spec whose cpp extension matches the installed torch version."""if not torch_version:return _TORCHAO_DEFAULT_SPEC- release = str(torch_version).split("+", 1)[0] # drop +cu130/+rocm6.4/+cpu+ release = str(torch_version).split("+", 1)[0]parts = release.split(".")try:- # Strip a pre-release suffix from the minor ('10rc1' -> '10').+ # ignore the minor's prerelease suffix.minor_str = re.sub(r"[^0-9].*", "", parts[1]) if len(parts) > 1 else ""major, minor = int(parts[0]), int(minor_str)except (IndexError, ValueError):@@ -743,21 +729,21 @@ def _select_torchao_spec(torch_version: str | None) -> str:if major != 2:return _TORCHAO_DEFAULT_SPECif minor >= 12:- return _TORCHAO_TORCH_212_PLUS_SPEC # newest known build; covers 2.12++ return _TORCHAO_TORCH_212_PLUS_SPECif minor == 11:- return _TORCHAO_TORCH_211_SPEC # 0.17.0's cpp is built for exactly this minor+ return _TORCHAO_TORCH_211_SPECif minor == 10:- # cu130+ can't load 0.16.0's CUDA-12 cpp; use 0.17.0 (cpp skipped, not crashed).+ # torchao 0.16's CUDA 12 cpp crashes on CUDA 13; 0.17 skips its mismatched cpp.cuda_major = _cuda_major_from_torch_version(str(torch_version))if cuda_major is not None and cuda_major >= _TORCHAO_CUDA13_MIN_MAJOR:return _TORCHAO_TORCH_210_CUDA13_SPECreturn _TORCHAO_TORCH_210_SPEC+ if minor == 9:+ return _TORCHAO_TORCH_29_SPECreturn _TORCHAO_DEFAULT_SPEC-# torchcodec up to 0.11 is built against one torch minor and declares no-# `Requires-Dist: torch`, so pip cannot catch a mismatch. 0.12+ is ABI-stable against torch-# >=2.11, hence the open floor. Mirrors pyproject's audio-torch2xx and import_fixes.+# torchcodec 0.11 and older target one torch minor; 0.12 is ABI-stable with torch 2.11+._TORCHCODEC_DEFAULT_SPEC = "torchcodec>=0.10.0,<0.11.0"_TORCHCODEC_ABI_STABLE_SPEC = "torchcodec>=0.12.0"_TORCHCODEC_TORCH_SPECS: dict[int, str] = {@@ -8374,14 +8360,27 @@ def _flash_attn_importable() -> bool:def _remove_rejected_flash_attn() -> bool:- """Uninstall a flash-attn that installed but will not import. True iff it is gone.-- uv gets --python as well as --system: --system ALONE would remove from the system- Python, leaving the rejected wheel in the venv while setup reported it gone.- """+ """remove rejected flash-attn and return whether it is gone; uv pairs --system with --python."""return _uninstall_distribution("flash-attn")+def _remove_stale_flash_attn() -> None:+ """remove stale flash-attn before xformers imports it and breaks every Diffusers pipeline."""+ if _remove_rejected_flash_attn():+ _step(+ "warning",+ "flash-attn was built for another torch or CUDA and does not import; removed it",+ _cyan,+ )+ else:+ _step(+ "warning",+ "flash-attn was built for another torch or CUDA and could not be removed; "+ "uninstall flash-attn manually",+ _cyan,+ )++def _ensure_flash_attn() -> None:if _flash_attn_install_disabled():return@@ -8393,10 +8392,12 @@ def _ensure_flash_attn() -> None:returnenv = probe_torch_wheel_env()+ # a failed flash-attn probe proves staleness only when torch still imports.+ stale = env is not None and _installed_distribution_version("flash-attn") is not Nonewheel_url = _build_flash_attn_wheel_url(env) if env else Nonewheel_available = url_exists(wheel_url) if wheel_url else Falseif wheel_available:- # Counted: it lands a distribution, so the caches keyed on the counter must be rebuilt.+ # installing a distribution invalidates caches keyed on the action counter._count_install_action()outcome = install_prebuilt(wheel_url,@@ -8408,13 +8409,12 @@ def _ensure_flash_attn() -> None:),use_uv = USE_UV,uv_needs_system = UV_NEEDS_SYSTEM,+ reinstall = stale,)if outcome == "installed":returnif outcome == "rejected":- # Remove it before giving up. Left installed, unsloth/models/_utils.py finds- # it by metadata (_package_available) and then imports the native module- # in process, so a wheel that killed the probe would kill training too.+ # metadata detection imports rejected wheels in the training process.if _remove_rejected_flash_attn():_step("warning",@@ -8422,13 +8422,15 @@ def _ensure_flash_attn() -> None:_cyan,)else:- # Still importable in process, unlike never having installed it.+ # the rejected native module remains discoverable and may terminate training._step("warning","flash-attn wheel is not importable on this GPU and could not be ""removed; uninstall flash-attn manually before training",_cyan,)+ elif stale:+ _remove_stale_flash_attn()_step("warning", "Continuing without flash-attn", _cyan)return@@ -8442,6 +8444,8 @@ def _ensure_flash_attn() -> None:)else:_step("warning", "No published flash-attn prebuilt wheel found", _cyan)+ if stale:+ _remove_stale_flash_attn()# -- uv bootstrap ------------------------------------------------------@@ -12723,9 +12727,12 @@ def install_python_stack() -> int:if _torch_after_repair and _torch_after_repair != _torch_before_repair:_note(f"torch moved from {_torch_before_repair or 'unknown'} to "- f"{_torch_after_repair} during the repair -- re-selecting torchao"+ f"{_torch_after_repair} during the repair -- re-selecting torchao and "+ "flash-attn")_install_torchao_for_torch(_torch_after_repair)+ # resync flash-attn because the repair can invalidate the wheel selected earlier.+ _ensure_flash_attn()# Unguarded: torch==2.10.0 accepts 2.10.0+rocm7.1, and an earlier run may have moved it._evict_xformers_built_for_another_torch(scope = "linux torch repair", family_only = True)_evict_xformers_requiring_another_torch()diff --git a/tests/python/test_flash_attn_install_python_stack.py b/tests/python/test_flash_attn_install_python_stack.pyindex bb0d81a2ba5..386cad40479 100644--- a/tests/python/test_flash_attn_install_python_stack.py+++ b/tests/python/test_flash_attn_install_python_stack.py@@ -556,6 +556,134 @@ class TestEnsureFlashAttn:assert ("warning", "No published flash-attn prebuilt wheel found") not in step_messagesassert any("could not" in message.lower() for _kind, message in step_messages)+ def _run_with_resident_copy(+ self,+ *,+ resident: str | None = "2.8.1",+ env: dict[str, str] | None = None,+ torch_imports: bool = True,+ url_available: bool | None = False,+ install_returncode: int = 0,+ fake_run = None,+ ) -> tuple[list[tuple[str, str]], list[list[str]], mock.Mock]:+ """#13244 leaves cu13torch2.10 under torch 2.9+cu126 on cp313, unsupported by v2.8.3."""+ step_messages: list[tuple[str, str]] = []+ removals: list[list[str]] = []++ def default_run(cmd, **kwargs):+ if "uninstall" in cmd:+ removals.append(list(cmd))+ return subprocess.CompletedProcess(cmd, 0)+ return self._import_check()++ if env is None:+ env = {+ "python_tag": "cp313",+ "torch_mm": "2.9",+ "cuda_major": "12",+ "cxx11abi": "TRUE",+ "platform_tag": "linux_x86_64",+ }+ with (+ mock.patch.object(ips, "NO_TORCH", False),+ mock.patch.object(ips, "IS_WINDOWS", False),+ mock.patch.object(ips, "IS_MACOS", False),+ mock.patch.object(+ ips, "probe_torch_wheel_env", return_value = env if torch_imports else None+ ),+ mock.patch.object(ips, "_installed_distribution_version", return_value = resident),+ mock.patch.object(ips, "url_exists", return_value = url_available),+ mock.patch.object(+ ips,+ "install_wheel",+ return_value = [("uv", subprocess.CompletedProcess(["uv"], install_returncode, ""))],+ ) as mock_install_wheel,+ mock.patch.object(+ ips,+ "_step",+ side_effect = lambda label, value, color_fn = None: step_messages.append(+ (label, value)+ ),+ ),+ mock.patch("subprocess.run", side_effect = fake_run or default_run),+ ):+ ips._ensure_flash_attn()+ return step_messages, removals, mock_install_wheel++ def test_stale_copy_is_removed_when_no_wheel_is_published(self):+ """if kept, xformers imports it and every diffusers pipeline fails (#13244)."""+ step_messages, removals, mock_install_wheel = self._run_with_resident_copy()++ mock_install_wheel.assert_not_called()+ assert any("flash-attn" in cmd for cmd in removals), removals+ assert ("warning", "No published flash-attn prebuilt wheel found") in step_messages+ assert (+ "warning",+ "flash-attn was built for another torch or CUDA and does not import; removed it",+ ) in step_messages++ def test_stale_copy_is_removed_when_no_wheel_matches(self):+ step_messages, removals, _ = self._run_with_resident_copy(+ env = {+ "python_tag": "cp313",+ "torch_mm": "2.3",+ "cuda_major": "12",+ "cxx11abi": "TRUE",+ "platform_tag": "linux_x86_64",+ },+ )++ assert any("flash-attn" in cmd for cmd in removals), removals+ assert ("warning", "No compatible flash-attn prebuilt wheel found") in step_messages++ def test_stale_copy_is_removed_when_the_replacement_fails_to_install(self):+ step_messages, removals, _ = self._run_with_resident_copy(+ url_available = True, install_returncode = 1+ )++ assert any("flash-attn" in cmd for cmd in removals), removals+ assert ("warning", "Continuing without flash-attn") in step_messages++ def test_stale_copy_is_force_replaced(self):+ """a same-version build for another CUDA counts as installed unless forced."""+ imports: list[int] = []++ def fake_run(cmd, **kwargs):+ imports.append(1)+ return self._import_check(1 if len(imports) == 1 else 0)++ step_messages, _, mock_install_wheel = self._run_with_resident_copy(+ url_available = True, fake_run = fake_run+ )++ assert mock_install_wheel.call_args.kwargs["reinstall"] is True+ assert step_messages == []++ def test_a_failed_stale_removal_is_reported(self):+ def fake_run(cmd, **kwargs):+ if "uninstall" in cmd:+ return subprocess.CompletedProcess(cmd, 1)+ return self._import_check()++ step_messages, _, _ = self._run_with_resident_copy(fake_run = fake_run)++ warnings = [value for _, value in step_messages]+ assert any("could not be removed" in value for value in warnings), warnings+ assert not any("removed it" in value for value in warnings), warnings++ def test_resident_copy_is_kept_when_torch_does_not_import(self):+ """the import probe loads torch first, so a broken torch says nothing about flash-attn."""+ _, removals, mock_install_wheel = self._run_with_resident_copy(torch_imports = False)++ assert removals == []+ mock_install_wheel.assert_not_called()++ def test_nothing_is_uninstalled_when_flash_attn_is_absent(self):+ step_messages, removals, _ = self._run_with_resident_copy(resident = None)++ assert removals == []+ assert ("warning", "No published flash-attn prebuilt wheel found") in step_messages+def test_skip_env_disables_setup_install(self):with (mock.patch.object(ips, "NO_TORCH", False),@@ -631,3 +759,14 @@ class TestInstallPythonStackFlashAttnIntegration:def test_windows_install_skips_flash_attn_step(self):assert self._run_install(no_torch = False, is_macos = False, is_windows = True) == 0++ def test_flash_attn_is_rechecked_after_the_linux_torch_repair(self):+ """step 13 can move torch from 2.12+cu130 to 2.9+cu126 under cu13torch2.10 (#13244)."""+ source = (STUDIO_DIR / "install_python_stack.py").read_text(encoding = "utf-8")+ step = source.split('_progress(_torch_step_label("final"))', 1)[1]+ step = step.split("# 13w.", 1)[0]+ moved = step.split(+ "if _torch_after_repair and _torch_after_repair != _torch_before_repair:", 1+ )[1]+ moved = moved.split("_evict_xformers_built_for_another_torch(", 1)[0]+ assert "_ensure_flash_attn()" in moveddiff --git a/tests/studio/install/test_windows_torch_flavor_invariant.py b/tests/studio/install/test_windows_torch_flavor_invariant.pyindex 39320627061..2a94bcfac14 100644--- a/tests/studio/install/test_windows_torch_flavor_invariant.py+++ b/tests/studio/install/test_windows_torch_flavor_invariant.py@@ -288,18 +288,18 @@ class TestStepThirteenWiring:calls = _calls_in(guard)assert [c for c in calls if c in repairs] == repairsassert calls[:2] == ["_progress", "_torch_step_label"]- # str() is the label coercion around the probe, not a step.+ # str() coerces the probe label and does not represent a step.step13 = [c for c in _calls_in(guards[1]) if c != "str"]- # Step 13 also re-selects torchao when a repair moved the torch label, which both the- # spec and the leaf are read from, then removes an xFormers the final torch cannot- # import (#11545). Nothing else may join the set.+ # repairs refresh torchao and flash-attn for final torch (#13244), then evict incompatible xFormers (#11545).assert step13 == (["_progress", "_torch_step_label", "_probe_installed_torch_version"]+ repairs+ ["_probe_installed_torch_version", "_note", "_install_torchao_for_torch"]+ + ["_ensure_flash_attn"]+ ["_evict_xformers_built_for_another_torch", "_evict_xformers_requiring_another_torch"]), step13assert "_install_torchao_for_torch" not in _calls_in(guards[0])+ assert "_ensure_flash_attn" not in _calls_in(guards[0])def test_the_invariant_is_wired_in_exactly_once(self):body = ast.unparse(_install_stack_ast())@@ -307,11 +307,7 @@ class TestStepThirteenWiring:def _base_total(**flags) -> int:- """Re-execute install_python_stack()'s step-total arithmetic under given flags.-- Read out of the function rather than duplicated, so a step added without a matching- total fails here instead of drawing a progress bar past 100%.- """+ """re-execute the source step-total arithmetic so new steps cannot silently push progress past 100%."""lines = _STACK_SRC.splitlines()start = next(i for i, line in enumerate(lines) if line.strip().startswith("base_total = "))end = next(i for i, line in enumerate(lines) if line.strip().startswith("base_requirements ="))