Skip to content

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.

Install a CUDA-matched xFormers on Windows instead of whatever PyPI serves (#8156)

Daniel Hane219b469a25d
diff --git a/install.ps1 b/install.ps1
index b71214bbed9..e77017c72ed 100644
--- a/install.ps1
+++ b/install.ps1
@@ -3597,6 +3597,20 @@ exit 0
return "${scheme}://${host_}"
}
+ # Append a path to a URL that may carry ?query / #fragment auth. A private mirror is
+ # allowed to be "https://mirror/whl?token=abc", and a naive "$base/$leaf" put the leaf
+ # INSIDE the token value, leaving the path still /whl -- so the tokenized mirror this
+ # exists to honour was the one case that could not resolve a wheel.
+ function Join-UrlPath {
+ param([string]$Base, [string]$Path)
+ if ([string]::IsNullOrWhiteSpace($Base)) { return $Path }
+ $cut = $Base.IndexOfAny([char[]]('?', '#'))
+ if ($cut -lt 0) { return "$($Base.TrimEnd('/'))/$Path" }
+ $head = $Base.Substring(0, $cut).TrimEnd('/')
+ $tail = $Base.Substring($cut)
+ return "$head/$Path$tail"
+ }
+
# ── Torch flavor helpers (to repair a stale CPU / wrong-CUDA wheel) ──
# torch.__version__ -> flavor tag (cuXXX / rocm / cpu); untagged wheel = cpu,
# matching setup.ps1's stale-venv parse.
@@ -3658,6 +3672,138 @@ exit 0
return ConvertTo-TorchFlavorTag $torchVer
}
+ # Full installed torch version in $PythonExe's venv ("2.10.0+cu130"), or $null. Separate
+ # from Get-InstalledTorchTag because the xFormers pin below needs the RELEASE as well as
+ # the flavor: xFormers publishes one wheel per exact torch patch (2.9.0 -> 0.0.33.post1,
+ # 2.9.1 -> 0.0.33.post2, 2.10.0 -> 0.0.34), not per minor.
+ function Get-InstalledTorchVersion {
+ param([string]$PythonExe)
+ if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code 'import torch; print(torch.__version__)'
+ if (-not $probe.Ok) { return $null }
+ $torchVer = $probe.Output.Trim()
+ if (-not $torchVer) { return $null }
+ return $torchVer
+ }
+
+ # ── xFormers must match the torch BUILD, not just the torch version ──
+ # xformers/_C.pyd is linked against one exact (torch, CUDA) pair. Loaded beside any
+ # other pair torch.ops.load_library raises, and xformers/_cpp_lib.py turns that into a
+ # log warning rather than an error -- so the import "succeeds" and memory-efficient
+ # attention, SwiGLU and the sparse ops are all silently gone. PyPI publishes only the
+ # CUDA-12.8 flavour, which is why a cu130 install that lets pip resolve xformers ends up
+ # reporting "xFormers was built for PyTorch 2.10.0+cu128 (you have 2.10.0+cu130)".
+ #
+ # Resolve from the same index the torch install used, so UNSLOTH_TORCH_INDEX_URL /
+ # UNSLOTH_TORCH_INDEX_FAMILY / UNSLOTH_PYTORCH_MIRROR keep working unchanged. Every row
+ # below was HEAD-verified live on download.pytorch.org and its xformers/cpp_lib.json read
+ # back, e.g. cu130/xformers-0.0.34 reports {"torch": "2.10.0+cu130"}. Keep in step with
+ # _XFORMERS_WHEEL_VERSIONS in studio/backend/utils/wheel_utils.py and the matrix in
+ # tests/python/test_windows_xformers_wheel_match.py.
+ #
+ # Deliberately NOT a floor-and-let-pip-pick: the cu130 index also serves
+ # xformers-0.0.35, whose extension is built for torch 2.10.0 while its metadata only
+ # asks for torch>=2.10, so a resolver is free to pair it with a torch it cannot load.
+ #
+ # torch 2.7.0 (xFormers 0.0.30) is deliberately absent: it predates the stable-ABI
+ # switch, publishes one wheel per interpreter and stops at cp312, and this installer
+ # defaults to Python 3.13 -- so the row would resolve to a wheel that does not exist.
+ $script:XformersWheelVersions = @{
+ "2.7.1" = @{ "cu126" = "0.0.31.post1"; "cu128" = "0.0.31.post1" }
+ "2.8.0" = @{ "cu126" = "0.0.32.post2"; "cu128" = "0.0.32.post2"; "cu129" = "0.0.32.post2" }
+ "2.9.0" = @{ "cu126" = "0.0.33.post1"; "cu128" = "0.0.33.post1"; "cu130" = "0.0.33.post1" }
+ "2.9.1" = @{ "cu126" = "0.0.33.post2"; "cu128" = "0.0.33.post2"; "cu130" = "0.0.33.post2" }
+ "2.10.0" = @{ "cu126" = "0.0.34"; "cu128" = "0.0.34"; "cu130" = "0.0.34" }
+ # Stable-ABI era: 0.0.35 targets torch 2.10+ and upstream guarantees it works on
+ # any later release, so one row per torch covers 2.11 onward with the same wheel.
+ "2.11.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
+ "2.12.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
+ "2.13.0" = @{ "cu126" = "0.0.35"; "cu128" = "0.0.35"; "cu130" = "0.0.35" }
+ }
+
+ # The stable-ABI era in one place: every torch STRICTLY ABOVE the floor resolves to this
+ # wheel, which is compiled against the floor release and works on any later one by
+ # upstream's own guarantee. The exact rows above still win.
+ #
+ # An exact-key table alone refuses the PATCH releases -- 2.10.1, 2.11.1, 2.12.1 are all
+ # supported builds, and none of them can be listed here, because they are published
+ # after this script ships. Each one silently left the machine with no xFormers.
+ $script:XformersStableAbiFloor = "2.10.0"
+ $script:XformersStableAbiVersion = "0.0.35"
+ $script:XformersStableAbiFamilies = @("cu126", "cu128", "cu130")
+
+ # "2.12.1" -> [version]2.12.1, or $null for a dev/rc/nightly string, which names no
+ # released torch and must not be swept into the era comparison.
+ function ConvertTo-TorchReleaseVersion {
+ param([string]$Release)
+ if (-not $Release -or -not [regex]::IsMatch($Release, '^\d+(\.\d+)*$')) { return $null }
+ try { return [version]$Release } catch { return $null }
+ }
+
+ # xFormers version built for exactly ($TorchVersion, $CudaTag), or $null when that pair
+ # has no published wheel -- in which case we install nothing rather than a mismatch.
+ function Get-XformersWheelVersion {
+ param([string]$TorchVersion, [string]$CudaTag)
+ if (-not $TorchVersion -or -not $CudaTag) { return $null }
+ # "2.10.0+cu130" -> "2.10.0"; a dev/rc suffix has no wheel and must miss the table.
+ $release = ($TorchVersion -split '\+', 2)[0].Trim()
+ if ($script:XformersWheelVersions.ContainsKey($release)) {
+ $byFamily = $script:XformersWheelVersions[$release]
+ if ($byFamily.ContainsKey($CudaTag)) { return $byFamily[$CudaTag] }
+ return $null
+ }
+ # Not listed: above the stable-ABI floor the answer is known without a row.
+ $parsed = ConvertTo-TorchReleaseVersion $release
+ if ($null -eq $parsed) { return $null }
+ if ($parsed -gt [version]$script:XformersStableAbiFloor -and $script:XformersStableAbiFamilies -contains $CudaTag) {
+ return $script:XformersStableAbiVersion
+ }
+ return $null
+ }
+
+ # The torch build the SELECTED wheel records in its cpp_lib.json, which is what
+ # Get-InstalledXformersBuild reads back. For an exact-era wheel that is the resident
+ # torch; for the stable-ABI wheel it is the floor release it was compiled against, so
+ # comparing against the resident torch marked a perfectly good 0.0.35 as mismatched and
+ # force-reinstalled it on every run.
+ function Get-XformersExpectedTorchBuild {
+ param([string]$Version, [string]$TorchVersion, [string]$CudaTag)
+ if ($Version -eq $script:XformersStableAbiVersion) {
+ return "$($script:XformersStableAbiFloor)+$CudaTag"
+ }
+ return $TorchVersion
+ }
+
+ # The interpreter tag in the wheel FILENAME: 0.0.31..0.0.34 ship one cp39-abi3 wheel,
+ # 0.0.35 switched to py39-none (a packaging change -- the extension never bound the
+ # CPython ABI). Unknown releases return $null so a direct URL is never guessed.
+ # Mirrors _XFORMERS_FILENAME_PYTHON_TAGS in studio/backend/utils/wheel_utils.py.
+ function Get-XformersFilenamePythonTag {
+ param([string]$Version)
+ $parsed = ConvertTo-TorchReleaseVersion (($Version -split '[^0-9.]', 2)[0].TrimEnd('.'))
+ if ($null -eq $parsed) { return $null }
+ if ($parsed -ge [version]"0.0.31" -and $parsed -le [version]"0.0.34") { return "cp39-abi3" }
+ if ($parsed -eq [version]"0.0.35") { return "py39-none" }
+ return $null
+ }
+
+ # What the RESIDENT xformers actually is: "<version> <torch-it-was-built-for>", e.g.
+ # "0.0.34 2.10.0+cu128", or $null when xformers is absent or carries no build metadata.
+ # BOTH halves are needed. The version alone cannot tell cu126 from cu128 from cu130 --
+ # all three publish the same version string -- and the build tag alone cannot tell
+ # 0.0.34 from 0.0.35, which report the same torch. Read from disk rather than
+ # "import xformers" so a mismatched .pyd cannot log its own warning into the probe.
+ function Get-InstalledXformersBuild {
+ param([string]$PythonExe)
+ if (-not $PythonExe -or -not (Test-Path -LiteralPath $PythonExe)) { return $null }
+ $code = 'import importlib.metadata as m,importlib.util,json,os;s=importlib.util.find_spec(''xformers'');l=(list(s.submodule_search_locations) if s and s.submodule_search_locations else []);p=(os.path.join(l[0],''cpp_lib.json'') if l else '''');t=(json.load(open(p))[''version''][''torch''] if p and os.path.isfile(p) else '''');v=m.version(''xformers'') if l else '''';print((v + '' '' + t) if (v and t) else '''')'
+ $probe = Invoke-BoundedPythonProbe -PythonExe $PythonExe -Code $code
+ if (-not $probe.Ok) { return $null }
+ $build = $probe.Output.Trim()
+ if (-not $build) { return $null }
+ return $build
+ }
+
# Post-install XPU runtime check. A +xpu wheel installing is not proof the GPU is usable: on
# an old Intel compute driver torch.xpu.is_available() is False and Unsloth then dies at
# import. Warn, never fall back -- a driver update fixes it.
@@ -4135,6 +4281,114 @@ exit 0
}
}
+ # ── Pin xFormers to the wheel built for the torch that is actually installed ──
+ # See $script:XformersWheelVersions above for why a version floor is not enough.
+ # Runs AFTER the flavor repair so it reads the final torch, and keys off THAT torch
+ # rather than off $TorchIndexUrl, which the repair does not always reconcile (it is
+ # skipped when the expected tag is 'cpu' or unrecognised, so a migrated venv can hold
+ # a +cu128 torch while the index leaf says /cpu, and /cpu serves no usable xFormers).
+ # xFormers is an optional accelerator, so every failure here warns and the install
+ # continues on torch SDPA; and when no wheel matches we install NOTHING, because
+ # installing a mismatched one is the bug being fixed. UNSLOTH_SKIP_XFORMERS=1 opts out.
+ if (-not $SkipTorch -and $env:UNSLOTH_SKIP_XFORMERS -ne "1") {
+ $_xfTorchVersion = Get-InstalledTorchVersion -PythonExe $VenvPython
+ $_xfCudaTag = ConvertTo-TorchFlavorTag $_xfTorchVersion
+ # cu<digits> only: cpu / rocm / xpu torch has no xFormers wheel on any index.
+ # IsMatch, not -match, so this does not clobber $Matches for the enclosing scope.
+ if ($_xfTorchVersion -and [regex]::IsMatch([string]$_xfCudaTag, '^cu\d+$')) {
+ $_xfVersion = Get-XformersWheelVersion -TorchVersion $_xfTorchVersion -CudaTag $_xfCudaTag
+ if (-not $_xfVersion) {
+ # "not in the table", which also covers families we have no row for (cu118,
+ # cu124) as well as torch releases upstream never built against.
+ substep "no matching xFormers wheel for torch $_xfTorchVersion -- skipping it (attention falls back to torch SDPA)."
+ } elseif ((Get-InstalledXformersBuild -PythonExe $VenvPython) -eq "$_xfVersion $(Get-XformersExpectedTorchBuild -Version $_xfVersion -TorchVersion $_xfTorchVersion -CudaTag $_xfCudaTag)") {
+ substep "xFormers $_xfVersion already matches torch $_xfTorchVersion."
+ } else {
+ # How to fetch it, in two cases.
+ #
+ # An EXPLICIT index pin is authoritative and stays whole. Its final component
+ # is not required to be the CUDA family: a documented full-URL override can be
+ # an authenticated PEP 503 mirror, and comparing its leaf threw exactly that
+ # index away -- the one that had just supplied the resident CUDA torch --
+ # leaving an air-gapped host unable to reach any wheel at all.
+ #
+ # Otherwise install the DIRECT wheel URL rather than resolving a version off
+ # an index. --default-index does not make an index exclusive (uv's --index /
+ # UV_INDEX are used "in addition to" it), and cu126 / cu128 / cu130 publish
+ # the SAME version string, so a machine with UV_INDEX set -- PyPI's CUDA-12.8
+ # build, say -- could satisfy a pinned 0.0.35 from the wrong family and
+ # recreate the silent extension failure this whole step exists to prevent.
+ # A URL cannot be resolved anywhere else. UNSLOTH_PYTORCH_MIRROR is still
+ # honoured, as it is everywhere else in this script.
+ $_xfIndexUrl = $null
+ $_xfWheelUrl = $null
+ $_xfPyTag = Get-XformersFilenamePythonTag $_xfVersion
+ $_xfWheelName = if ($_xfPyTag) { "xformers-$_xfVersion-$_xfPyTag-win_amd64.whl" } else { $null }
+ # A FULL-URL override only. UNSLOTH_TORCH_INDEX_FAMILY also sets
+ # $TorchIndexPinned, and routing that through the index reintroduced the very
+ # hole above: cu126 / cu128 / cu130 share a version string, so a machine-level
+ # UV_INDEX could satisfy the pin with the wrong family. A family pin names a
+ # leaf we can build a direct URL from, so it takes the URL path.
+ if ($TorchIndexUrl -and -not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL)) {
+ # Even here, prefer a URL. When the override already names a CUDA leaf
+ # (.../cu130, the documented shape) the wheel can be addressed under it
+ # directly, which no UV_INDEX can substitute for. Only an override whose
+ # leaf is not a family -- a bare PEP 503 mirror root -- has to be resolved,
+ # and that one gets the machine-level indexes cleared below.
+ $_xfOverrideLeaf = Get-TorchIndexLeafName $TorchIndexUrl
+ if ($_xfWheelName -and [regex]::IsMatch($_xfOverrideLeaf, '^cu\d+$')) {
+ $_xfWheelUrl = Join-UrlPath $TorchIndexUrl $_xfWheelName
+ } else {
+ $_xfIndexUrl = $TorchIndexUrl
+ }
+ } else {
+ $_xfBase = if ($env:UNSLOTH_PYTORCH_MIRROR) { $env:UNSLOTH_PYTORCH_MIRROR } else { "https://download.pytorch.org/whl" }
+ if ($_xfWheelName) {
+ $_xfWheelUrl = Join-UrlPath $_xfBase "$_xfCudaTag/$_xfWheelName"
+ } else {
+ # Unknown filename shape: fall back to the index rather than guessing
+ # a URL that 404s.
+ $_xfIndexUrl = Join-UrlPath $_xfBase $_xfCudaTag
+ }
+ }
+ $_xfSource = if ($_xfWheelUrl) { $_xfWheelUrl } else { $_xfIndexUrl }
+ substep "installing xFormers $_xfVersion for torch $_xfTorchVersion ($(Remove-IndexUrlCredentials $_xfSource))..."
+ # --no-deps: the wheel declares torch==<exact release>, and acting on that can
+ # pull a PyPI (CUDA 12.8) torch over the CUDA build just installed.
+ # --reinstall-package: cu126 / cu128 / cu130 all publish the SAME xformers
+ # version string, so a wrong-CUDA wheel is invisible to a version check and
+ # would otherwise be left in place on an upgrade of a broken install.
+ # Go through $script:UvExe when something has resolved one, so this call
+ # cannot be captured by a profile alias named uv. That variable is not set
+ # on this branch; Get-Variable rather than a bare read so the lookup is
+ # also safe under a profile's Set-StrictMode.
+ $_xfUv = Get-Variable -Name 'UvExe' -Scope Script -ValueOnly -ErrorAction SilentlyContinue
+ if (-not $_xfUv) { $_xfUv = 'uv' }
+ $_xfExit = if ($_xfWheelUrl) {
+ Invoke-InstallCommandRetry -Label "install xFormers" { & $_xfUv pip install --python $VenvPython --no-deps --reinstall-package xformers $_xfWheelUrl }
+ } else {
+ # --default-index does not make an index exclusive: uv reads UV_INDEX and
+ # UV_EXTRA_INDEX_URL "in addition to" it, and every CUDA family publishes the
+ # SAME xformers version, so a machine-level index could satisfy the pin from
+ # the wrong one. Cleared for this call only, and restored after.
+ $_xfSavedIndex = $env:UV_INDEX
+ $_xfSavedExtra = $env:UV_EXTRA_INDEX_URL
+ try {
+ $env:UV_INDEX = $null
+ $env:UV_EXTRA_INDEX_URL = $null
+ Invoke-InstallCommandRetry -Label "install xFormers" { & $_xfUv pip install --python $VenvPython --no-deps --reinstall-package xformers "xformers==$_xfVersion" --default-index $_xfIndexUrl }
+ } finally {
+ $env:UV_INDEX = $_xfSavedIndex
+ $env:UV_EXTRA_INDEX_URL = $_xfSavedExtra
+ }
+ }
+ if ($_xfExit -ne 0) {
+ substep "[WARN] could not install xFormers $_xfVersion (exit $_xfExit); attention falls back to torch SDPA." "Yellow"
+ }
+ }
+ }
+ }
+
# ── CI only: overlay a source checkout over the package just installed ──
# Mirrors install.sh. Not a consumer knob: no switch, absent from the usage text,
# ignored unless UNSLOTH_CI_SOURCE_OVERLAY names a directory with a pyproject.toml.
diff --git a/pyproject.toml b/pyproject.toml
index 9b705ad5756..e5f58c5a59f 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -165,6 +165,42 @@ huggingface = [
"torchvision",
"unsloth[triton]",
]
+# xFormers' win_amd64 wheels are per-CUDA-family, not just per-torch: the
+# xformers/_C.pyd is linked against ONE exact (torch, CUDA) pair, and next to any
+# other pair torch.ops.load_library raises and xformers/_cpp_lib.py downgrades to
+# "xFormers can't load C++/CUDA extensions", losing memory-efficient attention,
+# SwiGLU and the sparse ops for the rest of the process -- a silent warning, not
+# an install failure. PyPI publishes only the CUDA-12.8 flavour (0.0.34's
+# win_amd64 cpp_lib.json reads torch 2.10.0+cu128), which is wrong next to the
+# cu126 / cu130 torch install.ps1 pulls from download.pytorch.org -- and cannot
+# be right on a plain PyPI install either, because PyPI's WINDOWS torch carries
+# no CUDA at all (torch 2.10.0's win_amd64 wheel reports __version__
+# '2.10.0+cpu' with cuda = None; only the Linux wheel is +cu128).
+#
+# There is no PEP 508 marker for "which CUDA build of torch is resident", so a
+# single static extra cannot pick the right wheel. The CUDA-matched route on
+# Windows is therefore the same one Linux uses -- the cuXXX-torchYYY extras. Not
+# every one of them carries a win_amd64 row (the cu118 and cu121 rows do not, and
+# cu130onlytorch280 is empty), but the cu126 / cu128 / cu130 rows a current torch
+# resolves to all do:
+# pip install --index-url https://download.pytorch.org/whl/cu130 "unsloth[cu130-torch2100]"
+# pip install --index-url https://download.pytorch.org/whl/cu128 "unsloth[cu128-torch2100]"
+# The index is not optional. Those extras pin xFormers by direct URL but pin no
+# torch, and PyPI's Windows torch is CPU-only, so without it pip lands a cu130
+# extension beside a '2.10.0+cpu' torch -- the same silent mismatch, inverted.
+# install.ps1 needs none of this: it picks the wheel from the index it installed
+# torch from, so Studio never reaches the extra below.
+#
+# The extra below is what a `pip install "unsloth[windows]"` resolves, and it
+# stays CUDA-agnostic because it has nothing to key off. It is deliberately NOT
+# capped. An earlier revision bounded it at <0.0.35 on the reasoning that 0.0.35
+# declares only torch>=2.10 while its extension is built for 2.10.0. Upstream says
+# that pairing is supported: v0.0.34's notes record the migration to the PyTorch
+# stable API/ABI, "which means that binary builds targeting PyTorch 2.10+ will be
+# compatible with any later version". Capping also has a cost -- 0.0.34 pins
+# torch==2.10.0 EXACTLY, so a cap strands anyone on 2.10.1. The axis that actually
+# has to match is the CUDA family, which this extra cannot see and install.ps1
+# handles instead.
windows = [
"unsloth[huggingface]",
"bitsandbytes>=0.45.5,!=0.46.0,!=0.48.0 ; (sys_platform == 'win32')",
diff --git a/studio/backend/core/inference/diffusion_attention.py b/studio/backend/core/inference/diffusion_attention.py
index 6ccc3c4fdfb..d8b3371b982 100644
--- a/studio/backend/core/inference/diffusion_attention.py
+++ b/studio/backend/core/inference/diffusion_attention.py
@@ -29,6 +29,8 @@ Best-effort: an unavailable backend falls back to the diffusers default. torch/d
from __future__ import annotations
+import re
+import threading
from typing import Any, Optional
ATTN_AUTO = "auto"
@@ -158,6 +160,8 @@ _INSTALLABLE_BACKENDS: dict[str, tuple[str, str]] = {
"flash": ("flash_attn", "flash-attn"),
"_flash_3_hub": ("kernels", "kernels"), # FA3/FA4 from the HF kernels hub
"flash_4_hub": ("kernels", "kernels"),
+ # Never handed to pip as a name -- see _MATCHED_WHEEL_BACKENDS below; the package
+ # string survives only for logging and for the _INSTALL_ATTEMPTED bookkeeping.
"xformers": ("xformers", "xformers"),
}
@@ -167,6 +171,91 @@ _ATTENTION_INSTALL_ENV = "UNSLOTH_DIFFUSION_ATTENTION_INSTALL"
# Packages a pip install was already attempted for in THIS process. The loader pre-installs outside its locks, so a recorded attempt stops apply re-running the 600s install under _generate_lock.
_INSTALL_ATTEMPTED: set[str] = set()
+# Backends whose wheel must be resolved against the RUNNING torch build instead of handed
+# to pip as a name. Only DETERMINISTIC answers are memoised (a URL, or a refusal that
+# depends purely on the resident torch, which cannot change under a running interpreter).
+# A probe timeout is transient and is deliberately NOT cached: caching it would turn one
+# loaded-machine hiccup into "no xFormers for the rest of this Studio session".
+_MATCHED_WHEEL_BACKENDS = frozenset({"xformers"})
+_XFORMERS_WHEEL_TARGET: Optional[tuple[Optional[str], Optional[str]]] = None
+_XFORMERS_WHEEL_LOCK = threading.Lock()
+
+
+# Scheme-qualified URLs only; nothing else in these messages can carry a credential.
+_URL_IN_TEXT = re.compile(r"[a-zA-Z][a-zA-Z0-9+.\-]*://[^\s'\"<>]+")
+
+
+def _redacted_for_log(text: str) -> str:
+ """Every URL in ``text``, stripped of userinfo / query / fragment.
+
+ Takes free text, not just a URL, because pip echoes the URL it was handed back in its
+ stderr -- redacting only the name in the log line would leave the secret in the body.
+ """
+ try:
+ from utils.wheel_utils import redact_url_credentials
+ except Exception: # noqa: BLE001 -- redaction must never be the thing that breaks a log
+ return text
+ return _URL_IN_TEXT.sub(lambda m: redact_url_credentials(m.group(0)), text)
+
+
+def _xformers_wheel_target() -> tuple[Optional[str], Optional[str]]:
+ """Resolve the xFormers wheel built for the resident torch: (URL, refusal reason).
+
+ xformers' compiled extension is linked against ONE exact (torch, CUDA) pair, and next
+ to any other pair ``torch.ops.load_library`` raises -- which xformers/_cpp_lib.py then
+ downgrades to a log warning, so the import "succeeds" with memory-efficient attention,
+ SwiGLU and the sparse ops silently gone. That is invisible to ``find_spec`` and to pip.
+ PyPI publishes only the CUDA-12.8 flavour, so a plain ``pip install xformers`` beside a
+ cu130 torch installs the broken combination every time.
+
+ So resolve the exact download.pytorch.org wheel instead, and when no wheel matches
+ return a reason rather than a URL: installing nothing leaves the caller on torch SDPA,
+ which is strictly better than installing an extension that cannot load.
+
+ The URL is not HEAD-checked here. This can run under ``_generate_lock`` (the video
+ loader has no out-of-lock pre-install hop, unlike the image one), so it must not add
+ network round trips to a path that already blocks unload/cancel; a wrong row surfaces
+ as a pip failure instead, and the matrix has a live-URL test behind it.
+ """
+ global _XFORMERS_WHEEL_TARGET
+ with _XFORMERS_WHEEL_LOCK:
+ if _XFORMERS_WHEEL_TARGET is not None:
+ return _XFORMERS_WHEEL_TARGET
+ try:
+ from utils.wheel_utils import probe_torch_wheel_env, xformers_wheel_url
+
+ # include_windows: this is the one resolver that HAS win_amd64 wheels
+ # upstream. timeout matches the other probe_torch_wheel_env callers.
+ env = probe_torch_wheel_env(timeout = 30, include_windows = True)
+ except Exception as exc: # noqa: BLE001 -- must never break a model load
+ return (None, f"the xFormers wheel could not be resolved ({exc})")
+ if env is None:
+ # Ambiguous: a platform wheel_platform_tag() does not name (macOS, Windows on
+ # ARM) which is deterministic, or a probe that timed out on a busy box which is
+ # transient. Not cached, so the next request can settle it. Linux aarch64 is
+ # NOT here -- it gets a platform_tag and so lands on the branch below.
+ return (
+ None,
+ "torch could not be probed, or this platform has no xFormers wheel "
+ "(macOS / Windows on ARM)",
+ )
+ url = xformers_wheel_url(env)
+ if url is None:
+ # Name the platform. Linux aarch64 reaches here with a perfectly ordinary
+ # torch, and reporting only the torch and CUDA would read as "upstream never
+ # built this pair" when the truth is "upstream never built it for this arch".
+ target = (
+ None,
+ f"no xFormers wheel is published for torch "
+ f"{env.get('torch_version') or 'unknown'} with CUDA "
+ f"{env.get('cuda_version') or 'none'} on "
+ f"{env.get('platform_tag') or 'this platform'}",
+ )
+ else:
+ target = (url, None)
+ _XFORMERS_WHEEL_TARGET = target
+ return target
+
def _pip_requirement(backend: str, package: str) -> str:
"""Requirement to hand pip, carrying any floor the dispatcher enforces at set time.
@@ -221,22 +310,29 @@ def _kernels_hub_compatible() -> bool:
return True
-def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> None:
+def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Optional[str]:
"""Best-effort wheel-only install of the package ``backend`` needs, when allowed.
Called after arch gating, so only for a backend that could work here. Failure is swallowed:
- the subsequent set_attention_backend raises on the missing package and falls back to native."""
+ the subsequent set_attention_backend raises on the missing package and falls back to native.
+
+ Returns the reason the install was REFUSED (a policy decision, e.g. no CUDA-matched
+ xFormers wheel exists for the resident torch), or None when nothing stood in the way --
+ the install ran, was skipped as already present, or merely failed. Every refusal is also
+ logged at warning level; the return value is there so a caller that wants to surface the
+ reason (rather than silently falling back to native) can, and both current callers
+ deliberately ignore it."""
import importlib.util
import os
spec = _INSTALLABLE_BACKENDS.get(backend)
if spec is None:
- return
+ return None
module, package = spec
package = _pip_requirement(backend, package)
gate = os.environ.get(_ATTENTION_INSTALL_ENV, "auto").strip().lower()
if gate in ("0", "false", "no", "off"):
- return
+ return None
# Refusing is a POLICY decision, not a failed attempt, so it is checked before the
# _INSTALL_ATTEMPTED memo below and records nothing: a later request on a fixed environment
# must still be able to install. Scoped to kernels; the sage / flash-attn / xformers wheels
@@ -250,26 +346,59 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Non
backend,
*_KERNELS_HUB_FLOOR,
)
- return
+ return "the resident huggingface_hub is too old for the kernels package"
try:
if importlib.util.find_spec(module) is not None:
- return
+ # Present is present, including a MISMATCHED xformers: find_spec sees the
+ # package, so nothing below runs and the wrong-CUDA build stays. That is
+ # deliberate here. Repairing means reinstalling a package the user may have
+ # built or pinned on purpose, and this can run under _generate_lock, so a
+ # 100 MB download would block unload and cancel. install.ps1 is where the
+ # repair belongs -- it compares cpp_lib.json against the resident torch and
+ # passes --reinstall-package, outside any request. What this branch prevents
+ # is Studio CREATING the mismatch, which is how it got made in the first place.
+ return None
except Exception: # noqa: BLE001 — a broken install probes as missing; try the install
pass
+ # xFormers ships a compiled extension tied to one exact (torch, CUDA) pair, so the name
+ # `xformers` is not a safe thing to hand pip: PyPI serves only the CUDA-12.8 build and
+ # --no-deps below deliberately stops pip from ever reading its `Requires-Dist: torch==X`.
+ # Resolve the matching wheel URL instead, and REFUSE when there is none -- like the
+ # kernels gate above this is policy, so it is checked before the _INSTALL_ATTEMPTED memo
+ # and records nothing there (a refused backend never burns its one install attempt).
+ if backend in _MATCHED_WHEEL_BACKENDS:
+ wheel_url, refusal = _xformers_wheel_target()
+ if wheel_url is None:
+ if logger is not None:
+ logger.warning(
+ "diffusion.attention: not installing %s for backend=%s — %s; an unpinned "
+ "install would land an extension that cannot load next to the resident "
+ "torch and would disable memory-efficient attention silently. Using the "
+ "default backend",
+ package,
+ backend,
+ refusal,
+ )
+ return refusal
+ package = wheel_url
+ # What pip gets and what the log gets are not the same string. UNSLOTH_PYTORCH_MIRROR may
+ # carry userinfo or a token for a private index, and it is baked into the wheel URL, so
+ # logging the URL verbatim writes that secret into the backend log.
+ display = _redacted_for_log(package)
# Attempt each install once per process, else the in-lock apply re-runs it under _generate_lock and blocks unload/cancel.
if package in _INSTALL_ATTEMPTED:
- return
+ return None
_INSTALL_ATTEMPTED.add(package)
import subprocess
import sys
if logger is not None:
logger.info(
- "diffusion.attention: installing %s for backend=%s (wheel-only)", package, backend
+ "diffusion.attention: installing %s for backend=%s (wheel-only)", display, backend
)
try:
subprocess.run(
- # --no-deps: install ONLY this kernel wheel, since xformers/flash-attn pin an exact torch and normal resolution would replace the running one. An ABI mismatch just fails to import.
+ # --no-deps: install ONLY this kernel wheel, since xformers/flash-attn pin an exact torch and normal resolution would replace the running one. It also means pip never reads the wheel's `Requires-Dist: torch==X`, so nothing here would catch an ABI mismatch -- for xformers, whose mismatch is SILENT (the extension fails to load and _cpp_lib.py logs a warning), the URL was resolved against the running torch above precisely so there is nothing left to catch.
[
sys.executable,
"-m",
@@ -295,15 +424,18 @@ def _ensure_attention_backend_installed(backend: str, logger: Any = None) -> Non
stderr = stderr.decode("utf-8", errors = "replace")
logger.warning(
"diffusion.attention: could not install %s; pip failed with: %s",
- package,
- stderr.strip() or str(exc),
+ display,
+ # pip echoes the URL it was given, so redact the body too rather than
+ # only the name in front of it.
+ _redacted_for_log(stderr.strip()) or str(exc),
)
else:
logger.warning(
"diffusion.attention: could not install %s (%s); falling back to default",
- package,
- exc,
+ display,
+ _redacted_for_log(str(exc)),
)
+ return None
def _attention_dits(pipe: Any) -> list:
diff --git a/studio/backend/tests/conftest.py b/studio/backend/tests/conftest.py
index 03667d527da..7970098f53e 100644
--- a/studio/backend/tests/conftest.py
+++ b/studio/backend/tests/conftest.py
@@ -31,6 +31,12 @@ os.environ.setdefault("UNSLOTH_ALLOW_CPU", "1")
# The other half of the same guard: unsloth_zoo.__init__ refuses to import unless this is present, normally set by `import unsloth`. Without it
# the patch backend's only route to the helpers is that ~940 MB import, which a CPU-only host cannot complete. run.py and main.py do the same.
os.environ.setdefault("UNSLOTH_IS_PRESENT", "1")
+# The on-demand attention-backend installer defaults to "auto", so ANY test that loads a
+# pipeline with attention_backend="xformers"/"sage"/"flash" would shell out to a real pip
+# (up to 600s) and, for xformers, a real torch probe. test_diffusion_attention.py disables
+# it per-test; pin the default off for the whole suite so a new test elsewhere cannot
+# reintroduce that by accident. setdefault, so an explicit override still wins.
+os.environ.setdefault("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "0")
@pytest.fixture(scope = "session")
diff --git a/studio/backend/tests/test_diffusion_attention.py b/studio/backend/tests/test_diffusion_attention.py
index 7b696174f86..47508e8a132 100644
--- a/studio/backend/tests/test_diffusion_attention.py
+++ b/studio/backend/tests/test_diffusion_attention.py
@@ -256,6 +256,9 @@ def _no_real_installs(monkeypatch):
monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "0")
# The install once-per-process memo is module state; clear it so each test starts fresh.
att._INSTALL_ATTEMPTED.clear()
+ # So is the resolved xFormers wheel. Left set, one test's stub decides the next one's
+ # answer -- and unset, the resolver shells out to probe the real torch.
+ monkeypatch.setattr(att, "_XFORMERS_WHEEL_TARGET", None)
class _Recorder:
@@ -322,12 +325,25 @@ def test_sage_install_carries_the_dispatcher_version_floor(monkeypatch):
assert att._pip_requirement("xformers", "xformers") == "xformers"
+_XFORMERS_WHEEL = "https://download.pytorch.org/whl/cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl"
+
+
+def _stub_xformers_wheel(
+ monkeypatch,
+ url = _XFORMERS_WHEEL,
+ reason = None,
+):
+ """Pin the resolved xFormers wheel so no test probes the real torch."""
+ monkeypatch.setattr(att, "_xformers_wheel_target", lambda: (url, reason))
+
+
def test_install_uses_no_deps_to_protect_core_deps(monkeypatch):
- # A kernel add-on pins an exact torch, so --no-deps installs only the kernel wheel; an ABI-incompatible one merely fails to import.
+ # A kernel add-on pins an exact torch, so --no-deps installs only the kernel wheel.
monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
import importlib.util
monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(monkeypatch)
run = _Recorder()
_stub_subprocess(monkeypatch, run)
att._ensure_attention_backend_installed("xformers")
@@ -335,6 +351,179 @@ def test_install_uses_no_deps_to_protect_core_deps(monkeypatch):
assert "--no-deps" in run.calls[0]
+def test_xformers_installs_the_cuda_matched_wheel_not_the_package_name(monkeypatch):
+ """`pip install xformers` resolves the PyPI build, which exists only in the CUDA-12.8
+ flavour: beside a cu130 torch its extension fails to load and xformers/_cpp_lib.py
+ logs a warning instead of raising, so memory-efficient attention vanishes silently
+ while the import still succeeds. Only a URL resolved against the running torch is safe."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(monkeypatch)
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+
+ assert att._ensure_attention_backend_installed("xformers") is None
+ assert len(run.calls) == 1
+ assert _XFORMERS_WHEEL in run.calls[0]
+ assert "xformers" not in [arg for arg in run.calls[0] if arg != _XFORMERS_WHEEL]
+
+
+_CREDENTIALED_WHEEL = (
+ "https://svc:[email protected]/whl/cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl"
+)
+_REDACTED_WHEEL = "https://mirror.internal/whl/cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl"
+
+
+class _CapturingLogger:
+ def __init__(self):
+ self.lines: list[str] = []
+
+ def info(self, msg, *args):
+ self.lines.append(msg % args if args else msg)
+
+ def warning(self, msg, *args):
+ self.lines.append(msg % args if args else msg)
+
+
+def test_a_private_mirrors_credentials_never_reach_the_log(monkeypatch):
+ """UNSLOTH_PYTORCH_MIRROR is allowed to be an authenticated index, and the wheel URL is
+ built from it -- so logging the URL as the package name wrote the token into the backend
+ log on every install. pip is still handed the real URL; only the log is redacted, and
+ pip's own stderr echoes the URL back, so that is redacted too."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+ import subprocess as sp
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(monkeypatch, url = _CREDENTIALED_WHEEL)
+
+ def _boom(cmd, **kwargs):
+ raise sp.CalledProcessError(
+ returncode = 1,
+ cmd = cmd,
+ stderr = f"ERROR: Could not install {_CREDENTIALED_WHEEL} (404)".encode(),
+ )
+
+ _stub_subprocess(monkeypatch, _boom)
+ logger = _CapturingLogger()
+
+ att._ensure_attention_backend_installed("xformers", logger)
+
+ assert logger.lines
+ for line in logger.lines:
+ assert "s3cr3t" not in line
+ assert _REDACTED_WHEEL in line
+
+
+def test_a_query_string_token_is_stripped_too():
+ # Tokens live in the query as often as in the userinfo, and the free-text form has to
+ # find URLs inside a sentence, which is where pip puts them.
+ redacted = att._redacted_for_log(
+ "ERROR: HTTP 403 for https://mirror.internal/whl/cu130/x.whl?token=abc123 -- retry"
+ )
+ assert "abc123" not in redacted
+ assert "https://mirror.internal/whl/cu130/x.whl" in redacted
+
+
+def test_xformers_install_refused_when_no_matching_wheel_exists(monkeypatch):
+ """No matched wheel must mean NO install. Falling back to an unpinned resolve is the
+ bug; the caller stays on torch SDPA and gets the reason back."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(
+ monkeypatch, url = None, reason = "no xFormers wheel is published for torch 2.11.0"
+ )
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+
+ reason = att._ensure_attention_backend_installed("xformers")
+ assert reason == "no xFormers wheel is published for torch 2.11.0"
+ assert run.calls == []
+
+
+def test_xformers_refusal_is_logged_with_its_reason(monkeypatch):
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(monkeypatch, url = None, reason = "torch could not be probed")
+ _stub_subprocess(monkeypatch, _Recorder())
+
+ warnings = []
+
+ class _Logger:
+ def info(self, *args, **kwargs):
+ pass
+
+ def warning(self, msg, *args, **kwargs):
+ warnings.append(msg % args if args else msg)
+
+ att._ensure_attention_backend_installed("xformers", _Logger())
+ assert len(warnings) == 1
+ assert "torch could not be probed" in warnings[0]
+ assert "not installing" in warnings[0]
+
+
+def test_xformers_refusal_records_no_attempt(monkeypatch):
+ """Refusal is a POLICY decision, like the kernels/hub gate, so it must not burn the
+ one-shot install slot: once the resolver can answer, the install still happens."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ _stub_xformers_wheel(monkeypatch, url = None, reason = "nope")
+ _stub_subprocess(monkeypatch, _Recorder())
+
+ att._ensure_attention_backend_installed("xformers")
+ assert att._INSTALL_ATTEMPTED == set()
+
+ # Resolver can now answer -> the next request installs.
+ _stub_xformers_wheel(monkeypatch)
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+ att._ensure_attention_backend_installed("xformers")
+ assert len(run.calls) == 1
+ assert _XFORMERS_WHEEL in run.calls[0]
+
+
+def test_xformers_resolution_skipped_when_already_installed(monkeypatch):
+ """find_spec runs first, so a working xformers never pays for the torch probe."""
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: object())
+ resolved = []
+ monkeypatch.setattr(att, "_xformers_wheel_target", lambda: resolved.append(1) or (None, "x"))
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+
+ assert att._ensure_attention_backend_installed("xformers") is None
+ assert resolved == []
+ assert run.calls == []
+
+
+def test_matched_wheel_path_does_not_touch_other_backends(monkeypatch):
+ """sage / flash / kernels still go to pip by name -- only xFormers has the silent
+ ABI failure that forces URL resolution."""
+ assert att._MATCHED_WHEEL_BACKENDS == frozenset({"xformers"})
+ monkeypatch.setenv("UNSLOTH_DIFFUSION_ATTENTION_INSTALL", "auto")
+ import importlib.util
+
+ monkeypatch.setattr(importlib.util, "find_spec", lambda name: None)
+ monkeypatch.setattr(
+ att, "_xformers_wheel_target", lambda: pytest.fail("resolver must not run for sage")
+ )
+ run = _Recorder()
+ _stub_subprocess(monkeypatch, run)
+ att._ensure_attention_backend_installed("sage")
+ assert len(run.calls) == 1
+ assert "sageattention>=2.1.1" in run.calls[0]
+
+
def test_failed_install_not_retried_in_same_process(monkeypatch):
# The loader pre-installs the kernel OUTSIDE its locks and re-resolves under _generate_lock; a failed pre-install must NOT
# re-run pip in the lock (a second 600s install would block unload/cancel), so the once-per-process memo no-ops the retry.
@@ -511,3 +700,98 @@ def test_kernels_hub_compatible_reads_hub_version(monkeypatch):
# Undeterminable hub -> keep the previous (permissive) behaviour.
monkeypatch.setattr(importlib.metadata, "version", _boom)
assert att._kernels_hub_compatible() is True
+
+
+def test_transient_resolution_failure_is_not_memoised(monkeypatch):
+ """A probe that times out on a loaded box is transient. Caching it would turn one
+ hiccup into "no xFormers for the rest of this Studio session", so only DETERMINISTIC
+ answers (a URL, or a refusal that depends purely on the resident torch) are cached."""
+ import utils.wheel_utils as wu
+
+ calls = []
+
+ def _probe(**kwargs):
+ calls.append(kwargs)
+ return (
+ None
+ if len(calls) == 1
+ else {
+ "platform_tag": "win_amd64",
+ "python_tag": "cp313",
+ "torch_version": "2.10.0+cu130",
+ "cuda_version": "13.0",
+ }
+ )
+
+ monkeypatch.setattr(wu, "probe_torch_wheel_env", _probe)
+
+ url, reason = att._xformers_wheel_target()
+ assert url is None and "could not be probed" in reason
+ assert att._XFORMERS_WHEEL_TARGET is None, "a transient failure must not be cached"
+
+ url, reason = att._xformers_wheel_target()
+ assert reason is None and url == _XFORMERS_WHEEL
+ assert att._XFORMERS_WHEEL_TARGET == (_XFORMERS_WHEEL, None)
+ assert len(calls) == 2
+
+
+def test_deterministic_refusal_is_memoised(monkeypatch):
+ """torch cannot change under a running interpreter, so "no wheel for this torch" is
+ settled; re-probing it on every request would re-pay the subprocess under the lock."""
+ import utils.wheel_utils as wu
+
+ calls = []
+
+ def _probe(**kwargs):
+ calls.append(kwargs)
+ return {
+ "platform_tag": "win_amd64",
+ "python_tag": "cp313",
+ # A CUDA family with no xFormers wheel on any index: the refusal has to be a
+ # real one, and torch 2.11 itself now resolves through the stable-ABI rows.
+ "torch_version": "2.11.0+cu124",
+ "cuda_version": "12.4",
+ }
+
+ monkeypatch.setattr(wu, "probe_torch_wheel_env", _probe)
+
+ for _ in range(3):
+ url, reason = att._xformers_wheel_target()
+ assert url is None
+ assert "no xFormers wheel is published for torch 2.11.0+cu124" in reason
+ assert len(calls) == 1
+
+
+def test_resolution_does_no_network_io(monkeypatch):
+ """It can run under _generate_lock (the video loader has no out-of-lock pre-install),
+ so it must not add a HEAD to a path that already blocks unload/cancel."""
+ import utils.wheel_utils as wu
+
+ monkeypatch.setattr(
+ wu,
+ "probe_torch_wheel_env",
+ lambda **kw: {
+ "platform_tag": "win_amd64",
+ "python_tag": "cp313",
+ "torch_version": "2.10.0+cu130",
+ "cuda_version": "13.0",
+ },
+ )
+ monkeypatch.setattr(
+ wu, "url_exists", lambda url: pytest.fail("resolution must not hit the network")
+ )
+ assert att._xformers_wheel_target() == (_XFORMERS_WHEEL, None)
+
+
+def test_probe_timeout_matches_the_other_wheel_callers(monkeypatch):
+ import utils.wheel_utils as wu
+
+ seen = {}
+
+ def _probe(**kwargs):
+ seen.update(kwargs)
+ return None
+
+ monkeypatch.setattr(wu, "probe_torch_wheel_env", _probe)
+ att._xformers_wheel_target()
+ assert seen == {"timeout": 30, "include_windows": True}
diff --git a/studio/backend/tests/test_wheel_utils_xformers.py b/studio/backend/tests/test_wheel_utils_xformers.py
new file mode 100644
index 00000000000..4a15b57dd94
--- /dev/null
+++ b/studio/backend/tests/test_wheel_utils_xformers.py
@@ -0,0 +1,333 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+
+"""wheel_utils must resolve a CUDA-matched xFormers wheel, on Windows too.
+
+The platform-tag helper returned None for Windows, so nothing in the backend could
+resolve a Windows wheel URL at all -- which is why the on-demand xFormers install fell
+back to an unpinned ``pip install xformers`` and landed the PyPI CUDA-12.8 build next to
+a cu130 torch.
+"""
+
+from __future__ import annotations
+
+import sys
+from pathlib import Path
+
+import pytest
+
+
+_BACKEND = Path(__file__).resolve().parent.parent
+if str(_BACKEND) not in sys.path:
+ sys.path.insert(0, str(_BACKEND))
+
+from utils import wheel_utils # noqa: E402
+
+
+def _env(**overrides) -> dict[str, str]:
+ env = {
+ "python_tag": "cp313",
+ "torch_mm": "2.10",
+ "torch_version": "2.10.0+cu130",
+ "cuda_version": "13.0",
+ "cuda_major": "13",
+ "hip_version": "",
+ "cxx11abi": "TRUE",
+ "platform_tag": "win_amd64",
+ }
+ env.update(overrides)
+ return env
+
+
+class TestWheelPlatformTag:
+ def test_windows_x64_emits_win_amd64(self, monkeypatch):
+ monkeypatch.setattr(wheel_utils.sys, "platform", "win32")
+ monkeypatch.setattr(wheel_utils.platform, "machine", lambda: "AMD64")
+ assert wheel_utils.wheel_platform_tag() == "win_amd64"
+
+ def test_windows_on_arm_has_no_wheel(self, monkeypatch):
+ """No CUDA and no win_arm64 asset on any index -- must stay None."""
+ monkeypatch.setattr(wheel_utils.sys, "platform", "win32")
+ monkeypatch.setattr(wheel_utils.platform, "machine", lambda: "ARM64")
+ assert wheel_utils.wheel_platform_tag() is None
+
+ @pytest.mark.parametrize(
+ ("machine", "expected"),
+ [("x86_64", "linux_x86_64"), ("aarch64", "linux_aarch64")],
+ )
+ def test_linux_tags_are_unchanged(self, monkeypatch, machine, expected):
+ monkeypatch.setattr(wheel_utils.sys, "platform", "linux")
+ monkeypatch.setattr(wheel_utils.platform, "machine", lambda: machine)
+ assert wheel_utils.wheel_platform_tag() == expected
+
+ def test_macos_still_has_no_wheel(self, monkeypatch):
+ monkeypatch.setattr(wheel_utils.sys, "platform", "darwin")
+ monkeypatch.setattr(wheel_utils.platform, "machine", lambda: "arm64")
+ assert wheel_utils.wheel_platform_tag() is None
+
+ def test_probe_stays_linux_only_by_default(self, monkeypatch):
+ """flash-attn / causal-conv1d / mamba-ssm publish no win_amd64 assets, so the
+ existing callers must keep getting None on Windows even though the platform tag
+ now resolves. Guarded here because the probe shells out otherwise."""
+ monkeypatch.setattr(wheel_utils, "wheel_platform_tag", lambda: "win_amd64")
+ assert wheel_utils.probe_torch_wheel_env() is None
+ assert wheel_utils.probe_torch_wheel_env(timeout = 5) is None
+
+
+class TestXformersCudaFamily:
+ @pytest.mark.parametrize(
+ ("cuda_version", "expected"),
+ [
+ ("13.0", "cu130"),
+ ("12.8", "cu128"),
+ ("12.6", "cu126"),
+ ("12.9", "cu129"),
+ ("11.8", "cu118"),
+ ],
+ )
+ def test_maps_torch_cuda_to_the_index_leaf(self, cuda_version, expected):
+ assert wheel_utils.xformers_cuda_family(cuda_version) == expected
+
+ @pytest.mark.parametrize("value", ["", None, "rocm6.4", "abc"])
+ def test_non_cuda_builds_have_no_family(self, value):
+ assert wheel_utils.xformers_cuda_family(value) is None
+
+
+class TestXformersWheelUrl:
+ @pytest.mark.parametrize(
+ ("torch_version", "cuda_version", "expected_family", "expected_version"),
+ [
+ ("2.10.0+cu130", "13.0", "cu130", "0.0.34"),
+ ("2.10.0+cu128", "12.8", "cu128", "0.0.34"),
+ ("2.10.0+cu126", "12.6", "cu126", "0.0.34"),
+ ("2.9.1+cu130", "13.0", "cu130", "0.0.33.post2"),
+ ("2.9.0+cu128", "12.8", "cu128", "0.0.33.post1"),
+ ("2.8.0+cu129", "12.9", "cu129", "0.0.32.post2"),
+ ],
+ )
+ def test_windows_url_matches_the_resident_cuda_build(
+ self, torch_version, cuda_version, expected_family, expected_version
+ ):
+ url = wheel_utils.xformers_wheel_url(
+ _env(torch_version = torch_version, cuda_version = cuda_version)
+ )
+ assert url == (
+ f"https://download.pytorch.org/whl/{expected_family}"
+ f"/xformers-{expected_version}-cp39-abi3-win_amd64.whl"
+ )
+
+ def test_linux_keeps_its_own_platform_leaf(self):
+ url = wheel_utils.xformers_wheel_url(_env(platform_tag = "linux_x86_64"))
+ assert url == (
+ "https://download.pytorch.org/whl/cu130"
+ "/xformers-0.0.34-cp39-abi3-manylinux_2_28_x86_64.whl"
+ )
+
+ def test_url_is_interpreter_independent(self):
+ """0.0.31..0.0.34 ship a single cp39-abi3 wheel, so the interpreter must not leak
+ into the URL. (0.0.30 and earlier did ship one wheel per cpXY, which is exactly why
+ torch 2.7.0 is not in the matrix.)"""
+ urls = {
+ wheel_utils.xformers_wheel_url(_env(python_tag = tag))
+ for tag in ("cp39", "cp310", "cp311", "cp312", "cp313", "cp314")
+ }
+ assert len(urls) == 1 and None not in urls
+
+ @pytest.mark.parametrize(
+ ("torch_version", "cuda_version", "why"),
+ [
+ ("2.8.0+cu130", "13.0", "no cu130 xFormers build exists for torch 2.8"),
+ ("2.7.0+cu128", "12.8", "xFormers 0.0.30 predates abi3 and stops at cp312"),
+ (
+ "2.9.0+cu118",
+ "11.8",
+ "cu118 stops before the abi3 switch, so its wheels "
+ "are per-interpreter and unnameable here",
+ ),
+ ("2.10.0+cu124", "12.4", "cu124 stopped at xFormers 0.0.29"),
+ (
+ "2.11.0+cu124",
+ "12.4",
+ "cu124 stopped at xFormers 0.0.29, so the stable-ABI era does not rescue it",
+ ),
+ ("2.10.0.dev20260101+cu130", "13.0", "a nightly torch has no matching wheel"),
+ ("2.6.0+cu126", "12.6", "below the oldest row"),
+ ],
+ )
+ def test_unmatched_pairs_resolve_to_nothing(self, torch_version, cuda_version, why):
+ """The whole point: no match must mean "install nothing", never "install the
+ closest thing" -- a neighbouring CUDA family is exactly the reported bug."""
+ assert (
+ wheel_utils.xformers_wheel_url(
+ _env(torch_version = torch_version, cuda_version = cuda_version)
+ )
+ is None
+ ), why
+
+ @pytest.mark.parametrize(
+ "overrides",
+ [
+ {"cuda_version": "", "cuda_major": ""}, # CPU / ROCm torch
+ {"platform_tag": "linux_aarch64"}, # no aarch64 xFormers wheels
+ {"platform_tag": ""},
+ {"torch_version": ""},
+ ],
+ )
+ def test_missing_inputs_resolve_to_nothing(self, overrides):
+ assert wheel_utils.xformers_wheel_url(_env(**overrides)) is None
+
+ def test_none_env_is_tolerated(self):
+ assert wheel_utils.xformers_wheel_url(None) is None
+
+
+def test_flash_attn_resolution_is_untouched():
+ """direct_wheel_url / flash_attn_wheel_url share the env dict; the two new keys must
+ not change a single flash-attn URL."""
+ env = _env(platform_tag = "linux_x86_64", python_tag = "cp312", cuda_major = "12")
+ assert wheel_utils.flash_attn_wheel_url(env) == (
+ "https://github.com/Dao-AILab/flash-attention/releases/download/v2.8.1"
+ "/flash_attn-2.8.1+cu12torch2.10cxx11abiTRUE-cp312-cp312-linux_x86_64.whl"
+ )
+
+
+def test_filename_python_tag_is_ranged_not_open_ended():
+ """xFormers has changed its wheel filename tag twice. Guessing the tag for an unreleased
+ version is how a resolver starts emitting URLs that 404, so an unknown release must
+ resolve to nothing. Verified against the real WHEEL metadata: 0.0.34 is
+ cp39-abi3-win_amd64, 0.0.35 is py39-none-win_amd64."""
+ assert wheel_utils.xformers_filename_python_tag("0.0.31.post1") == "cp39-abi3"
+ assert wheel_utils.xformers_filename_python_tag("0.0.34") == "cp39-abi3"
+ assert wheel_utils.xformers_filename_python_tag("0.0.35") == "py39-none"
+ for unknown in ("0.0.30", "0.0.29.post3", "0.0.36", "0.1.0", "", "nonsense"):
+ assert wheel_utils.xformers_filename_python_tag(unknown) is None, unknown
+
+
+def test_every_matrix_version_has_a_known_filename_tag():
+ for families in wheel_utils._XFORMERS_WHEEL_VERSIONS.values():
+ for version in families.values():
+ assert wheel_utils.xformers_filename_python_tag(version) is not None, version
+
+
[email protected]("platform_tag", ["win_amd64", "linux_x86_64"])
+def test_every_url_the_matrix_can_produce_is_live(platform_tag):
+ """The matrix is a hand-maintained list of URLs; the only way to know a row is real is
+ to ask. A 404 fails (that row is wrong); a network outage skips, matching
+ tests/version_compat/_fetch.py."""
+ import urllib.error
+ import urllib.request
+
+ cuda_for_family = {"cu126": "12.6", "cu128": "12.8", "cu129": "12.9", "cu130": "13.0"}
+ urls: set[str] = set()
+ for release, families in wheel_utils._XFORMERS_WHEEL_VERSIONS.items():
+ for family, _version in families.items():
+ assert family in cuda_for_family, f"unmapped CUDA family {family}"
+ for python_tag in ("cp39", "cp310", "cp311", "cp312", "cp313", "cp314"):
+ url = wheel_utils.xformers_wheel_url(
+ _env(
+ torch_version = f"{release}+{family}",
+ cuda_version = cuda_for_family[family],
+ python_tag = python_tag,
+ platform_tag = platform_tag,
+ )
+ )
+ if url is not None:
+ urls.add(url)
+ assert urls, "the matrix produced no URLs at all"
+
+ dead = []
+ for url in sorted(urls):
+ try:
+ with urllib.request.urlopen(urllib.request.Request(url, method = "HEAD"), timeout = 30):
+ pass
+ except urllib.error.HTTPError as exc:
+ # Only a 404 says the matrix row names a wheel that does not exist. A 403 / 429
+ # / 5xx is the CDN having a moment, and failing the suite on one turns a
+ # correct matrix into a red build whenever download.pytorch.org rate-limits the
+ # 14-request sweep -- the opposite of this test's stated contract.
+ if exc.code == 404:
+ dead.append(f"{exc.code} {url}")
+ else:
+ pytest.skip(f"download.pytorch.org returned {exc.code} for {url}")
+ except (urllib.error.URLError, TimeoutError) as exc:
+ pytest.skip(f"download.pytorch.org unreachable: {exc}")
+ assert dead == [], "matrix rows pointing at wheels that do not exist:\n" + "\n".join(dead)
+
+
+class TestStableAbiPatchReleases:
+ """A supported resident build must not be refused for want of a table row.
+
+ The exact-key matrix can only ever list releases that exist when it is written, so
+ 2.10.1 / 2.11.1 / 2.12.1 -- all of them builds this repo names as supported elsewhere --
+ resolved to nothing and left Studio on native attention with no xFormers at all.
+ """
+
+ @pytest.mark.parametrize(
+ "torch_version",
+ ["2.10.1+cu130", "2.11.1+cu130", "2.12.4+cu130", "2.14.0+cu130", "2.13.2+cu128"],
+ )
+ def test_a_patch_release_above_the_floor_resolves_to_the_stable_abi_wheel(self, torch_version):
+ family = torch_version.split("+", 1)[1]
+ cuda = {"cu126": "12.6", "cu128": "12.8", "cu130": "13.0"}[family]
+ url = wheel_utils.xformers_wheel_url(_env(torch_version = torch_version, cuda_version = cuda))
+ assert url is not None and "xformers-0.0.35-py39-none-win_amd64.whl" in url
+ assert f"/{family}/" in url
+
+ def test_an_exact_row_still_wins_over_the_fallback(self):
+ # 2.10.0 is the last exact-pinned era release: it must keep resolving to 0.0.34.
+ url = wheel_utils.xformers_wheel_url(
+ _env(torch_version = "2.10.0+cu130", cuda_version = "13.0")
+ )
+ assert url is not None and "xformers-0.0.34-" in url
+
+ @pytest.mark.parametrize(
+ ("torch_version", "cuda_version", "why"),
+ [
+ ("2.9.2+cu130", "13.0", "below the floor there is no stable ABI to lean on"),
+ ("2.11.0.dev20260101+cu130", "13.0", "a nightly is not a released torch"),
+ ("2.12.0+cu124", "12.4", "cu124 publishes nothing in the stable-ABI era"),
+ ],
+ )
+ def test_the_fallback_stays_bounded(self, torch_version, cuda_version, why):
+ assert (
+ wheel_utils.xformers_wheel_url(
+ _env(torch_version = torch_version, cuda_version = cuda_version)
+ )
+ is None
+ ), why
+
+
+class TestPytorchMirror:
+ def test_the_wheel_url_follows_the_configured_mirror(self, monkeypatch):
+ # An air-gapped install has one lever, UNSLOTH_PYTORCH_MIRROR, and the rest of the
+ # installer stack already honours it. A hard-coded download.pytorch.org here was the
+ # one path that could not reach a mirror-only host.
+ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://mirror.example/pytorch/whl/")
+ url = wheel_utils.xformers_wheel_url(_env())
+ assert url is not None
+ assert url.startswith("https://mirror.example/pytorch/whl/cu130/xformers-")
+
+ def test_a_query_token_mirror_keeps_its_token(self, monkeypatch):
+ """Private mirrors authenticate by query string as often as by userinfo. Appending
+ after the query buried the wheel path inside the token value -- the request path
+ stayed /whl and the token became "abc/cu130/xformers-..." -- so the one shape this
+ setting exists for was the one that could not resolve a wheel."""
+ monkeypatch.setenv("UNSLOTH_PYTORCH_MIRROR", "https://mirror.example/whl?token=abc")
+ url = wheel_utils.xformers_wheel_url(_env())
+ assert url is not None
+ assert url.startswith("https://mirror.example/whl/cu130/xformers-")
+ assert url.endswith("?token=abc")
+
+ def test_a_fragment_survives_the_join_too(self):
+ assert (
+ wheel_utils.join_wheel_url("https://m/whl#frag", "cu130/x.whl")
+ == "https://m/whl/cu130/x.whl#frag"
+ )
+ # And the ordinary case is unchanged, trailing slash or not.
+ assert wheel_utils.join_wheel_url("https://m/whl/", "cu130/x.whl") == (
+ "https://m/whl/cu130/x.whl"
+ )
+
+ def test_the_default_is_unchanged_without_the_mirror(self, monkeypatch):
+ monkeypatch.delenv("UNSLOTH_PYTORCH_MIRROR", raising = False)
+ url = wheel_utils.xformers_wheel_url(_env())
+ assert url is not None and url.startswith("https://download.pytorch.org/whl/cu130/")
diff --git a/studio/backend/utils/wheel_utils.py b/studio/backend/utils/wheel_utils.py
index ffdfdd4a4ce..0d8d6099d91 100644
--- a/studio/backend/utils/wheel_utils.py
+++ b/studio/backend/utils/wheel_utils.py
@@ -6,7 +6,9 @@ from __future__ import annotations
import functools
import json
import logging
+import os
import platform
+import re
import shutil
import subprocess
import sys
@@ -67,21 +69,42 @@ def has_blackwell_gpu() -> bool:
return False
-def linux_wheel_platform_tag() -> str | None:
+def wheel_platform_tag() -> str | None:
+ """pip platform tag for this host, or None where nothing we resolve is published.
+
+ Windows is included because download.pytorch.org publishes CUDA-matched
+ ``win_amd64`` xFormers wheels (see ``xformers_wheel_url``). It is NOT included for
+ flash-attn / causal-conv1d / mamba-ssm, whose upstreams publish Linux assets only --
+ ``probe_torch_wheel_env`` keeps that gate, not this function.
+ """
machine = platform.machine().lower()
if sys.platform.startswith("linux"):
if machine in {"x86_64", "amd64"}:
return "linux_x86_64"
if machine in {"aarch64", "arm64"}:
return "linux_aarch64"
- # No prebuilt wheels published for macOS or Windows
+ elif sys.platform == "win32":
+ if machine in {"x86_64", "amd64"}:
+ return "win_amd64"
+ # Windows on ARM: no CUDA, and no win_arm64 wheel on any index.
+ # No prebuilt wheels published for macOS
return None
-def probe_torch_wheel_env(*, timeout: int | None = None) -> dict[str, str] | None:
- platform_tag = linux_wheel_platform_tag()
+def probe_torch_wheel_env(
+ *, timeout: int | None = None, include_windows: bool = False
+) -> dict[str, str] | None:
+ """Describe the resident torch build for wheel-URL resolution, or None.
+
+ Windows is opt-in via ``include_windows``: every existing caller resolves a
+ flash-attn / causal-conv1d / mamba-ssm asset, and those projects publish no
+ win_amd64 wheels at all, so returning an env there would only build 404s.
+ """
+ platform_tag = wheel_platform_tag()
if platform_tag is None:
return None
+ if platform_tag == "win_amd64" and not include_windows:
+ return None
try:
probe = subprocess.run(
@@ -96,6 +119,12 @@ def probe_torch_wheel_env(*, timeout: int | None = None) -> dict[str, str] | Non
"print(json.dumps({"
"'python_tag': f'cp{sys.version_info.major}{sys.version_info.minor}', "
"'torch_mm': torch_mm, "
+ # Full release + full CUDA version: xFormers publishes one wheel per
+ # exact torch PATCH and per CUDA MINOR (cu126 and cu128 are different
+ # builds of the same version string), so 'torch_mm' / 'cuda_major'
+ # cannot pick between them.
+ "'torch_version': str(torch.__version__), "
+ "'cuda_version': str(torch.version.cuda) if torch.version.cuda else '', "
"'cuda_major': str(int(str(torch.version.cuda).split('.', 1)[0])) if torch.version.cuda else '', "
"'hip_version': str(torch.version.hip) if getattr(torch.version, 'hip', None) else '', "
"'cxx11abi': str(torch._C._GLIBCXX_USE_CXX11_ABI).upper()"
@@ -165,6 +194,263 @@ def direct_wheel_url(
return f"{release_base_url}/{release_tag}/{filename}"
+# ── xFormers ──────────────────────────────────────────────────────────────────
+# xformers/_C.pyd (_C.so on Linux) is linked against ONE exact (torch, CUDA) pair.
+# Loaded beside any other pair torch.ops.load_library raises, and xformers/_cpp_lib.py
+# turns that into a log warning rather than an error -- so the import "succeeds" and
+# memory-efficient attention, SwiGLU and the sparse ops are silently gone. PyPI publishes
+# exactly one win_amd64 flavour, and today that is the CUDA-12.8 one (0.0.34's win_amd64
+# cpp_lib.json reads torch 2.10.0+cu128), which is why `pip install xformers` next to a
+# cu130 torch reports "xFormers was built for PyTorch 2.10.0+cu128 with CUDA 1208 (you
+# have 2.10.0+cu130)". WHICH flavour that is is not stable and must not be assumed: across
+# releases the PyPI win wheel has been cu124 (0.0.29.post2), cu126 (0.0.30), cu128
+# (0.0.32), cu130 (0.0.33) and cu128 again (0.0.33.post1 onward). That churn is the
+# argument for resolving a URL rather than pinning a version.
+#
+# Note also that cpp_lib.json's `cuda` is the NVCC TOOLKIT version, not torch's CUDA
+# family: download.pytorch.org's cu126 0.0.34 also reports 1208. Only the `torch` field
+# ("2.10.0+cu128") separates the flavours, which is the field this resolver keys on and
+# the field xFormers' own error message does not lead with.
+#
+# download.pytorch.org publishes one wheel per (CUDA family, torch patch), so resolve
+# the exact URL instead. torch release -> {CUDA family: xFormers version}. Every row was
+# HEAD-verified live and its xformers/cpp_lib.json read back, e.g.
+# cu130/xformers-0.0.34-cp39-abi3-win_amd64.whl reports {"torch": "2.10.0+cu130"}.
+#
+# Rows are exact, never interpolated: xFormers' extension ABI does not survive a torch
+# minor bump (unlike the flash-attn window above, which was measured), and no cu130 build
+# exists for torch <= 2.8. An unlisted pair means "install nothing", the safe answer.
+#
+# cu118 / cu121 / cu124 are absent for a different reason, and not because those families
+# publish nothing on Windows -- they do, e.g. cu124/xformers-0.0.28.post1-cp312-cp312-
+# win_amd64.whl is live. They all stop BEFORE the cp39-abi3 switch at 0.0.31, so their
+# wheels are one file per interpreter and the single filename template below cannot name
+# them; expressing those rows needs a per-interpreter gate here and a second one in
+# install.ps1, for CUDA families no supported torch install pulls any more.
+#
+# Two deliberate over-approximations, recorded so nobody "fixes" them by interpolating:
+#
+# * Keying on the CUDA MINOR is stricter than the ABI needs. The cu126 and cu128 _C.so
+# have identical undefined-symbol sets and both link libcudart.so.12, so either loads
+# against either runtime; only a MAJOR bump changes the interface (cu130 links
+# libcudart.so.13). The minor is in the key because it names a real directory on
+# download.pytorch.org, so an exact hit guarantees the URL exists. The cost is that a
+# family with no row of its own resolves to nothing even when a sibling would work --
+# torch 2.10.0+cu129 on Linux is the live example.
+# * torch 2.11+ maps to 0.0.35, which is compiled against 2.10.0 and works there by
+# design rather than by luck: xFormers moved to the PyTorch stable API/ABI in 0.0.34,
+# and its notes state that "binary builds targeting PyTorch 2.10+ will be compatible
+# with any later version". So one 0.0.35 row per CUDA family covers every later torch,
+# and the rows below are exact only up to 2.10.0, where upstream still shipped an
+# exact-pinned wheel per torch release.
+#
+# Keep in step with $script:XformersWheelVersions in install.ps1 and the matrix in
+# tests/python/test_windows_xformers_wheel_match.py.
+PYTORCH_WHEEL_INDEX_BASE_URL = "https://download.pytorch.org/whl"
+
+
+def pytorch_wheel_index_base_url() -> str:
+ """Where torch-family wheels are fetched from: ``UNSLOTH_PYTORCH_MIRROR`` when set.
+
+ Read per call rather than frozen at import: this module is imported early, and the
+ mirror is the one setting an air-gapped deployment has. The whole installer stack
+ already honours it (``install_python_stack._PYTORCH_WHL_BASE``, install.sh, setup.ps1),
+ so a direct-URL install that hard-coded download.pytorch.org was the one path that
+ could not reach a mirror-only host -- it failed the explicit xFormers request and
+ dropped the user back to native attention.
+ """
+ return (os.environ.get("UNSLOTH_PYTORCH_MIRROR") or PYTORCH_WHEEL_INDEX_BASE_URL).rstrip("/")
+
+
+_XFORMERS_WHEEL_VERSIONS: dict[str, dict[str, str]] = {
+ # torch 2.7.0 (xFormers 0.0.30) is deliberately absent: it predates the stable-ABI
+ # switch, so it publishes one wheel per interpreter and stops at cp312, and Studio's
+ # default interpreter is 3.13. Supporting it would mean a per-interpreter gate here
+ # and a second one in install.ps1 for a four-year-old torch that resolves to nothing
+ # on the default install anyway.
+ "2.7.1": {"cu126": "0.0.31.post1", "cu128": "0.0.31.post1"},
+ "2.8.0": {"cu126": "0.0.32.post2", "cu128": "0.0.32.post2", "cu129": "0.0.32.post2"},
+ "2.9.0": {"cu126": "0.0.33.post1", "cu128": "0.0.33.post1", "cu130": "0.0.33.post1"},
+ "2.9.1": {"cu126": "0.0.33.post2", "cu128": "0.0.33.post2", "cu130": "0.0.33.post2"},
+ "2.10.0": {"cu126": "0.0.34", "cu128": "0.0.34", "cu130": "0.0.34"},
+ # Stable-ABI era: one wheel serves every torch from 2.11 on. The rows stay listed so a
+ # future exact-pinned release can displace a single one of them, but they are no longer
+ # the only way in: _XFORMERS_STABLE_ABI below covers the patch releases between them.
+ "2.11.0": {"cu126": "0.0.35", "cu128": "0.0.35", "cu130": "0.0.35"},
+ "2.12.0": {"cu126": "0.0.35", "cu128": "0.0.35", "cu130": "0.0.35"},
+ "2.13.0": {"cu126": "0.0.35", "cu128": "0.0.35", "cu130": "0.0.35"},
+}
+
+# The stable-ABI floor and what serves it: every torch STRICTLY ABOVE this maps to this
+# release, per CUDA family. Exact rows above still win, so a future exact-pinned wheel
+# displaces the fallback for its own release.
+#
+# An exact-key table alone refuses the patch releases: 2.10.1, 2.11.1 and 2.12.1 are all
+# supported resident builds this file names elsewhere, and each of them missed and left
+# Studio on native attention. Enumerating patches is not an option -- they are published
+# after this code ships -- and 0.0.35 is compiled against 2.10.0 by design, with upstream
+# stating that "binary builds targeting PyTorch 2.10+ will be compatible with any later
+# version". So above 2.10.0 the answer is known without a table.
+#
+# Still bounded, not open-ended in the other direction: below the floor there is no stable
+# ABI and an unlisted pair must keep resolving to nothing rather than guessing.
+_XFORMERS_STABLE_ABI_FLOOR: tuple[int, ...] = (2, 10, 0)
+_XFORMERS_STABLE_ABI_VERSIONS = {"cu126": "0.0.35", "cu128": "0.0.35", "cu130": "0.0.35"}
+
+# The interpreter tag in the wheel FILENAME, which xFormers has changed twice: 0.0.30 and
+# earlier ship one wheel per cpXY (and stop at cp312), 0.0.31..0.0.34 ship a single
+# cp39-abi3 wheel, and 0.0.35 switched to py39-none. That last switch is a PACKAGING
+# change, not an architectural one: 0.0.35's setup.py drops py_limited_api=True and
+# force-tags the wheel through a custom bdist_wheel, on the grounds that the extension
+# never bound the CPython ABI in the first place -- it is loaded by
+# torch.ops.load_library, and its _C.so defines no PyInit and references no Py* symbol.
+# The wheel still carries a per-CUDA _C.pyd; it just dropped the bundled flash_attn_3
+# kernels, which is the whole 103 MB -> 2.6 MB difference. Verified by reading the WHEEL
+# metadata, setup.py and the extension's symbol table out of each.
+#
+# Ranges, not an open-ended floor: guessing the tag for an unreleased version is how a
+# resolver starts emitting URLs that 404, so an unknown release resolves to nothing until
+# somebody checks the real filename.
+_XFORMERS_FILENAME_PYTHON_TAGS: tuple[tuple[tuple[int, ...], tuple[int, ...], str], ...] = (
+ ((0, 0, 31), (0, 0, 34), "cp39-abi3"),
+ ((0, 0, 35), (0, 0, 35), "py39-none"),
+)
+
+# platform_tag from wheel_platform_tag() -> the leaf in the wheel filename. aarch64 and
+# macOS are absent because download.pytorch.org publishes no xFormers wheel for them.
+_XFORMERS_PLATFORM_LEAVES = {
+ "linux_x86_64": "manylinux_2_28_x86_64",
+ "win_amd64": "win_amd64",
+}
+
+
+def _xformers_version_tuple(version: str) -> tuple[int, ...]:
+ """'0.0.33.post1' -> (0, 0, 33). Stops at the first non-numeric component."""
+ parts: list[int] = []
+ for chunk in str(version).split("."):
+ digits = re.sub(r"[^0-9].*", "", chunk)
+ if not digits:
+ break
+ parts.append(int(digits))
+ return tuple(parts)
+
+
+def xformers_filename_python_tag(version: str) -> str | None:
+ """The interpreter tag in an xFormers wheel filename, or None for an unknown release."""
+ parsed = _xformers_version_tuple(version)
+ if not parsed:
+ return None
+ for low, high, tag in _XFORMERS_FILENAME_PYTHON_TAGS:
+ if low <= parsed <= high:
+ return tag
+ return None
+
+
+def xformers_cuda_family(cuda_version: str | None) -> str | None:
+ """torch.version.cuda -> the download.pytorch.org index leaf ('12.8' -> 'cu128').
+
+ None for a ROCm / CPU / XPU torch, which has no xFormers wheel anywhere.
+ """
+ if not cuda_version:
+ return None
+ parts = str(cuda_version).strip().split(".")
+ try:
+ major = int(re.sub(r"[^0-9].*", "", parts[0]))
+ minor = int(re.sub(r"[^0-9].*", "", parts[1])) if len(parts) > 1 else 0
+ except (IndexError, ValueError):
+ return None
+ return f"cu{major}{minor}"
+
+
+def xformers_wheel_version(torch_version: str | None, cuda_family: str | None) -> str | None:
+ """The xFormers release for this (torch, CUDA family), else None.
+
+ An exact row wins. Failing that, any release above the stable-ABI floor resolves to the
+ wheel that serves that whole era: the exact table cannot list patch releases that are
+ published after this code ships, and refusing them left supported builds (2.11.1,
+ 2.12.1) with no xFormers at all.
+ """
+ if not torch_version or not cuda_family:
+ return None
+ # '2.10.0+cu130' -> '2.10.0'. A dev/rc torch has no wheel and must miss the table.
+ release = str(torch_version).split("+", 1)[0].strip()
+ exact = _XFORMERS_WHEEL_VERSIONS.get(release, {}).get(cuda_family)
+ if exact is not None:
+ return exact
+ # A dev/nightly/rc suffix ('2.11.0.dev20260101') is not a released torch, so it stays
+ # out: _xformers_version_tuple stops at the first non-numeric chunk, which would read
+ # it as the release itself.
+ if not re.fullmatch(r"[0-9]+(?:\.[0-9]+)*", release):
+ return None
+ if _xformers_version_tuple(release) > _XFORMERS_STABLE_ABI_FLOOR:
+ return _XFORMERS_STABLE_ABI_VERSIONS.get(cuda_family)
+ return None
+
+
+def xformers_wheel_url(env: dict[str, str] | None) -> str | None:
+ """Direct URL of the xFormers wheel matching ``env``'s torch build, else None.
+
+ None means "no matched wheel exists" and callers must install nothing rather than
+ fall back to an unpinned resolve -- an unpinned install is what produces the
+ mismatched extension in the first place.
+ """
+ if env is None:
+ return None
+ platform_leaf = _XFORMERS_PLATFORM_LEAVES.get(str(env.get("platform_tag") or ""))
+ if platform_leaf is None:
+ return None
+ family = xformers_cuda_family(env.get("cuda_version"))
+ version = xformers_wheel_version(env.get("torch_version"), family)
+ if version is None:
+ return None
+ python_tag = xformers_filename_python_tag(version)
+ if python_tag is None:
+ return None
+ return join_wheel_url(
+ pytorch_wheel_index_base_url(),
+ f"{family}/xformers-{version}-{python_tag}-{platform_leaf}.whl",
+ )
+
+
+def join_wheel_url(base: str, path: str) -> str:
+ """``base`` + ``path``, with any ?query / #fragment kept at the end.
+
+ UNSLOTH_PYTORCH_MIRROR is allowed to authenticate by query string
+ (``https://mirror/whl?token=abc``), and appending after the query put the wheel path
+ INSIDE the token value -- leaving the request path at /whl and the token unusable. The
+ tokenized private mirror this setting exists for was the one shape that could not
+ resolve a wheel.
+ """
+ cut = min([i for i in (base.find("?"), base.find("#")) if i >= 0], default = -1)
+ if cut < 0:
+ return f"{base.rstrip('/')}/{path}"
+ return f"{base[:cut].rstrip('/')}/{path}{base[cut:]}"
+
+
+def redact_url_credentials(url: str) -> str:
+ """A URL safe to log: no userinfo, no query, no fragment.
+
+ UNSLOTH_PYTORCH_MIRROR is allowed to be a private index, and people put credentials in
+ it -- ``https://user:token@mirror/whl`` or ``...?token=``. The wheel URL built from it
+ is handed to pip AND printed, so without this the secret lands in the backend log the
+ first time Studio installs (or fails to install) xFormers. Same rule as the installer's
+ Remove-IndexUrlCredentials, so both sides redact identically.
+ """
+ separator = url.find("://")
+ if separator < 0:
+ return url
+ scheme, rest = url[:separator], url[separator + 3 :]
+ cut = min([i for i in (rest.find("?"), rest.find("#")) if i >= 0], default = -1)
+ if cut >= 0:
+ rest = rest[:cut]
+ slash = rest.find("/")
+ authority, path = (rest[:slash], rest[slash:]) if slash >= 0 else (rest, "")
+ at = authority.rfind("@")
+ if at >= 0:
+ authority = authority[at + 1 :]
+ return f"{scheme}://{authority}{path}"
+
+
def flash_attn_package_version(torch_mm: str) -> str | None:
if torch_mm == "2.10":
# Newest flash-attn release still carrying the full torch2.10 asset
diff --git a/tests/python/test_windows_xformers_installer.py b/tests/python/test_windows_xformers_installer.py
new file mode 100644
index 00000000000..ff6d6b48245
--- /dev/null
+++ b/tests/python/test_windows_xformers_installer.py
@@ -0,0 +1,352 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""install.ps1 must install the xFormers wheel built for the torch it installed.
+
+Before this, install.ps1 never mentioned xFormers at all: it installed torch from a
+cu126 / cu128 / cu130 index and then plain `unsloth`, whose `windows` extra pulled
+xFormers from PyPI -- which publishes only the CUDA-12.8 flavour. On a cu130 host that
+produced the NVIDIA QA report "xFormers was built for PyTorch 2.10.0+cu128 with CUDA
+1208 (you have 2.10.0+cu130)", with memory-efficient attention silently disabled.
+"""
+
+from __future__ import annotations
+
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+INSTALL_PS1 = REPO_ROOT / "install.ps1"
+
+
+def _source() -> str:
+ return INSTALL_PS1.read_text(encoding = "utf-8")
+
+
+def _extract(pattern: str, source: str) -> str:
+ match = re.search(pattern, source, flags = re.DOTALL | re.MULTILINE)
+ assert match is not None, f"installer block not found: {pattern}"
+ return match.group(0)
+
+
+def _selector_harness() -> str:
+ """`$script:XformersWheelVersions` + the two pure helpers, ready to dot-source."""
+ source = _source()
+ return "\n".join(
+ (
+ _extract(r"^ \$script:XformersWheelVersions = @\{.*?^ \}", source),
+ _extract(r"^ \$script:XformersStableAbiFloor = [^\n]*", source),
+ _extract(r"^ \$script:XformersStableAbiVersion = [^\n]*", source),
+ _extract(r"^ \$script:XformersStableAbiFamilies = [^\n]*", source),
+ _extract(r"^ function ConvertTo-TorchFlavorTag \{.*?^ \}", source),
+ _extract(r"^ function ConvertTo-TorchReleaseVersion \{.*?^ \}", source),
+ _extract(r"^ function Get-XformersWheelVersion \{.*?^ \}", source),
+ _extract(r"^ function Get-XformersExpectedTorchBuild \{.*?^ \}", source),
+ _extract(r"^ function Get-XformersFilenamePythonTag \{.*?^ \}", source),
+ )
+ )
+
+
+def _run_pwsh(script: str) -> str:
+ result = subprocess.run(
+ ["pwsh", "-NoProfile", "-NonInteractive", "-Command", script],
+ check = True,
+ capture_output = True,
+ text = True,
+ )
+ return result.stdout.strip()
+
+
+# (torch.__version__, expected xFormers version or "" for "no wheel, install nothing").
+# The live wheels behind each row were HEAD-verified on download.pytorch.org and their
+# xformers/cpp_lib.json read back -- cu130/xformers-0.0.34 reports {"torch":
+# "2.10.0+cu130"}, cu128/xformers-0.0.34 reports {"torch": "2.10.0+cu128"}.
+SELECTION_CASES = [
+ ("2.10.0+cu130", "0.0.34"),
+ ("2.10.0+cu128", "0.0.34"),
+ ("2.10.0+cu126", "0.0.34"),
+ ("2.9.1+cu130", "0.0.33.post2"),
+ ("2.9.1+cu128", "0.0.33.post2"),
+ ("2.9.0+cu130", "0.0.33.post1"),
+ ("2.9.0+cu126", "0.0.33.post1"),
+ ("2.8.0+cu129", "0.0.32.post2"),
+ ("2.7.1+cu128", "0.0.31.post1"),
+ # 0.0.30 predates the abi3 switch and has no cp313 wheel; the row is deliberately gone.
+ ("2.7.0+cu128", ""),
+ # No cu130 build of xFormers exists for torch 2.8 or earlier, and no cu118 /
+ # cu124 win_amd64 build exists at all -- refuse rather than serve a neighbour.
+ ("2.8.0+cu130", ""),
+ ("2.9.0+cu118", ""),
+ ("2.10.0+cu124", ""),
+ # torch 2.11+ resolves to 0.0.35. It is built against 2.10.0 and loads there by
+ # design: xFormers moved to the PyTorch stable API/ABI in 0.0.34, whose notes state
+ # such builds are "compatible with any later version".
+ ("2.11.0+cu130", "0.0.35"),
+ ("2.13.0+cu128", "0.0.35"),
+ # And so does every release above the floor that the table cannot list, because they
+ # are published after this script ships. Refusing them left supported builds with no
+ # xFormers at all.
+ ("2.10.1+cu130", "0.0.35"),
+ ("2.11.1+cu128", "0.0.35"),
+ ("2.12.4+cu126", "0.0.35"),
+ ("2.14.0+cu130", "0.0.35"),
+ # Bounded in both directions: below the floor there is no stable ABI to lean on, and a
+ # CUDA family that publishes nothing gains no wheel from the era.
+ ("2.9.2+cu130", ""),
+ ("2.12.0+cu124", ""),
+ # Non-CUDA and nightly builds must miss the table outright.
+ ("2.10.0+cpu", ""),
+ ("2.10.0+rocm6.4", ""),
+ ("2.10.0.dev20260101+cu130", ""),
+]
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
[email protected](("torch_version", "expected"), SELECTION_CASES)
+def test_selector_picks_the_matching_wheel(torch_version: str, expected: str):
+ out = _run_pwsh(
+ f"{_selector_harness()}\n"
+ f"$v = '{torch_version}'\n"
+ "$tag = ConvertTo-TorchFlavorTag $v\n"
+ "$sel = Get-XformersWheelVersion -TorchVersion $v -CudaTag $tag\n"
+ 'Write-Output "[$sel]"\n'
+ )
+ assert out == f"[{expected}]", f"{torch_version} selected {out}, expected [{expected}]"
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+def test_selector_refuses_a_missing_or_blank_input():
+ out = _run_pwsh(
+ f"{_selector_harness()}\n"
+ "Write-Output \"[$(Get-XformersWheelVersion -TorchVersion '' -CudaTag 'cu130')]\"\n"
+ "Write-Output \"[$(Get-XformersWheelVersion -TorchVersion '2.10.0+cu130' -CudaTag '')]\"\n"
+ )
+ assert out.splitlines() == ["[]", "[]"]
+
+
+def test_installer_installs_xformers_from_the_torch_index():
+ source = _source()
+ block = _extract(r" # ── Pin xFormers to the wheel built for the torch.*?^ \}\n", source)
+ assert "--no-deps" in block, (
+ "the xFormers wheel declares torch==<exact release>; without --no-deps uv can pull "
+ "a PyPI (CUDA 12.8) torch over the CUDA build just installed"
+ )
+ assert "--reinstall-package xformers" in block, (
+ "cu126/cu128/cu130 publish the SAME xformers version string, so a wrong-CUDA wheel "
+ "is invisible to a version check and must be force-replaced"
+ )
+ assert "--default-index $_xfIndexUrl" in block
+ assert "xformers==$_xfVersion" in block
+ assert "UNSLOTH_SKIP_XFORMERS" in block
+ # A full-URL index pin is authoritative and is reused WHOLE. Its leaf is not required
+ # to name the CUDA family: a documented full-URL override can be an authenticated
+ # mirror, and rebuilding a download.pytorch.org URL over it strands an air-gapped host.
+ assert (
+ "if ($TorchIndexUrl -and -not [string]::IsNullOrWhiteSpace($env:UNSLOTH_TORCH_INDEX_URL))"
+ in block
+ )
+ # The leaf is read to BUILD a URL under the override, never to throw the override away:
+ # a full-URL override can be an authenticated mirror whose leaf is not a family, and
+ # rebuilding a download.pytorch.org URL over it strands an air-gapped host.
+ assert "$_xfIndexUrl = $TorchIndexUrl" in block
+ # Unpinned, install the direct wheel URL: --default-index does not make an index
+ # exclusive, and cu126/cu128/cu130 share a version string, so a machine with UV_INDEX
+ # set can satisfy the pin from the wrong CUDA family.
+ assert '$_xfWheelUrl = Join-UrlPath $_xfBase "$_xfCudaTag/$_xfWheelName"' in block
+ assert "--reinstall-package xformers $_xfWheelUrl" in block
+ # The already-installed check compares against the wheel's OWN build target, not the
+ # resident torch: the stable-ABI wheel records the floor release it was compiled
+ # against, so the old comparison force-reinstalled a correct 0.0.35 on every run.
+ assert "Get-XformersExpectedTorchBuild -Version $_xfVersion" in block
+
+
+def test_a_family_pin_still_gets_the_direct_wheel_url():
+ """UNSLOTH_TORCH_INDEX_FAMILY sets $TorchIndexPinned too, so keying the index branch off
+ that flag sent a plain `cu130` pin down --default-index -- and uv's --index / UV_INDEX
+ are used "in addition to" the default one, so a machine-level UV_INDEX carrying the same
+ xFormers version could satisfy the pin from the wrong CUDA family, which is the failure
+ this step exists to prevent. A family pin names a leaf, so a direct URL can be built for
+ it; only a full-URL override (possibly an authenticated mirror we cannot rebuild) has to
+ go through the index."""
+ block = _extract(
+ r" # ── Pin xFormers to the wheel built for the torch.*?^ \}\n", _source()
+ )
+ condition = re.search(r"if \(\$TorchIndexUrl[^\n]*\) \{", block)
+ assert condition is not None, "the index branch must be gated on the full-URL override"
+ assert "UNSLOTH_TORCH_INDEX_URL" in condition.group(0)
+ assert "$TorchIndexPinned" not in condition.group(0)
+ # ...and the family-pin side builds a URL rather than resolving a version.
+ assert '$_xfWheelUrl = Join-UrlPath $_xfBase "$_xfCudaTag/$_xfWheelName"' in block
+
+
+def test_a_full_url_override_naming_a_cuda_leaf_gets_a_direct_url():
+ """`--default-index` is not exclusive -- uv reads UV_INDEX "in addition to" it -- and every
+ CUDA family publishes the same xFormers version, so an index resolve can always be
+ satisfied from the wrong one. A documented `.../cu130` override names the leaf, so the
+ wheel is addressed under it directly, which nothing can substitute for."""
+ block = _extract(
+ r" # ── Pin xFormers to the wheel built for the torch.*?^ \}\n", _source()
+ )
+ assert "$_xfOverrideLeaf = Get-TorchIndexLeafName $TorchIndexUrl" in block
+ assert "'^cu\\d+$'" in block
+ assert "$_xfWheelUrl = Join-UrlPath $TorchIndexUrl $_xfWheelName" in block
+
+
+def test_the_index_fallback_hides_the_machine_level_indexes():
+ """The one path that still resolves rather than fetching a URL: a mirror root whose leaf
+ is not a CUDA family. UV_INDEX / UV_EXTRA_INDEX_URL are cleared around that call so the
+ chosen index really is the only one, and restored afterwards."""
+ block = _extract(
+ r" # ── Pin xFormers to the wheel built for the torch.*?^ \}\n", _source()
+ )
+ assert "$env:UV_INDEX = $null" in block
+ assert "$env:UV_EXTRA_INDEX_URL = $null" in block
+ assert "$env:UV_INDEX = $_xfSavedIndex" in block
+ assert "$env:UV_EXTRA_INDEX_URL = $_xfSavedExtra" in block
+ assert "} finally {" in block, "the restore must survive a failing install"
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+def test_the_url_join_keeps_a_tokenized_mirrors_query():
+ """Executed, not read: a private mirror may authenticate by query string, and appending
+ after the query put the wheel path inside the token value -- request path still /whl,
+ token unusable. Same rule as the Python side's join_wheel_url."""
+ joiner = _extract(r"^ function Join-UrlPath \{.*?^ \}", _source())
+ out = _run_pwsh(
+ f"{joiner}\n"
+ "Write-Output (Join-UrlPath 'https://m/whl?token=abc' 'cu130/x.whl')\n"
+ "Write-Output (Join-UrlPath 'https://m/whl/' 'cu130/x.whl')\n"
+ "Write-Output (Join-UrlPath 'https://m/whl#f' 'cu130/x.whl')\n"
+ )
+ assert out.splitlines() == [
+ "https://m/whl/cu130/x.whl?token=abc",
+ "https://m/whl/cu130/x.whl",
+ "https://m/whl/cu130/x.whl#f",
+ ]
+
+
+def test_installer_never_installs_an_unpinned_xformers():
+ """A bare `xformers` resolves to whatever the index serves newest, which is not
+ necessarily built for the CUDA family the resident torch came from. The installer
+ picks the exact version for (torch, cuda) instead, so every spec must be pinned."""
+ source = _source()
+ for match in re.finditer(r'"xformers[^"]*"', source):
+ spec = match.group(0)
+ # A wheel FILENAME is not a spec: it names one exact file and cannot resolve to
+ # anything else, which is the whole point of preferring it.
+ if spec.endswith('.whl"'):
+ continue
+ assert spec == '"xformers==$_xfVersion"', f"unpinned xFormers spec in install.ps1: {spec}"
+
+
+def test_xformers_step_runs_after_the_torch_flavor_repair():
+ """The repair can reinstall torch from a different index; selecting the wheel before it
+ would pin against a torch build that is about to be replaced."""
+ source = _source()
+ repair = source.index("Enforce the installed torch flavor matches the detected GPU build")
+ xformers = source.index("Pin xFormers to the wheel built for the torch")
+ overlay = source.index("CI only: overlay a source checkout")
+ assert repair < xformers < overlay
+
+
+def test_xformers_step_is_skipped_for_no_torch_installs():
+ block = _extract(
+ r" # ── Pin xFormers to the wheel built for the torch.*?^ \}\n", _source()
+ )
+ assert "if (-not $SkipTorch" in block
+ # cu<digits> only: cpu / rocm / xpu torch has no xFormers wheel on any index.
+ assert "'^cu\\d+$'" in block
+
+
+def test_installed_build_probe_reads_cpp_lib_json():
+ """The version string cannot distinguish cu128 from cu130, so the repair check has to read
+ the build metadata xFormers itself reports in its error message."""
+ block = _extract(r" function Get-InstalledXformersBuild \{.*?^ \}", _source())
+ assert "cpp_lib.json" in block
+ assert "find_spec" in block
+ # Reading the file rather than importing xformers keeps a mismatched .pyd from writing
+ # its own warning into the probe output. Every release from 0.0.31 on ships
+ # cpp_lib.json, 0.0.35 included, so absence means an unbuilt or source install.
+ assert "import xformers" not in block
+ # Invoke-BoundedPythonProbe interpolates the code into a double-quoted -c argument.
+ assert '"' not in block.split("$code = ", 1)[1].split("\n", 1)[0].strip("'")
+
+
+# Torch releases the exact tables cannot list, and the answer both selectors must give.
+# The two implementations resolve the same machine (install.ps1 during install, wheel_utils
+# on demand from Studio), so a fallback that lives in only one of them is a machine whose
+# answer changes depending on which one asked.
+STABLE_ABI_PARITY_CASES = [
+ ("2.10.1+cu130", "13.0", "0.0.35"),
+ ("2.11.1+cu128", "12.8", "0.0.35"),
+ ("2.12.4+cu126", "12.6", "0.0.35"),
+ ("2.14.0+cu130", "13.0", "0.0.35"),
+ ("2.9.2+cu130", "13.0", ""),
+ ("2.12.0+cu124", "12.4", ""),
+]
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
[email protected](("torch_version", "cuda_version", "expected"), STABLE_ABI_PARITY_CASES)
+def test_both_selectors_agree_outside_the_exact_tables(torch_version, cuda_version, expected):
+ import sys
+
+ sys.path.insert(0, str(REPO_ROOT / "studio" / "backend"))
+ try:
+ from utils import wheel_utils
+ finally:
+ sys.path.pop(0)
+
+ family = wheel_utils.xformers_cuda_family(cuda_version)
+ python_side = wheel_utils.xformers_wheel_version(torch_version, family) or ""
+ ps_side = _run_pwsh(
+ f"{_selector_harness()}\n"
+ f"$v = '{torch_version}'\n"
+ "$tag = ConvertTo-TorchFlavorTag $v\n"
+ 'Write-Output "[$(Get-XformersWheelVersion -TorchVersion $v -CudaTag $tag)]"\n'
+ )
+ assert python_side == expected
+ assert ps_side == f"[{expected}]"
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+def test_the_already_installed_check_uses_the_wheels_own_build_target():
+ """A resident 0.0.35 records the torch it was COMPILED against (the stable-ABI floor),
+ not the torch it is running under. Comparing against the resident torch made every
+ correct install look mismatched, so each run force-reinstalled a good wheel -- and
+ warned about a failed xFormers install whenever the index was unreachable."""
+ out = _run_pwsh(
+ f"{_selector_harness()}\n"
+ "Write-Output \"[$(Get-XformersExpectedTorchBuild -Version '0.0.35' "
+ "-TorchVersion '2.12.1+cu130' -CudaTag 'cu130')]\"\n"
+ "Write-Output \"[$(Get-XformersExpectedTorchBuild -Version '0.0.34' "
+ "-TorchVersion '2.10.0+cu128' -CudaTag 'cu128')]\"\n"
+ )
+ # The stable-ABI wheel reports the floor release; an exact-era wheel reports the torch
+ # it was pinned to, which is the resident one.
+ assert out.splitlines() == ["[2.10.0+cu130]", "[2.10.0+cu128]"]
+
+
[email protected](shutil.which("pwsh") is None, reason = "PowerShell is unavailable")
+def test_the_direct_wheel_filename_tag_matches_the_python_resolver():
+ import sys
+
+ sys.path.insert(0, str(REPO_ROOT / "studio" / "backend"))
+ try:
+ from utils import wheel_utils
+ finally:
+ sys.path.pop(0)
+
+ versions = ["0.0.31.post1", "0.0.32.post2", "0.0.33.post2", "0.0.34", "0.0.35"]
+ ps_out = _run_pwsh(
+ f"{_selector_harness()}\n"
+ + "\n".join(f"Write-Output \"[$(Get-XformersFilenamePythonTag '{v}')]\"" for v in versions)
+ )
+ assert ps_out.splitlines() == [
+ f"[{wheel_utils.xformers_filename_python_tag(v)}]" for v in versions
+ ]
diff --git a/tests/python/test_windows_xformers_wheel_match.py b/tests/python/test_windows_xformers_wheel_match.py
new file mode 100644
index 00000000000..4865bafcc9f
--- /dev/null
+++ b/tests/python/test_windows_xformers_wheel_match.py
@@ -0,0 +1,199 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
+
+"""xFormers must match the CUDA build of the resident torch on Windows.
+
+xformers/_C.pyd is linked against ONE exact (torch, CUDA) pair. Loaded next to any
+other pair, ``torch.ops.load_library`` raises and xformers/_cpp_lib.py swallows it
+into a warning -- memory-efficient attention, SwiGLU and the sparse ops all vanish
+while the import still "succeeds". PyPI publishes only the CUDA-12.8 flavour, so a
+cu130 install that resolves xformers from PyPI loses every kernel silently.
+
+These tests pin the two halves of the fix that live in pyproject.toml:
+ * the CUDA-matched Windows route (the cuXXX-torchYYY extras) really does resolve
+ to a win_amd64 wheel from the MATCHING CUDA index, and
+ * the CUDA-agnostic ``windows`` extra can no longer float onto an arbitrary
+ xFormers release.
+"""
+
+from __future__ import annotations
+
+import re
+import sys
+from pathlib import Path
+
+import pytest
+
+
+REPO_ROOT = Path(__file__).resolve().parents[2]
+PYPROJECT = REPO_ROOT / "pyproject.toml"
+
+WHEEL_INDEX_BASE = "https://download.pytorch.org/whl"
+
+# (CUDA family, torch release) -> xFormers version, i.e. the wheel that index
+# actually publishes for that torch. Every row was HEAD-verified as live on
+# download.pytorch.org, and the cu128/cu130 0.0.34 wheels were downloaded and
+# their xformers/cpp_lib.json read back:
+# cu128 -> {"cuda": 1208, "torch": "2.10.0+cu128"}
+# cu130 -> {"cuda": 1300, "torch": "2.10.0+cu130"}
+# Keep this in step with _XFORMERS_WHEEL_VERSIONS in
+# studio/backend/utils/wheel_utils.py and $script:XformersWheelVersions in
+# install.ps1 -- test_xformers_matrix_agrees_with_wheel_utils below enforces it.
+XFORMERS_WHEEL_MATRIX: dict[tuple[str, str], str] = {
+ ("cu126", "290"): "0.0.33.post1",
+ ("cu128", "290"): "0.0.33.post1",
+ ("cu130", "290"): "0.0.33.post1",
+ ("cu126", "291"): "0.0.33.post2",
+ ("cu128", "291"): "0.0.33.post2",
+ ("cu130", "291"): "0.0.33.post2",
+ ("cu126", "2100"): "0.0.34",
+ ("cu128", "2100"): "0.0.34",
+ ("cu130", "2100"): "0.0.34",
+}
+
+# torch 2.11 publishes no xFormers wheel on any index yet, and the Windows torch
+# pin in install.ps1 is torch<2.11.0 for exactly that kind of reason. Assert the
+# absence so a future 2.11 row has to be added deliberately (with a live wheel)
+# rather than inherited from 2.10 -- xFormers' extension ABI does not survive a
+# torch minor bump, so reusing the 2.10 wheel there would reintroduce this bug.
+TORCH_RELEASES_WITHOUT_XFORMERS_WHEELS = ("2110",)
+
+
+def _tomllib():
+ if sys.version_info >= (3, 11):
+ import tomllib
+ return tomllib
+ return pytest.importorskip("tomli")
+
+
+def _extras() -> dict[str, list[str]]:
+ tomllib = _tomllib()
+ return tomllib.loads(PYPROJECT.read_text(encoding = "utf-8"))["project"]["optional-dependencies"]
+
+
+def _windows_xformers_urls(deps: list[str]) -> list[str]:
+ """Every xformers direct-URL dep in ``deps`` whose marker holds on Windows x64."""
+ markers = pytest.importorskip("packaging.markers")
+ env = {
+ "sys_platform": "win32",
+ "platform_machine": "AMD64",
+ "platform_system": "Windows",
+ "os_name": "nt",
+ "python_version": "3.13",
+ "python_full_version": "3.13.2",
+ "implementation_name": "cpython",
+ "platform_python_implementation": "CPython",
+ }
+ urls: list[str] = []
+ for dep in deps:
+ spec, _, marker_text = dep.partition(";")
+ if "xformers @ " not in spec:
+ continue
+ if marker_text.strip() and not markers.Marker(marker_text.strip()).evaluate(env):
+ continue
+ urls.append(spec.split("@", 1)[1].strip())
+ return urls
+
+
[email protected](("family", "torch_tag"), sorted(XFORMERS_WHEEL_MATRIX))
+def test_windows_resolves_a_cuda_matched_wheel(family: str, torch_tag: str):
+ """`unsloth[cu128-torch2100]` / `unsloth[cu130-torch2100]` and friends must land on
+ a win_amd64 wheel served by their OWN CUDA index -- never PyPI, never a neighbour's."""
+ version = XFORMERS_WHEEL_MATRIX[(family, torch_tag)]
+ deps = _extras()[f"{family}onlytorch{torch_tag}"]
+ urls = _windows_xformers_urls(deps)
+
+ assert len(urls) == 1, (
+ f"{family}onlytorch{torch_tag} must resolve exactly one xformers wheel on "
+ f"Windows, got {urls}"
+ )
+ assert urls[0] == (f"{WHEEL_INDEX_BASE}/{family}/xformers-{version}-cp39-abi3-win_amd64.whl")
+
+
[email protected](("family", "torch_tag"), sorted(XFORMERS_WHEEL_MATRIX))
+def test_aggregate_extra_pulls_in_the_matched_wheel(family: str, torch_tag: str):
+ """The user-facing `cuXXX-torchYYY` extra must reference the `only` extra that
+ carries the win_amd64 row, else the Windows route documented in pyproject.toml
+ silently degrades to whatever `unsloth[huggingface]` drags in."""
+ aggregate = _extras()[f"{family}-torch{torch_tag}"]
+ assert f"unsloth[{family}onlytorch{torch_tag}]" in aggregate
+
+
[email protected]("torch_tag", TORCH_RELEASES_WITHOUT_XFORMERS_WHEELS)
+def test_no_extras_invented_for_torch_without_xformers_wheels(torch_tag: str):
+ extras = _extras()
+ # CUDA extras only -- the intel-gpu-torch2110 / intelgputorch2110 XPU extras carry
+ # no xformers row and are not affected.
+ pattern = re.compile(rf"^cu\d+(?:only)?-?torch{torch_tag}$")
+ offenders = [n for n in extras if pattern.match(n)]
+ assert offenders == [], (
+ f"no xFormers wheel is published for torch {torch_tag}; extras {offenders} "
+ "would resolve a wheel built for a different torch minor"
+ )
+
+
+def test_windows_extra_xformers_spec_is_a_version_range():
+ """The windows extra is the CUDA-agnostic fallback, so it must stay a plain range.
+
+ It is deliberately uncapped. 0.0.35 declares torch>=2.10 rather than an exact pin
+ because xFormers moved to the PyTorch stable API/ABI in 0.0.34, and upstream states
+ that such builds "will be compatible with any later version". A cap would also strand
+ anyone on torch 2.10.1, since 0.0.34 pins torch==2.10.0 exactly. The CUDA family is
+ the axis that has to match, and this extra cannot see it -- install.ps1 does that.
+ """
+ deps = _extras()["windows"]
+ specs = [d for d in deps if d.split(";")[0].strip().startswith("xformers")]
+ assert len(specs) == 1, f"expected one xformers spec in the windows extra, got {specs}"
+ spec = specs[0].split(";")[0].strip()
+ assert "xformers @ " not in spec, (
+ "the windows extra is the CUDA-agnostic fallback and must stay a version range; "
+ "a direct URL here hard-pins torch for every Windows user"
+ )
+
+
+def test_windows_extra_documents_the_cuda_matched_route():
+ """The comment block is load bearing: it is the only place a Windows user is told
+ that `unsloth[windows]` cannot pick a CUDA-matched wheel and `unsloth[cu130-torch2100]`
+ can. Losing it is how this regressed the first time."""
+ text = PYPROJECT.read_text(encoding = "utf-8")
+ header = text.split("\nwindows = [", 1)[0]
+ assert "unsloth[cu130-torch2100]" in header
+ assert "unsloth[cu128-torch2100]" in header
+
+
+def test_xformers_matrix_agrees_with_wheel_utils():
+ """One matrix, three consumers (pyproject, wheel_utils, install.ps1). Drift here is
+ exactly the bug: a runtime resolver that disagrees with the packaged pin."""
+ source = (REPO_ROOT / "studio" / "backend" / "utils" / "wheel_utils.py").read_text(
+ encoding = "utf-8"
+ )
+ body = re.search(
+ r"_XFORMERS_WHEEL_VERSIONS[^=]*=\s*\{(.*?)^\}", source, re.DOTALL | re.MULTILINE
+ )
+ assert body, "could not find _XFORMERS_WHEEL_VERSIONS in wheel_utils.py"
+ for (family, torch_tag), version in XFORMERS_WHEEL_MATRIX.items():
+ release = f"{torch_tag[0]}.{torch_tag[1:-1]}.{torch_tag[-1]}" # "2100" -> "2.10.0"
+ row = re.search(rf'^\s*"{re.escape(release)}":\s*\{{(.*?)\}}', body.group(1), re.MULTILINE)
+ assert row, f"wheel_utils has no row for torch {release}"
+ assert f'"{family}": "{version}"' in row.group(1), (
+ f"wheel_utils torch {release} row must map {family} -> {version}, got "
+ f"{row.group(1)!r}"
+ )
+
+
+def test_install_ps1_matrix_agrees_with_pyproject():
+ source = (REPO_ROOT / "install.ps1").read_text(encoding = "utf-8")
+ body = re.search(
+ r"\$script:XformersWheelVersions\s*=\s*@\{(.*?)^\s*\}", source, re.DOTALL | re.MULTILINE
+ )
+ assert body, "could not find $script:XformersWheelVersions in install.ps1"
+ for (family, torch_tag), version in XFORMERS_WHEEL_MATRIX.items():
+ release = f"{torch_tag[0]}.{torch_tag[1:-1]}.{torch_tag[-1]}"
+ row = re.search(
+ rf'^\s*"{re.escape(release)}"\s*=\s*@\{{(.*?)\}}', body.group(1), re.MULTILINE
+ )
+ assert row, f"install.ps1 has no row for torch {release}"
+ assert f'"{family}" = "{version}"' in row.group(1), (
+ f"install.ps1 torch {release} row must map {family} -> {version}, got "
+ f"{row.group(1)!r}"
+ )