mirror of
https://github.com/unslothai/unsloth.git
synced 2026-08-09 08:54:06 +00:00
* install: let UNSLOTH_TORCH_INDEX_FAMILY / _URL override CUDA wheel detection
get_torch_index_url (and the studio-update mirror _detect_cuda_torch_index_url)
chose the torch wheel family solely by probing the host GPU, with no override.
In a headless / container / CI build the host driver is visible via the
/proc/driver/nvidia/gpus fallback but nvidia-smi cannot report a CUDA version,
so the function fell back to its cu126 default and installed the wrong wheels
(e.g. a cu128 image got cu126 torch).
Add an explicit override checked before any probing, in both the shell installer
and the Python studio-update path:
- UNSLOTH_TORCH_INDEX_URL full index URL, used verbatim (wins)
- UNSLOTH_TORCH_INDEX_FAMILY family (cpu, cu128, rocm6.4, ...) appended to the
mirror base (UNSLOTH_PYTORCH_MIRROR still honoured)
This matches how the published GPU images select CUDA -- vLLM and SGLang take the
CUDA version from an explicit build ARG rather than detecting it, and the Unsloth
Docker base image already pins the cu128 index directly. Desktop installs are
unchanged: with no override set, detection runs exactly as before.
Adds test_get_torch_index_url.sh cases for the override (family, full URL,
precedence, mirror base, trailing-slash strip, empty-ignored).
* install: make the torch-index override authoritative across ROCm paths
Address review feedback on the override added in this PR so a pinned index is
honoured everywhere, not just in get_torch_index_url:
- Skip the WSL ROCm bootstrap (root privilege + large downloads, probes
/dev/dxg) when UNSLOTH_TORCH_INDEX_URL / _FAMILY is set; it previously ran
before the override was consulted.
- Skip the Radeon/Strix rerouting (which re-probes the GPU and overwrites the
resolved URL with repo.radeon.com / repo.amd.com) when the index is pinned, so
an explicit ROCm override (e.g. UNSLOTH_TORCH_INDEX_FAMILY=rocm6.4) is kept.
- install_python_stack.py: derive _TORCH_BACKEND from the override when
UNSLOTH_TORCH_BACKEND is unset (standalone studio update), so _ensure_rocm_torch
/ _ensure_cuda_torch repair to the requested family instead of re-detecting.
- Strip ALL leading/trailing slashes in the shell override to match the Python
side (avoids 404s on strict pip proxies).
Adds test cases for double-slash and leading/trailing-slash overrides.
* install: honor pinned torch index in CUDA/ROCm repair paths
Follow-up to the override work in this PR: the get_torch_index_url / install.sh
reroute already respect a pinned UNSLOTH_TORCH_INDEX_URL / _FAMILY, but the
Python repair helpers in install_python_stack.py still re-probed the GPU and
could overwrite the pinned family. Make the pin authoritative there too:
- _ensure_cuda_torch: an explicit cu* pin commits to CUDA wheels, so repair a
ROCm-poisoned venv even when no NVIDIA GPU is visible here (headless /
container / CI cross-install), instead of bailing on the GPU-presence gate.
- _ensure_rocm_torch: skip the AMD per-gfx (Strix) reroute when a ROCm index is
pinned, and in the generic reinstall path install from the pinned URL verbatim
rather than re-detecting the host ROCm version. gfx*/rocm7.2 indexes serve
torch 2.11+, so select the 2.11 package specs for a gfx leaf.
- install.sh: raise the torch constraint to 2.11 for */gfx* indexes too, matching
rocm7.2, so a pinned full-URL/family override that returns early keeps a valid
constraint.
Add _explicit_torch_index_url / _explicit_rocm_torch_index_url helpers and tests
covering the no-GPU CUDA pin repair and the explicit gfx index honored verbatim.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: honor torch-index override on the Windows installers too
The pinned-index work landed for install.sh and install_python_stack.py, but the
Windows installers still picked the wheel index from GPU probing. Extend the same
UNSLOTH_TORCH_INDEX_URL / _FAMILY contract so a pinned index wins on every platform:
- install.ps1: Get-TorchIndexUrl returns the pinned URL/family before nvidia-smi
probing; the AMD ROCm reroute is skipped when the index is pinned, so an explicit
cpu/cu* pin on an AMD host is not overwritten.
- studio/setup.ps1: add shared Get-PinnedTorchIndexUrl / Get-TorchIndexLeaf helpers;
the stale-venv check, the install selection and the AMD reroute all honor the pin,
and the CPU/CUDA install pulls from the resolved index URL.
- tests: parity test that all four installers read both override vars and the two
Windows installers gate the AMD reroute on the pinned flag.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: complete pinned-index handling for ROCm/Windows edge cases
Follow-ups to the override work flagged in review:
- install.ps1: a pinned gfx*/rocm>=7.2 index previously skipped the AMD reroute
that sets the torch>=2.11 floor, so the generic install used torch>=2.4,<2.11
and could resolve the known-bad _grouped_mm wheel. Route a pinned ROCm index
through the ROCm install path with the 2.11 floor + companions, and guard the
companion-spec lookup so a skipped reroute block cannot null-deref.
- studio/setup.ps1: the stale-venv check compared the installed flavor (cuXXX/cpu,
with +rocm misread as cpu) against the raw pinned leaf (gfx1151 / rocm6.4), so a
correct pinned ROCm venv was always marked stale. Classify +rocm wheels as the
generic 'rocm' flavor and normalize a pinned rocm*/gfx* leaf to 'rocm' before
comparing (cu* stays specific so cu126-vs-cu128 still rebuilds).
- install_python_stack.py: _ensure_cuda_torch now also reinstalls from a pinned
CUDA index when the venv carries a CPU wheel (headless CPU-venv-to-CUDA
cross-install via 'studio update'), not only when it finds a ROCm build.
- tests: parity assertions already cover all four installers honoring the override.
* install: finish pinned ROCm/CUDA edge cases on Windows + repair path
Follow-ups to the previous round:
- studio/setup.ps1: a pinned gfx*/rocm>=7.2 index now routes through the ROCm
install path with the 2.11 floor + companions (it previously fell through to the
CUDA branch with bare torch/torchvision/torchaudio against the ROCm index). The
CPU/CUDA fallback index is forced to the CPU wheel index when a ROCm index is
active, so a failed pinned-ROCm install does not retry the ROCm mirror.
- studio/setup.ps1: the stale-venv check no longer treats an unrecognized pinned
URL leaf (e.g. a PEP 503 mirror ending in /simple) as a torch flavor tag, which
was marking a correct venv stale; cu*/cpu/rocm/gfx leaves are still compared.
- install.ps1: the post-failure CPU fallback uses an explicit CPU index instead of
, which for a pinned ROCm index was the ROCm mirror itself (so the
'fallback' just retried the failing index and aborted the installer).
- install_python_stack.py: _ensure_cuda_torch now also reinstalls when the venv's
CUDA family differs from a pinned one (installed cu126 vs pinned cu128), not only
CPU->CUDA; the probe reports the installed cuXXX tag for the comparison.
* install: keep the ROCm to CPU fallback install inside the retry-helper window
The pinned-ROCm CPU fallback computes an explicit CPU index, but the comment
explaining why it cannot reuse $TorchIndexUrl pushed the actual
Invoke-InstallCommandRetry / --force-reinstall call more than 600 chars past the
"ROCm PyTorch install failed" message, so test_pr5940_followups's window check
no longer saw the retry helper. Move the CPU-index computation and its comment
above the failure substep so the retrying force-reinstall stays adjacent to the
message. No behavior change: same explicit CPU index, same retry, same
--force-reinstall.
* install: address #6692 review round 5 (ROCm/CPU pin edge cases)
setup.ps1:
- Stale-venv check: treat an AMD/ROCm host (HasROCm or a resolved gfx arch) with
no explicit pin as expecting "rocm", not "cpu", so a healthy +rocm venv is not
flagged stale (which made installer-managed setup exit and direct update rebuild).
- Pinned-ROCm install failure now routes into the force-reinstall CPU branch:
CuTag stays the rocm/gfx leaf on failure, so the condition also checks
ROCmCpuFallback; otherwise the CUDA branch installed from the CPU index without
--force-reinstall and kept the partial ROCm torch.
- Explicit ROCm pin compare no longer collapses gfx*/rocm* to a generic "rocm":
it compares the +rocmX.Y version (and the torch 2.11 line for gfx pins) so
changing the pinned family (e.g. rocm6.4 -> gfx1151) rebuilds and applies it.
install_python_stack.py:
- _ensure_rocm_torch: an explicit ROCm wheel-index pin now bypasses the
NVIDIA-present / no-AMD-GPU / unreadable-ROCm gates (headless/container/CI
cross-install), mirroring the explicit-CUDA-pin bypass in _ensure_cuda_torch.
- Add _ensure_cpu_torch: an explicit CPU pin (FAMILY=cpu or /cpu URL) now has a
repair path that reinstalls CPU torch over an existing CUDA/ROCm build on a
standalone update (which skips install.sh's flavor enforcement).
install.sh:
- Pin torchvision/torchaudio companions alongside torch for the rocm7.2 / per-gfx
index and the Strix reroute (those AMD indexes publish companions independently
and a bare name can resolve a torch-2.12-built wheel, an ABI mismatch).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* torch-index override: classify CUDA pin by leaf; trim blank shell overrides
_ensure_cuda_torch only overrode the NVIDIA-presence gate for *any* pinned index,
so a non-CUDA mirror URL (or a ROCm/CPU pin) on a non-NVIDIA host with ROCm torch
could force a CUDA reinstall over a working ROCm venv. Add
_explicit_cuda_torch_index_url() (leaf cu*), matching the ROCm/CPU helpers, and
gate on it instead.
install.sh::get_torch_index_url treated a whitespace-only UNSLOTH_TORCH_INDEX_URL
/ _FAMILY as authoritative (yielding an invalid index), unlike the Python .strip()
and PowerShell IsNullOrWhiteSpace paths; trim leading/trailing whitespace first.
* install: honor pinned torch index over CVD/GPU gates and fix leaf-based ROCm classification
- install_python_stack.py: an explicit cu* pin now clears the CUDA_VISIBLE_DEVICES
empty/-1 hide gate as well as the NVIDIA-presence gate, so
CVD=-1 UNSLOTH_TORCH_INDEX_FAMILY=cu128 studio update repairs to CUDA wheels
(parity with install.sh's get_torch_index_url override, which skips all GPU
probing). Unpinned CVD=-1 still skips.
- install_python_stack.py: _ensure_cpu_torch installs the bounded _CPU_TORCH_PKG_SPEC
instead of a bare torch/torchvision/torchaudio trio; the /cpu index now also
serves torch 2.11+, which is outside the supported <2.11 range.
- install.sh: the torch>=2.11 constraint case matches the index leaf (rocm7.2|gfx*)
instead of the whole URL, so a mirror base path containing a gfx/rocm7.2 segment
with a cu*/cpu family is not false-matched onto the 2.11 line.
- setup.ps1: the stale-venv check expects rocm torch only for arches the install
path maps to a repo.amd.com wheel index; an unmapped/unreadable arch installs
CPU, so a correct CPU venv is no longer marked stale.
- Tests for each of the above.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: tighten pinned torch-index override edge cases
- install.sh: trim whitespace-only UNSLOTH_TORCH_INDEX_URL/_FAMILY before the
_torch_index_pinned guard, matching get_torch_index_url, so a blank override no
longer skips the WSL bootstrap and Radeon/Strix reroutes while detection still
picks the normal index.
- install.sh / install.ps1 / setup.ps1 / install_python_stack.py: force the torch
2.11 floor only for the gfx families with the <2.11 _grouped_mm bug (gfx120X-all,
gfx1151, gfx1150). A pinned override to gfx110X-all/gfx90a/gfx908 stays on the
default range, matching the automatic AMD path.
- install_python_stack.py _ensure_cuda_torch: treat an untagged CUDA build under a
CUDA pin as a family mismatch (reinstall), and match cuXXX pins narrowly (cu +
digits) so a custom/current mirror leaf no longer forces CUDA over a CPU/ROCm venv.
- install_python_stack.py _ensure_rocm_torch: reinstall when an explicit ROCm pin
names a different ROCm family than the already-installed ROCm torch (the ROCm
analogue of the CUDA cuXXX mismatch repair).
Adds tests for each case.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: fix second-order edge cases in pinned torch-index ROCm/CUDA handling
Parse the ROCm torch probe positionally so an empty HIP marker is kept:
CPU/CUDA torch no longer reads as HIP, so the ROCm reinstall is not skipped.
Emit one "<marker>|<version>" line (like the CUDA probe) for a robust parse.
Limit the gfx torch 2.11 expectation to the install allowlist
(gfx120X-all/gfx1151/gfx1150). A pinned gfx110X-all/gfx90a/gfx908 index stays
on the default <2.11 specs, so a correct 2.10+rocm wheel is no longer judged a
mismatch and force-reinstalled every update.
Distinguish an AMD per-arch wheel (three-part +rocmA.B.C) from a generic
pytorch.org wheel (two-part +rocmA.B): a gfx per-arch pin over a generic 2.11
wheel now reinstalls the per-arch wheel, while an already-installed per-arch
wheel is not re-flagged (no reinstall loop).
Mirror all of the above in setup.ps1 via new Test-RocmGfx211Leaf /
Test-CudaFamilyLeaf / Get-RocmPinStaleTags helpers, reused by both the
install-spec path and the stale-venv check so they cannot diverge again.
Require a digit after "cu" (^cu[0-9]) in setup.ps1, install.ps1 and install.sh
so a mirror leaf like /custom or /current is not branded CUDA and does not
rebuild the venv every run.
Add tests: CPU/CUDA probe -> has_hip_torch False; gfx110X-all pin + 2.10 wheel
not stale; gfx1151 pin + generic 2.11 wheel stale; gfx1151 pin + per-arch wheel
not stale; /custom and /current not CUDA; plus cross-language allowlist and
cu-digit parity guards, and a PowerShell unit test for the new setup.ps1 helpers.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* Fix ROCm/gfx pin case normalization, ROCm-tag requirement, and CUDA-leaf classification
Normalize torch-index leaves to lowercase before the gfx*/rocm*/cu* allowlist
matches so the canonical gfx120X-all (capital X) gets the torch 2.11 floor in
install.sh (leaf, flavor and repairable helpers). Require an installed +rocm
local tag before a rocmX.Y or non-2.11 gfx pin is judged satisfied in
setup.ps1 Get-RocmPinStaleTags and the Python _rocm_pin_family_mismatch, so an
untagged CPU/CUDA wheel never leaves the pin unapplied. Classify a leaf as CUDA
only via ^cu[0-9]: the Python _TORCH_BACKEND derivation now uses
_is_cuda_family_leaf, and install.sh brands cuda only on cu[0-9]* (unset on an
unknown /current /custom mirror leaf) so the stack probes the GPU instead of
skipping ROCm repair. Add bash, Python and PowerShell tests for capital
gfx120X-all floor, current/custom not-cuda, and untagged-wheel ROCm pins.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: converge torch-index pin detection via a per-venv marker
Introduce a torch-index MARKER that records the exact wheel --index-url used
after each successful torch install, so `unsloth studio update` / repair makes
the "did the pinned index change?" decision by an EXACT string compare rather
than inferring it from the wheel +rocm/+cu version tag. The tag cannot encode
the AMD per-arch gfx family (two 2.11 gfx indexes both install +rocm7.13.0), so
the tag heuristic missed a gfx1151 -> gfx120X-all switch and a custom-URL swap.
Marker path is per-venv (.unsloth-torch-index), one line = the resolved index
URL, written atomically (temp + rename). Path, format and normalization are
shared across all four installers (install.sh, install_python_stack.py,
setup.ps1, install.ps1).
- Reapply gfx pins on a per-arch target change: the marker's exact compare
reinstalls when the pinned index differs, even when both wheels share a tag.
- Honor custom ROCm URL pins during repair: an explicit index whose leaf is not
rocm/gfx/cu/cpu (e.g. simple, current) now reinstalls torch VERBATIM from the
pin when it differs from the marker ("URL wins verbatim").
- Align the KNOWN-2.11 rocm/gfx set to exactly rocm7.2 plus the gfx allowlist
gfx120x-all/gfx1151/gfx1150 in every language; stop treating an unknown newer
rocm (rocm7.3, which does not exist) as the 2.11 line speculatively.
Backward compatible: with no marker (old venvs, torch installed out-of-band) the
existing +rocm/version-tag heuristics still decide, and a matching marker never
reinstall-loops. A cu128 CUDA pin stays a CUDA pin; custom and current leaves are
not CUDA. Adds marker tests (py/sh/ps) plus cross-installer parity checks.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: keep the torch-index marker additive to flavor validation
Three narrow fixes in the marker-based stale-venv detection:
- setup.ps1: a matching marker no longer overwrites the detected installed
flavor. The marker compare is now an additional rebuild trigger, so a stale
wheel (torch swapped to a +cpu build while the marker still records a cuXXX
pin) is still caught by the flavor check instead of being masked as up to date.
- setup.ps1: a supported AMD arch carrying CPU torch is no longer marked stale
and wiped. The downstream AMD Windows ROCm override upgrades CPU torch to ROCm
in place, so wiping first would delete the venv and abort with "Virtual
environment not found". Only a genuinely wrong CUDA wheel still rebuilds.
- install.sh: the Radeon --find-links path records its repo.radeon.com base in
the marker instead of the generic pytorch.org ROCm fallback index, so a later
pin to that generic family correctly reinstalls rather than comparing equal.
Mirrors install.ps1/setup.ps1, which already record the real AMD index.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: honor custom pins and repair pinned venvs in place
Four follow-ups to the torch-index marker work:
- install_python_stack.py: _ensure_cuda_torch/_ensure_rocm_torch now bail when an
explicit custom-index pin names no known torch family, so a verbatim URL override
(a private/simple mirror) is not clobbered by auto-detected CUDA/ROCm wheels
before _ensure_verbatim_torch_index applies it.
- install_python_stack.py: the ROCm marker is additive, not a substitute -- a
matching marker still runs the family/version check so a wheel swapped after the
marker was written is caught. Mirrors setup.ps1.
- setup.ps1: a stale venv under an explicit pin, whose torch still imports, is
repaired in place (force-reinstall torch from the pin in the dependency pass)
instead of wiped. The wipe path only delegates to install.ps1, so on a direct
update it stranded the user at "Virtual environment not found" instead of
applying the new pin. A broken venv or unpinned drift still wipes/delegates.
- install.ps1: when a pinned ROCm install fails over to a CPU base, the marker now
records the CPU index actually used instead of the ROCm pin, so the next managed
setup does not see CPU torch under a ROCm pin and abort as stale.
* setup.ps1: keep the ROCm CPU-fallback force line the pr5940 test guards
5c93ffd4 folded the pin-change force-reinstall into the ROCm CPU-fallback
condition on one line, so the exact literal that test_pr5940_followups.py checks
(if ($ROCmCpuFallback) { $cpuForce = @("--force-reinstall") }) no longer appeared
and the test failed. Split the two conditions into separate if lines: the ROCm
fallback line is restored verbatim and the pin-change force is its own line. Both
still set $cpuForce to the array, so @splat passes one arg.
* install: honor exact CUDA/custom index URL pins in the torch-index marker
Address three Codex review findings on the torch-index marker mechanism:
- install.sh: after the ROCm CPU repair reinstalls torch from the generic
$TORCH_INDEX_URL, record that as the marker source. A Radeon --find-links
install set _TORCH_MARKER_INDEX_URL to its repo.radeon.com base earlier, so
leaving it made the marker misreport Radeon wheels and a later Radeon pin would
compare equal and skip a needed reinstall.
- install_python_stack.py: _ensure_cuda_torch now consults the exact-URL marker
(_marker_pin_mismatch) when the installed +cuXXX tag matches the pinned leaf,
so a same-leaf CUDA mirror change (official cu128 to an internal cu128 mirror)
is reinstalled and re-recorded instead of skipped.
- _normalize_index_url / _normalize_family_leaf (install.sh, setup.ps1,
install_python_stack.py): lowercase only KNOWN wheel-family leaves (rocm/gfx/
cpu/cuXXX) so gfx120X-all still matches gfx120x-all, while a custom
(unknown-family) leaf keeps its case so a verbatim URL pin like /Current does
not compare equal to /current. Tests updated to assert the refined behavior.
* install: fix 3 torch-index marker edge cases (CPU mirror pin, Radeon leaf, migrated venv)
Addresses three review findings on the torch-index override path:
1. CPU index URL change on an already-CPU venv. _ensure_cpu_torch returned
early whenever torch was already a CPU build, so a standalone update that
moved the pin (official /cpu -> a private UNSLOTH_PYTORCH_MIRROR /cpu, same
+cpu tag) never reinstalled. It now consults the exact-URL marker and
reinstalls only when _marker_pin_mismatch reports a different index,
mirroring the CUDA/ROCm same-family handling. A matching marker (or none)
still leaves CPU torch untouched, so there is no reinstall loop.
2. Radeon find-links directory misclassified as a pip ROCm family. A
repo.radeon.com/.../rocm-rel-7.2.1 leaf starts with "rocm" but is a
find-links listing, not a pip --index-url. The old startswith(("rocm",
"gfx")) test routed it into a --index-url reinstall that fails against
find-links. New _is_pip_rocm_family_leaf gates on ^rocm\d / gfx (matching
install.sh's rocm[0-9]* and setup.ps1's ^(rocm[0-9]|gfx)), so a Radeon URL
routes to the verbatim/marker path instead.
3. Migrated venv rewriting its marker to a pin it did not install. install.sh
and install.ps1 write the marker unconditionally, so a migration that
preserves existing torch recorded the newly requested pin and a later
update then found a matching marker and skipped the reinstall the pin
needs (e.g. a per-arch gfx1151 -> gfx120X-all switch, identical +rocm tag).
Both now track _TORCH_INSTALLED_THIS_RUN and write the marker only when
torch was actually installed or repaired this run.
Also add Get-NormalizedFamilyLeaf to the setup.ps1 helper-extraction list in
test_torch_index_marker.ps1 (it was added to setup.ps1 and the shell test in an
earlier round but missed here) and add two unit tests covering findings 1 and 2.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: keep pinned torch repairs on the pinned index
Two fixes for explicit index pins (UNSLOTH_TORCH_INDEX_FAMILY / _URL):
1. install_python_stack.py's repair paths ran uv without clearing the
inherited uv index env vars. uv resolves the default index (--index-url
or --default-index) at the LOWEST priority, so a UV_INDEX or
UV_EXTRA_INDEX_URL mirror in the environment won for any package it
served: a cu128-pinned repair could install torch from the mirror and
then record the cu128 marker it never used. Verified empirically: with
UV_EXTRA_INDEX_URL=.../cu126 exported, uv pip install torch
--index-url .../cu128 resolves torch 2.13.0+cu126. Strip the four uv
index env vars for pinned-index commands only, mirroring the gate
install.sh, install.ps1 and setup.ps1 already have; non-pinned installs
keep the user's mirror.
2. install.ps1 routed any pinned leaf matching rocm* through the ROCm
--default-index path, so a custom find-links leaf like rocm-rel-7.2.1
was treated as a PEP 503 ROCm index and could silently fall back to CPU
torch on resolution failure. Require a digit after rocm, matching
install.sh's rocm[0-9]* and install_python_stack.py's ^rocm\d.
Adds parity + unit tests for both (11 new tests).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: keep pinned repairs off UV_TORCH_BACKEND and narrow setup.ps1's rocm pin match
Round 2 of the pinned-index hardening:
1. _build_uv_cmd converted UV_TORCH_BACKEND into --torch-backend before the
new env isolation could act, and uv's torch backend redirects torch
resolution to its own per-backend index even when --index-url is given
(verified: a cu128-pinned dry run with UV_TORCH_BACKEND=cpu resolves
torch 2.13.0+cpu). Pinned-index commands now never receive the flag and
UV_TORCH_BACKEND joins the stripped env vars, so uv cannot re-read it.
2. setup.ps1's pinned reroute had the same bare rocm* glob install.ps1 had:
a custom find-links leaf like rocm-rel-7.2.1 was routed through the ROCm
--index-url path instead of the verbatim unknown-pin path. Now requires
a digit after rocm, matching install.ps1, install.sh and
_is_pip_rocm_family_leaf.
3. The marker test's case-normalization checks used -eq, which is
case-insensitive in PowerShell, making them vacuous, and the unknown-leaf
expectation was written lowercased while the implementation deliberately
preserves custom-leaf case. Tightened to -ceq with the case-preserving
expected value.
Adds unit + parity tests for 1 and 2 (5 new tests).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: extend the pinned-index guards to every remaining surface
Round 3 of the pinned-index hardening, closing the same holes on the
surfaces the earlier rounds missed:
1. install.sh's pinned-install env scrub now clears UV_TORCH_BACKEND (uv's
torch backend redirects torch resolution to its own per-backend index
even against --default-index), and both PowerShell wrappers clear it in
their pinned-install scrubs, matching install_python_stack.py.
2. setup.ps1's marker stale check still classified any rocm* leaf as a
PyTorch ROCm family while the install selection is digit-gated, so a
custom rocm-current / rocm-rel-7.2.1 pin stale-compared as
not-rocm vs rocm and force-reinstalled on every studio update. The
stale check now uses the same ^rocm\d gate.
3. install_python_stack.py's pinned-command scrub also strips
PIP_EXTRA_INDEX_URL for the pip fallback: pip adds the env extra index
in addition to --index-url, so an inherited mirror could satisfy torch
off the pin while the marker recorded the pinned URL. PIP_INDEX_URL
needs no strip since the explicit --index-url flag overrides it.
Parity + unit tests extended (4 new tests).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: scrub find-links and carry the pinned scrub through pip fallbacks
Round 4 of the pinned-index hardening:
1. UV_FIND_LINKS joins every pinned-install scrub (install.sh, install.ps1,
setup.ps1, install_python_stack.py): uv's --find-links locations can
satisfy torch off the pinned index the same way an extra index does.
2. setup.ps1's Fast-Install restored the scrubbed vars in its finally
BEFORE the pip fallback ran, and never touched the pip env vars at all,
so a failed uv attempt fell back to python -m pip with an inherited
PIP_EXTRA_INDEX_URL / PIP_FIND_LINKS able to win over the pinned
--index-url. The scrub now wraps the whole function (uv attempt + pip
fallback) and includes the pip vars; restore happens after both.
3. install_python_stack.py's scrub also strips PIP_FIND_LINKS for its own
pip fallback, completing the PIP_EXTRA_INDEX_URL fix from round 3.
Parity tests extended (2 new tests).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: digit-gate rocm leaves in marker normalization and ROCm side effects
Round 5 of the pinned-index hardening (three custom-rocm-leaf edge cases):
1. _normalize_family_leaf lowercased every leaf starting with rocm, so a
custom mirror leaf like rocm-Current compared equal to its lowercase form
and a case-only pin change was skipped. URL paths can be case-sensitive.
The rocm prefix is now digit-gated (rocm[0-9]*, matching
_is_pip_rocm_family_leaf) in install.sh, setup.ps1 and
install_python_stack.py, so only true family leaves (rocm7.2) are
lowercased; a custom rocm-* leaf keeps its case.
2. setup.ps1 Test-MarkerPinMismatch compared normalized URLs with -ne, which
is case-insensitive in PowerShell, so a case-only marker change (Simple
vs simple) was treated as matching and the reinstall skipped. Now -cne.
3. install.sh gated the AMD bitsandbytes install and the "repair ROCm torch"
--default-index reinstall on a bare whole-URL rocm glob, so a custom
CPU/CUDA/private index whose leaf merely starts with rocm (rocm-current)
was force-repaired from the wrong ROCm-only path whenever torch.version.hip
was empty. Both now gate on _torch_index_is_rocm_family, computed once from
the digit-gated leaf (rocm[0-9]*/gfx*).
Tests: 4 new parity assertions plus 2 case-sensitivity marker checks.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: apply an explicit custom torch-index pin on the first update
Round 6: an explicitly-set custom (unknown-family) UNSLOTH_TORCH_INDEX_URL
was silently ignored on the first `studio update` of a venv that predates
the marker feature, on both platforms, because the no-marker case was
treated as "do nothing" and the version-tag heuristics cannot judge an
unknown leaf.
1. install_python_stack.py _ensure_verbatim_torch_index now reinstalls
verbatim when the marker is ABSENT (None), not only when it differs, and
short-circuits only when the marker already records this exact pin. It
then writes the marker, so every later update is a no-op. A user who did
not set the override gets pin=None and is untouched, so an out-of-band
torch install is never clobbered.
2. setup.ps1: for an unknown-family pin on a marker-less venv the stale-venv
check now sets PinChangedForceReinstall so the torch block reinstalls in
place from the pin. It deliberately does NOT set shouldRebuild, which
would wipe the venv and strand a direct `studio update`.
3. setup.sh (the Linux `studio update` entry point) skipped
install_python_stack.py entirely when unsloth was already current, so the
marker-driven reinstall (both the verbatim custom pin and the cu/rocm
flavor and family-change repair, e.g. gfx1151 to gfx120X-all) never ran.
It now forces the dependency pass when a torch-index pin env var is set;
the pass is idempotent and no-ops when the marker already matches. This
mirrors setup.ps1's stale-venv pre-check.
Tests: 3 new parity assertions.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* test: expect first-update reinstall for a no-marker custom index pin
Follow-up to d671d8fb2: _ensure_verbatim_torch_index now applies an
explicit unknown-family URL pin verbatim on the first update when the
marker is absent (instead of no-op), so the old
test_verbatim_custom_url_no_marker_is_noop assertion was stale. Rewritten
as test_verbatim_custom_url_no_marker_reinstalls_once: asserts the one
verbatim reinstall from the pinned URL, that the marker is written, and
that a second call with the pin still set is idempotent (no reinstall
loop).
* install: gate the pinned update pass on the marker and record a pin baseline
Round 8, two follow-ups to the round-6 first-update pin fix:
1. setup.sh forced the full dependency pass on EVERY `studio update` while a
torch-index pin stayed exported, even after the marker already recorded the
same pin, turning quick updates into the expensive pass every time. It now
probes install_python_stack.py --torch-pin-needs-apply (which reuses the
exact marker normalization) and forces the pass only when the pin is not yet
applied (marker absent or different); an already-applied persistent pin keeps
the fast path. A probe error fails safe toward running the pass. setup.ps1
gets the same probe in its fast path for parity.
2. A known-family full-URL pin on a venv predating the marker (e.g. an installed
cu128 build and UNSLOTH_TORCH_INDEX_URL pointing at a same-family mirror) left
the marker absent forever: the _ensure_* helpers deliberately do not force a
multi-GB reinstall of identical-family wheels on an old venv, so nothing
recorded the pin and every update re-entered the pass. _record_torch_index_pin_baseline
now records the resolved pin as a baseline after the ensure sequence when the
family already matches and no marker exists, so the pin is tracked (a later
genuine change is detected and applied) and the update loop is broken, without
the redundant reinstall.
Tests: 3 new baseline unit tests, 4 new parity assertions, and the CLI probe.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* setup.sh: keep the pin probe's exit 1 from killing the update under set -e
The --torch-pin-needs-apply probe deliberately exits 1 for the common
steady-state answer (pin already recorded, keep the fast path), but it ran
as a bare command under set -euo pipefail, so the whole studio update
aborted before the exit code was even captured. Absorb the status with
|| _PIN_NEEDS_APPLY=$? and pre-seed 0 so all three outcomes route as
documented: 0 runs the pass, 1 keeps the fast path, anything else fails
safe into the pass. Parity test asserts the guard.
* install: strip pin credentials, disable uv config discovery, bound verbatim installs
Four verified fix groups from a 12-reviewer audit of the torch-index
override feature, each reproduced before fixing:
1. Credential persistence: all four marker writers stored the raw pin URL,
so an authenticated pin (https://user:token@mirror/simple) persisted its
credentials in .unsloth-torch-index (mode 0644 under a default POSIX
umask) and install_python_stack.py printed pin URLs verbatim in repair
messages. Userinfo is now stripped before persisting and in every
log/substep that interpolates a pin, via lockstep helpers
(_strip_index_url_credentials in install.sh / install_python_stack.py,
Remove-IndexUrlCredentials in install.ps1 / setup.ps1). The three
normalizers strip too, so an OLD marker that already carries credentials
still compares equal to the same pin: no reinstall loop on upgrade.
Query strings deliberately stay in the marker; two indexes distinguished
only by query must not compare equal.
2. uv configuration discovery beat the explicit pin: with a discovered
uv.toml declaring torch-backend = "cpu" or a [[index]] entry, uv 0.10.12
resolves torch 2.13.0+cpu against an explicit --index-url/.../cu126 pin;
UV_NO_CONFIG=1 restores +cu126 (reproduced both ways). The pinned-install
scrub in all four installers now sets UV_NO_CONFIG=1 and drops
UV_CONFIG_FILE.
3. The verbatim custom-index update path installed a bare, unconstrained
torch trio while fresh installs from the same unknown-leaf pin apply the
supported range; _ensure_verbatim_torch_index now installs the bounded
trio spec, closing the fresh-vs-update asymmetry.
4. Query-bearing pins (.../cu128?token=x) classified by raw leaf split and
force-reinstalled on every update (the installed cu128 never equals
cu128?token=x). Query/fragment are now stripped before leaf
classification in all four implementations; the marker comparison keeps
the query per (1).
Rejected after verification (no change): the pin-baseline record cannot
produce a wrong later decision (every pin change still mismatches and
reinstalls from the new pin); the venv temp-file symlink scenarios require
an attacker who already owns the environment; pathological inputs like
" / cu128 / " have no realistic caller and fail loudly.
Parity, stack, rocm-support, marker (sh + ps1), pin-stale, index-url and
flavor suites all pass (455 python + full shell/ps1 batteries).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: harden custom-pin repair against clobber, broken torch, and pip config
Four follow-ups to the pinned-index audit fixes:
1. setup.ps1 routed an unknown-leaf custom pin through the CUDA branch with
a bare torch trio while install.ps1 (fresh) and the Python verbatim path
bound the supported range; the pinned unknown-leaf route now applies the
same torch>=2.4,<2.11.0 bound. Known cu* leaves and unpinned runs are
unchanged.
2. The final torch safety pass could not repair a clobbered unknown-family
pin: intermediate dependency steps can pull torch from PyPI (the pass
exists for exactly that reason), but the verbatim helper short-circuited
on marker==pin and no flavor tag exists to probe. The helper now keeps a
per-run snapshot of the installed trio (taken after a verbatim reinstall
or on the first matching-marker pass) and reinstalls from the pin when
the final pass sees the trio drifted. Probe failure skips the
comparison; a reinstall refreshes the snapshot, so no loop.
3. _record_torch_index_pin_baseline could freeze a known-family pin as
applied on a venv whose torch is missing or broken (every family helper
returns without reinstalling when its probe fails), making
--torch-pin-needs-apply report done forever. The baseline now probes the
installed flavor and records only on a match: a cuXXX pin requires the
matching +cuXXX tag, cpu requires a cpu build, rocm/gfx requires hip;
probe failure records nothing.
4. The pinned pip fallback stripped PIP_* env vars but user/site pip config
files still applied (a configured global.extra-index-url can satisfy
torch off the pin). PIP_CONFIG_FILE is now pointed at the null device
for pinned commands (pip loads no config files then), in
_install_env_for_cmd and setup.ps1's Fast-Install pinned scrub.
install.sh / install.ps1 have no pip fallback (uv-only), verified.
Tests: 7 new rocm_support tests (snapshot reset fixture), 1 stack test,
2 parity tests. Full battery green (464 python, sh and ps1 suites).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: complete the pin-repair coverage across the fast path and platforms
Three cross-platform follow-ups to the round-2 pin-repair fixes:
1. The --torch-pin-needs-apply probe only compared marker==pin, so a torch
trio clobbered to the wrong family (a cpu wheel replacing cu128 via a
later pip install) with a still-matching marker reported "already
applied" and the _ensure_{cuda,rocm,cpu} repair never ran on the Linux
fast path. The probe is now a testable _torch_pin_needs_apply() that also
checks the installed flavor against a known-family pin (via a shared
_torch_flavor_matches_pin() helper, so the baseline and the probe cannot
drift). An unknown-family pin has no flavor to validate and a failed
probe cannot prove drift, so both keep the fast path.
2. macOS ARM (real CPU/MPS torch, not NO_TORCH) never applied an unknown-
family custom pin on update: both the verbatim path and the baseline
returned on IS_MACOS while fresh install.sh honors the pin, so the marker
was never written and setup.sh forced the dependency pass on every update
forever. The guards are now IS_MAC_INTEL (Intel mac is already NO_TORCH),
and the final pass applies the pin on macOS ARM.
3. The round-2 final verbatim repair sat in the step-13 sequence guarded
not IS_WINDOWS, so on Windows a dependency step that clobbered torch after
the pin was applied was masked by the matching marker (setup.ps1 does not
re-validate the main venv's torch after calling this script -- verified).
Step 13 now runs the verbatim snapshot-drift repair on Windows and macOS
ARM too; the Linux-oriented cuda/rocm/cpu family helpers stay Linux-only.
Tests: 13 new rocm_support cases (flavor drift, macOS ARM, Windows repair),
parity updates. Full battery green (475 python, sh and ps1 suites).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: strip query tokens from the marker and tighten the pin-drift probe
Four follow-ups to the round-3 pin-repair fixes:
1. The credential stripper feeding the torch-index marker and the logged repair
messages dropped only user:pass@ userinfo, so a private feed that carries its
auth token in the query string (.../simple?token=SECRET) persisted the token
in the world-readable marker (mode 0644 under a default umask) and printed it
in substep output. All four strippers (install.sh, install.ps1,
studio/setup.ps1, install_python_stack.py) now drop the query and fragment
before building the sanitized URL. A query is not part of a PEP 503 index's
identity, so this also stops a rotated token from spuriously mismatching the
marker and forcing a needless reinstall.
2. The --torch-pin-needs-apply fast-path probe accepted an untagged CUDA build
(no +cuXXX local tag) under a specific cuXXX pin, but _ensure_cuda_torch
reinstalls exactly that build to enforce the pin. The probe was more lenient
than the repair, so the repair pass was skipped on the fast path.
_torch_flavor_matches_pin now reports a mismatch for an untagged build under a
cuXXX pin, forcing the pass.
3. The probe's ROCm branch accepted any HIP build for a rocm/gfx pin, while
_ensure_rocm_torch decides a reinstall with the per-arch
_rocm_pin_family_mismatch predicate (a generic +rocm7.2 wheel under a per-arch
gfx pin, or a wrong ROCm version, is a mismatch). The probe now reuses that
predicate, so it is as strict as the repair. This needs the installed torch
version, so _probe_torch_flavor now returns (marker, cutag, version) and
_torch_flavor_matches_pin takes the pin URL (extracting the leaf internally).
4. On Windows a known-family cu*/cpu pin is applied to the main venv by setup.ps1
before install_python_stack.py runs; a later dependency step can clobber it,
and the GPU-aware _ensure_{cuda,cpu}_torch self-skip on Windows while the
verbatim helper handles only unknown-family pins, so nothing repaired the
clobber (setup.ps1 does not re-validate the main venv's torch afterward,
verified). New _ensure_pinned_known_family_torch reinstalls a drifted cu*/cpu
pin in the step-13 Windows/macOS-ARM branch; rocm/gfx per-arch specs stay owned
by setup.ps1, unknown-family by the verbatim helper.
A speculative ROCm 2.11 floor was also raised but is unreachable: the rocm7.2
index publishes no 2.x wheel below 2.11.0, and an unknown newer rocm is not
floored speculatively.
Tests: query/fragment strip cases in the sh + ps1 marker suites and the Python
strip/marker tests; the tri-state helper and the probe/baseline harnesses moved
to the (marker, cutag, version) flavor with matching versions; new probe cases
(untagged CUDA, generic-rocm-under-gfx) and 8 _ensure_pinned_known_family_torch
tests; a four-way query-strip parity assertion. Full battery green (1150 python,
sh 26/26 marker, ps1 marker/flavor/pin-stale).
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: reinstall markerless gfx pins and cap custom-index updates at torch 2.11
Two follow-ups from the pin-marker audit:
1. A markerless venv with a gfx per-arch 2.11 pin trusted the wheel version
tag, which is byte-identical (+rocm7.13.0) across gfx120X-all / gfx1151 /
gfx1150. A pre-marker install holding one gfx arch's wheel that is now
pinned to a DIFFERENT gfx index was therefore never switched:
_rocm_pin_family_mismatch returns no-mismatch for any three-part +rocm
2.11 wheel, and _ensure_rocm_torch's absent-marker branch fell through to
that heuristic. _ensure_rocm_torch now forces a one-time reinstall when the
marker is absent AND the pin leaf is a 2.11 gfx per-arch index; the reinstall
writes the marker, so the next update compares exactly and does not loop
(the correctly-pinned no-reinstall guarantee then comes from the exact marker
compare, not the ambiguous tag). Non-gfx-2.11 pins (rocmX.Y, non-2.11 gfx)
stay on the tag heuristic -- their tags are distinguishable.
2. The verbatim custom-index update path used _CUDA_TORCH_PKG_SPEC (torch
<2.12.0) while a FRESH install of the same unknown leaf caps torch at
<2.11.0 (install.sh's default TORCH_CONSTRAINT, and setup.ps1's custom-pin
branch), so a private /simple mirror publishing torch 2.11 could upgrade a
`studio update` to a state the fresh installer never produces. Added
_CUSTOM_INDEX_TORCH_PKG_SPEC (torch>=2.4,<2.11.0), used only by the verbatim
path; companions stay pinned for the same exclusive --index-url ABI reason
as _CUDA_TORCH_PKG_SPEC (a bare name could pull a torch-2.12-built
torchvision). _CUDA_TORCH_PKG_SPEC is unchanged (known-family cu/cpu repair
correctly tracks install.sh's widened cu ceiling).
Tests: 2 new markerless-gfx cases (one-time reinstall + marker write + no-loop
second run, and the rocmX.Y absent-marker no-op), the pre-existing markerless
gfx no-reinstall test flipped to assert the one-time reinstall (it had encoded
the old tag-trusting behavior), and the custom-index bound assertions. 488
passed.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: a matching marker must not mask a broken, clobbered, or misclassified torch
Four round-6 follow-ups, all closing cases where a matching torch-index
marker wrongly vouched for a torch that is not actually the pinned one:
1. _is_cuda_family_leaf matched cu+digits by PREFIX (^cu[0-9]), so a custom
mirror leaf like cu128-private classified as CUDA family; the flavor check
then compared the installed cu128 tag to the whole leaf cu128-private and
forced a reinstall on EVERY update (never converging). The cu family is
now matched EXACTLY (re.fullmatch cu[0-9]+), so a cu-suffixed custom leaf
routes through the verbatim/unknown path with a stable marker. Mirrored in
install.sh (_normalize_family_leaf: strip cu, require an all-digit
remainder) and setup.ps1 / install.ps1 (^cu[0-9]+$).
2. _torch_pin_needs_apply returned False on a failed torch probe (missing or
unimportable) under a matching marker, so setup.sh kept the fast path and
a broken torch was never repaired. A failed probe now forces the pass: the
marker cannot vouch for a torch that does not import, forcing is idempotent,
and once torch imports again the probe succeeds and the forcing stops
(self-resolving). Reverses the round-4 conservative choice for this case.
3. _ensure_verbatim_torch_index snapshotted the installed trio on the first
pass with a matching marker and treated an unimportable torch (snapshot
None) as "no drift, skip", so a torch clobbered to a broken state before
the run was masked. A None snapshot now reapplies the pin. A torch
clobbered to a WORKING-but-wrong build under an unknown-family pin remains
undetectable from metadata (no flavor tag; reinstalling every update would
be the loop this avoids) and is documented as a known limitation.
4. The step-13 Windows final repair reran only the verbatim (unknown-family)
and known-family cu*/cpu paths, so a clobbered explicit rocm/gfx pin (the
wheel setup.ps1 installed from AMD's per-arch index) was left in place. The
branch now also runs _ensure_rocm_torch on Windows for an explicit rocm/gfx
pin; it has a Windows path and no-ops when torch already links HIP, so it
only reinstalls a genuinely clobbered ROCm venv (loop-safe).
Tests: the round-4 failed-probe-trusts-marker test flipped to force the pass;
new cases for the cu-suffix no-loop, the broken-torch verbatim reinstall, and
the Windows rocm final-repair structure; item-2 exact-cu parity assertions.
490 passed. sh/ps1 marker + flavor + pin-stale suites all green.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: repair Windows ROCm pins from the pinned URL and honor NO_TORCH
Four round-7 review items, two of them regressions in the round-6 work:
1. _torch_pin_needs_apply ignored UNSLOTH_NO_TORCH. With a torch-index env
var set and no marker, the failed-probe branch forced the dependency pass
on every `studio update`, and the pass (which also honors NO_TORCH) never
installs torch or writes a marker, so nothing could ever stop the forcing.
It now returns False immediately under NO_TORCH: the pin only matters once
torch is actually installed.
2. The step-13 Windows final repair (round-6) restored a clobbered explicit
rocm/gfx pin by calling _ensure_rocm_torch, whose Windows path reinstalls
from the arch AUTO-DETECTED via hipinfo, not from the pin. A user pinning a
different gfx family or a private mirror was restored from the wrong source
(and the wrong marker written), and a headless box was skipped entirely
(the arch probe returns nothing). The repair now goes through
_ensure_pinned_known_family_torch, which reinstalls from the PINNED url with
the same per-arch floor setup.ps1 uses (2.11-line gfx leaves) or a bare trio
(older arches, rocmN mirrors). It is gated on IS_WINDOWS since macOS ARM has
no ROCm, and the existing flavor check keeps it loop-safe (a matching HIP
wheel is left alone).
3. _ensure_verbatim_torch_index's broken-torch check (round-6) used
"_installed_trio_snapshot() is None", but that helper reports a REMOVED torch
as "torch==absent" (a non-None tuple) and a broken import as the stale
on-disk version, so a missing or unimportable torch under a matching marker
was read as "no drift" and skipped. The matching-marker path now confirms
torch health with an import probe (_probe_torch_flavor): a torch that does
not import reapplies the pin, while a healthy torch keeps the snapshot-based
intra-run drift detection.
4. A unit test for _ensure_cpu_torch did not pin NO_TORCH False like its
siblings, so a suite run with UNSLOTH_NO_TORCH=1 in the environment made the
guard return early and the reinstall assertions fail spuriously.
Tests: the round-6 broken-torch verbatim test re-encodes the non-None
"torch==absent" snapshot case (the exact state the old "is None" check missed);
new Windows-ROCm pinned-repair cases (reinstall from the pin, per-arch floor vs
bare spec, matching-wheel no-op, off-Windows no-op); a NO_TORCH fast-path probe
case; the parity test now asserts the Windows final branch does not auto-detect
the ROCm index and that the helper reinstalls from the explicit pin. 494 passed.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: floor the rocm7.2 index in the Windows pin repair; isolate marker tests
Three round-8 review items, two of them downstream of the round-7 changes:
1. _ensure_pinned_known_family_torch gave a rocm<d> index leaf a bare
torch/torchvision/torchaudio trio while flooring only gfx* leaves, so a
Windows venv clobbered under an explicit rocm7.2 pin could reinstall an
unbounded or ABI-mismatched trio from that exclusive --index-url. It now
mirrors the spec the initial ROCm paths pin: the rocm7.2 floor for 2.11-line
gfx leaves and rocm<d> leaves that serve torch 2.11, the <2.11 default for
older rocm versions, and a bare trio only for older gfx per-arch leaves
(which publish no floor), matching _ROCM_TORCH_PKG_SPECS / _ensure_rocm_torch.
2. test_verbatim_custom_url_no_marker_reinstalls_once called
_ensure_verbatim_torch_index twice; the second call now hits the
matching-marker health probe, and with pip_install mocked torch never becomes
importable, so in a no-torch environment _probe_torch_flavor returned None and
forced another reinstall, failing the idempotence assertion. The test now pins
a healthy flavor so the idempotence check is about the marker, not ambient
torch.
3. The TestEnsureRocmTorchMarker fixture patched os.environ per test but not
_TORCH_BACKEND, which install_python_stack.py computes once at import from
UNSLOTH_TORCH_BACKEND. A runner starting with a cuda/cpu backend made
_ensure_rocm_torch early-return and skip the mocked repair these tests
exercise. The fixture now neutralizes _TORCH_BACKEND so the marker tests are
independent of the caller's installer-pin environment.
Tests: the Windows floor-spec test now asserts a rocm7.2 mirror pin uses the
rocm7.2 floor (not bare), plus a new rocm7.1 case that must fall back to the
<2.11 default; the marker suite passes under a hostile
UNSLOTH_TORCH_BACKEND=cuda / UNSLOTH_TORCH_INDEX_URL env. 495 passed.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: apply same-flavor pin repoints, keep ROCm fallback nonfatal, bound custom companions
Four round-9 review items, two of them regressions in the round-7 pin helper:
1. _ensure_pinned_known_family_torch returned as satisfied whenever the installed
flavor matched the pin, so a same-flavor SOURCE change (one /cpu or /cu128
mirror to another, or a gfx1151 -> gfx120x-all per-arch switch, both carrying
the same wheel tag) was never applied, while _torch_pin_needs_apply kept forcing
the pass on the marker mismatch forever. It now also reinstalls when the marker
records a DIFFERENT index of the same flavor, rewriting the marker so the next
update matches (no loop), exactly as the Linux _ensure_{cuda,cpu}_torch helpers
do. An absent marker on an already-matching venv is still left to the baseline
recorder (no forced reinstall of a correct pre-marker venv).
2. That helper reinstalled a Windows ROCm pin with the FATAL pip_install, so when
setup.ps1 had taken its CPU fallback (the pinned AMD index unavailable), the
final repair re-hit the same missing index and aborted the whole install. The
ROCm reinstall is now nonfatal (pip_install_try): on failure it leaves the CPU
base in place and writes no ROCm marker, so the install completes -- matching
_ensure_rocm_torch's Windows path. cu*/cpu pins stay fatal (authoritative source).
3. install.sh left torchvision/torchaudio bare for a pinned custom/unknown-leaf
index (a private /simple mirror), unlike the Python update path's
_CUSTOM_INDEX_TORCH_PKG_SPEC, so a mirror also exposing newer companion wheels
could resolve a torch-2.12-built torchvision against the capped <2.11 torch. It
now bounds the companions (torchvision>=0.19,<0.26.0 / torchaudio>=2.4,<2.11.0)
for a custom leaf, gated on an empty _expected_torch_flavor_tag so known families
keep their curated bare/floored companions.
4. install.sh's _expected_torch_flavor_tag matched cu[0-9]* by prefix, so a custom
leaf like cu128-private classified as the cu128 family and force-reinstalled a
correct +cu128 wheel on every run. It now requires exact cu+digits (routing the
suffixed leaf to the custom path), matching the Python re.fullmatch(cu[0-9]+) and
PowerShell, and feeding item 3's custom-leaf detection.
Tests: new cases for the same-flavor marker-change reinstall, the nonfatal ROCm
fallback (no marker on failure), the rocm7.2/older-rocm floor selection now split
across the nonfatal path, cu-suffixed custom leaves in test_torch_flavor.sh, and the
custom-leaf companion bounds in test_torch_constraint.sh. 497 python + 143 shell
assertions pass; the marker suite still passes under a hostile
UNSLOTH_TORCH_BACKEND=cuda env.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: bound custom-pin companions on the Windows setup path; isolate pin-probe tests
Two round-10 review items:
1. setup.ps1's custom/unknown-leaf pin branch capped only torch ($cudaTorchSpec)
and still asked the exclusive index for bare torchvision/torchaudio, so a
private mirror that also serves newer companion wheels could install a
torch<2.11 wheel alongside a torchvision>=0.26 / torchaudio>=2.11 built for a
newer torch ABI, after which the marker records the pin as applied. It now
bounds the whole trio (torch>=2.4,<2.11.0 / torchvision>=0.19,<0.26.0 /
torchaudio>=2.4,<2.11.0) for a pinned non-cu-family leaf, matching install.sh,
install.ps1's fresh pinned install, and install_python_stack.py's
_CUSTOM_INDEX_TORCH_PKG_SPEC. This completes the companion-bounds fix across all
three installers; known cu* leaves keep bare specs (the family index bounds them).
2. The _torch_pin_needs_apply probe tests did not pin NO_TORCH False, so a test
process launched with UNSLOTH_NO_TORCH=1 short-circuited the probe (the round-7
guard) and returned False for cases that expect the pass to run. The _needs_apply
helper now patches NO_TORCH (default False) around the call, and the dedicated
no-torch case passes no_torch=True explicitly.
Tests: the cross-platform parity test now asserts setup.ps1 bounds the full trio
(not just torch) for a custom leaf; the pin-probe suite passes under a hostile
UNSLOTH_NO_TORCH=1 environment. setup.ps1 parses clean; 497 python + shell suites
green.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: bound custom rocm-* pins, redact diag tokens, snapshot custom pins before base update
Three round-11 review items, all reproduced before fixing:
1. install.sh's custom-index companion bounds gated on _expected_torch_flavor_tag
returning empty, but that helper returned "rocm" for ANY rocm* leaf, so a custom
mirror whose leaf starts with rocm but is not a pip family (a private rocm-current
mirror, a Radeon find-links rocm-rel-7.2.1) escaped the bounds and installed bare
torchvision/torchaudio. It now digit-gates rocm to rocm[0-9]* (matching the Python
_is_pip_rocm_family_leaf ^rocm\d), so those custom leaves return "" and the <2.11
companion caps apply; real rocm7.2 / gfx per-arch indexes still classify as rocm.
2. _tauri_torch_index_family classified by the raw last path segment, so a pinned URL
carrying auth in the query (.../rocm7.2?token=SECRET) had the token echoed verbatim
into the emitted [TAURI:DIAG] line. It now strips query/fragment before classifying
(mirroring the marker/log credential stripping), so no token reaches the diagnostic
output; as a side effect .../cu128?token=x now classifies as cu128 instead of auto.
3. On studio update, the core package step (a newer unsloth can require a torch the
custom pin does not satisfy, pulling a default PyPI trio) runs BEFORE the step-2b
verbatim check, which then recorded the already-clobbered trio as the baseline for a
matching marker and left the pin unapplied. A new _capture_verbatim_baseline() records
the pre-clobber trio before the core step, so the verbatim pass detects the drift and
reapplies the pin. Captures only for a matching custom pin with importable torch; a
mismatched/absent marker or broken torch is left to _ensure_verbatim_torch_index.
Tests: _expected_torch_flavor_tag rocm-current / rocm-rel cases; _tauri_torch_index_family
token/fragment redaction with a no-leak regression guard; _capture_verbatim_baseline
record/skip cases plus an end-to-end clobber-detection scenario; a structural guard that
the capture runs before the core step. 501 python + shell suites pass; install.sh bash -n
clean, shellcheck unchanged from base.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: match rocm family leaves exactly, enforce the rocm7.2 torch line, repair a broken pinned torch
A pinned index is a pip ROCm --index-url family only when its leaf is an exact
rocm<digits> / rocm<digits>.<digits> (rocm7.2) or a gfx* per-arch leaf. The prior
^rocm[0-9] prefix match also caught suffixed private-mirror leaves (rocm7.2-private,
rocm7-current), routing them through the ROCm/companion-family path instead of the
verbatim pin: the companion bounds were skipped and, on a pre-marker venv with a
compatible +rocm wheel, the pin was never applied. Match the family exactly through one
shared helper at every site:
- install_python_stack.py: _is_pip_rocm_family_leaf (re.fullmatch), plus the two other
loose gates it feeds (_normalize_family_leaf, _torch_flavor_matches_pin).
- install.sh: a new _is_pip_rocm_family_leaf routes _expected_torch_flavor_tag,
_torch_index_repairable, _normalize_family_leaf and the ROCm side-effect gate.
- setup.ps1: a new Test-PipRocmFamilyLeaf routes Get-NormalizedFamilyLeaf and both
pinned reroutes; install.ps1 anchors its reroute regex.
_rocm_pin_family_mismatch (and its setup.ps1 mirror Get-RocmPinStaleTags) compared only
the ROCm version, so a +rocm7.2 wheel whose torch release drifted off the 2.11 line
(2.12/2.13 from an out-of-band upgrade or a custom rocm7.2 mirror) satisfied the family
check while violating _ROCM_TORCH_PKG_SPECS['rocm7.2'] (torch>=2.11,<2.12). Flag it stale
so the repair reinstalls to floor; >=2.11 alone is not enough, so the release is compared
exactly against the 2.11 line for a KNOWN-2.11 rocm pin.
_ensure_pinned_known_family_torch returned on a failed import probe, but
_torch_pin_needs_apply forces the dependency pass on that same failed probe: a broken
torch under a known-family pin was left in place and the pass was forced on every update.
Treat an unimportable torch as drift and reinstall the pinned trio (the spec and marker
derive from the pinned leaf, not the absent flavor); once it lands the probe succeeds and
the fast path returns.
Tests: exact-match cases across test_torch_flavor.sh, test_rocm_support.py,
test_cross_platform_parity.py and the two .ps1 helper suites; the rocm7.2 release-line
and broken-probe-reinstall cases; extraction lists updated for the new helpers.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: anchor the PS pinned-ROCm floor gate and bound install.ps1 custom-pin companions
Round 12 made every family CLASSIFIER exact, but the Windows install-flow floor gate reads
$_pinRocm211 directly from the raw pinned leaf with an unanchored -match '^rocm(\d+)\.(\d+)'
BEFORE any exact classification runs. A suffixed custom leaf (rocm7.2-private) matches that
rocm7.2 prefix, so it takes the 2.11-floor branch and is force-routed through the ROCm
install path before the exact-match elseif can send it to the verbatim install. Anchor the
match ($) in both install.ps1 and setup.ps1 so only an exact rocmX.Y leaf is floored; a
suffixed or newer-suffix leaf falls through to the verbatim path. The Python floor
selection is already exact (dict lookups gated on _is_pip_rocm_family_leaf), so only the two
PS scripts needed this.
install.ps1's custom (non-cu-family) pinned-torch install bounded torch>=2.4,<2.11.0 but
left torchvision/torchaudio bare, so a private mirror serving newer companions could pull a
wheel built for a newer torch ABI while the marker records the pin as applied. Bound both
companions (torchvision>=0.19,<0.26.0 / torchaudio>=2.4,<2.11.0) when the leaf is not a
cu<digits> family index (a cu index bounds its own resolution), matching setup.ps1's
Test-CudaFamilyLeaf gate and _CUSTOM_INDEX_TORCH_PKG_SPEC.
Tests: parity guards for the anchored floor gate in both PS scripts and for install.ps1's
bounded custom-pin companions.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: tighten comments in the torch-index-override paths
Collapse the verbose comment and docstring blocks added across the installer
scripts and their tests to fewer, clearer lines without changing behaviour.
Remove a duplicated CUDA-spec comment block. Comments/docstrings only; no code
changes (AST-verified).
* install: repair a broken pinned torch on Linux, strip trailing slash in tauri family, count the final step
_ensure_cuda_torch / _ensure_cpu_torch returned on a failed import probe (torch present but
unimportable). With an explicit CUDA/CPU pin, _torch_pin_needs_apply forces the dependency
pass on that same failed probe, and the base package update does not force-reinstall an
already-installed torch distribution, so the broken torch was left in place and the pass
reran every update without repairing it. Treat a failed probe under a pin as drift and
reinstall from the pinned index (the reinstall rewrites the marker and the next probe
imports, so no loop). This is the Linux counterpart of the known-family repair fix.
_tauri_torch_index_family stripped the query/fragment before classifying but not a trailing
slash, so a token-authenticated pin like .../cu128/?token=x collapsed to .../cu128/ and fell
through the exact-suffix */cu128 and */cpu arms to "auto". Strip a trailing slash too,
mirroring _torch_index_url_leaf.
The Windows / macOS-ARM final torch-repair step (_ensure_pinned_known_family_torch) runs a
progress step that base_total never counted (the final-step increment was gated to Linux),
so _STEP ran one past _TOTAL on those platforms. Add the missing increment.
Tests: broken-probe reinstall for the CUDA (family and URL pins) and CPU paths; trailing
slash / slash+token cases for _tauri_torch_index_family; a full-flow progress-count guard
asserting _STEP == _TOTAL on Windows and Linux.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: tighten comments in the torch-index-override paths
* install: harden the torch-index pin across all four installers
Redact index-URL credentials from captured install logs before they print on
failure. uv/pip failure text embeds the failing --index-url verbatim, so a
user:token@ or ?token= secret could leak into the console. Add a shared
redaction pass (_redact_install_output / Redact-InstallOutput) wired into the
error-output dump in install.sh, install.ps1, setup.ps1 and
install_python_stack.py. Verbose mode still streams live uncaptured output, so
it is intentionally left unredacted (developer opt-in).
Trim trailing slashes on the PATH only for a verbatim UNSLOTH_TORCH_INDEX_URL
override, preserving a ?query/#fragment token. A whole-URL rstrip corrupted a
base64 token ending in "/", and a single-slash strip left .../cu128//
classifying as an empty leaf. Add _trim_index_path_slashes /
Trim-IndexPathSlashes and route the override through it; strip ALL trailing
slashes in the backend-branding leaf classifier so a double slash still yields
the real leaf.
Reject a trailing-dot ROCm leaf (rocm7.) in the bash family validator so it
matches Python re.fullmatch(rocm\d+(?:\.\d+)?) and the PowerShell regex: both the
major and the minor must be non-empty digits, so rocm7. is a custom verbatim pin,
not a pip ROCm family.
Scrub PIP_NO_INDEX and PIP_INDEX_URL for a pinned install in the two installers
that have a plain-pip fallback (install_python_stack.py, setup.ps1):
PIP_NO_INDEX=1 makes the fallback ignore every index including the pinned
--index-url, and PIP_INDEX_URL replaces it. install.sh and install.ps1 install
via uv --default-index (which ignores pip config/env), so they are unaffected.
Add unit tests (bash, Python, PowerShell) and cross-platform parity tests
covering credential redaction, path-only slash trimming, the rocm7. validator,
the double-slash leaf, and the PIP_NO_INDEX/PIP_INDEX_URL scrub.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: redact captured torch-install output and warn on a failed pinned ROCm repair
Close a redaction gap the earlier pass missed: setup.ps1's direct
`Fast-Install ... | Out-String` branches (ROCm from $ROCmIndexUrl, CPU/CUDA from
$TorchInstallIndexUrl, plus the Triton and T5 sub-venv installs) printed the
captured $output verbatim on failure, bypassing Redact-InstallOutput. A private
index carrying userinfo or a ?token= in the pin could leak into Windows Studio
setup logs. Route every `Write-Host $output` through Redact-InstallOutput.
Warn on a failed pinned Windows ROCm reinstall in
_ensure_pinned_known_family_torch: the branch printed "reinstalling from it" then
called pip_install_try, but had no else, so a failure continued silently and left
the user believing the pin was applied while the old CPU/wrong torch survived.
Mirror the auto-ROCm Windows path and warn, telling the user to retry.
* install: redact captured output on the pip fallback and optional-install failure paths
The uv install path already redacted its captured output, but pip_install's pip
fallback runs through run(), which printed result.stdout verbatim on failure, and
_print_optional_install_failure did the same. A pinned --index-url carrying
userinfo or a ?token= could still leak there when uv is unavailable or the pip
fallback also fails. Route both through _redact_install_output. The verbose
pip_install_try path stays raw (developer opt-in), matching the other installers.
* install: split the survive-updates marker subsystem into a follow-up
The torch-index override PR grew a persisted per-venv marker plus repair
machinery (stale-pin detection, verbatim re-apply, update-time reinstall
triggers) that roughly doubled it. That subsystem is orthogonal to the core
feature and is being reworked in a follow-up (versioned/hashed marker,
full-URL pin baseline), so it moves there wholesale instead of shipping
twice.
What this PR still does: UNSLOTH_TORCH_INDEX_URL / UNSLOTH_TORCH_INDEX_FAMILY
pick the torch wheel index at install time in all four installers, with the
exact rocm/gfx/cpu/cu leaf classification, the torch 2.11 floor for the
per-arch AMD indexes, bounded companions for custom leaves, credential
redaction of captured installer output, path-only slash trimming, and the
uv/pip index env scrubs. Flavor-based repair keeps honoring the pin: a wrong
family under an explicit pin still reinstalls from the pinned URL, and
setup.ps1 repairs a pinned stale venv in place instead of wiping it.
What moves to the follow-up: the .unsloth-torch-index marker file and its
writers/readers/normalizers, exact-URL pin-change detection on update
(same-tag gfx switches, custom-mirror repoints), the verbatim trio snapshot
and clobber re-apply, the pin-baseline recorder, and the
--torch-pin-needs-apply fast-path probe in setup.sh / setup.ps1. Their tests
(the marker sh/ps1 suites, the stale-pin suite, and the marker classes in the
rocm/cuda/parity suites) move with them; the removed code is preserved on a
local archive branch to seed that PR.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: re-apply a ROCm pin over an existing HIP wheel via the version tag
The subsystem split left an explicit ROCm/gfx pin unenforced on `studio
update` whenever the venv already imported ANY ROCm torch: the pinned
reinstall lived inside the `elif not has_hip_torch` branch, so a rocm6.4 to
rocm7.2 switch, a gfx1151 pin over a generic +rocm7.2 wheel, or a broken
2.12+rocm7.2 drift never re-applied the pin.
Restore the markerless half of that detection: _rocm_pin_family_mismatch
compares the pinned leaf against the installed wheel tag (exact rocmX.Y
compare, the 2.11 gfx per-arch allowlist, the untagged-wheel rule), the HIP
probe emits "<hip_marker>|<version>" again so the installed tag is available,
and _ensure_rocm_torch reinstalls from the pinned URL when the tag mismatches
even though HIP torch is present. setup.ps1 mirrors it: the stale-venv check
routes a pinned rocm/gfx leaf through Get-RocmPinStaleTags instead of
collapsing it to a generic "rocm" flavor, and the existing pinned in-place
repair (no wipe) applies the change.
What still waits for the follow-up marker PR, by design: pin changes the
wheel tag cannot see -- a per-arch switch between two 2.11 gfx indexes
(identical +rocm7.13.0 tag), a custom-mirror URL repoint under the same
family leaf, and unknown-family verbatim pins. Those need the persisted
index record.
Tests restored with the code: the _rocm_pin_family_mismatch table, the five
update-path cases (older-rocm reinstall, gfx-over-pre-2.11 reinstall,
matching-pin no-reinstall, non-2.11 gfx no-reinstall, gfx-over-generic-2.11
reinstall), the "|" probe-format guards, and the AST-extracted
Get-RocmPinStaleTags suite for setup.ps1.
* install: compare major-only rocm pins, redact URL fragments, bound pinned CPU trio
Three review fixes on the restored pin-repair path.
The family classifier accepts a major-only rocm<d> leaf (rocm7), but the
mismatch comparators only parsed rocmX.Y, so a rocm7 pin fell through to the
2.11-line fallback and INVERTED both verdicts: an installed +rocm6.4 wheel
compared as satisfied (pin never re-applied) while a matching +rocm7.2 wheel
compared as stale (reinstall loop). Major-only pins now compare on the major
alone in _rocm_pin_family_mismatch and Get-RocmPinStaleTags: rocm6.x under a
rocm7 pin is a mismatch, any rocm7.x satisfies it, an untagged wheel never
does, and a bare +rocm tag with an unreadable version is accepted (matching
the existing lenient unreadable fallback).
The output redactors scrubbed userinfo and ?query= values but not #fragments,
so a pin like https://mirror/whl/cu128#token=secret leaked the secret in
captured uv/pip failure text -- inconsistent with the URL handling itself,
which already treats fragments as sensitive. All four redactors gain a
URL-anchored fragment rule (anchored so a bare "# comment" line in tool
output is never touched).
setup.ps1's CPU branch installed a bare torch/torchvision/torchaudio trio;
fine for the unpinned host default, but a PINNED cpu index routes through the
same branch and the /cpu index serves newer torch, so a fresh pinned CPU
install could land an unsupported trio that _ensure_cpu_torch then keeps
(it accepts any CPU build). Under a pin the branch now installs the bounded
trio mirroring _CPU_TORCH_PKG_SPEC (torch>=2.4,<2.12.0 and matching
companions); the unpinned path is unchanged.
Tests: major-only rows in the Python mismatch table and the AST-extracted
setup.ps1 suite; fragment + query-plus-fragment + bare-hash-comment cases in
all four redactor suites; a parity check that the pinned CPU trio bounds
exist, are gated on the pin, and mirror the Python repair spec.
* [pre-commit.ci] auto fixes from pre-commit.com hooks
for more information, see https://pre-commit.ci
* install: tighten comments in the torch index override paths
* tests: track the moved pass-through inheritance in the gguf order check
Main moved the llama_extra_args pass-through inheritance out of the
GGUF branch into _resolve_inherited_extra_args, which runs before it,
so the source-order assertion's "if request.llama_extra_args is None"
anchor no longer exists inside the branch and the check failed after
the main merge. The test now asserts the same property in the current
shape: inheritance before the GGUF branch (a carried --no-mmproj still
shapes the hub guard's companion requirement), and marker, hub guard,
unload in order within the branch. Full file passes (32 tests).
* tests: anchor the inheritance order check on the call, not the definition
source.index("_resolve_inherited_extra_args(") matched the function
definition, which always precedes the endpoint, so the ordering
assertion was vacuously true. Anchoring on "= _resolve_inherited_
extra_args(" pins the first call site inside the load endpoint (line
4505), which is the statement whose position relative to the GGUF
branch the test is meant to guard. 32 tests pass.
* tests: align the gguf order test with main
Main fixed the stale ordering assertion in PR 7252; adopting its
version verbatim removes this file from the branch diff entirely and
avoids a conflict on the next main merge. 32 tests pass.
* install: bound the companion constraints to torch's window everywhere
A full platform x vendor validation matrix over this branch surfaced a
real trio mismatch on the cpu/mac paths: torch is capped <2.11 (installs
2.10.0+cpu) but the bare torchaudio companion resolves 2.11.0+cpu,
because torchaudio 2.11 dropped its exact torch pin. Reproduced in a
sandboxed end to end cpu install. torchvision still exact-pins torch and
self-corrected.
The default companion constraints are now bounded to torch's window
(<0.26 / <2.11) and widen together with the cu* torch window (<0.27 /
<2.12), so every leaf resolves a paired trio. Verified with uv dry-runs
on the cpu, cu130, and rocm6.4 leaves (2.10.0/0.25.0/2.10.0,
2.11.0/0.26.0/2.11.0, 2.9.1/0.24.1/2.9.1) and a rerun of the sandboxed
cpu install, which now lands torch 2.10.0+cpu with torchaudio
2.10.0+cpu.
The Strix WSL reroute now also forwards UNSLOTH_TORCH_INDEX_URL and
UNSLOTH_TORCH_INDEX_FAMILY into the rerouted 24.04 distro; dropping
them silently reverted the child install to auto-detection, defeating
the pin this branch introduces.
test_torch_constraint.sh updated: the bounded companions must appear at
the defaults and the custom-leaf block, no bare companion may remain,
and the cu* widen must carry the companions with it.
* install: harden the override path against reroute drift and credential leaks
Review sweep focused on default-path idempotency found no defects on the
unset path; these fixes cover the override path and failure reporting.
install.sh:
- The early WSL Strix Halo distro reroute now honors an explicit index
pin (UNSLOTH_TORCH_INDEX_URL / _FAMILY): the pin is used in the current
distro instead of probing the GPU and re-entering another distribution,
matching the contract of the later Radeon and Strix guards. Whitespace
only values do not gate, in parity with get_torch_index_url.
- Verbose mode now streams installer output through the credential
redactor; it previously bypassed the redaction the quiet path applies.
The exit code survives the pipe via an rc file since the script runs
under plain sh with no pipefail.
- The kept-release fallback warning now strips credentials from the
index URL before printing it.
install.ps1:
- Bounded torchvision and torchaudio next to every capped torch install
(custom pin, ROCm CPU fallback, CUDA flavor repair). torchaudio 2.11
dropped its exact torch pin from the wheel metadata, so a bare
companion beside torch<2.11 can resolve a mismatched 2.11.0 build,
cu family indexes included. Mirrors the install.sh companion bounds.
studio/install_python_stack.py:
- The verbose failure path now redacts index URLs in pip and uv output
before printing, matching every other output site in the file.
All sh, ps1 and python installer test suites pass (the host-defaults
suite has a known pre-existing failure unrelated to this change).
* install: redact verbose Windows installer output and repair the parity tests
Follow-ups to the override-hardening commit, from review:
- install.ps1 Invoke-InstallCommand and setup.ps1 Invoke-SetupCommand now
pipe verbose output through Redact-InstallOutput per record, and the
three verbose Fast-Install torch call sites (ROCm, CPU, CUDA) do the
same: uv and pip echo the pinned index URL, credentials included, in
their errors, and verbose mode previously bypassed the redaction the
quiet paths apply. ForEach-Object and Out-Host leave $LASTEXITCODE
untouched, verified with a native command exiting 7 behind the pipe.
- test_cross_platform_parity.py: the install.ps1 companion-bounds
assertion now matches the implemented behavior (bounds on every index,
no cu-family exemption, since torchaudio 2.11 dropped its exact torch
pin) instead of requiring the removed $_pinCuLeaf gate.
- test_rocm_support.py: the WSL reroute guard test slices the whole
function body to its closing brace instead of a fixed 1200-character
window, which the new pin-gate preamble had outgrown.
428 tests pass across the parity, install stack and rocm support suites;
the sh and ps1 installer suites pass unchanged.
* install: tighten comments in the torch-index and ROCm/CUDA repair paths
* install: digit-gate the gfx family leaf and honor ROCm pins in the Windows repair
Two review follow-ups on the override path:
- The pip ROCm family predicate accepted ANY gfx-prefixed leaf, so a
custom verbatim pin like /gfx-private classified as a ROCm family and
enabled the ROCm-only side effects (AMD bitsandbytes, ROCm torch
repair) on a mirror that may serve CPU/CUDA wheels. gfx now requires a
following digit (gfx90a, gfx1151, gfx120X-all), consistently in
install.sh, install_python_stack.py, install.ps1 (family gate and
expected-flavor classifier) and setup.ps1, matching the strictness the
rocm side already had (rocm7.2-private stays verbatim). The broader
backend BRANDING globs are unchanged on purpose: radeon repo leaves
(rocm-rel-X.Y) must still brand the rocm backend without being
force-repaired as a family.
- The Windows branch of the ROCm torch repair always installed from the
public per-arch index, ignoring an explicit ROCm-family pin: after a
pinned setup.ps1 install failed to a CPU base, the repair retried
repo.amd.com instead of the pinned index. The branch now resolves
_explicit_rocm_torch_index_url() first, uses it as the install index
when set, and mirrors the Linux pin contract by skipping the NVIDIA
and gfx-detection gates a pin is documented to override.
Source-assertion tests updated to the tightened predicate and the new
repair label. 1165 tests pass across the parity, install stack and
studio install suites; the sh and ps1 suites pass; both PowerShell
installers parse clean.
* Remove scratch archives accidentally committed with the comment pass
The temp/ archive copies of installer and test files were working
scratch, not PR content, and inflated the diff by about nine thousand
lines.
---------
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
2879 lines
114 KiB
Python
2879 lines
114 KiB
Python
#!/usr/bin/env python3
|
|
|
|
# SPDX-License-Identifier: AGPL-3.0-only
|
|
# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
|
|
|
|
"""Cross-platform Python dependency installer for Unsloth Studio.
|
|
|
|
Called by setup.sh (Linux/WSL) and setup.ps1 (Windows) after the venv is
|
|
activated. Expects `pip` and `python` on PATH to point at the venv.
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import glob
|
|
import os
|
|
import platform
|
|
import re
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
import sysconfig
|
|
import tempfile
|
|
import textwrap
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
_BACKEND_DIR = Path(__file__).resolve().parent / "backend"
|
|
if str(_BACKEND_DIR) not in sys.path:
|
|
sys.path.insert(1, str(_BACKEND_DIR))
|
|
|
|
from backend.utils.wheel_utils import (
|
|
flash_attn_package_version,
|
|
flash_attn_wheel_url,
|
|
has_blackwell_gpu,
|
|
install_wheel,
|
|
probe_torch_wheel_env,
|
|
url_exists,
|
|
)
|
|
from backend.utils.uv_path_safety import uv_safe_path as _uv_safe_path
|
|
|
|
IS_WINDOWS = sys.platform == "win32"
|
|
IS_MACOS = sys.platform == "darwin"
|
|
IS_MAC_INTEL = IS_MACOS and platform.machine() == "x86_64"
|
|
IS_MAC_ARM = IS_MACOS and platform.machine() == "arm64"
|
|
IS_LINUX = sys.platform.startswith("linux")
|
|
|
|
# amd-smi auto-elevates on Windows (UAC/DiskPart prompt mid-install). This installer
|
|
# only spawns probes and pip/uv (no elevation), so set __COMPAT_LAYER=RunAsInvoker
|
|
# process-wide; amd-smi then runs un-elevated. setup.ps1 keeps per-call guards (it
|
|
# also spawns winget installers that need elevation).
|
|
if IS_WINDOWS:
|
|
os.environ.setdefault("__COMPAT_LAYER", "RunAsInvoker")
|
|
# torchcodec ships wheels only for manylinux_2_28_x86_64, macosx_12_0_arm64,
|
|
# and win_amd64. On other hosts the audio extras must be filtered out (the
|
|
# extras-no-deps step would otherwise fail), regardless of NO_TORCH.
|
|
PLATFORM_LACKS_TORCHCODEC_WHEEL = (
|
|
(IS_LINUX and platform.machine() in {"aarch64", "arm64"})
|
|
or (IS_WINDOWS and platform.machine().lower() in {"arm64", "aarch64"})
|
|
or IS_MAC_INTEL
|
|
)
|
|
|
|
# ── ROCm / AMD GPU support ─────────────────────────────────────────────────────
|
|
# Detected ROCm (major, minor) -> best PyTorch wheel tag on
|
|
# download.pytorch.org. Checked newest-first (>=).
|
|
_ROCM_TORCH_INDEX: dict[tuple[int, int], str] = {
|
|
(7, 2): "rocm7.2", # torch 2.11.0
|
|
(7, 1): "rocm7.1", # torch 2.10.0
|
|
(7, 0): "rocm7.0",
|
|
(6, 4): "rocm6.4",
|
|
(6, 3): "rocm6.3",
|
|
(6, 2): "rocm6.2",
|
|
(6, 1): "rocm6.1",
|
|
(6, 0): "rocm6.0",
|
|
}
|
|
|
|
# AMD per-arch leaves needing the torch 2.11 floor (the _grouped_mm <2.11 bug).
|
|
# Mirrors *FloorMap in install.ps1 / setup.ps1; other arches ship <2.11 and stay bare.
|
|
_ROCM_GFX_TORCH211_LEAVES: frozenset[str] = frozenset({"gfx120x-all", "gfx1151", "gfx1150"})
|
|
|
|
# pytorch.org rocmX.Y indexes KNOWN to ship torch 2.11 (rocm7.2 only today); don't
|
|
# floor an unknown newer rocm speculatively. Match install.sh / setup.ps1 / install.ps1.
|
|
_ROCM_KNOWN_TORCH211_VERSIONS: frozenset[tuple[int, int]] = frozenset({(7, 2)})
|
|
|
|
# Per-tag pip specs; rocm7.2 ships torch 2.11.0 (older tags cap at 2.10.x).
|
|
_ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {
|
|
"rocm7.2": (
|
|
"torch>=2.11.0,<2.12.0",
|
|
"torchvision>=0.26.0,<0.27.0",
|
|
"torchaudio>=2.11.0,<2.12.0",
|
|
),
|
|
# rocm7.1 and earlier: torch 2.x below 2.11
|
|
"_default": (
|
|
"torch>=2.4,<2.11.0",
|
|
"torchvision>=0.19,<0.26.0",
|
|
"torchaudio>=2.4,<2.11.0",
|
|
),
|
|
}
|
|
# Windows AMD per-arch companion pins for the repo.amd.com index (mirrors the install.ps1 /
|
|
# setup.ps1 floor maps): pinning stops the per-arch index (each published independently) from
|
|
# resolving an ABI-mismatched companion. Unlisted arches have no floor, so stay bare.
|
|
_WINDOWS_ROCM_TORCH_PKG_SPECS: dict[str, tuple[str, str, str]] = {
|
|
"gfx1201": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
|
|
"gfx1200": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
|
|
"gfx1151": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
|
|
"gfx1150": _ROCM_TORCH_PKG_SPECS["rocm7.2"],
|
|
}
|
|
_PYTORCH_WHL_BASE = (
|
|
os.environ.get("UNSLOTH_PYTORCH_MIRROR") or "https://download.pytorch.org/whl"
|
|
).rstrip("/")
|
|
|
|
|
|
def _strip_index_url_credentials(url: str) -> str:
|
|
"""Strip userinfo (user:password@) AND query/fragment from a wheel index URL.
|
|
|
|
An authenticated pin must not leak credentials in printed output; query/fragment
|
|
may hold tokens and aren't part of the PEP 503 index identity. Host/path stay
|
|
exact. MUST match install.sh / setup.ps1 / install.ps1.
|
|
"""
|
|
scheme, sep, rest = url.partition("://")
|
|
if not sep:
|
|
return url
|
|
rest = rest.split("?", 1)[0].split("#", 1)[0] # drop query / fragment
|
|
authority, slash, tail = rest.partition("/")
|
|
host = authority.rpartition("@")[2] # drop user:pass@ userinfo
|
|
return f"{scheme}://{host}{slash}{tail}"
|
|
|
|
|
|
_URL_USERINFO_RE = re.compile(r"(https?://)[^/@\s`]+@")
|
|
_URL_QUERY_VALUE_RE = re.compile(r"([?&][^=\s&`]+)=[^&#\s`]+")
|
|
# URL-anchored so a bare "#..." (a shell comment in tool output) is never touched.
|
|
_URL_FRAGMENT_RE = re.compile(r"(https?://[^\s`#]+)#[^\s`]+")
|
|
|
|
|
|
def _redact_install_output(output: "bytes | str") -> str:
|
|
"""Redact index-URL credentials (userinfo + query values + fragments) from captured
|
|
installer output before printing. uv/pip failure text embeds the failing --index-url
|
|
verbatim, which can carry a user:token@, ?token= or #token= secret. MUST match
|
|
install.sh / setup.ps1 / install.ps1's output sanitizers."""
|
|
text = output.decode(errors = "replace") if isinstance(output, bytes) else output
|
|
text = _URL_USERINFO_RE.sub(r"\1<redacted>@", text)
|
|
text = _URL_QUERY_VALUE_RE.sub(r"\1=<redacted>", text)
|
|
return _URL_FRAGMENT_RE.sub(r"\1#<redacted>", text)
|
|
|
|
|
|
def _trim_index_path_slashes(url: str) -> str:
|
|
"""Trim trailing slashes from the URL PATH only, preserving ?query / #fragment. A
|
|
whole-URL rstrip("/") corrupts a token that ends in "/" (e.g. base64 ...abc/) and a
|
|
single-slash strip leaves .../cu128// classifying as an empty leaf. MUST match
|
|
install.sh / setup.ps1 / install.ps1."""
|
|
value = url.strip()
|
|
match = re.fullmatch(r"([^?#]*)([?#].*)?", value)
|
|
if match is None:
|
|
return value.rstrip("/")
|
|
return match.group(1).rstrip("/") + (match.group(2) or "")
|
|
|
|
|
|
def _torch_index_leaf(url: str) -> str:
|
|
"""Final URL path segment, lowercased, query/fragment removed first.
|
|
|
|
So a token-authenticated pin (.../cu128?token=x) classifies as cu128 (a raw leaf
|
|
keeps the query, never equals the +cu128 tag, and force-reinstalls every update).
|
|
CLASSIFICATION only; the install keeps the full URL. MUST match install.sh /
|
|
setup.ps1 / install.ps1.
|
|
"""
|
|
path = url.split("?", 1)[0].split("#", 1)[0]
|
|
return path.rstrip("/").rsplit("/", 1)[-1].lower()
|
|
|
|
|
|
# CUDA torch repair specs (see _ensure_cuda_torch). torch 2.11 is allowed (torchao
|
|
# 0.17 cpp loads cleanly, and the flash-attn/causal-conv1d/mamba wheels pass on 2.11).
|
|
# torchvision/torchaudio are pinned (not bare) so the exclusive --index-url can't
|
|
# resolve one built against a different torch major -> ABI mismatch.
|
|
_CUDA_TORCH_PKG_SPEC: tuple[str, str, str] = (
|
|
"torch>=2.4,<2.12.0",
|
|
"torchvision>=0.19,<0.27.0",
|
|
"torchaudio>=2.4,<2.12.0",
|
|
)
|
|
|
|
# CPU torch repair specs (see _ensure_cpu_torch). Same bounds/reasoning as CUDA: the
|
|
# /cpu index also serves newer torch, so a bare trio could resolve out of range or ABI-
|
|
# mismatched.
|
|
_CPU_TORCH_PKG_SPEC: tuple[str, str, str] = _CUDA_TORCH_PKG_SPEC
|
|
|
|
# torchao's cpp extensions are pinned to ONE torch release AND CUDA major. A torch
|
|
# mismatch just skips the cpp kernels (slow Python fallback); a CUDA mismatch fails
|
|
# to import ("libcudart.so.12: cannot open shared object file"). The torch pin is a
|
|
# range, so match torchao to the installed torch (table: pytorch/ao#2919):
|
|
# 2.9.x -> 0.14.0
|
|
# 2.10.x, CUDA<=12 -> 0.16.0 (cpp built for 2.10, loads via the CUDA-12 wheel)
|
|
# 2.10.x, CUDA>=13 -> 0.17.0 (cu130: 0.16.0's CUDA-12 cpp crashes on load; 0.17.0
|
|
# targets torch 2.11 so its cpp is cleanly skipped, not crashed)
|
|
# 2.11.x -> 0.17.0 (reachable via CUDA or ROCm rocm7.2)
|
|
# Unknown/older torch keeps the conservative default.
|
|
_TORCHAO_DEFAULT_SPEC = "torchao==0.14.0"
|
|
_TORCHAO_TORCH_210_SPEC = "torchao==0.16.0"
|
|
_TORCHAO_TORCH_210_CUDA13_SPEC = "torchao==0.17.0"
|
|
_TORCHAO_TORCH_211_PLUS_SPEC = "torchao==0.17.0"
|
|
# torch 2.10 built against CUDA >= this major can't load 0.16.0's CUDA-12 cpp.
|
|
_TORCHAO_CUDA13_MIN_MAJOR = 13
|
|
|
|
|
|
def _cuda_major_from_torch_version(torch_version: str) -> int | None:
|
|
"""Extract the CUDA major from a torch local version tag, e.g. '2.10.0+cu130'
|
|
-> 13, '2.10.0+cu128' -> 12. Returns None for rocm/cpu/tagless builds."""
|
|
local = str(torch_version).split("+", 1)
|
|
if len(local) < 2 or not local[1].startswith("cu"):
|
|
return None
|
|
digits = re.sub(r"[^0-9].*", "", local[1][2:]) # 'cu130' -> '130'
|
|
if not digits:
|
|
return None
|
|
return int(digits) // 10 # '130' -> 13, '128' -> 12, '118' -> 11
|
|
|
|
|
|
def _select_torchao_spec(torch_version: str | None) -> str:
|
|
"""Map an installed torch version string (e.g. '2.10.0+cu130') to the torchao
|
|
pip spec whose cpp extensions match it. Falls back to _TORCHAO_DEFAULT_SPEC for
|
|
torch <=2.9, a non-2.x major, or an unparseable/missing version. Pure function.
|
|
"""
|
|
if not torch_version:
|
|
return _TORCHAO_DEFAULT_SPEC
|
|
release = str(torch_version).split("+", 1)[0] # drop +cu130/+rocm6.4/+cpu
|
|
parts = release.split(".")
|
|
try:
|
|
# Strip any pre-release/dev suffix from the minor (e.g. '10rc1' -> '10'),
|
|
# matching wheel_utils.probe_torch_wheel_env.
|
|
minor_str = re.sub(r"[^0-9].*", "", parts[1]) if len(parts) > 1 else ""
|
|
major, minor = int(parts[0]), int(minor_str)
|
|
except (IndexError, ValueError):
|
|
return _TORCHAO_DEFAULT_SPEC
|
|
if major != 2:
|
|
return _TORCHAO_DEFAULT_SPEC
|
|
if minor >= 11:
|
|
return _TORCHAO_TORCH_211_PLUS_SPEC # newest known build; covers 2.11+
|
|
if minor == 10:
|
|
# cu130+ can't load 0.16.0's CUDA-12 cpp; use 0.17.0 (cpp skipped, not crashed).
|
|
cuda_major = _cuda_major_from_torch_version(str(torch_version))
|
|
if cuda_major is not None and cuda_major >= _TORCHAO_CUDA13_MIN_MAJOR:
|
|
return _TORCHAO_TORCH_210_CUDA13_SPEC
|
|
return _TORCHAO_TORCH_210_SPEC
|
|
return _TORCHAO_DEFAULT_SPEC
|
|
|
|
|
|
def _probe_installed_torch_version() -> str | None:
|
|
"""Return torch.__version__ from the target venv (sys.executable), or None if
|
|
torch is absent/unimportable. Cross-platform (unlike probe_torch_wheel_env,
|
|
which is Linux-only); mirrors the subprocess probe in _ensure_cuda_torch.
|
|
"""
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
"import torch, sys; sys.stdout.write(getattr(torch, '__version__', ''))",
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 90,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return None
|
|
if probe.returncode != 0:
|
|
return None
|
|
lines = [line.strip() for line in (probe.stdout or "").splitlines() if line.strip()]
|
|
return lines[-1] if lines else None
|
|
|
|
|
|
def _installed_torch_is_windows_rocm() -> bool:
|
|
"""Return True when the target venv currently has a Windows ROCm torch build.
|
|
|
|
This is a belt-and-suspenders guard for the torchao override step: if the
|
|
earlier ROCm install path failed to set _rocm_windows_torch_installed but the
|
|
venv already contains a ROCm torch wheel, still skip torchao because it
|
|
crashes on import on Windows ROCm.
|
|
"""
|
|
if not IS_WINDOWS:
|
|
return False
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import sys, torch; "
|
|
"hip = getattr(getattr(torch, 'version', None), 'hip', None) or ''; "
|
|
"ver = getattr(torch, '__version__', '').lower(); "
|
|
"sys.stdout.write('yes' if (hip or 'rocm' in ver or 'rocmsdk' in ver) else '')"
|
|
),
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 90,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return False
|
|
lines = [line.strip() for line in (probe.stdout or "").splitlines() if line.strip()]
|
|
return probe.returncode == 0 and bool(lines and lines[-1] == "yes")
|
|
|
|
|
|
# constraints.txt caps new anyio resolutions at <4.14 (#6483), but an install
|
|
# from before the cap existed can already be stuck at 4.14+, which later
|
|
# constrained installs won't touch since it already satisfies mcp/fastmcp.
|
|
_ANYIO_BAD_FLOOR = (4, 14)
|
|
|
|
|
|
def _installed_anyio_version() -> tuple[int, int] | None:
|
|
try:
|
|
from importlib.metadata import version as _pkg_version
|
|
raw = _pkg_version("anyio")
|
|
except Exception:
|
|
return None
|
|
parts = raw.split(".")
|
|
try:
|
|
major = int(parts[0])
|
|
minor = int(re.sub(r"[^0-9].*", "", parts[1])) if len(parts) > 1 else 0
|
|
except (IndexError, ValueError):
|
|
return None
|
|
return (major, minor)
|
|
|
|
|
|
def _repair_bad_anyio() -> None:
|
|
installed = _installed_anyio_version()
|
|
if installed is None or installed < _ANYIO_BAD_FLOOR:
|
|
return
|
|
_safe_print(_dim(f" anyio {installed[0]}.{installed[1]} found -- reinstalling anyio<4.14..."))
|
|
pip_install(
|
|
"Repairing anyio version",
|
|
"--no-cache-dir",
|
|
"--force-reinstall",
|
|
"anyio<4.14.0",
|
|
constrain = False,
|
|
)
|
|
|
|
|
|
# AMD Windows ROCm wheels (repo.amd.com/rocm/whl/{arch_family}/).
|
|
# Override with UNSLOTH_ROCM_WINDOWS_MIRROR for air-gapped/mirror installs.
|
|
_ROCM_WINDOWS_INDEX_BASE = (
|
|
os.environ.get("UNSLOTH_ROCM_WINDOWS_MIRROR") or "https://repo.amd.com/rocm/whl"
|
|
).rstrip("/")
|
|
|
|
# gfx arch → AMD index arch-family suffix; each family is a separate
|
|
# pip index on repo.amd.com.
|
|
_GFX_TO_AMD_INDEX_ARCH: dict[str, str] = {
|
|
"gfx1201": "gfx120X-all",
|
|
"gfx1200": "gfx120X-all", # RDNA 4
|
|
"gfx1151": "gfx1151",
|
|
"gfx1150": "gfx1150", # RDNA 3.5 (Strix Halo/Point)
|
|
"gfx1103": "gfx110X-all",
|
|
"gfx1102": "gfx110X-all", # RDNA 3
|
|
"gfx1101": "gfx110X-all",
|
|
"gfx1100": "gfx110X-all",
|
|
"gfx90a": "gfx90a",
|
|
"gfx908": "gfx908", # MI200/MI100
|
|
}
|
|
|
|
# bitsandbytes continuous-release_main wheels with the ROCm 4-bit GEMV fix
|
|
# (bnb PR #1887, post-0.49.2). bnb <= 0.49.2 NaNs at decode shape on every
|
|
# AMD GPU. Drop the pin once bnb 0.50+ ships on PyPI.
|
|
_BNB_ROCM_PRERELEASE_URLS: dict[str, str] = {
|
|
"x86_64": (
|
|
"https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
|
|
"download/continuous-release_main/"
|
|
"bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_x86_64.whl"
|
|
),
|
|
"aarch64": (
|
|
"https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
|
|
"download/continuous-release_main/"
|
|
"bitsandbytes-1.33.7.preview-py3-none-manylinux_2_24_aarch64.whl"
|
|
),
|
|
# Windows ROCm wheel ships libbitsandbytes_rocm{VER}.dll. BNB's HIP
|
|
# auto-detect may mismatch the DLL suffix, so we scan the wheel and set
|
|
# BNB_ROCM_VERSION in _install_bnb_windows_rocm() and worker.py.
|
|
"win_amd64": (
|
|
"https://github.com/bitsandbytes-foundation/bitsandbytes/releases/"
|
|
"download/continuous-release_main/"
|
|
"bitsandbytes-1.33.7.preview-py3-none-win_amd64.whl"
|
|
),
|
|
}
|
|
_BNB_ROCM_PYPI_FALLBACK = "bitsandbytes>=0.49.1"
|
|
|
|
|
|
def _bnb_rocm_prerelease_url() -> str | None:
|
|
"""Return the continuous-release_main bnb wheel URL for the current arch,
|
|
or None when no pre-release wheel is available.
|
|
"""
|
|
arch = platform.machine().lower()
|
|
arch = {"amd64": "x86_64", "arm64": "aarch64"}.get(arch, arch)
|
|
return _BNB_ROCM_PRERELEASE_URLS.get(arch)
|
|
|
|
|
|
def _amd_smi_env() -> dict[str, str] | None:
|
|
"""On Windows, env with __COMPAT_LAYER=RunAsInvoker; None elsewhere.
|
|
NB: RunAsInvoker doesn't stop amd-smi's runtime elevation (its manifest is
|
|
asInvoker -- it elevates a child via ShellExecute). The real guard is
|
|
_amd_smi_allowed() below; this is harmless belt-and-suspenders."""
|
|
if platform.system() != "Windows":
|
|
return None
|
|
return {**os.environ, "__COMPAT_LAYER": "RunAsInvoker"}
|
|
|
|
|
|
def _path_inside_venv(path: str) -> bool:
|
|
"""True if ``path`` is inside the active venv (sys.prefix).
|
|
|
|
The venv hipInfo.exe (AMD wheel, put on PATH by the bnb fix) is NOT a HIP SDK
|
|
(_amd_smi_allowed)."""
|
|
try:
|
|
# realpath (not abspath): resolve symlinks/8.3 names so an aliased venv matches.
|
|
_root = os.path.normcase(os.path.realpath(sys.prefix))
|
|
# Guard a root-dir prefix (C:\ or /): commonpath would match every path on
|
|
# it. A venv is never at root, so treat that as outside.
|
|
if os.path.dirname(_root) == _root:
|
|
return False
|
|
return os.path.normcase(os.path.commonpath([os.path.realpath(path), _root])) == _root
|
|
except (ValueError, OSError):
|
|
# Different drive / unresolvable -> treat as outside the venv.
|
|
return False
|
|
|
|
|
|
def _external_hipinfo_on_path() -> bool:
|
|
"""True if a hipinfo OUTSIDE the venv is on PATH.
|
|
|
|
shutil.which returns only the first hit, so the venv hipInfo could shadow a
|
|
real HIP SDK's; scan every PATH entry and skip the venv copy."""
|
|
for _dir in os.environ.get("PATH", "").split(os.pathsep):
|
|
_dir = _dir.strip('"') # PATH entries can be quoted on Windows
|
|
if not _dir:
|
|
continue
|
|
_candidate = os.path.join(_dir, "hipinfo.exe")
|
|
if os.path.isfile(_candidate) and not _path_inside_venv(_candidate):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _amd_smi_allowed() -> bool:
|
|
"""Whether it is safe to spawn amd-smi here.
|
|
|
|
On Windows w/o a working HIP runtime, amd-smi elevates a child and pops a
|
|
UAC/DiskPart prompt RunAsInvoker can't suppress. Only call it on Windows with
|
|
a HIP SDK (hipinfo present) or UNSLOTH_ENABLE_AMD_SMI=1; Linux/macOS always.
|
|
"""
|
|
if platform.system() != "Windows":
|
|
return True
|
|
flag = os.environ.get("UNSLOTH_ENABLE_AMD_SMI", "").strip().lower()
|
|
if flag in ("1", "true", "yes", "on"):
|
|
return True
|
|
if flag in ("0", "false", "no", "off"):
|
|
return False
|
|
# A real HIP SDK lets amd-smi run un-elevated; hipinfo-on-PATH is the proxy.
|
|
# Ignore the venv hipInfo.exe (AMD wheel via bnb fix): not a HIP SDK, doesn't
|
|
# stop amd-smi's DiskPart UAC.
|
|
if _external_hipinfo_on_path():
|
|
return True
|
|
for _var in ("HIP_PATH", "HIP_PATH_57", "ROCM_PATH"):
|
|
_root = os.environ.get(_var)
|
|
if not _root:
|
|
continue
|
|
_candidate = os.path.join(_root, "bin", "hipinfo.exe")
|
|
if os.path.isfile(_candidate) and not _path_inside_venv(_candidate):
|
|
return True
|
|
return False
|
|
|
|
|
|
def _detect_rocm_version() -> tuple[int, int] | None:
|
|
"""Return (major, minor) of the installed ROCm stack, or None."""
|
|
rocm_root = os.environ.get("ROCM_PATH") or "/opt/rocm"
|
|
for path in (
|
|
os.path.join(rocm_root, ".info", "version"),
|
|
os.path.join(rocm_root, "lib", "rocm_version"),
|
|
):
|
|
try:
|
|
with open(path) as fh:
|
|
parts = fh.read().strip().split("-")[0].split(".")
|
|
# Explicit length guard: don't rely on the broad except below to
|
|
# swallow IndexError on a single-component version (e.g. "6\n").
|
|
if len(parts) >= 2:
|
|
return int(parts[0]), int(parts[1])
|
|
except Exception:
|
|
pass
|
|
|
|
# Try amd-smi version (outputs "... | ROCm version: X.Y.Z").
|
|
# Gated off on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt);
|
|
# hipconfig below covers that case.
|
|
amd_smi = shutil.which("amd-smi") if _amd_smi_allowed() else None
|
|
if amd_smi:
|
|
try:
|
|
result = subprocess.run(
|
|
[amd_smi, "version"],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 5,
|
|
env = _amd_smi_env(),
|
|
)
|
|
if result.returncode == 0:
|
|
m = re.search(r"ROCm version:\s*(\d+)\.(\d+)", result.stdout)
|
|
if m:
|
|
return int(m.group(1)), int(m.group(2))
|
|
except Exception:
|
|
pass
|
|
|
|
# Try hipconfig --version (outputs bare version like "6.3.21234.2")
|
|
hipconfig = shutil.which("hipconfig")
|
|
if hipconfig:
|
|
try:
|
|
result = subprocess.run(
|
|
[hipconfig, "--version"],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 5,
|
|
)
|
|
if result.returncode == 0:
|
|
raw = result.stdout.decode().strip().split("\n")[0]
|
|
parts = raw.split(".")
|
|
if len(parts) >= 2 and parts[0].isdigit() and parts[1].split("-")[0].isdigit():
|
|
return int(parts[0]), int(parts[1].split("-")[0])
|
|
except Exception:
|
|
pass
|
|
|
|
# Distro package-manager fallbacks: package-managed ROCm can expose GPUs via
|
|
# rocminfo/amd-smi but lack /opt/rocm/.info/version and hipconfig, so probe
|
|
# dpkg (Debian/Ubuntu) and rpm (RHEL/Fedora/SUSE) for the rocm-core version.
|
|
# Matches install.sh::get_torch_index_url so `studio update` == fresh install.
|
|
for cmd in (
|
|
["dpkg-query", "-W", "-f=${Version}\n", "rocm-core"],
|
|
["rpm", "-q", "--qf", "%{VERSION}\n", "rocm-core"],
|
|
):
|
|
exe = shutil.which(cmd[0])
|
|
if not exe:
|
|
continue
|
|
try:
|
|
result = subprocess.run(
|
|
[exe, *cmd[1:]],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 5,
|
|
)
|
|
except Exception:
|
|
continue
|
|
if result.returncode != 0 or not result.stdout.strip():
|
|
continue
|
|
raw = result.stdout.strip()
|
|
# dpkg can prepend an epoch ("1:6.3.0-1"); strip it before parsing.
|
|
raw = re.sub(r"^\d+:", "", raw)
|
|
m = re.match(r"(\d+)[.-](\d+)", raw)
|
|
if m:
|
|
return int(m.group(1)), int(m.group(2))
|
|
|
|
return None
|
|
|
|
|
|
def _pick_visible_index(num_tokens: int) -> int:
|
|
"""Resolve HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES to an index into a
|
|
list of length num_tokens. Returns 0 (first GPU) for unset, empty, '-1',
|
|
UUID-style, or out-of-range values."""
|
|
for _env in ("HIP_VISIBLE_DEVICES", "ROCR_VISIBLE_DEVICES"):
|
|
_val = os.environ.get(_env)
|
|
if _val is None:
|
|
continue
|
|
_val = _val.strip()
|
|
if _val == "" or _val == "-1":
|
|
return 0
|
|
_first = _val.split(",")[0].strip()
|
|
try:
|
|
_idx = int(_first)
|
|
if 0 <= _idx < num_tokens:
|
|
return _idx
|
|
except ValueError:
|
|
pass
|
|
return 0
|
|
return 0
|
|
|
|
|
|
def _detect_windows_gfx_arch() -> str | None:
|
|
"""Return the gcnArchName on Windows (e.g. 'gfx1200'), or None.
|
|
|
|
Probe order matches the PowerShell installer: env-var override, then
|
|
hipinfo (PATH or HIP_PATH/ROCM_PATH bin), then amd-smi. Without the
|
|
amd-smi fallback, runtime-only AMD installs lacking hipinfo on PATH
|
|
return early and `studio update` cannot repair a CPU-only venv.
|
|
|
|
On multi-GPU hosts, detected gfx tokens are deduplicated (preserving
|
|
enumeration order) and HIP_VISIBLE_DEVICES / ROCR_VISIBLE_DEVICES picks
|
|
which to install for. The first GPU is used when no env var is set.
|
|
"""
|
|
# 1. Explicit override (matches PowerShell installer's env-var path).
|
|
_override = os.environ.get("UNSLOTH_ROCM_GFX_ARCH")
|
|
if _override and _override.strip():
|
|
return _override.strip().lower()
|
|
|
|
def _dedup_pick(tokens: list[str]) -> "str | None":
|
|
if not tokens:
|
|
return None
|
|
# Index into the full ordered list so HIP_VISIBLE_DEVICES addresses
|
|
# GPU N on mixed-arch hosts, then return that arch.
|
|
return tokens[_pick_visible_index(len(tokens))]
|
|
|
|
# 2. hipinfo via PATH, then HIP_PATH\bin / ROCM_PATH\bin.
|
|
hipinfo = shutil.which("hipinfo")
|
|
if not hipinfo:
|
|
for _env_var in ("HIP_PATH", "ROCM_PATH"):
|
|
_root = os.environ.get(_env_var)
|
|
if _root:
|
|
_candidate = os.path.join(_root, "bin", "hipinfo.exe")
|
|
if os.path.isfile(_candidate):
|
|
hipinfo = _candidate
|
|
break
|
|
if not hipinfo:
|
|
# 2b. AMD torch wheels ship hipInfo.exe into the venv Scripts dir
|
|
# (next to python.exe); resolvable even on driver-only hosts with no
|
|
# SDK install at all. Lets `studio update` re-detect the arch on a
|
|
# venv that already has the AMD wheel.
|
|
_venv_hipinfo = os.path.join(os.path.dirname(sys.executable), "hipInfo.exe")
|
|
if os.path.isfile(_venv_hipinfo):
|
|
hipinfo = _venv_hipinfo
|
|
if hipinfo:
|
|
try:
|
|
result = subprocess.run(
|
|
[hipinfo],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 10,
|
|
)
|
|
# Accept partial output even when hipinfo crashes (e.g. 0xC0000005 /
|
|
# STATUS_ACCESS_VIOLATION on some RDNA 4 hosts): a gcnArchName in stdout
|
|
# means the device was enumerated pre-crash, so the arch is trustworthy.
|
|
# Ignoring it causes a silent CPU PyTorch fallback (issue #6043).
|
|
text = result.stdout.decode(errors = "replace")
|
|
# findall gets every gcnArchName line so multi-GPU hosts are
|
|
# enumerable and HIP_VISIBLE_DEVICES selects correctly.
|
|
_tokens = [
|
|
t.strip().lower() for t in re.findall(r"(?im)^\s*gcnArchName\s*:\s*(\S+)", text)
|
|
]
|
|
_pick = _dedup_pick(_tokens)
|
|
if _pick:
|
|
return _pick
|
|
except Exception:
|
|
pass
|
|
|
|
# 3. amd-smi fallback -- runtime-only Radeon installs ship amd-smi but no hipinfo.
|
|
# Gated off on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt); the arch
|
|
# arrives via --rocm-gfx / name inference there, so this is only needed when safe.
|
|
amd_smi = shutil.which("amd-smi") if _amd_smi_allowed() else None
|
|
if amd_smi:
|
|
for _args in (("static", "--asic"), ("list",)):
|
|
try:
|
|
result = subprocess.run(
|
|
[amd_smi, *_args],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 10,
|
|
env = _amd_smi_env(),
|
|
)
|
|
if result.returncode != 0:
|
|
continue
|
|
text = result.stdout.decode(errors = "replace")
|
|
# Prefer labelled gfx lines; fall back to bare tokens.
|
|
_labelled = re.findall(
|
|
r"(?im)^\s*(?:target_graphics_version|gfx|arch|asic)\b[^:\r\n]*:\s*(gfx[1-9][0-9a-z]{2,3})\b",
|
|
text,
|
|
)
|
|
_tokens = [t.lower() for t in _labelled]
|
|
if not _tokens:
|
|
_tokens = re.findall(r"\bgfx[1-9][0-9a-z]{2,3}\b", text.lower())
|
|
_pick = _dedup_pick(_tokens)
|
|
if _pick:
|
|
return _pick
|
|
except Exception:
|
|
continue
|
|
|
|
# 4. Last resort: GPU marketing name via WMI → arch table. Driver-only
|
|
# hosts (Adrenalin, no HIP SDK) have neither hipinfo nor amd-smi
|
|
# (amd-smi does not exist on Windows at all), but the display driver
|
|
# always knows the GPU name. Mirrors setup.ps1's $nameArchTable so a
|
|
# standalone `studio update` can repair a CPU-only venv on such hosts.
|
|
try:
|
|
result = subprocess.run(
|
|
[
|
|
"powershell.exe",
|
|
"-NoProfile",
|
|
"-NonInteractive",
|
|
"-Command",
|
|
"(Get-CimInstance Win32_VideoController).Name",
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 30,
|
|
creationflags = getattr(subprocess, "CREATE_NO_WINDOW", 0),
|
|
)
|
|
if result.returncode == 0:
|
|
_tokens = []
|
|
for _name in result.stdout.decode(errors = "replace").splitlines():
|
|
_arch = _gfx_arch_from_gpu_name(_name.strip())
|
|
if _arch:
|
|
_tokens.append(_arch)
|
|
_pick = _dedup_pick(_tokens)
|
|
if _pick:
|
|
print(f" gfx arch inferred from GPU name (WMI): {_pick}")
|
|
return _pick
|
|
except Exception:
|
|
pass
|
|
return None
|
|
|
|
|
|
# GPU marketing-name → gfx arch table, mirroring setup.ps1's $nameArchTable.
|
|
# Most-specific first; first match wins. Covers only arches the ROCm
|
|
# prebuilts / AMD Windows torch indexes support; unknown names return None
|
|
# (callers then fall back cleanly to CPU).
|
|
_WIN_GPU_NAME_ARCH_TABLE: "list[tuple[str, str]]" = [
|
|
(r"9070 XT|9080", "gfx1201"), # RDNA 4 (Radeon RX 9070 XT / 9080)
|
|
(r"9070|9060", "gfx1200"), # RDNA 4 (Radeon RX 9070 / 9060)
|
|
# RDNA 3.5 (Strix Halo: Radeon 8060S/8050S/8040S iGPU, Ryzen AI Max+)
|
|
(r"8060S|8050S|8040S|Strix Halo|Ryzen AI Max|AI Max", "gfx1151"),
|
|
# RDNA 3.5 (Strix/Krackan Point: Radeon 890M/880M iGPU, Ryzen AI 9 HX 370/375)
|
|
(
|
|
r"890M|880M|860M|840M|Strix Point|Krackan|HX 37[05]|AI 9 HX|AI 9 36[05]"
|
|
r"|AI 7 35[05]|AI 5 34[05]|AI 7 PRO 35|AI 5 33",
|
|
"gfx1150",
|
|
),
|
|
# RDNA 3 desktop / workstation (Navi 31)
|
|
(r"RX 7900|RX 7800|RX 7700(?!S)|PRO W7900|PRO W7800|PRO W7700", "gfx1100"),
|
|
(r"RX 7600|RX 7700S|RX 7650|PRO W7600|PRO W7500|PRO V710", "gfx1102"), # Navi 33
|
|
# RDNA 3 iGPU (Phoenix / Hawk Point)
|
|
(r"780M|760M|740M|Phoenix|Hawk Point|Z1 Extreme|Z2 Extreme", "gfx1103"),
|
|
(r"RX 6900|RX 6800|RX 6750|RX 6700|PRO W6800|PRO W6900", "gfx1030"), # Navi 21
|
|
(r"RX 6650|RX 6600|PRO W6600|PRO W6650", "gfx1032"), # Navi 23
|
|
(r"RX 6500|RX 6400|RX 6300|PRO W6400|PRO W6500", "gfx1034"), # Navi 24
|
|
]
|
|
|
|
|
|
def _gfx_arch_from_gpu_name(name: str) -> "str | None":
|
|
"""Map a GPU marketing name to its gfx arch via _WIN_GPU_NAME_ARCH_TABLE."""
|
|
if not name:
|
|
return None
|
|
for _pat, _arch in _WIN_GPU_NAME_ARCH_TABLE:
|
|
if re.search(_pat, name, re.IGNORECASE):
|
|
return _arch
|
|
return None
|
|
|
|
|
|
def _windows_rocm_index_url(gfx_arch: str | None) -> str | None:
|
|
"""Return the AMD pip index URL for the given GPU arch, or None if unsupported."""
|
|
arch_family = _GFX_TO_AMD_INDEX_ARCH.get(gfx_arch or "")
|
|
if arch_family is None:
|
|
return None
|
|
return f"{_ROCM_WINDOWS_INDEX_BASE}/{arch_family}/"
|
|
|
|
|
|
def _detect_bnb_rocm_dll_ver() -> str | None:
|
|
"""Scan the installed bitsandbytes package for libbitsandbytes_rocm{VER}.dll.
|
|
|
|
Returns the version suffix (e.g. ``"72"``, ``"713"``) or ``None`` if
|
|
bitsandbytes is not installed or no ROCm DLL is found. Does NOT import
|
|
bitsandbytes — uses importlib.util.find_spec, so it is safe to call
|
|
before BNB is imported.
|
|
"""
|
|
import importlib.util
|
|
|
|
spec = importlib.util.find_spec("bitsandbytes")
|
|
if spec is None or not spec.submodule_search_locations:
|
|
return None
|
|
all_vers: list[str] = []
|
|
for pkg_dir in spec.submodule_search_locations:
|
|
for dll in glob.glob(os.path.join(pkg_dir, "libbitsandbytes_rocm*.dll")):
|
|
m = re.search(r"libbitsandbytes_rocm(\d+)\.dll", os.path.basename(dll))
|
|
if m:
|
|
all_vers.append(m.group(1))
|
|
# Highest numeric suffix wins (e.g. "713" over "72"); glob order is not
|
|
# guaranteed, so sort rather than take the first match.
|
|
return max(all_vers, key = lambda v: int(v)) if all_vers else None
|
|
|
|
|
|
_BNB_ROCM_SITECUSTOMIZE_BEGIN = "# BEGIN Unsloth BNB_ROCM_VERSION"
|
|
_BNB_ROCM_SITECUSTOMIZE_END = "# END Unsloth BNB_ROCM_VERSION"
|
|
_BNB_ROCM_VERSION_SOURCE_ENV = "UNSLOTH_BNB_ROCM_VERSION_SOURCE"
|
|
_BNB_ROCM_VERSION_SOURCE_SITECUSTOMIZE = "sitecustomize"
|
|
_BNB_ROCM_VERSION_SOURCE_DETECTED = "detected"
|
|
|
|
|
|
def _persist_bnb_rocm_version(version: str) -> bool:
|
|
"""Persist BNB_ROCM_VERSION for future Python processes in this venv."""
|
|
version = str(version).strip()
|
|
if not version:
|
|
return False
|
|
|
|
site_packages = sysconfig.get_path("purelib")
|
|
if not site_packages:
|
|
return False
|
|
|
|
sitecustomize_path = Path(site_packages) / "sitecustomize.py"
|
|
block = (
|
|
f"{_BNB_ROCM_SITECUSTOMIZE_BEGIN}\n"
|
|
"import os as _unsloth_os\n"
|
|
"_unsloth_existing_bnb_rocm = _unsloth_os.environ.get('BNB_ROCM_VERSION')\n"
|
|
f"_unsloth_os.environ.setdefault('BNB_ROCM_VERSION', {version!r})\n"
|
|
"if _unsloth_existing_bnb_rocm is None and "
|
|
f"_unsloth_os.environ.get('BNB_ROCM_VERSION') == {version!r}:\n"
|
|
" _unsloth_os.environ.setdefault("
|
|
f"{_BNB_ROCM_VERSION_SOURCE_ENV!r}, "
|
|
f"{_BNB_ROCM_VERSION_SOURCE_SITECUSTOMIZE!r})\n"
|
|
"del _unsloth_existing_bnb_rocm\n"
|
|
f"{_BNB_ROCM_SITECUSTOMIZE_END}\n"
|
|
)
|
|
|
|
try:
|
|
sitecustomize_path.parent.mkdir(parents = True, exist_ok = True)
|
|
existing = (
|
|
sitecustomize_path.read_text(encoding = "utf-8") if sitecustomize_path.exists() else ""
|
|
)
|
|
# Strip all managed regions, including one whose END marker was lost to
|
|
# an interrupted write, then append exactly one fresh block.
|
|
pattern = re.compile(
|
|
rf"{re.escape(_BNB_ROCM_SITECUSTOMIZE_BEGIN)}.*?"
|
|
rf"(?:{re.escape(_BNB_ROCM_SITECUSTOMIZE_END)}\n?|\Z)",
|
|
re.DOTALL,
|
|
)
|
|
remainder = pattern.sub("", existing)
|
|
separator = "" if not remainder or remainder.endswith("\n") else "\n"
|
|
updated = f"{remainder}{separator}{block}"
|
|
tmp_path = sitecustomize_path.with_name(
|
|
f"{sitecustomize_path.name}.unsloth-tmp{os.getpid()}"
|
|
)
|
|
try:
|
|
tmp_path.write_text(updated, encoding = "utf-8")
|
|
if sitecustomize_path.exists():
|
|
shutil.copymode(sitecustomize_path, tmp_path)
|
|
os.replace(tmp_path, sitecustomize_path)
|
|
finally:
|
|
tmp_path.unlink(missing_ok = True)
|
|
except (OSError, UnicodeDecodeError) as exc:
|
|
print(
|
|
f" Warning: could not persist BNB_ROCM_VERSION={version} "
|
|
f"to {sitecustomize_path}: {exc}"
|
|
)
|
|
return False
|
|
|
|
return True
|
|
|
|
|
|
def _has_rocm_gpu() -> bool:
|
|
"""Return True only if an actual AMD GPU is visible (not just ROCm tools installed).
|
|
|
|
Always returns False when an NVIDIA GPU is present -- NVIDIA takes
|
|
priority on mixed hosts and prevents every detection path below
|
|
(rocminfo, amd-smi, KFD sysfs) from producing a false positive even
|
|
if ROCm tools are installed alongside the NVIDIA driver.
|
|
"""
|
|
if _has_usable_nvidia_gpu():
|
|
return False
|
|
for cmd, check_fn in (
|
|
# rocminfo: look for a real gfx GPU id (3-4 chars, nonzero first digit).
|
|
# gfx000 is the CPU agent; ROCm 6.1+ also emits generic ISA lines like
|
|
# "gfx11-generic"/"gfx9-4-generic" with only 1-2 digits before the dash,
|
|
# which must not be treated as a real GPU.
|
|
(
|
|
["rocminfo"],
|
|
lambda out: bool(re.search(r"gfx[1-9][0-9a-z]{2,3}", out.lower())),
|
|
),
|
|
# amd-smi list: require "GPU: <number>" data rows, not just a header
|
|
(
|
|
["amd-smi", "list"],
|
|
lambda out: bool(re.search(r"(?im)^gpu\s*[:\[]\s*\d", out)),
|
|
),
|
|
):
|
|
exe = shutil.which(cmd[0])
|
|
if not exe:
|
|
continue
|
|
# Skip amd-smi on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt);
|
|
# rely on rocminfo / the sysfs fallback there.
|
|
if cmd[0] == "amd-smi" and not _amd_smi_allowed():
|
|
continue
|
|
try:
|
|
result = subprocess.run(
|
|
[exe, *cmd[1:]],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 10,
|
|
env = _amd_smi_env() if cmd[0] == "amd-smi" else None,
|
|
)
|
|
except Exception:
|
|
continue
|
|
if result.returncode == 0 and result.stdout.strip():
|
|
if check_fn(result.stdout):
|
|
return True
|
|
# sysfs KFD topology fallback (Linux only) -- matches install.sh's runtime-only
|
|
# detection. On minimal package-managed installs (no rocminfo / amd-smi), the
|
|
# kernel exposes AMD GPUs via /sys/class/kfd so `studio update` can still repair.
|
|
#
|
|
# Guard: reject any KFD node whose properties file reports a non-AMD vendor. The
|
|
# NVIDIA open kernel module (driver 560+) registers KFD nodes with a non-zero
|
|
# gpu_id and vendor_id 4318 (0x10DE), not the AMD 4098 (0x1002); without this
|
|
# check the fallback returns True on NVIDIA-only hosts, installing ROCm wheels.
|
|
if sys.platform != "win32":
|
|
try:
|
|
kfd_nodes = "/sys/class/kfd/kfd/topology/nodes"
|
|
if os.path.isdir(kfd_nodes):
|
|
for entry in os.listdir(kfd_nodes):
|
|
gpu_id_path = os.path.join(kfd_nodes, entry, "gpu_id")
|
|
try:
|
|
with open(gpu_id_path) as fh:
|
|
gpu_id = fh.read().strip()
|
|
except OSError:
|
|
continue
|
|
if not gpu_id or gpu_id == "0": # gpu_id 0 = CPU node
|
|
continue
|
|
# Require AMD vendor_id 4098 (0x1002). KFD properties files exist
|
|
# on every kernel exposing /sys/class/kfd, so a missing file means
|
|
# AMD ownership is unconfirmed -- skip the node rather than risk a
|
|
# false positive (e.g. NVIDIA open-driver KFD nodes lacking it).
|
|
props_path = os.path.join(kfd_nodes, entry, "properties")
|
|
try:
|
|
with open(props_path) as fh:
|
|
props = fh.read()
|
|
except OSError:
|
|
continue # can't confirm vendor -- skip
|
|
if not re.search(r"\bvendor_id\s+4098\b", props):
|
|
continue
|
|
return True
|
|
except OSError:
|
|
pass
|
|
return False
|
|
|
|
|
|
def _has_usable_nvidia_gpu() -> bool:
|
|
"""Return True when an NVIDIA GPU is present and usable.
|
|
|
|
Primary probe: nvidia-smi -L (subprocess).
|
|
Fallback: /proc/driver/nvidia/gpus/ sysfs (Linux only) -- handles the
|
|
case where nvidia-smi is present but the subprocess fails (PATH gap,
|
|
timeout, driver initialisation race). If either probe confirms an
|
|
NVIDIA GPU the function returns True so _has_rocm_gpu() is blocked.
|
|
|
|
CUDA_VISIBLE_DEVICES set to "" or "-1" hides every NVIDIA device (mixed
|
|
AMD+NVIDIA hosts steering work to the AMD card); neither probe honours
|
|
that env var, so check it first and report the GPU as not usable. Unset
|
|
means all devices visible.
|
|
"""
|
|
cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
|
|
if cvd is not None and cvd.strip() in ("", "-1"):
|
|
return False
|
|
exe = shutil.which("nvidia-smi")
|
|
if exe:
|
|
try:
|
|
result = subprocess.run(
|
|
[exe, "-L"],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 10,
|
|
)
|
|
if result.returncode == 0 and "GPU " in result.stdout:
|
|
return True
|
|
except Exception:
|
|
pass
|
|
# Fallback: the NVIDIA driver exposes one subdirectory per GPU under
|
|
# /proc/driver/nvidia/gpus/ on Linux regardless of nvidia-smi state.
|
|
if sys.platform != "win32":
|
|
try:
|
|
gpu_dir = "/proc/driver/nvidia/gpus"
|
|
if os.path.isdir(gpu_dir) and os.listdir(gpu_dir):
|
|
return True
|
|
except OSError:
|
|
pass
|
|
return False
|
|
|
|
|
|
def _detect_amd_gfx_codes() -> list[str]:
|
|
"""Return the AMD gfx ISA strings visible to ROCm (e.g. ['gfx1151']).
|
|
|
|
Probes rocminfo, then falls back to ``amd-smi list`` and ``amd-smi
|
|
static --asic`` for runtime-only Radeon hosts that ship amd-smi but no
|
|
rocminfo. Returns an empty list when no probe yields a gfx target.
|
|
"""
|
|
|
|
def _extract(text: str) -> list[str]:
|
|
codes = re.findall(r"gfx([1-9][0-9a-z]{2,3})", text.lower())
|
|
return list(dict.fromkeys(f"gfx{c}" for c in codes))
|
|
|
|
probes: list[list[str]] = []
|
|
if shutil.which("rocminfo"):
|
|
probes.append(["rocminfo"])
|
|
# Gate amd-smi off on Windows w/o a HIP SDK (avoids the UAC/DiskPart prompt).
|
|
if shutil.which("amd-smi") and _amd_smi_allowed():
|
|
probes.append(["amd-smi", "list"])
|
|
probes.append(["amd-smi", "static", "--asic"])
|
|
for cmd in probes:
|
|
try:
|
|
result = subprocess.run(
|
|
cmd,
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 15,
|
|
env = _amd_smi_env() if cmd[0] == "amd-smi" else None,
|
|
)
|
|
except Exception:
|
|
continue
|
|
if result.returncode != 0 or not result.stdout.strip():
|
|
continue
|
|
codes = _extract(result.stdout)
|
|
if codes:
|
|
return codes
|
|
return []
|
|
|
|
|
|
# Set by _ensure_rocm_torch() on success; suppresses the post-install AMD warning.
|
|
_rocm_windows_torch_installed: bool = False
|
|
|
|
|
|
def _install_bnb_windows_rocm() -> bool:
|
|
"""Install the AMD Windows BNB prerelease wheel. Returns True on success.
|
|
|
|
The continuous-release wheel is intentionally mismatched: the filename
|
|
encodes 1.33.7.preview (parsed as 1.33.7rc0 by PEP 440) while the wheel
|
|
metadata reports 0.50.0.dev0. uv rejects this filename/metadata mismatch,
|
|
and bypassing it with UV_SKIP_WHEEL_FILENAME_CHECK still leaves uv mangling
|
|
the bitsandbytes install. Per the AMD install guide
|
|
(https://unsloth.ai/docs/get-started/install/amd/amd-hackathon) the wheel
|
|
must be installed with plain pip, not uv, so we force pip (force_pip=True);
|
|
plain pip performs no wheel filename/metadata check.
|
|
"""
|
|
_bnb_win_url = _BNB_ROCM_PRERELEASE_URLS.get("win_amd64")
|
|
if _bnb_win_url is None:
|
|
return False
|
|
_ok = pip_install_try(
|
|
"bitsandbytes (AMD Windows, pre-release main)",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
_bnb_win_url,
|
|
constrain = False,
|
|
force_pip = True,
|
|
)
|
|
if not _ok:
|
|
return False
|
|
# Detect the actual ROCm DLL suffix in the wheel and set BNB_ROCM_VERSION so bnb
|
|
# loads the right DLL regardless of torch.version.hip (the wheel may ship "72"
|
|
# while torch reports 7.13). The worker subprocess inherits it; fall back to "72"
|
|
# if detection fails (e.g. a no-op / dry-run install).
|
|
_env_ver = os.environ.get("BNB_ROCM_VERSION")
|
|
_env_is_persisted_default = (
|
|
os.environ.get(_BNB_ROCM_VERSION_SOURCE_ENV) == _BNB_ROCM_VERSION_SOURCE_SITECUSTOMIZE
|
|
)
|
|
_persist_detected_version = False
|
|
if _env_ver and not _env_is_persisted_default:
|
|
_ver = _env_ver
|
|
else:
|
|
_ver = _detect_bnb_rocm_dll_ver() or "72"
|
|
os.environ["BNB_ROCM_VERSION"] = _ver
|
|
os.environ[_BNB_ROCM_VERSION_SOURCE_ENV] = _BNB_ROCM_VERSION_SOURCE_DETECTED
|
|
_persist_detected_version = True
|
|
if _persist_detected_version:
|
|
_persist_bnb_rocm_version(_ver)
|
|
# Make hipInfo.exe (shipped into venv Scripts by the AMD torch wheel) resolvable
|
|
# via PATH for this process and every child python (import checks, precompile):
|
|
# bitsandbytes runs hipinfo.exe at import to detect the GPU arch and logs a scary
|
|
# (harmless) ERROR + WARNING when it is missing. Scripts is on PATH only for an
|
|
# activated venv, which neither Unsloth nor the installer's children ever do.
|
|
_scripts_dir = os.path.dirname(sys.executable)
|
|
if os.path.isfile(os.path.join(_scripts_dir, "hipInfo.exe")) and not shutil.which(
|
|
"hipinfo.exe"
|
|
):
|
|
os.environ["PATH"] = _scripts_dir + os.pathsep + os.environ.get("PATH", "")
|
|
return True
|
|
|
|
|
|
def _detect_cuda_torch_index_url() -> str:
|
|
"""Return the pytorch.org CUDA wheel index URL for the host's NVIDIA driver.
|
|
|
|
Mirrors install.sh::get_torch_index_url's CUDA ladder so `studio update` repairs
|
|
to the same wheel family a fresh install would pick. Honours the explicit
|
|
overrides first (UNSLOTH_TORCH_INDEX_URL / _FAMILY) so a headless / CI install
|
|
never lets the host GPU decide. Otherwise probes nvidia-smi (parsing both "CUDA
|
|
Version:" and "CUDA UMD Version:"), defaulting to cu126 when unreadable.
|
|
"""
|
|
_override_url = os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip()
|
|
if _override_url:
|
|
return _trim_index_path_slashes(_override_url)
|
|
_override_family = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip()
|
|
if _override_family:
|
|
return f"{_PYTORCH_WHL_BASE}/{_override_family.strip('/')}"
|
|
exe = shutil.which("nvidia-smi")
|
|
if not exe and os.path.isfile("/usr/bin/nvidia-smi"):
|
|
exe = "/usr/bin/nvidia-smi"
|
|
tag = "cu126" # default when the driver CUDA version cannot be read
|
|
if exe:
|
|
try:
|
|
result = subprocess.run(
|
|
[exe],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 10,
|
|
)
|
|
if result.returncode == 0:
|
|
m = re.search(r"CUDA(?: UMD)? Version:\s*(\d+)\.(\d+)", result.stdout)
|
|
if m:
|
|
major, minor = int(m.group(1)), int(m.group(2))
|
|
if major >= 13:
|
|
tag = "cu130"
|
|
elif major == 12 and minor >= 8:
|
|
tag = "cu128"
|
|
elif major == 12 and minor >= 6:
|
|
tag = "cu126"
|
|
elif major >= 12:
|
|
tag = "cu124"
|
|
elif major >= 11:
|
|
tag = "cu118"
|
|
else:
|
|
tag = "cpu" # ancient driver: no usable CUDA wheels
|
|
except Exception:
|
|
pass
|
|
return f"{_PYTORCH_WHL_BASE}/{tag}"
|
|
|
|
|
|
def _explicit_torch_index_url() -> "str | None":
|
|
"""The wheel index URL pinned via UNSLOTH_TORCH_INDEX_URL / _FAMILY, else None.
|
|
|
|
Lets the CUDA/ROCm repair helpers honour the exact pinned family/URL instead
|
|
of re-probing the GPU. Mirrors install.sh::get_torch_index_url's override.
|
|
"""
|
|
url = os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip()
|
|
if url:
|
|
return _trim_index_path_slashes(url)
|
|
family = os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip()
|
|
if family:
|
|
return f"{_PYTORCH_WHL_BASE}/{family.strip('/')}"
|
|
return None
|
|
|
|
|
|
def _is_pip_rocm_family_leaf(leaf: str) -> bool:
|
|
"""True when a lowercased leaf names a pip --index-url ROCm family: an EXACT
|
|
rocm<digits>[.<digits>] leaf or a gfx leaf. A suffixed leaf (rocm-rel-7.2.1,
|
|
rocm7.2-private) starts with "rocm" but is a custom pin the verbatim path owns, so
|
|
match EXACTLY. Mirrors install.sh / setup.ps1.
|
|
"""
|
|
# gfx must be followed by a digit (gfx90a, gfx1151, gfx120X-all): a gfx-prefixed
|
|
# custom leaf (gfx-private) is a verbatim pin, like rocm7.2-private.
|
|
return bool(re.fullmatch(r"rocm\d+(?:\.\d+)?", leaf)) or bool(re.match(r"gfx\d", leaf))
|
|
|
|
|
|
def _explicit_rocm_torch_index_url() -> "str | None":
|
|
"""The pinned wheel index URL when it names a pip ROCm family (rocm<d>/gfx*), else None."""
|
|
url = _explicit_torch_index_url()
|
|
if url is None:
|
|
return None
|
|
return url if _is_pip_rocm_family_leaf(_torch_index_leaf(url)) else None
|
|
|
|
|
|
def _rocm_pin_family_mismatch(pin_url: str, installed_ver: str) -> bool:
|
|
"""True when an explicit ROCm pin names a different ROCm family than the installed
|
|
ROCm torch, so the pin needs a reinstall. Mirrors setup.ps1's stale-venv comparison;
|
|
same three pin-leaf cases as _ensure_rocm_torch. A same-family pin is NOT a mismatch.
|
|
"""
|
|
leaf = _torch_index_leaf(pin_url)
|
|
# Pinned ROCm version. The family classifier accepts a major-only rocm<d> leaf too,
|
|
# so parse the minor as optional; a major-only pin compares on the major alone.
|
|
_pin_rocm = re.match(r"^rocm(\d+)(?:\.(\d+))?", leaf)
|
|
_pin_major = int(_pin_rocm.group(1)) if _pin_rocm else None
|
|
_pin_ver = (
|
|
(int(_pin_rocm.group(1)), int(_pin_rocm.group(2)))
|
|
if _pin_rocm and _pin_rocm.group(2) is not None
|
|
else None
|
|
)
|
|
# Installed +rocmX.Y version; a THREE-part +rocmA.B.C tag is the AMD per-arch
|
|
# (repo.amd.com/gfx*) signature vs a two-part pytorch.org wheel.
|
|
_inst_rocm = re.search(r"\+rocm(\d+)\.(\d+)", installed_ver)
|
|
_inst_ver = (int(_inst_rocm.group(1)), int(_inst_rocm.group(2))) if _inst_rocm else None
|
|
_inst_is_perarch = re.search(r"\+rocm\d+\.\d+\.\d+", installed_ver) is not None
|
|
# A ROCm build MUST carry a +rocm tag; an untagged wheel never satisfies a ROCm pin.
|
|
_inst_has_rocm = re.search(r"\+rocm", installed_ver) is not None
|
|
# Installed torch RELEASE (before "+") is 2.11+.
|
|
_inst_rel = re.match(r"^(\d+)\.(\d+)", installed_ver)
|
|
_inst_is_211 = (
|
|
(int(_inst_rel.group(1)), int(_inst_rel.group(2))) >= (2, 11) if _inst_rel else False
|
|
)
|
|
|
|
if leaf.startswith("gfx"):
|
|
# 2.11-allowlist arches expect the AMD per-arch wheel (three-part +rocmA.B.C,
|
|
# torch 2.11+); a generic or pre-2.11 build is a mismatch.
|
|
if leaf in _ROCM_GFX_TORCH211_LEAVES:
|
|
return not (_inst_is_211 and _inst_is_perarch)
|
|
# Non-2.11 gfx leaf (<2.11 specs): mismatch on an untagged wheel or torch 2.11+.
|
|
return (not _inst_has_rocm) or _inst_is_211
|
|
|
|
# Major-only rocm pin (rocm7): compare majors only -- a +rocm6.4 wheel under a rocm7
|
|
# pin is a mismatch, any +rocm7.x wheel satisfies it (there is no pinned minor to
|
|
# compare, and the 2.11-line fallback below would invert both verdicts).
|
|
if _pin_major is not None and _pin_ver is None:
|
|
if _inst_ver is not None:
|
|
return _inst_ver[0] != _pin_major
|
|
# Untagged wheel never satisfies a ROCm pin; a +rocm tag with an unreadable
|
|
# version is accepted (matches the lenient unreadable fallback below).
|
|
return not _inst_has_rocm
|
|
|
|
# rocmX.Y pin. Only KNOWN-2.11 rocm is the 2.11 line (no speculative floor).
|
|
_pin_is_211 = _pin_ver in _ROCM_KNOWN_TORCH211_VERSIONS if _pin_ver is not None else False
|
|
if _pin_ver is not None and _inst_ver is not None:
|
|
# Both readable: exact (major, minor) compare (rocm7.2 pin over +rocm7.13.x ->
|
|
# mismatch, reinstall the pinned wheel).
|
|
if _pin_ver != _inst_ver:
|
|
return True
|
|
# Same family: a KNOWN-2.11 pin whose release drifted off 2.11 (2.12+rocm7.2)
|
|
# violates the spec -> reinstall to floor (exact compare, not >=2.11).
|
|
if _pin_is_211 and _inst_rel is not None:
|
|
if (int(_inst_rel.group(1)), int(_inst_rel.group(2))) != (2, 11):
|
|
return True
|
|
return False
|
|
# rocm pin, unreadable installed version: compare on the 2.11 line, but an untagged
|
|
# wheel never satisfies a rocmX.Y pin -> mismatch.
|
|
if not _inst_has_rocm:
|
|
return True
|
|
return _pin_is_211 != _inst_is_211
|
|
|
|
|
|
def _explicit_cpu_torch_index_url() -> "str | None":
|
|
"""The pinned wheel index URL when it names the CPU family (leaf == cpu), else None.
|
|
|
|
An explicit CPU pin (UNSLOTH_TORCH_INDEX_FAMILY=cpu or a URL ending in /cpu)
|
|
is authoritative -- see _ensure_cpu_torch.
|
|
"""
|
|
url = _explicit_torch_index_url()
|
|
if url is None:
|
|
return None
|
|
return url if _torch_index_leaf(url) == "cpu" else None
|
|
|
|
|
|
def _is_cuda_family_leaf(leaf: str) -> bool:
|
|
"""True only for a real CUDA wheel-family leaf: "cu" + digits (cu118, cu128, ...).
|
|
|
|
A bare startswith("cu") would match "custom"/"current". The match is EXACT so
|
|
"cu128-private" is NOT a family leaf and routes to the verbatim path instead.
|
|
"""
|
|
return re.fullmatch(r"cu[0-9]+", leaf) is not None
|
|
|
|
|
|
def _explicit_cuda_torch_index_url() -> "str | None":
|
|
"""The pinned wheel index URL when it names a CUDA family (leaf cuXXX), else None.
|
|
|
|
Mirrors _explicit_rocm/cpu_torch_index_url so _ensure_cuda_torch only treats a
|
|
*CUDA* pin as authority to override the NVIDIA-presence gate (an arbitrary mirror
|
|
or a ROCm/CPU pin must not force a CUDA reinstall on a non-NVIDIA host).
|
|
"""
|
|
url = _explicit_torch_index_url()
|
|
if url is None:
|
|
return None
|
|
return url if _is_cuda_family_leaf(_torch_index_leaf(url)) else None
|
|
|
|
|
|
def _explicit_unknown_family_torch_index_url() -> "str | None":
|
|
"""The pinned index URL when its leaf names NO known torch family, else None.
|
|
|
|
Known = rocm* / gfx* / cpu / cuXXX. Anything else (a private mirror /simple,
|
|
/current) is UNKNOWN: version-tag heuristics can't judge it, so the family
|
|
repair helpers must leave it alone (the install applied it verbatim).
|
|
Matches install.sh / setup.ps1 / install.ps1.
|
|
"""
|
|
url = _explicit_torch_index_url()
|
|
if url is None:
|
|
return None
|
|
leaf = _torch_index_leaf(url)
|
|
if _is_pip_rocm_family_leaf(leaf) or leaf == "cpu" or _is_cuda_family_leaf(leaf):
|
|
return None
|
|
return url
|
|
|
|
|
|
def _ensure_cuda_torch() -> None:
|
|
"""Repair a venv whose torch is a ROCm build on an NVIDIA host.
|
|
|
|
Counterpart to _ensure_rocm_torch. A venv poisoned by the pre-fix KFD
|
|
gpu_id false positive (ROCm torch installed on an NVIDIA-only machine)
|
|
keeps that broken torch on `studio update`, because a torch+rocm wheel
|
|
satisfies the version constraint and nothing force-reinstalls it. This
|
|
detects that exact case and reinstalls CUDA torch.
|
|
|
|
Only repairs when torch actually links against HIP/ROCm. Healthy CUDA
|
|
torch and deliberate CPU-only torch are left untouched.
|
|
"""
|
|
# Respect install.sh's backend: only "" (standalone update) or "cuda" force CUDA
|
|
# wheels; "rocm"/"cpu"/unrecognised are deliberate.
|
|
if _TORCH_BACKEND not in ("", "cuda"):
|
|
return
|
|
# An explicit unknown-family pin was applied VERBATIM at install time; leave it alone.
|
|
if _explicit_unknown_family_torch_index_url() is not None:
|
|
return
|
|
# No CUDA torch on macOS; Windows torch is owned by install.ps1 (KFD bug is Linux-only).
|
|
if IS_MACOS or IS_WINDOWS or NO_TORCH:
|
|
return
|
|
# Never undo a deliberate ROCm install (setup.ps1 sets this marker).
|
|
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
|
|
return
|
|
# An explicit CUDA pin (headless / CI cross-install) commits to CUDA wheels and skips ALL
|
|
# GPU probing, so it clears both the CUDA_VISIBLE_DEVICES hide gate and the NVIDIA gate below.
|
|
_cuda_pinned = _explicit_cuda_torch_index_url() is not None
|
|
# CUDA_VISIBLE_DEVICES="" / "-1" deliberately hides the NVIDIA GPU; never force CUDA
|
|
# wheels over that unless a CUDA index is pinned.
|
|
_cvd = os.environ.get("CUDA_VISIBLE_DEVICES")
|
|
if not _cuda_pinned and _cvd is not None and _cvd.strip() in ("", "-1"):
|
|
return
|
|
# Only NVIDIA hosts carry CUDA torch (the CUDA pin overrides this gate too).
|
|
if not _cuda_pinned and not _has_usable_nvidia_gpu():
|
|
return
|
|
|
|
# Classify the installed torch: "hip" (ROCm poisoning signature), "cuda" (healthy),
|
|
# or "cpu". A non-zero exit means torch is missing/un-importable: without a pin the
|
|
# base install owns it, but a pinned CUDA index reinstalls it below.
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import torch, re; "
|
|
"hip = getattr(torch.version, 'hip', '') or ''; "
|
|
"cuda = getattr(torch.version, 'cuda', '') or ''; "
|
|
"ver = getattr(torch, '__version__', '').lower(); "
|
|
"m = re.search(r'\\+(cu\\d+)', ver); "
|
|
"marker = 'hip' if (hip or 'rocm' in ver) else ('cuda' if cuda else 'cpu'); "
|
|
"print(marker + '|' + (m.group(1) if m else ''))"
|
|
),
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 90,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return
|
|
if probe.returncode != 0:
|
|
# torch present but can't import. Without a pin the base install owns it; but an
|
|
# explicit CUDA pin forces this pass (failed probe) and the base update won't
|
|
# reinstall an already-installed torch, so reinstall from the pin (self-resolving).
|
|
if not _cuda_pinned:
|
|
return
|
|
index_url = _detect_cuda_torch_index_url()
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
|
|
print(
|
|
f" torch cannot import but an explicit CUDA index is pinned -- reinstalling "
|
|
f"CUDA torch from {_strip_index_url_credentials(index_url)}"
|
|
)
|
|
pip_install(
|
|
"CUDA torch repair",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
index_url,
|
|
constrain = False,
|
|
)
|
|
return
|
|
# Last non-empty line: stray sitecustomize/import-hook output must not mask the marker.
|
|
_marker_lines = [
|
|
line.strip() for line in probe.stdout.decode(errors = "replace").splitlines() if line.strip()
|
|
]
|
|
if not _marker_lines:
|
|
return
|
|
_marker, _, _installed_cu = _marker_lines[-1].partition("|")
|
|
# Reinstall CUDA torch on a ROCm build on an NVIDIA host (poisoning signature), or when a
|
|
# CUDA index is pinned but the venv has the wrong family (CPU or a different cuXXX). A
|
|
# healthy match, or a CPU wheel with no CUDA pin, is left alone.
|
|
_pin = _explicit_torch_index_url()
|
|
_pin_leaf = _torch_index_leaf(_pin) if _pin else ""
|
|
_pinned_cuda = _is_cuda_family_leaf(_pin_leaf)
|
|
if _marker == "hip":
|
|
_why = "torch is a ROCm build on an NVIDIA host"
|
|
elif _marker == "cpu" and _pinned_cuda:
|
|
_why = "torch is a CPU build but an explicit CUDA index is pinned"
|
|
elif _marker == "cuda" and _pinned_cuda and _installed_cu != _pin_leaf:
|
|
# Installed cuXXX differs from the pin. An untagged build (empty) counts too:
|
|
# the family can't be confirmed, so reinstall to enforce it (idempotent).
|
|
_installed_desc = _installed_cu if _installed_cu else "an untagged CUDA build"
|
|
_why = f"torch is {_installed_desc} but the pinned CUDA index is {_pin_leaf}"
|
|
else:
|
|
return # healthy CUDA torch matching the pin, or a deliberate CPU wheel
|
|
|
|
index_url = _detect_cuda_torch_index_url()
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _CUDA_TORCH_PKG_SPEC
|
|
print(
|
|
f" {_why} -- reinstalling CUDA torch from {_strip_index_url_credentials(index_url)}\n"
|
|
f" (set UNSLOTH_TORCH_BACKEND=rocm or cpu to keep a deliberate "
|
|
f"non-CUDA torch)"
|
|
)
|
|
pip_install(
|
|
"CUDA torch repair",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
index_url,
|
|
constrain = False,
|
|
)
|
|
|
|
|
|
def _ensure_cpu_torch() -> None:
|
|
"""Reinstall CPU torch when an explicit CPU pin is set but the venv has a GPU build.
|
|
|
|
Counterpart to _ensure_cuda/rocm_torch for the explicit-CPU case (those treat a CPU
|
|
backend as a skip, so a standalone `studio update` would ignore the authoritative CPU
|
|
pin). Only fires for an EXPLICIT pin.
|
|
"""
|
|
if NO_TORCH:
|
|
return
|
|
pin = _explicit_cpu_torch_index_url()
|
|
if pin is None:
|
|
return
|
|
|
|
# Classify the installed torch family. A non-zero exit means torch is missing or
|
|
# un-importable: the explicit CPU pin reinstalls it below.
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import torch, re; "
|
|
"hip = getattr(torch.version, 'hip', '') or ''; "
|
|
"cuda = getattr(torch.version, 'cuda', '') or ''; "
|
|
"ver = getattr(torch, '__version__', '').lower(); "
|
|
"gpu = bool(hip) or 'rocm' in ver or bool(cuda) or bool(re.search(r'\\+cu\\d+', ver)); "
|
|
"print('gpu' if gpu else 'cpu')"
|
|
),
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 90,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
return
|
|
if probe.returncode != 0:
|
|
# torch present but can't import. The explicit CPU pin forces this pass (failed
|
|
# probe) and the base update won't reinstall an already-installed torch, so
|
|
# reinstall from the pin (self-resolving, no loop).
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _CPU_TORCH_PKG_SPEC
|
|
print(
|
|
f" torch cannot import but an explicit CPU index is pinned -- reinstalling "
|
|
f"CPU torch from {_strip_index_url_credentials(pin)}"
|
|
)
|
|
pip_install(
|
|
"CPU torch repair",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
pin,
|
|
constrain = False,
|
|
)
|
|
return
|
|
_lines = [
|
|
line.strip() for line in probe.stdout.decode(errors = "replace").splitlines() if line.strip()
|
|
]
|
|
if not _lines:
|
|
return # unreadable -- the base install step handles a missing torch
|
|
if _lines[-1] != "gpu":
|
|
return # already a CPU build
|
|
|
|
print(
|
|
" torch is a GPU build but an explicit CPU index is pinned -- reinstalling "
|
|
f"CPU torch from {_strip_index_url_credentials(pin)}"
|
|
)
|
|
# Pin the supported torch<2.11 family (the /cpu index now serves 2.11+, so a bare
|
|
# trio could resolve out of range or ABI-mismatched).
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _CPU_TORCH_PKG_SPEC
|
|
pip_install(
|
|
"CPU torch repair",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
pin,
|
|
constrain = False,
|
|
)
|
|
|
|
|
|
def _ensure_rocm_torch() -> None:
|
|
"""Reinstall torch with ROCm wheels when the venv received CPU-only torch.
|
|
|
|
On Linux x86_64: uses pytorch.org ROCm wheel index tags.
|
|
On Windows: uses AMD's repo.amd.com arch-specific pip index.
|
|
No-op on macOS, non-x86_64 Linux, NVIDIA-primary hosts, or when torch
|
|
already links against HIP.
|
|
Uses pip_install() to respect uv, constraints, and --python targeting.
|
|
"""
|
|
global _rocm_windows_torch_installed
|
|
# install.sh's resolved backend is authoritative: skip ROCm when it already chose a
|
|
# non-ROCm family (avoids re-detecting in a subprocess that may see a different env).
|
|
if _TORCH_BACKEND in ("cuda", "cpu"):
|
|
return
|
|
# An explicit unknown-family pin was applied VERBATIM at install time; leave it alone.
|
|
if _explicit_unknown_family_torch_index_url() is not None:
|
|
return
|
|
# setup.ps1 sets this after installing AMD wheels; skip only when torch is actually
|
|
# importable as ROCm (a wiped venv leaves a stale env-var that must not suppress it).
|
|
if os.environ.get("UNSLOTH_ROCM_TORCH_INSTALLED") == "1":
|
|
_torch_ok = False
|
|
try:
|
|
_probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import torch; "
|
|
"hip=getattr(torch.version,'hip','') or ''; "
|
|
"import sys; "
|
|
"sys.exit(0 if (hip or 'rocm' in torch.__version__.lower()) else 1)"
|
|
),
|
|
],
|
|
stdout = subprocess.DEVNULL,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 90,
|
|
)
|
|
_torch_ok = _probe.returncode == 0
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
if _torch_ok:
|
|
_rocm_windows_torch_installed = True
|
|
# ROCm torch is already installed, but the AMD Windows BNB wheel is still
|
|
# needed (the PyPI bitsandbytes ships only CUDA DLLs, fails on ROCm).
|
|
_install_bnb_windows_rocm()
|
|
return
|
|
# torch was wiped between runs; fall through to the full install path
|
|
if IS_MACOS:
|
|
return
|
|
|
|
if IS_WINDOWS:
|
|
# An explicit ROCm-family pin commits to ROCm wheels regardless of the visible
|
|
# GPU and overrides the public per-arch index (mirrors the Linux pin handling
|
|
# below): after a pinned setup.ps1 install fails to CPU, this repair must retry
|
|
# the PINNED index, not repo.amd.com.
|
|
_win_rocm_pin = _explicit_rocm_torch_index_url()
|
|
if _win_rocm_pin is None and _has_usable_nvidia_gpu():
|
|
return
|
|
gfx_arch = _detect_windows_gfx_arch()
|
|
if not gfx_arch and _win_rocm_pin is None:
|
|
return # no AMD GPU visible via hipinfo
|
|
# Probe whether torch already links against HIP.
|
|
_torch_already_rocm = False
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import torch; "
|
|
"hip=getattr(torch.version,'hip','') or ''; "
|
|
"ver=torch.__version__; "
|
|
"print('yes' if hip or 'rocm' in ver.lower() else '')"
|
|
),
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 90,
|
|
)
|
|
if probe.returncode == 0 and probe.stdout.decode().strip() == "yes":
|
|
_torch_already_rocm = True
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
pass
|
|
if not _torch_already_rocm:
|
|
index_url = _win_rocm_pin or _windows_rocm_index_url(gfx_arch)
|
|
if index_url is None:
|
|
print(f" No AMD Windows torch index for GPU arch {gfx_arch} -- skipping")
|
|
return
|
|
print(
|
|
f" {gfx_arch or 'pinned ROCm index'} (Windows) -- installing torch from "
|
|
f"{_strip_index_url_credentials(index_url)}"
|
|
)
|
|
# Pin companions for the arches install.ps1/setup.ps1 pin (gfx120X / Strix)
|
|
# so the per-arch index resolves an ABI-consistent trio; other arches stay bare.
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _WINDOWS_ROCM_TORCH_PKG_SPECS.get(
|
|
gfx_arch, ("torch", "torchvision", "torchaudio")
|
|
)
|
|
# Nonfatal: a transient AMD-index failure must not abort the install.
|
|
# --force-reinstall resolves before uninstalling, so a failed index keeps the
|
|
# existing build intact; let the user retry.
|
|
if not pip_install_try(
|
|
f"ROCm torch (Windows, {gfx_arch or 'pinned'})",
|
|
"--force-reinstall",
|
|
"--index-url",
|
|
index_url,
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
constrain = False,
|
|
):
|
|
print(
|
|
f" Warning: AMD Windows ROCm torch install failed for {gfx_arch or 'the pinned index'}; "
|
|
"keeping the existing torch build. Re-run 'unsloth studio update' "
|
|
"later to retry ROCm."
|
|
)
|
|
return
|
|
# ROCm torch is installed (or already was); flag it so later phases
|
|
# do not overwrite it with the generic CPU torch wheel. BNB is a
|
|
# separate dependency -- a BNB install failure must NOT roll back the
|
|
# torch ROCm install.
|
|
_rocm_windows_torch_installed = True
|
|
# Always install AMD Windows bitsandbytes -- the PyPI wheel ships only
|
|
# CUDA DLLs and fails on ROCm. Install even when torch was already a
|
|
# ROCm build so `studio update` repairs a broken bnb.
|
|
if not _install_bnb_windows_rocm():
|
|
print(
|
|
" Warning: AMD Windows bitsandbytes install failed; "
|
|
"ROCm torch is installed but bitsandbytes may need manual install"
|
|
)
|
|
return
|
|
|
|
# ── Linux x86_64 only: PyTorch ROCm wheels are not published for aarch64 ──
|
|
if platform.machine().lower() not in {"x86_64", "amd64"}:
|
|
return
|
|
# An explicit ROCm pin commits to ROCm wheels regardless of the visible GPU (headless / CI).
|
|
# Mirror _ensure_cuda_torch: skip the NVIDIA/no-AMD/unreadable gates.
|
|
_rocm_pin = _explicit_rocm_torch_index_url()
|
|
if _rocm_pin is None:
|
|
# NVIDIA takes precedence on mixed hosts (only if a GPU is usable).
|
|
if _has_usable_nvidia_gpu():
|
|
return
|
|
# _has_rocm_gpu() (rocminfo / amd-smi rows) is the authoritative AMD-host signal;
|
|
# the old /opt/rocm-or-hipcc gate broke runtime-only ROCm installs.
|
|
if not _has_rocm_gpu():
|
|
return # no AMD GPU visible
|
|
|
|
ver = _detect_rocm_version()
|
|
if ver is None:
|
|
if _rocm_pin is None:
|
|
print(" ROCm detected but version unreadable -- skipping torch reinstall")
|
|
return
|
|
# Explicit pin: the pinned leaf drives the install, so an unreadable host version
|
|
# is fine (sentinel keeps ver comparisons defined).
|
|
ver = (0, 0)
|
|
|
|
# Probe whether torch links against HIP, capturing the installed ROCm tag for pin-mismatch
|
|
# detection. Emit ONE "<hip_marker>|<version>" line: marker (HIP version, "rocm" sentinel,
|
|
# or empty for CPU/CUDA) before "|", wheel version after.
|
|
try:
|
|
probe = subprocess.run(
|
|
[
|
|
sys.executable,
|
|
"-c",
|
|
(
|
|
"import torch; "
|
|
"hip=getattr(torch.version,'hip','') or ''; "
|
|
"ver=getattr(torch,'__version__','').lower(); "
|
|
# HIP version if present, else a "rocm" sentinel when only the
|
|
# version string flags ROCm; empty marker = CPU/CUDA torch.
|
|
"marker=hip if hip else ('rocm' if 'rocm' in ver else ''); "
|
|
"print(marker + '|' + ver)"
|
|
),
|
|
],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
timeout = 90,
|
|
)
|
|
except (OSError, subprocess.TimeoutExpired):
|
|
probe = None
|
|
# Last non-empty line, split on the FIRST "|" so the empty HIP field is preserved.
|
|
_marker_lines = (
|
|
[ln.strip() for ln in probe.stdout.decode(errors = "replace").splitlines() if ln.strip()]
|
|
if (probe is not None and probe.returncode == 0)
|
|
else []
|
|
)
|
|
_hip_marker, _sep, _installed_torch_ver = (
|
|
_marker_lines[-1].partition("|") if _marker_lines else ("", "", "")
|
|
)
|
|
# A "|"-delimited line is required; without it treat HIP as absent -> reinstall.
|
|
has_hip_torch = bool(_sep) and _hip_marker != ""
|
|
|
|
# An explicit ROCm pin whose family differs from the installed torch must reinstall, else a
|
|
# rocm7.2/gfx* pin over an older +rocm6.4/7.1 build never applies. Version-tag heuristic
|
|
# only: a same-tag per-arch switch (gfx1151 -> gfx120X-all, both +rocm7.13.0) isn't detectable.
|
|
_rocm_pin_mismatch = (
|
|
_rocm_pin_family_mismatch(_rocm_pin, _installed_torch_ver)
|
|
if (has_hip_torch and _rocm_pin is not None)
|
|
else False
|
|
)
|
|
|
|
rocm_torch_ready = has_hip_torch and not _rocm_pin_mismatch
|
|
|
|
# Strix Halo / Point (gfx1151 / gfx1150) segfault under ROCm 7.1 in torch._grouped_mm;
|
|
# AMD's per-gfx repo ships 2.11.0+rocm7.13.0 with the fix, so route those hosts there
|
|
# (mirrors install.sh). On mixed hosts, reroute only when HIP's runtime GPU is the Strix one.
|
|
_strix_override_url: "str | None" = None
|
|
_strix_override_pkgs: "tuple[str, str, str] | None" = None
|
|
# An explicit ROCm pin is authoritative: never auto-reroute it.
|
|
if ver < (7, 2) and _explicit_rocm_torch_index_url() is None:
|
|
gfx_codes = _detect_amd_gfx_codes()
|
|
_strix_gfx = {"gfx1151", "gfx1150"}
|
|
_detected_strix = _strix_gfx.intersection(gfx_codes)
|
|
if _detected_strix:
|
|
# Runtime-visible GPU (HIP_VISIBLE_DEVICES index into gfx_codes, else first);
|
|
# skip the override unless it's Strix.
|
|
_runtime_gfx = gfx_codes[_pick_visible_index(len(gfx_codes))] if gfx_codes else None
|
|
if _runtime_gfx in _strix_gfx:
|
|
_selected_gfx = _runtime_gfx
|
|
_amd_mirror = (
|
|
os.environ.get("UNSLOTH_AMD_ROCM_MIRROR") or "https://repo.amd.com/rocm/whl"
|
|
).rstrip("/")
|
|
_strix_override_url = f"{_amd_mirror}/{_selected_gfx}/"
|
|
_strix_override_pkgs = (
|
|
"torch>=2.11.0,<2.12.0",
|
|
# Pin companions to the 2.11.x range: the exclusive --index-url could
|
|
# otherwise resolve a build for a different torch major (ABI mismatch).
|
|
"torchvision>=0.26.0,<0.27.0",
|
|
"torchaudio>=2.11.0,<2.12.0",
|
|
)
|
|
print(
|
|
f"\n {_selected_gfx} (AMD Strix) is the runtime target with ROCm "
|
|
f"{ver[0]}.{ver[1]}.\n"
|
|
f" ROCm 7.1 has a known _grouped_mm segfault on this GPU;\n"
|
|
f" routing torch install to AMD's arch-specific index\n"
|
|
f" ({_strix_override_url}) which serves torch 2.11.0+rocm7.13.0\n"
|
|
f" with the upstream fix.\n"
|
|
)
|
|
else:
|
|
_gfx_str = ", ".join(sorted(_detected_strix))
|
|
print(
|
|
f"\n Strix GPU ({_gfx_str}) present but HIP_VISIBLE_DEVICES "
|
|
f"selects a non-Strix runtime target ({_runtime_gfx});\n"
|
|
f" skipping AMD per-gfx index override.\n"
|
|
)
|
|
|
|
# The Strix override must fire even when has_hip_torch is True: an existing
|
|
# torch.version.hip == "7.1" is exactly the broken combo it repairs.
|
|
if _strix_override_url is not None and _strix_override_pkgs is not None:
|
|
index_url = _strix_override_url
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _strix_override_pkgs
|
|
print(
|
|
f" Strix ROCm 7.1 override -- installing torch from "
|
|
f"{_strip_index_url_credentials(index_url)}"
|
|
)
|
|
pip_install(
|
|
"ROCm torch (Strix arch-specific)",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
index_url,
|
|
constrain = False,
|
|
)
|
|
rocm_torch_ready = True
|
|
elif not has_hip_torch or _rocm_pin_mismatch:
|
|
# Reinstall when torch is not ROCm yet, OR a ROCm build's family differs from a pin.
|
|
# Honour a ROCm pin verbatim; else pick the newest wheel tag <= host.
|
|
_override_idx = _explicit_rocm_torch_index_url()
|
|
if _override_idx is not None:
|
|
index_url = _override_idx
|
|
tag = _torch_index_leaf(index_url)
|
|
else:
|
|
tag = next(
|
|
(
|
|
t
|
|
for (maj, mn), t in sorted(_ROCM_TORCH_INDEX.items(), reverse = True)
|
|
if ver >= (maj, mn)
|
|
),
|
|
None,
|
|
)
|
|
if tag is None:
|
|
print(f" No PyTorch wheel for ROCm {ver[0]}.{ver[1]} -- skipping torch reinstall")
|
|
else:
|
|
if _override_idx is None:
|
|
index_url = f"{_PYTORCH_WHL_BASE}/{tag}"
|
|
print(f" ROCm torch -- installing from {_strip_index_url_credentials(index_url)}")
|
|
# Only the _grouped_mm-bug gfx arches need the 2.11 spec; other gfx indexes ship
|
|
# <2.11 and stay on the default range (matches install.ps1 / setup.ps1).
|
|
if tag in _ROCM_GFX_TORCH211_LEAVES:
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _ROCM_TORCH_PKG_SPECS["rocm7.2"]
|
|
elif tag.startswith("gfx"):
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _ROCM_TORCH_PKG_SPECS["_default"]
|
|
else:
|
|
_torch_pkg, _vision_pkg, _audio_pkg = _ROCM_TORCH_PKG_SPECS.get(
|
|
tag, _ROCM_TORCH_PKG_SPECS["_default"]
|
|
)
|
|
pip_install(
|
|
f"ROCm torch ({tag})",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torch_pkg,
|
|
_vision_pkg,
|
|
_audio_pkg,
|
|
"--index-url",
|
|
index_url,
|
|
constrain = False,
|
|
)
|
|
rocm_torch_ready = True
|
|
|
|
# Install bitsandbytes only when torch links against ROCm. Prefers the
|
|
# continuous-release_main wheel (bnb PR #1887 4-bit GEMV fix), falling back
|
|
# to PyPI when the pre-release wheel won't install. Use pip for the
|
|
# pre-release wheel because uv rejects its filename/metadata version mismatch.
|
|
if rocm_torch_ready:
|
|
_bnb_url = _bnb_rocm_prerelease_url()
|
|
_bnb_installed = False
|
|
if _bnb_url is not None:
|
|
_bnb_installed = pip_install_try(
|
|
"bitsandbytes (AMD, pre-release main)",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
_bnb_url,
|
|
constrain = False,
|
|
force_pip = True,
|
|
)
|
|
if not _bnb_installed:
|
|
print(
|
|
_red(
|
|
" bnb pre-release install failed; falling back to PyPI "
|
|
"(4-bit decode will be broken on ROCm)"
|
|
)
|
|
)
|
|
if not _bnb_installed:
|
|
pip_install(
|
|
"bitsandbytes (AMD)",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
_BNB_ROCM_PYPI_FALLBACK,
|
|
constrain = False,
|
|
)
|
|
|
|
|
|
# _uv_safe_path is imported from backend.utils.uv_path_safety (shared with mlx_repair).
|
|
|
|
|
|
def _windows_hidden_subprocess_kwargs() -> dict[str, object]:
|
|
"""Return Windows-only subprocess kwargs that suppress console windows."""
|
|
if not IS_WINDOWS:
|
|
return {}
|
|
|
|
kwargs: dict[str, object] = {}
|
|
create_no_window = getattr(subprocess, "CREATE_NO_WINDOW", 0)
|
|
if create_no_window:
|
|
kwargs["creationflags"] = create_no_window
|
|
|
|
startupinfo_factory = getattr(subprocess, "STARTUPINFO", None)
|
|
startf_use_showwindow = getattr(subprocess, "STARTF_USESHOWWINDOW", 0)
|
|
sw_hide = getattr(subprocess, "SW_HIDE", 0)
|
|
if startupinfo_factory is not None and startf_use_showwindow:
|
|
startupinfo = startupinfo_factory()
|
|
startupinfo.dwFlags |= startf_use_showwindow
|
|
startupinfo.wShowWindow = sw_hide
|
|
kwargs["startupinfo"] = startupinfo
|
|
|
|
return kwargs
|
|
|
|
|
|
def _infer_no_torch() -> bool:
|
|
"""Determine whether to run in no-torch (GGUF-only) mode.
|
|
|
|
Checks UNSLOTH_NO_TORCH first. When unset, falls back to platform
|
|
detection so Intel Macs use GGUF-only mode even when invoked from
|
|
``unsloth studio update`` (which does not inject the env var).
|
|
"""
|
|
env = os.environ.get("UNSLOTH_NO_TORCH")
|
|
if env is not None:
|
|
return env.strip().lower() in ("1", "true")
|
|
return IS_MAC_INTEL
|
|
|
|
|
|
NO_TORCH = _infer_no_torch()
|
|
|
|
# UNSLOTH_TORCH_BACKEND is set by install.sh after get_torch_index_url() ("cuda", "rocm",
|
|
# "cpu"; empty = standalone `studio update`, where we re-detect).
|
|
_TORCH_BACKEND: str = os.environ.get("UNSLOTH_TORCH_BACKEND", "").lower()
|
|
# Standalone update with an explicit pin: derive the backend from the override (classify on
|
|
# the final URL/family segment, mirroring install.sh) instead of re-probing the GPU.
|
|
if not _TORCH_BACKEND:
|
|
_idx_override = (
|
|
os.environ.get("UNSLOTH_TORCH_INDEX_URL", "").strip()
|
|
or os.environ.get("UNSLOTH_TORCH_INDEX_FAMILY", "").strip()
|
|
)
|
|
_idx_leaf = _torch_index_leaf(_idx_override)
|
|
if _idx_leaf.startswith(("rocm", "gfx")):
|
|
_TORCH_BACKEND = "rocm"
|
|
elif _idx_leaf == "cpu":
|
|
_TORCH_BACKEND = "cpu"
|
|
elif _is_cuda_family_leaf(_idx_leaf):
|
|
# Require a digit after "cu" so /current or /custom is NOT branded CUDA (a wrong backend
|
|
# makes _ensure_rocm_torch return early on AMD hosts). An unknown leaf keeps "" so the
|
|
# helpers probe the GPU.
|
|
_TORCH_BACKEND = "cuda"
|
|
|
|
|
|
def _torch_step_label(suffix: str) -> str:
|
|
"""Return a progress label like 'torch check (cuda)' using the known backend.
|
|
|
|
Falls back to GPU detection when UNSLOTH_TORCH_BACKEND is not set (e.g.
|
|
standalone `unsloth studio update` runs that bypass install.sh).
|
|
"""
|
|
backend = _TORCH_BACKEND
|
|
if not backend:
|
|
if _has_usable_nvidia_gpu():
|
|
backend = "cuda"
|
|
elif _has_rocm_gpu():
|
|
backend = "rocm"
|
|
else:
|
|
backend = "cpu"
|
|
return f"torch {suffix} ({backend})"
|
|
|
|
|
|
# -- Verbosity control ----------------------------------------------------------
|
|
# By default the installer shows a minimal in-place one-line progress bar.
|
|
# Set UNSLOTH_VERBOSE=1 to restore full per-step output:
|
|
# CLI: unsloth studio setup --verbose
|
|
# Linux/Mac: UNSLOTH_VERBOSE=1 ./studio/setup.sh
|
|
# Windows: $env:UNSLOTH_VERBOSE="1" ; .\studio\setup.ps1
|
|
VERBOSE: bool = os.environ.get("UNSLOTH_VERBOSE", "0") == "1"
|
|
|
|
# Progress bar state -- updated by _progress() per install step.
|
|
# Update _TOTAL if you add/remove steps in install_python_stack().
|
|
_STEP: int = 0
|
|
_TOTAL: int = 0 # set at runtime in install_python_stack() based on platform
|
|
_PROGRESS_LINE_ACTIVE: bool = False
|
|
|
|
# -- Paths --------------------------------------------------------------
|
|
SCRIPT_DIR = Path(__file__).resolve().parent
|
|
REQ_ROOT = SCRIPT_DIR / "backend" / "requirements"
|
|
SINGLE_ENV = REQ_ROOT / "single-env"
|
|
CONSTRAINTS = SINGLE_ENV / "constraints.txt"
|
|
LOCAL_DD_UNSTRUCTURED_PLUGIN = (
|
|
SCRIPT_DIR / "backend" / "plugins" / "data-designer-unstructured-seed"
|
|
)
|
|
LOCAL_DD_GITHUB_PLUGIN = SCRIPT_DIR / "backend" / "plugins" / "data-designer-github-repo-seed"
|
|
|
|
# mlx-lm 0.31.3 broke gemma4 / qwen3_5 loading (strict load_weights rejects the
|
|
# QK-norm q_norm/k_norm tensors); exclude just that release. See mlx-lm #1242.
|
|
MLX_LM_BAD_VERSION_EXCLUSION = "!=0.31.3"
|
|
|
|
# Apple Silicon: override mlx-vlm/mlx-lm's transformers pin (see overrides).
|
|
# _uv_safe_path: uv truncates UV_OVERRIDE at the first space too (issue #6503).
|
|
_MLX_OVERRIDES = SINGLE_ENV / "overrides-darwin-arm64.txt"
|
|
if IS_MAC_ARM and _MLX_OVERRIDES.is_file() and "UV_OVERRIDE" not in os.environ:
|
|
os.environ["UV_OVERRIDE"] = _uv_safe_path(_MLX_OVERRIDES)
|
|
|
|
# -- Unicode-safe printing ---------------------------------------------
|
|
# On Windows the console encoding may be a legacy code page (e.g. CP1252)
|
|
# that cannot represent glyphs like ✅ or ❌. _safe_print() degrades to ASCII
|
|
# equivalents so the installer never crashes over a status glyph.
|
|
|
|
_UNICODE_TO_ASCII: dict[str, str] = {
|
|
"\u2705": "[OK]", # ✅
|
|
"\u274c": "[FAIL]", # ❌
|
|
"\u26a0\ufe0f": "[!]", # ⚠️ (warning + variation selector)
|
|
"\u26a0": "[!]", # ⚠ (warning without variation selector)
|
|
}
|
|
|
|
|
|
def _safe_print(*args: object, **kwargs: object) -> None:
|
|
"""Drop-in print() replacement that survives non-UTF-8 consoles and detached stdout."""
|
|
try:
|
|
print(*args, **kwargs)
|
|
except OSError:
|
|
return
|
|
except UnicodeEncodeError:
|
|
# Stringify, then swap emoji for ASCII equivalents.
|
|
text = " ".join(str(a) for a in args)
|
|
for uni, ascii_alt in _UNICODE_TO_ASCII.items():
|
|
text = text.replace(uni, ascii_alt)
|
|
# Final fallback: replace any remaining unencodable chars.
|
|
print(
|
|
text.encode(sys.stdout.encoding or "ascii", errors = "replace").decode(
|
|
sys.stdout.encoding or "ascii", errors = "replace"
|
|
),
|
|
**kwargs,
|
|
)
|
|
|
|
|
|
# ── Color support ──────────────────────────────────────────────────────
|
|
# Same logic as startup_banner: NO_COLOR disables, FORCE_COLOR or TTY enables.
|
|
|
|
|
|
def _stdout_supports_color() -> bool:
|
|
"""True if we should emit ANSI colors (matches startup_banner)."""
|
|
if os.environ.get("NO_COLOR", "").strip():
|
|
return False
|
|
if os.environ.get("FORCE_COLOR", "").strip():
|
|
return True
|
|
try:
|
|
if not sys.stdout.isatty():
|
|
return False
|
|
except (AttributeError, OSError, ValueError):
|
|
return False
|
|
if IS_WINDOWS:
|
|
try:
|
|
import ctypes
|
|
|
|
kernel32 = ctypes.windll.kernel32
|
|
handle = kernel32.GetStdHandle(-11)
|
|
mode = ctypes.c_ulong()
|
|
kernel32.GetConsoleMode(handle, ctypes.byref(mode))
|
|
kernel32.SetConsoleMode(handle, mode.value | 0x0004)
|
|
except (ImportError, AttributeError, OSError):
|
|
return False
|
|
return True
|
|
|
|
|
|
_HAS_COLOR = _stdout_supports_color()
|
|
|
|
|
|
# Column layout — matches setup.sh step() helper:
|
|
# 2-space indent, 15-char label (dim), then value.
|
|
_LABEL = "deps"
|
|
_COL = 15
|
|
_INDENT = 2
|
|
|
|
|
|
def _green(msg: str) -> str:
|
|
return f"\033[38;5;108m{msg}\033[0m" if _HAS_COLOR else msg
|
|
|
|
|
|
def _cyan(msg: str) -> str:
|
|
return f"\033[96m{msg}\033[0m" if _HAS_COLOR else msg
|
|
|
|
|
|
def _red(msg: str) -> str:
|
|
return f"\033[91m{msg}\033[0m" if _HAS_COLOR else msg
|
|
|
|
|
|
def _dim(msg: str) -> str:
|
|
return f"\033[38;5;245m{msg}\033[0m" if _HAS_COLOR else msg
|
|
|
|
|
|
def _title(msg: str) -> str:
|
|
return f"\033[38;5;150m{msg}\033[0m" if _HAS_COLOR else msg
|
|
|
|
|
|
_RULE = "\u2500" * 52
|
|
|
|
|
|
def _step(
|
|
label: str,
|
|
value: str,
|
|
color_fn = None,
|
|
) -> None:
|
|
"""Print a single step line in the column format."""
|
|
global _PROGRESS_LINE_ACTIVE
|
|
if color_fn is None:
|
|
color_fn = _green
|
|
padded = label[:_COL]
|
|
plain_prefix_width = _INDENT + _COL
|
|
prefix = f"{' ' * _INDENT}{_dim(padded)}{' ' * (_COL - len(padded))}"
|
|
wrap_width = max(
|
|
24,
|
|
shutil.get_terminal_size((100, 20)).columns - plain_prefix_width,
|
|
)
|
|
lines = textwrap.wrap(
|
|
value,
|
|
width = wrap_width,
|
|
break_long_words = False,
|
|
break_on_hyphens = False,
|
|
) or [""]
|
|
if _PROGRESS_LINE_ACTIVE and not VERBOSE:
|
|
try:
|
|
sys.stdout.write("\n")
|
|
sys.stdout.flush()
|
|
except OSError:
|
|
pass
|
|
_PROGRESS_LINE_ACTIVE = False
|
|
_safe_print(f"{prefix}{color_fn(lines[0])}")
|
|
continuation_prefix = " " * plain_prefix_width
|
|
for line in lines[1:]:
|
|
_safe_print(f"{continuation_prefix}{color_fn(line)}")
|
|
|
|
|
|
def _progress(label: str) -> None:
|
|
"""Print an in-place progress bar aligned to the step column layout."""
|
|
global _STEP, _PROGRESS_LINE_ACTIVE
|
|
_STEP += 1
|
|
if VERBOSE:
|
|
return
|
|
width = 20
|
|
filled = int(width * _STEP / _TOTAL)
|
|
bar = "=" * filled + "-" * (width - filled)
|
|
pad = " " * (_COL - len(_LABEL))
|
|
end = "\n" if _STEP >= _TOTAL else ""
|
|
try:
|
|
sys.stdout.write(f"\r {_dim(_LABEL)}{pad}[{bar}] {_STEP:2}/{_TOTAL} {label:<20}{end}")
|
|
sys.stdout.flush()
|
|
_PROGRESS_LINE_ACTIVE = end == ""
|
|
except OSError:
|
|
pass
|
|
|
|
|
|
def run(
|
|
label: str,
|
|
cmd: list[str],
|
|
*,
|
|
quiet: bool = True,
|
|
) -> subprocess.CompletedProcess[bytes]:
|
|
"""Run a command; on failure print output and exit."""
|
|
if VERBOSE:
|
|
_step(_LABEL, f"{label}...", _dim)
|
|
result = subprocess.run(
|
|
cmd,
|
|
stdout = subprocess.PIPE if quiet else None,
|
|
stderr = subprocess.STDOUT if quiet else None,
|
|
env = _install_env_for_cmd(cmd),
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
if result.returncode != 0:
|
|
_step("error", f"{label} failed (exit code {result.returncode})", _red)
|
|
if result.stdout:
|
|
# Redact before printing: the failing pip command may carry a pinned --index-url
|
|
# with userinfo/?token= creds, so raw pip error text would leak them.
|
|
print(_redact_install_output(result.stdout))
|
|
sys.exit(result.returncode)
|
|
return result
|
|
|
|
|
|
# Packages to skip on Windows (require special build steps)
|
|
WINDOWS_SKIP_PACKAGES = {"triton_kernels"}
|
|
|
|
# Packages to skip when torch is unavailable (Intel Mac GGUF-only mode). These
|
|
# either *are* torch extensions or have unconditional ``Requires-Dist: torch``, so
|
|
# installing them pulls torch back in. ``librosa`` is here despite not requiring
|
|
# torch: upstream ``llvmlite`` dropped its macOS x86_64 wheel (0.46.0+ ships only
|
|
# macosx_arm64 / manylinux / win_amd64), so on Intel Mac the librosa -> numba ->
|
|
# llvmlite chain triggers a from-source build that fails without LLVM 14/15 headers.
|
|
# Tracked in unslothai/unsloth#5046.
|
|
NO_TORCH_SKIP_PACKAGES = {
|
|
"torch-stoi",
|
|
"timm",
|
|
"torchcodec",
|
|
"torch-c-dlpack-ext",
|
|
"openai-whisper",
|
|
"librosa",
|
|
}
|
|
|
|
|
|
def _select_flash_attn_version(torch_mm: str) -> str | None:
|
|
return flash_attn_package_version(torch_mm)
|
|
|
|
|
|
def _build_flash_attn_wheel_url(env: dict[str, str]) -> str | None:
|
|
return flash_attn_wheel_url(env)
|
|
|
|
|
|
def _print_optional_install_failure(label: str, result: subprocess.CompletedProcess[str]) -> None:
|
|
_step("warning", f"{label} failed (exit code {result.returncode})", _cyan)
|
|
if result.stdout:
|
|
# Redact any pinned --index-url credentials before printing captured output.
|
|
print(_redact_install_output(result.stdout).strip())
|
|
|
|
|
|
def _flash_attn_install_disabled() -> bool:
|
|
return os.getenv("UNSLOTH_STUDIO_SKIP_FLASHATTN_INSTALL") == "1"
|
|
|
|
|
|
def _ensure_flash_attn() -> None:
|
|
if _flash_attn_install_disabled():
|
|
return
|
|
if NO_TORCH:
|
|
return
|
|
if has_blackwell_gpu():
|
|
_step(
|
|
"warning",
|
|
"Skipping flash-attn: Blackwell GPU detected (sm_100+); no compatible prebuilt wheel",
|
|
_cyan,
|
|
)
|
|
return
|
|
if IS_WINDOWS or IS_MACOS:
|
|
return
|
|
if (
|
|
subprocess.run(
|
|
[sys.executable, "-c", "import flash_attn"],
|
|
stdout = subprocess.DEVNULL,
|
|
stderr = subprocess.DEVNULL,
|
|
).returncode
|
|
== 0
|
|
):
|
|
return
|
|
|
|
env = probe_torch_wheel_env()
|
|
wheel_url = _build_flash_attn_wheel_url(env) if env else None
|
|
if wheel_url and url_exists(wheel_url):
|
|
for installer, wheel_result in install_wheel(
|
|
wheel_url,
|
|
python_executable = sys.executable,
|
|
use_uv = USE_UV,
|
|
uv_needs_system = UV_NEEDS_SYSTEM,
|
|
):
|
|
if wheel_result.returncode == 0:
|
|
return
|
|
_print_optional_install_failure(
|
|
f"Installing flash-attn prebuilt wheel with {installer}",
|
|
wheel_result,
|
|
)
|
|
_step("warning", "Continuing without flash-attn", _cyan)
|
|
return
|
|
|
|
if wheel_url is None:
|
|
_step("warning", "No compatible flash-attn prebuilt wheel found", _cyan)
|
|
else:
|
|
_step("warning", "No published flash-attn prebuilt wheel found", _cyan)
|
|
|
|
|
|
# -- uv bootstrap ------------------------------------------------------
|
|
|
|
USE_UV = False # Set by _bootstrap_uv() at the start of install_python_stack()
|
|
UV_NEEDS_SYSTEM = False # Set by _bootstrap_uv() via probe
|
|
|
|
|
|
def _bootstrap_uv() -> bool:
|
|
"""Check if uv is available and probe whether --system is needed."""
|
|
global UV_NEEDS_SYSTEM
|
|
if not shutil.which("uv"):
|
|
return False
|
|
# Probe: try a dry-run install targeting the current Python explicitly.
|
|
# Without --python, uv can ignore the activated venv on some platforms.
|
|
probe = subprocess.run(
|
|
["uv", "pip", "install", "--dry-run", "--python", sys.executable, "pip"],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.STDOUT,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
if probe.returncode != 0:
|
|
# Retry with --system (some envs need it when uv can't find a venv)
|
|
probe_sys = subprocess.run(
|
|
["uv", "pip", "install", "--dry-run", "--system", "pip"],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.STDOUT,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
if probe_sys.returncode != 0:
|
|
return False # uv is broken, fall back to pip
|
|
UV_NEEDS_SYSTEM = True
|
|
return True
|
|
|
|
|
|
def _filter_requirements(req: Path, skip: set[str]) -> Path:
|
|
"""Return a temp copy of a requirements file with certain packages removed."""
|
|
lines = req.read_text(encoding = "utf-8").splitlines(keepends = True)
|
|
filtered = [
|
|
line for line in lines if not any(line.strip().lower().startswith(pkg) for pkg in skip)
|
|
]
|
|
tmp = tempfile.NamedTemporaryFile(
|
|
mode = "w",
|
|
suffix = ".txt",
|
|
delete = False,
|
|
encoding = "utf-8",
|
|
)
|
|
tmp.writelines(filtered)
|
|
tmp.close()
|
|
return Path(tmp.name)
|
|
|
|
|
|
def _translate_pip_args_for_uv(args: tuple[str, ...]) -> list[str]:
|
|
"""Translate pip flags to their uv equivalents."""
|
|
translated: list[str] = []
|
|
for arg in args:
|
|
if arg == "--no-cache-dir":
|
|
continue # uv cache is fast; drop this flag
|
|
elif arg == "--force-reinstall":
|
|
translated.append("--reinstall")
|
|
else:
|
|
translated.append(arg)
|
|
return translated
|
|
|
|
|
|
def _build_pip_cmd(args: tuple[str, ...]) -> list[str]:
|
|
"""Build a standard pip install command.
|
|
|
|
Strips uv-only flags like --upgrade-package that pip doesn't understand.
|
|
"""
|
|
cmd = [sys.executable, "-m", "pip", "install"]
|
|
skip_next = False
|
|
for arg in args:
|
|
if skip_next:
|
|
skip_next = False
|
|
continue
|
|
if arg == "--upgrade-package":
|
|
skip_next = True # skip the flag and its value
|
|
continue
|
|
cmd.append(arg)
|
|
return cmd
|
|
|
|
|
|
def _build_uv_cmd(args: tuple[str, ...]) -> list[str]:
|
|
"""Build a uv pip install command with translated flags."""
|
|
cmd = ["uv", "pip", "install"]
|
|
if UV_NEEDS_SYSTEM:
|
|
cmd.append("--system")
|
|
# Always pass --python so uv targets the right environment. Without it, uv
|
|
# can ignore an activated venv and install into the system Python (seen on
|
|
# Colab and similar).
|
|
cmd.extend(["--python", sys.executable])
|
|
cmd.extend(_translate_pip_args_for_uv(args))
|
|
# Torch is pre-installed, so don't add --torch-backend by default (solver dead-ends on
|
|
# CPU-only machines); callers can set UV_TORCH_BACKEND. Never add it to a pinned-index
|
|
# command: uv's torch backend redirects torch to its own per-backend index, defeating the pin.
|
|
_tb = os.environ.get("UV_TORCH_BACKEND", "")
|
|
if _tb and not _is_pinned_index_cmd(cmd):
|
|
cmd.append(f"--torch-backend={_tb}")
|
|
return cmd
|
|
|
|
|
|
# uv resolves --index-url / --default-index at LOWEST priority, so an inherited UV_INDEX /
|
|
# UV_EXTRA_INDEX_URL mirror wins and a pinned torch repair silently ignores the pin.
|
|
# Neutralise these for pinned installs (as install.sh #6898 / install.ps1 / setup.ps1 do).
|
|
# UV_TORCH_BACKEND redirects torch; PIP_* matter for the pip FALLBACK; UV_CONFIG_FILE is
|
|
# stripped + UV_NO_CONFIG=1 (a discovered uv.toml outranks the CLI pin, uv 0.10).
|
|
_UV_INDEX_ENV_VARS = (
|
|
"UV_CONFIG_FILE",
|
|
"UV_DEFAULT_INDEX",
|
|
"UV_INDEX_URL",
|
|
"UV_INDEX",
|
|
"UV_EXTRA_INDEX_URL",
|
|
"UV_TORCH_BACKEND",
|
|
"UV_FIND_LINKS",
|
|
"PIP_EXTRA_INDEX_URL",
|
|
"PIP_FIND_LINKS",
|
|
# PIP_NO_INDEX=1 makes the pip fallback ignore ALL indexes (defeating --index-url);
|
|
# PIP_INDEX_URL is dropped too so a stale mirror env can't outrank the pin.
|
|
"PIP_NO_INDEX",
|
|
"PIP_INDEX_URL",
|
|
)
|
|
|
|
|
|
def _is_pinned_index_cmd(cmd: "list[str] | tuple[str, ...]") -> bool:
|
|
"""True when the command pins an index via --index-url / --default-index."""
|
|
return any(arg in ("--index-url", "--default-index") for arg in cmd)
|
|
|
|
|
|
def _install_env_for_cmd(cmd: "list[str]") -> "dict[str, str] | None":
|
|
"""Return an env with the uv index vars stripped for a pinned-index install.
|
|
|
|
None (inherit env) when the command does NOT pin an index, so ordinary installs honour
|
|
the user's mirror. For pinned commands, the uv index/backend vars are removed,
|
|
UV_NO_CONFIG=1 set (a discovered uv.toml outranks the CLI pin), and PIP_CONFIG_FILE
|
|
pointed at os.devnull for the pip fallback. Mirrors install.sh's gate (#6898).
|
|
"""
|
|
if not _is_pinned_index_cmd(cmd):
|
|
return None
|
|
env = os.environ.copy()
|
|
for name in _UV_INDEX_ENV_VARS:
|
|
env.pop(name, None)
|
|
env["UV_NO_CONFIG"] = "1"
|
|
env["PIP_CONFIG_FILE"] = os.devnull
|
|
return env
|
|
|
|
|
|
def pip_install_try(
|
|
label: str,
|
|
*args: str,
|
|
constrain: bool = True,
|
|
force_pip: bool = False,
|
|
) -> bool:
|
|
"""Like pip_install but returns False on failure instead of exiting.
|
|
For optional installs that have a follow-up fallback.
|
|
"""
|
|
constraint_args_pip: list[str] = []
|
|
constraint_args_uv: list[str] = []
|
|
if constrain and CONSTRAINTS.is_file():
|
|
constraint_args_pip = ["-c", str(CONSTRAINTS)]
|
|
constraint_args_uv = ["-c", _uv_safe_path(CONSTRAINTS)]
|
|
|
|
if USE_UV and not force_pip:
|
|
cmd = _build_uv_cmd(args) + constraint_args_uv
|
|
else:
|
|
cmd = _build_pip_cmd(args) + constraint_args_pip
|
|
|
|
if VERBOSE:
|
|
_step(_LABEL, f"{label}...", _dim)
|
|
result = subprocess.run(
|
|
cmd,
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.STDOUT,
|
|
env = _install_env_for_cmd(cmd),
|
|
)
|
|
if result.returncode == 0:
|
|
return True
|
|
if VERBOSE and result.stdout:
|
|
# pip/uv echo index URLs (credentials included) in failure output.
|
|
print(_redact_install_output(result.stdout))
|
|
return False
|
|
|
|
|
|
def pip_install(
|
|
label: str,
|
|
*args: str,
|
|
req: Path | None = None,
|
|
constrain: bool = True,
|
|
) -> None:
|
|
"""Build and run a pip install command (uses uv when available, falls back to pip)."""
|
|
constraint_args_pip: list[str] = []
|
|
constraint_args_uv: list[str] = []
|
|
if constrain and CONSTRAINTS.is_file():
|
|
constraint_args_pip = ["-c", str(CONSTRAINTS)]
|
|
constraint_args_uv = ["-c", _uv_safe_path(CONSTRAINTS)]
|
|
|
|
actual_req = req
|
|
temp_reqs: list[Path] = []
|
|
if req is not None and IS_WINDOWS and WINDOWS_SKIP_PACKAGES:
|
|
actual_req = _filter_requirements(req, WINDOWS_SKIP_PACKAGES)
|
|
temp_reqs.append(actual_req)
|
|
if actual_req is not None and NO_TORCH and NO_TORCH_SKIP_PACKAGES:
|
|
actual_req = _filter_requirements(actual_req, NO_TORCH_SKIP_PACKAGES)
|
|
temp_reqs.append(actual_req)
|
|
if actual_req is not None and PLATFORM_LACKS_TORCHCODEC_WHEEL:
|
|
# Linux aarch64 / Windows ARM64 / Intel Mac have no torchcodec
|
|
# wheel. `unsloth studio update --local` does not pass
|
|
# --no-torch, so the NO_TORCH filter above does not fire; do
|
|
# the targeted skip independently so the audio extras step
|
|
# does not take down the whole update.
|
|
actual_req = _filter_requirements(actual_req, {"torchcodec"})
|
|
temp_reqs.append(actual_req)
|
|
req_args_pip: list[str] = []
|
|
req_args_uv: list[str] = []
|
|
if actual_req is not None:
|
|
req_args_pip = ["-r", str(actual_req)]
|
|
req_args_uv = ["-r", _uv_safe_path(actual_req)]
|
|
|
|
try:
|
|
if USE_UV:
|
|
uv_cmd = _build_uv_cmd(args) + constraint_args_uv + req_args_uv
|
|
if VERBOSE:
|
|
print(f" {label}...")
|
|
result = subprocess.run(
|
|
uv_cmd,
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.STDOUT,
|
|
env = _install_env_for_cmd(uv_cmd),
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
if result.returncode == 0:
|
|
return
|
|
print(_red(f" uv failed, falling back to pip..."))
|
|
if result.stdout:
|
|
print(_redact_install_output(result.stdout))
|
|
|
|
pip_cmd = _build_pip_cmd(args) + constraint_args_pip + req_args_pip
|
|
run(f"{label} (pip)" if USE_UV else label, pip_cmd)
|
|
finally:
|
|
for temp_req in temp_reqs:
|
|
temp_req.unlink(missing_ok = True)
|
|
|
|
|
|
def download_file(url: str, dest: Path) -> None:
|
|
"""Download a file using urllib (no curl dependency)."""
|
|
urllib.request.urlretrieve(url, dest)
|
|
|
|
|
|
def patch_package_file(package_name: str, relative_path: str, url: str) -> None:
|
|
"""Download a file from url and overwrite a file inside an installed package."""
|
|
result = subprocess.run(
|
|
[sys.executable, "-m", "pip", "show", package_name],
|
|
capture_output = True,
|
|
text = True,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
if result.returncode != 0:
|
|
_step(_LABEL, f"package {package_name} not found, skipping patch", _red)
|
|
return
|
|
|
|
location = None
|
|
for line in result.stdout.splitlines():
|
|
if line.lower().startswith("location:"):
|
|
location = line.split(":", 1)[1].strip()
|
|
break
|
|
|
|
if not location:
|
|
_step(_LABEL, f"could not locate {package_name}", _red)
|
|
return
|
|
|
|
dest = Path(location) / relative_path
|
|
_step(_LABEL, f"patching {dest.name} in {package_name}...", _dim)
|
|
download_file(url, dest)
|
|
|
|
|
|
# -- Main install sequence ---------------------------------------------
|
|
|
|
|
|
def install_python_stack() -> int:
|
|
global USE_UV, _STEP, _TOTAL
|
|
_STEP = 0
|
|
|
|
# install.sh sets SKIP_STUDIO_BASE=1 to avoid reinstalling base packages;
|
|
# `studio update` does NOT, so unsloth + unsloth-zoo are reinstalled to pick
|
|
# up new versions.
|
|
skip_base = os.environ.get("SKIP_STUDIO_BASE", "0") == "1"
|
|
# --package installs a different package name (for testing).
|
|
package_name = os.environ.get("STUDIO_PACKAGE_NAME", "unsloth")
|
|
# --local overlays a local repo checkout after updating deps.
|
|
local_repo = os.environ.get("STUDIO_LOCAL_REPO", "")
|
|
base_total = 11 if IS_WINDOWS else 12 # +1 for the anyio repair check (step 8b)
|
|
if IS_MACOS:
|
|
base_total -= 1 # triton step is skipped on macOS
|
|
if not IS_MACOS and not NO_TORCH:
|
|
base_total += 1 # ROCm torch check (step 2b), non-macOS
|
|
if not IS_WINDOWS:
|
|
base_total += 2 # flash-attn + torch final repair (step 13), Linux
|
|
_TOTAL = (base_total - 1) if skip_base else base_total
|
|
|
|
# 1. Try uv for faster installs (before pip upgrade -- uv venvs don't
|
|
# include pip by default).
|
|
USE_UV = _bootstrap_uv()
|
|
|
|
# 2. Ensure pip is available (uv venvs from install.sh omit pip).
|
|
_progress("pip bootstrap")
|
|
if USE_UV:
|
|
run(
|
|
"Bootstrapping pip via uv",
|
|
[
|
|
"uv",
|
|
"pip",
|
|
"install",
|
|
"--python",
|
|
sys.executable,
|
|
"pip",
|
|
],
|
|
)
|
|
else:
|
|
# pip may not exist yet (uv-created venvs omit it). Try ensurepip,
|
|
# then upgrade. Direct upgrade only when pip is already present.
|
|
_has_pip = (
|
|
subprocess.run(
|
|
[sys.executable, "-m", "pip", "--version"],
|
|
stdout = subprocess.DEVNULL,
|
|
stderr = subprocess.DEVNULL,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
).returncode
|
|
== 0
|
|
)
|
|
|
|
if not _has_pip:
|
|
run(
|
|
"Bootstrapping pip via ensurepip",
|
|
[sys.executable, "-m", "ensurepip", "--upgrade"],
|
|
)
|
|
else:
|
|
run(
|
|
"Upgrading pip",
|
|
[sys.executable, "-m", "pip", "install", "--upgrade", "pip"],
|
|
)
|
|
|
|
# macOS arm64: install MLX stack at latest (UV_OVERRIDE relaxes the
|
|
# mlx-vlm / mlx-lm transformers pin -- set at module load).
|
|
# Exclude mlx-lm 0.31.3 (see MLX_LM_BAD_VERSION_EXCLUSION); it broke
|
|
# gemma4 / qwen3_5 QK-norm loading. mlx-lm #1242.
|
|
if IS_MAC_ARM and not skip_base:
|
|
_progress("MLX stack (Apple Silicon)")
|
|
pip_install(
|
|
"Installing MLX stack (mlx + mlx-lm + mlx-vlm)",
|
|
"--no-cache-dir",
|
|
"--upgrade",
|
|
"mlx",
|
|
"mlx-metal",
|
|
f"mlx-lm{MLX_LM_BAD_VERSION_EXCLUSION}",
|
|
"mlx-vlm",
|
|
)
|
|
|
|
# 3. Core packages: unsloth-zoo + unsloth (or custom package name)
|
|
if skip_base:
|
|
pass
|
|
elif NO_TORCH:
|
|
# No-torch update path: install unsloth + unsloth-zoo, then runtime deps,
|
|
# both with --no-deps (PyPI metadata declares torch a hard dep; avoid it).
|
|
_progress("base packages (no torch)")
|
|
pip_install(
|
|
f"Updating {package_name} + unsloth-zoo (no-torch mode)",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
"--upgrade-package",
|
|
package_name,
|
|
"--upgrade-package",
|
|
"unsloth-zoo",
|
|
package_name,
|
|
"unsloth-zoo",
|
|
)
|
|
# Resolve pydantic WITH deps so pip pins pydantic-core to the exact version
|
|
# its metadata declares (under --no-deps pip picks the latest of each and
|
|
# trips pydantic's _ensure_pydantic_core_version check). Deps are torch-free.
|
|
pip_install(
|
|
"Installing pydantic (with deps for compatible core)",
|
|
"--no-cache-dir",
|
|
"pydantic",
|
|
)
|
|
pip_install(
|
|
"Installing no-torch runtime deps",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
req = REQ_ROOT / "no-torch-runtime.txt",
|
|
)
|
|
if local_repo:
|
|
_step(_LABEL, f"overlaying local repo (editable): {local_repo}")
|
|
pip_install(
|
|
"Overlaying local repo (editable)",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
"-e",
|
|
local_repo,
|
|
constrain = False,
|
|
)
|
|
_step(_LABEL, "overlaying unsloth-zoo from git main")
|
|
pip_install(
|
|
"Overlaying unsloth-zoo from git main",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
"--force-reinstall",
|
|
"unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
|
|
constrain = False,
|
|
)
|
|
elif local_repo:
|
|
# Local dev install: update deps from base.txt, then overlay the local
|
|
# checkout as an editable install (--no-deps so torch is not re-resolved).
|
|
_progress("base packages")
|
|
pip_install(
|
|
"Updating base packages",
|
|
"--no-cache-dir",
|
|
"--upgrade-package",
|
|
"unsloth",
|
|
"--upgrade-package",
|
|
"unsloth-zoo",
|
|
req = REQ_ROOT / "base.txt",
|
|
)
|
|
_step(_LABEL, f"overlaying local repo (editable): {local_repo}")
|
|
pip_install(
|
|
"Overlaying local repo (editable)",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
"-e",
|
|
local_repo,
|
|
constrain = False,
|
|
)
|
|
_step(_LABEL, "overlaying unsloth-zoo from git main")
|
|
pip_install(
|
|
"Overlaying unsloth-zoo from git main",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
"--force-reinstall",
|
|
"unsloth-zoo @ git+https://github.com/unslothai/unsloth-zoo",
|
|
constrain = False,
|
|
)
|
|
elif package_name != "unsloth":
|
|
# Custom package name (for testing): install directly.
|
|
_progress("base packages")
|
|
pip_install(
|
|
f"Installing {package_name}",
|
|
"--no-cache-dir",
|
|
package_name,
|
|
)
|
|
else:
|
|
# Update path: upgrade only unsloth + unsloth-zoo, preserving existing
|
|
# torch/CUDA installs. Torch is pre-installed by install.sh/setup.ps1;
|
|
# --upgrade-package targets only base pkgs.
|
|
_progress("base packages")
|
|
pip_install(
|
|
"Updating base packages",
|
|
"--no-cache-dir",
|
|
"--upgrade-package",
|
|
"unsloth",
|
|
"--upgrade-package",
|
|
"unsloth-zoo",
|
|
req = REQ_ROOT / "base.txt",
|
|
)
|
|
|
|
# 2b. AMD ROCm: reinstall torch with HIP wheels if the host has ROCm but the
|
|
# venv got CPU-only torch (common when pip resolves torch from PyPI).
|
|
# Must follow base packages so torch is present for inspection.
|
|
if not IS_MACOS and not NO_TORCH:
|
|
_progress(_torch_step_label("check"))
|
|
_ensure_cuda_torch()
|
|
_ensure_rocm_torch()
|
|
_ensure_cpu_torch()
|
|
|
|
# Windows + AMD GPU: warn if ROCm torch was not installed (wrong Python
|
|
# version or unknown ROCm version).
|
|
if IS_WINDOWS and not NO_TORCH and not _has_usable_nvidia_gpu():
|
|
# Validate actual AMD GPU presence (not just tool existence).
|
|
import re as _re_win
|
|
|
|
def _win_amd_smi_has_gpu(stdout: str) -> bool:
|
|
return bool(_re_win.search(r"(?im)^gpu\s*[:\[]\s*\d", stdout))
|
|
|
|
_win_amd_gpu = False
|
|
for _wcmd, _check_fn in (
|
|
(["hipinfo"], lambda out: "gcnarchname" in out.lower()),
|
|
(["amd-smi", "list"], _win_amd_smi_has_gpu),
|
|
):
|
|
_wexe = shutil.which(_wcmd[0])
|
|
if not _wexe:
|
|
continue
|
|
# Skip amd-smi on Windows w/o a HIP SDK (avoids the UAC/DiskPart
|
|
# prompt), as _has_rocm_gpu()/_detect_amd_gfx_codes do. The only loss
|
|
# is the best-effort "AMD GPU detected" note; ROCm-torch state below
|
|
# comes from the install itself.
|
|
if _wcmd[0] == "amd-smi" and not _amd_smi_allowed():
|
|
continue
|
|
try:
|
|
_wr = subprocess.run(
|
|
[_wexe, *_wcmd[1:]],
|
|
stdout = subprocess.PIPE,
|
|
stderr = subprocess.DEVNULL,
|
|
text = True,
|
|
timeout = 10,
|
|
env = _amd_smi_env() if _wcmd[0] == "amd-smi" else None,
|
|
)
|
|
except Exception:
|
|
continue
|
|
if _wr.returncode == 0 and _check_fn(_wr.stdout):
|
|
_win_amd_gpu = True
|
|
break
|
|
if _win_amd_gpu and not _rocm_windows_torch_installed:
|
|
_safe_print(
|
|
_dim(" Note:"),
|
|
"AMD GPU detected but ROCm PyTorch could not be auto-installed.",
|
|
)
|
|
_safe_print(
|
|
" " * 8,
|
|
"Manual install may be required. See: https://docs.unsloth.ai/get-started/install-and-update/amd",
|
|
)
|
|
|
|
# 3. Extra dependencies
|
|
_progress("unsloth extras")
|
|
pip_install(
|
|
"Installing additional unsloth dependencies",
|
|
"--no-cache-dir",
|
|
req = REQ_ROOT / "extras.txt",
|
|
)
|
|
|
|
# 3b. Extra dependencies (no-deps) -- audio model support etc.
|
|
_progress("extra codecs")
|
|
pip_install(
|
|
"Installing extras (no-deps)",
|
|
"--no-deps",
|
|
"--no-cache-dir",
|
|
req = REQ_ROOT / "extras-no-deps.txt",
|
|
)
|
|
|
|
# 4. Overrides (torchao) -- force-reinstall to a version matching the venv's
|
|
# torch so its C++ extensions load (see _select_torchao_spec). Skipped when
|
|
# torch is unavailable (Intel Mac GGUF-only) and on Windows ROCm (no working
|
|
# build; see below).
|
|
if NO_TORCH:
|
|
_progress("dependency overrides (skipped, no torch)")
|
|
elif _rocm_windows_torch_installed or _installed_torch_is_windows_rocm():
|
|
# No working Windows ROCm torchao build: it imports an absent c10d backend
|
|
# and crashes transformers.quantizers. Unsloth stubs it at runtime, so
|
|
# installing it only ships a package that crashes on import -- skip it.
|
|
_progress("dependency overrides (skipped, Windows ROCm)")
|
|
_safe_print(" Windows ROCm -- skipping torchao (no working build; stubbed at runtime)")
|
|
else:
|
|
_progress("dependency overrides")
|
|
_torch_ver = _probe_installed_torch_version()
|
|
_torchao_spec = _select_torchao_spec(_torch_ver)
|
|
_safe_print(f" torch {_torch_ver or 'unknown'} detected -- installing {_torchao_spec}")
|
|
pip_install(
|
|
"Installing dependency overrides",
|
|
"--force-reinstall",
|
|
"--no-cache-dir",
|
|
_torchao_spec,
|
|
)
|
|
|
|
# 5. Triton kernels (no-deps, from source). Skip on Windows and macOS
|
|
# (no support).
|
|
if not IS_WINDOWS and not IS_MACOS:
|
|
_progress("triton kernels")
|
|
pip_install(
|
|
"Installing triton kernels",
|
|
"--no-deps",
|
|
"--no-cache-dir",
|
|
req = REQ_ROOT / "triton-kernels.txt",
|
|
constrain = False,
|
|
)
|
|
|
|
if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:
|
|
_progress("flash-attn")
|
|
_ensure_flash_attn()
|
|
|
|
# # 6. Patch: override llama_cpp.py with fix from unsloth-zoo feature/llama-cpp-windows-support branch
|
|
# patch_package_file(
|
|
# "unsloth-zoo",
|
|
# os.path.join("unsloth_zoo", "llama_cpp.py"),
|
|
# "https://raw.githubusercontent.com/unslothai/unsloth-zoo/refs/heads/main/unsloth_zoo/llama_cpp.py",
|
|
# )
|
|
|
|
# # 7a. Patch: override vision.py with fix from unsloth PR #4091
|
|
# patch_package_file(
|
|
# "unsloth",
|
|
# os.path.join("unsloth", "models", "vision.py"),
|
|
# "https://raw.githubusercontent.com/unslothai/unsloth/80e0108a684c882965a02a8ed851e3473c1145ab/unsloth/models/vision.py",
|
|
# )
|
|
|
|
# # 7b. Patch : override save.py with fix from feature/llama-cpp-windows-support
|
|
# patch_package_file(
|
|
# "unsloth",
|
|
# os.path.join("unsloth", "save.py"),
|
|
# "https://raw.githubusercontent.com/unslothai/unsloth/refs/heads/main/unsloth/save.py",
|
|
# )
|
|
|
|
# 8. Unsloth dependencies
|
|
_progress("studio deps")
|
|
pip_install(
|
|
"Installing studio dependencies",
|
|
"--no-cache-dir",
|
|
req = REQ_ROOT / "studio.txt",
|
|
)
|
|
|
|
# 8b. anyio repair (#6483)
|
|
_progress("anyio check")
|
|
_repair_bad_anyio()
|
|
|
|
# 9. Data-designer dependencies
|
|
_progress("data designer deps")
|
|
pip_install(
|
|
"Installing data-designer base dependencies",
|
|
"--no-cache-dir",
|
|
req = SINGLE_ENV / "data-designer-deps.txt",
|
|
)
|
|
|
|
# 10. Data-designer packages (no-deps to avoid conflicts)
|
|
_progress("data designer")
|
|
pip_install(
|
|
"Installing data-designer",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
req = SINGLE_ENV / "data-designer.txt",
|
|
)
|
|
|
|
# 11. Local Data Designer seed plugins
|
|
local_dd_plugins = [
|
|
("unstructured", LOCAL_DD_UNSTRUCTURED_PLUGIN),
|
|
("github", LOCAL_DD_GITHUB_PLUGIN),
|
|
]
|
|
for _plugin_name, plugin_dir in local_dd_plugins:
|
|
if not plugin_dir.is_dir():
|
|
_safe_print(
|
|
_red(
|
|
f"❌ Missing local plugin directory: {plugin_dir}",
|
|
),
|
|
)
|
|
return 1
|
|
_progress("local plugin")
|
|
for plugin_name, plugin_dir in local_dd_plugins:
|
|
pip_install(
|
|
f"Installing local data-designer {plugin_name} plugin",
|
|
"--no-cache-dir",
|
|
"--no-deps",
|
|
str(plugin_dir),
|
|
constrain = False,
|
|
)
|
|
|
|
# 12. Patch metadata for single-env compatibility
|
|
_progress("finalizing")
|
|
run(
|
|
"Patching single-env metadata",
|
|
[sys.executable, str(SINGLE_ENV / "patch_metadata.py")],
|
|
)
|
|
|
|
# 13. Final torch repair. Steps above can pull CUDA torch from PyPI, so repair last.
|
|
if not IS_WINDOWS and not IS_MACOS and not NO_TORCH:
|
|
_progress(_torch_step_label("final"))
|
|
_ensure_cuda_torch()
|
|
_ensure_rocm_torch()
|
|
_ensure_cpu_torch()
|
|
|
|
# 14. Final check (silent; third-party conflicts are expected)
|
|
subprocess.run(
|
|
[sys.executable, "-m", "pip", "check"],
|
|
stdout = subprocess.DEVNULL,
|
|
stderr = subprocess.DEVNULL,
|
|
**_windows_hidden_subprocess_kwargs(),
|
|
)
|
|
|
|
_step(_LABEL, "installed")
|
|
return 0
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(install_python_stack())
|