Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: verify the installed version after the update pass (#8505)
Nilayfe79a5bbc204
diff --git a/studio/setup.ps1 b/studio/setup.ps1index 9d5787b6078..ceb4c285631 100644--- a/studio/setup.ps1+++ b/studio/setup.ps1@@ -4727,11 +4727,16 @@ function Fast-Download {# Skip all Python dependency work if versions match (fast update path).$_PkgName = if ($env:STUDIO_PACKAGE_NAME) { $env:STUDIO_PACKAGE_NAME } else { "unsloth" }$SkipPythonDeps = $false+$LatestVer = ""+# True only when the version-check gate ran: the post-update probe must stay off in+# installer-driven/local runs, but it must not depend on the PyPI fetch succeeding --+# a missing package is missing on any index.+$_verifyUpdate = $falseif ($env:SKIP_STUDIO_BASE -ne "1" -and $env:STUDIO_LOCAL_INSTALL -ne "1") {# Only check when NOT called from install.ps1 (which just installed the package)+ $_verifyUpdate = $true$InstalledVer = try { (& python -c "from importlib.metadata import version; print(version('$_PkgName'))" 2>$null | Out-String).Trim() } catch { "" }- $LatestVer = ""try {$pypiJson = Invoke-RestMethod -Uri "https://pypi.org/pypi/$_PkgName/json" -TimeoutSec 5 -ErrorAction Stop$LatestVer = "$($pypiJson.info.version)".Trim()@@ -5443,6 +5448,190 @@ if ($stackExit -ne 0) {Exit-SetupFailure "Python dependency installation failed (exit code $stackExit)"}+# a corporate mirror (PIP_INDEX_URL, UV_INDEX_URL, ...) can lag PyPI: the pass+# resolves from the mirror while $LatestVer came from pypi.org, so version+# comparisons are muted when a custom index is active. The missing-package check+# below still runs: a pass that leaves nothing installed is broken on any index.+$_customIndex = "$env:PIP_INDEX_URL$env:PIP_EXTRA_INDEX_URL$env:PIP_FIND_LINKS$env:UV_INDEX_URL$env:UV_EXTRA_INDEX_URL$env:UV_FIND_LINKS$env:UV_DEFAULT_INDEX$env:UV_INDEX"+if ($_verifyUpdate) {+ # __MISSING__ only when the metadata positively reports no such package: a probe+ # that merely crashed must not read as "not installed" and fail setup. Names are+ # PEP 503-normalized on both sides, matching importlib.metadata's own lookup, and+ # PYTHONPATH and working-directory entries are dropped from sys.path so same-name+ # metadata outside the managed environment cannot satisfy the probe (python -c+ # leaves the inherited cwd on sys.path; the shell probe's -I covers both) --+ # except the interpreter's own site-packages, which stays even when the caller+ # launched from inside it or named it on PYTHONPATH. Metadata only counts when+ # its recorded top-level modules exist on disk: a leftover dist-info with the+ # payload deleted still reports a version. The initializer is matched by stem and+ # suffix rather than by its joined name: a bare filename literal inside an+ # installer reads as an invoked helper to the guard in+ # tests/test_installer_interactive_prompts.py, which resolves it against the+ # script's own directory and lands on the real package initializer.+ $_postProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code "import os, site, sys; _keep = set(os.path.abspath(_k) for _k in (site.getsitepackages() if hasattr(site, 'getsitepackages') else [])); _pp = set(os.path.abspath(_p) for _p in (os.environ.get('PYTHONPATH') or '').split(os.pathsep) if _p); _pp.add(os.getcwd()); sys.path[:] = [_sp for _sp in sys.path if _sp and (os.path.abspath(_sp) in _keep or os.path.abspath(_sp) not in _pp)]; import importlib.metadata as m, importlib.util, re; _norm = lambda s: re.sub('[-_.]+', '-', (s or '').lower()); _d = next((d for d in m.distributions() if _norm(d.metadata['Name']) == _norm('$_PkgName')), None); _tl = ((_d.read_text('top_level.txt') if _d is not None else None) or '').split(); _files = (_d.files if _d is not None else None) or []; _ftops = [_f for _f in _files if len(_f.parts) == 2 and _f.stem == '__init__' and _f.suffix == '.py'] or [_f for _f in _files if len(_f.parts) == 1 and str(_f).endswith('.py')]; _broken = (not any(importlib.util.find_spec(_t) for _t in _tl if _t)) if _tl else (bool(_ftops) and not any(_d.locate_file(_f).exists() for _f in _ftops)); print('POSTVER=' + ('__MISSING__' if (_d is None or _broken) else _d.version))"+ $PostVer = if ($_postProbe.Ok -and $_postProbe.Output -match '(?m)^POSTVER=(\S+)\s*$') { $Matches[1] } else { "" }+ $_updateOk = [bool]($LatestVer -and ($PostVer -eq $LatestVer))+ if (-not $_updateOk -and $LatestVer -and $PostVer -and $PostVer -ne "__MISSING__") {+ # newer than announced is fine (a release can land mid-update); PEP 440+ # ordering so an installed pre/post/dev build never passes as the release+ $_pepProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code "import os, site, sys; _keep = set(os.path.abspath(_k) for _k in (site.getsitepackages() if hasattr(site, 'getsitepackages') else [])); _pp = set(os.path.abspath(_p) for _p in (os.environ.get('PYTHONPATH') or '').split(os.pathsep) if _p); _pp.add(os.getcwd()); sys.path[:] = [_sp for _sp in sys.path if _sp and (os.path.abspath(_sp) in _keep or os.path.abspath(_sp) not in _pp)]; from packaging.version import Version; print('PEPCMP=' + ('ge' if Version('$PostVer') >= Version('$LatestVer') else 'lt'))"+ if ($_pepProbe.Ok -and $_pepProbe.Output -match '(?m)^PEPCMP=(ge|lt)\s*$') {+ $_updateOk = ($Matches[1] -eq "ge")+ } else {+ $_postNum = ($PostVer -replace '[^0-9.].*$', '').TrimEnd('.')+ $_latestNum = ($LatestVer -replace '[^0-9.].*$', '').TrimEnd('.')+ if ($_postNum -match '^\d+\.\d+' -and $_latestNum -match '^\d+\.\d+') {+ try { $_updateOk = [version]$_postNum -ge [version]$_latestNum } catch {}+ }+ }+ if (-not $_updateOk -and $pypiJson -and $pypiJson.releases) {+ # the announced release cannot install on this interpreter (Requires-Python+ # bump): accept only the newest release this interpreter CAN install, so a+ # no-op pass below that bar still fails loudly. Reuses the PyPI response+ # already fetched above (flattened to version/yanked/requires_python lines --+ # no second request that could fail under Python's own proxy/TLS setup);+ # base64 keeps the multi-line probe clear of the -c double-quote wrapping.+ # The whole probe is best-effort: a full or unwritable temp dir (or an+ # exhausted GetTempFileName pool) must fall through to the warning+ # outcome below, not abort setup under ErrorActionPreference Stop.+ $_relPath = $null+ try {+ $_relPath = [System.IO.Path]::GetTempFileName()+ $_relLines = foreach ($_rel in $pypiJson.releases.PSObject.Properties) {+ foreach ($_relFile in $_rel.Value) {+ "$($_rel.Name)`t$(if ($_relFile.yanked) { 1 } else { 0 })`t$($_relFile.requires_python)`t$($_relFile.packagetype)`t$($_relFile.filename)"+ }+ }+ Set-Content -LiteralPath $_relPath -Value ($_relLines -join "`n") -Encoding UTF8+ # the path rides in as base64: a profile name like O'Neil would otherwise+ # end the generated Python string literal early+ $_relPathB64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($_relPath))+ $_bestCode = @"+import base64, os, sys+import site+_keep = set(os.path.abspath(_k) for _k in (site.getsitepackages() if hasattr(site, 'getsitepackages') else []))+_pp = set(os.path.abspath(_p) for _p in (os.environ.get('PYTHONPATH') or '').split(os.pathsep) if _p)+_pp.add(os.getcwd())+sys.path[:] = [_sp for _sp in sys.path if _sp and (os.path.abspath(_sp) in _keep or os.path.abspath(_sp) not in _pp)]+try:+ from packaging.specifiers import SpecifierSet+ from packaging.version import Version, InvalidVersion+ post = Version('$PostVer')+ latest = Version('$LatestVer')+ with open(base64.b64decode('$_relPathB64').decode('utf-8'), encoding='utf-8-sig') as fh:+ lines = fh.read().splitlines()+except Exception:+ sys.exit(1)+try:+ from packaging.tags import sys_tags+ from packaging.utils import parse_wheel_filename+ supported = set(str(t) for t in sys_tags())+except Exception:+ supported = None+cur = Version('.'.join(map(str, sys.version_info[:3])))+best = None+for line in lines:+ parts = line.split('\t')+ if len(parts) != 5 or parts[1] == '1':+ continue+ try:+ v = Version(parts[0])+ except InvalidVersion:+ continue+ if v.is_prerelease:+ continue+ rp = parts[2]+ try:+ if rp and cur not in SpecifierSet(rp):+ continue+ except Exception:+ pass+ pt = parts[3]+ if pt == 'bdist_wheel' and supported is not None:+ try:+ if not any(str(t) in supported for t in parse_wheel_filename(parts[4])[3]):+ continue+ except Exception:+ pass+ elif pt and pt != 'sdist' and pt != 'bdist_wheel':+ continue+ if best is None or v > best:+ best = v+print('VERIFYVER=' + ('ok' if best is not None and best < latest and post >= best else 'stale'))+"@+ $_b64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($_bestCode))+ $_bestProbe = Invoke-BoundedPythonProbe -PythonExe "python" -Code "import base64; exec(base64.b64decode('$_b64').decode())"+ if ($_bestProbe.Ok -and $_bestProbe.Output -match '(?m)^VERIFYVER=ok\s*$') {+ substep "$_PkgName $PostVer kept: no $LatestVer artifact installs on this environment"+ $_updateOk = $true+ }+ } catch {+ # Temp-table write failed: leave $_updateOk false and let the+ # older-but-successful outcome below stay a warning, not a failure.+ } finally {+ if ($_relPath) {+ Remove-Item -LiteralPath $_relPath -Force -ErrorAction SilentlyContinue+ }+ }+ }+ }+ if ($_updateOk) {+ substep "$_PkgName $PostVer confirmed"+ } elseif ($PostVer -eq "__MISSING__") {+ # the one unambiguous failure: a "successful" pass with no package left+ # behind (no-op pass, stale dist-info) -- the case this check exists for.+ # The pass already wrote its success manifest (step 15, before this check)+ # and verify_install accepts a null recorded version, so the marker must+ # not survive: its presence means "install completed".+ $_manifestState = ""+ try {+ $_manifestState = (& python -c "+import sys, time+sys.path.insert(0, sys.argv[1])+try:+ import install_manifest+except Exception:+ print('MANIFEST=gone')+ sys.exit(0)+ok = False+for _ in range(3):+ if install_manifest.remove_manifest():+ ok = True+ break+ time.sleep(0.2)+if not ok:+ # deletion blocked (AV lock, read-only): write is a different access right+ # than delete on Windows, and a schema-busted manifest also reads incomplete+ try:+ install_manifest.manifest_path().write_text(__import__('json').dumps({'schema': -1}), encoding='utf-8')+ ok = True+ except Exception:+ pass+print('MANIFEST=' + ('gone' if ok else 'stuck'))+" "$PSScriptRoot" 2>$null | Out-String).Trim()+ } catch {}+ if ($_manifestState -notmatch 'MANIFEST=gone') {+ substep "[WARN] stale success manifest could not be removed or invalidated -- later checks may misread this venv as complete" "Yellow"+ }+ $_expected = if ($LatestVer) { " (expected $LatestVer)" } else { "" }+ Write-StudioLine "[FAILED] update ran but $_PkgName is not installed$_expected" -ForegroundColor Red+ Exit-SetupFailure "update ran but $_PkgName is not installed$_expected"+ } elseif (-not $PostVer) {+ $_expected = if ($LatestVer) { " (expected $LatestVer)" } else { "" }+ substep "[WARN] could not verify $_PkgName version after update$_expected" "Yellow"+ } elseif (-not $LatestVer) {+ substep "$_PkgName $PostVer present (PyPI unreachable; compare skipped)"+ } elseif ($_customIndex) {+ substep "$_PkgName $PostVer present (custom package index; PyPI compare skipped)"+ } else {+ # older-but-successful is a resolver outcome (constraints, config-file+ # mirrors, wheels for this platform), not an install failure: pypi.org's+ # announced latest is not authoritative for what this environment can+ # run -- surface it, don't brick the update+ substep "[WARN] update left $_PkgName at $PostVer ($LatestVer announced on PyPI)" "Yellow"+ }+}+} else {step "python" "dependencies up to date"# Restore ErrorActionPreference (was lowered for pip/python section)diff --git a/studio/setup.sh b/studio/setup.shindex 734e0dd04f7..5a6c4f002bc 100755--- a/studio/setup.sh+++ b/studio/setup.sh@@ -1793,15 +1793,26 @@ if [ "$_COLAB_NO_VENV" = true ]; then_SKIP_VERSION_CHECK=truefi_PKG_NAME="${STUDIO_PACKAGE_NAME:-unsloth}"+# Never inherited from the caller's environment: the post-update check below keys on+# these, and the block that assigns them is skipped in installer-driven/local/Colab+# runs (mirrors $LatestVer = "" in setup.ps1).+LATEST_VER=""+_PYPI_JSON=""+# True only when the version-check gate ran: the post-update probe needs the venv+# python and must stay off in installer-driven/local/Colab runs, but it must not+# depend on the PyPI fetch succeeding -- a missing package is missing on any index.+_VERIFY_UPDATE=falseif [ "$_SKIP_VERSION_CHECK" != true ] && [ "${SKIP_STUDIO_BASE:-0}" != "1" ] && [ "${STUDIO_LOCAL_INSTALL:-0}" != "1" ]; then# Only check when NOT called from install.sh (which just installed the package)- INSTALLED_VER=$("$VENV_DIR/bin/python" -c "+ _VERIFY_UPDATE=true+ INSTALLED_VER=$("$VENV_DIR/bin/python" -I -c "import sys; from importlib.metadata import versionprint(version(sys.argv[1]))" "$_PKG_NAME" 2>/dev/null || echo "")- LATEST_VER=$(_setup_http_get_timed "https://pypi.org/pypi/$_PKG_NAME/json" 2>/dev/null \- | "$VENV_DIR/bin/python" -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null \+ _PYPI_JSON=$(_setup_http_get_timed "https://pypi.org/pypi/$_PKG_NAME/json" 2>/dev/null || echo "")+ LATEST_VER=$(printf '%s' "$_PYPI_JSON" \+ | "$VENV_DIR/bin/python" -I -c "import sys,json; print(json.load(sys.stdin)['info']['version'])" 2>/dev/null \|| echo "")if [ -n "$INSTALLED_VER" ] && [ -n "$LATEST_VER" ] && [ "$INSTALLED_VER" = "$LATEST_VER" ]; then@@ -1935,6 +1946,169 @@ fiif [ "$_SKIP_PYTHON_DEPS" = false ]; theninstall_python_stack+ # a corporate mirror (PIP_INDEX_URL, UV_INDEX_URL, ...) can lag PyPI: the pass+ # resolves from the mirror while LATEST_VER came from pypi.org, so version+ # comparisons are muted when a custom index is active. The missing-package+ # check below still runs: a pass that leaves nothing installed is broken on+ # any index.+ _CUSTOM_INDEX="${PIP_INDEX_URL:-}${PIP_EXTRA_INDEX_URL:-}${PIP_FIND_LINKS:-}${UV_INDEX_URL:-}${UV_EXTRA_INDEX_URL:-}${UV_FIND_LINKS:-}${UV_DEFAULT_INDEX:-}${UV_INDEX:-}"+ if [ "$_VERIFY_UPDATE" = true ]; then+ # __MISSING__ only when the metadata positively reports no such package: a+ # probe that merely crashed must not read as "not installed" and fail setup.+ # -I so an inherited PYTHONPATH cannot satisfy the probe with same-name+ # metadata from outside the managed venv+ POST_VER=$("$VENV_DIR/bin/python" -I -c "+import importlib.util, sys+from importlib.metadata import distribution, PackageNotFoundError+try:+ d = distribution(sys.argv[1])+except PackageNotFoundError:+ print('__MISSING__')+ sys.exit(0)+# a leftover dist-info with the payload deleted still reports a version:+# metadata only counts when its top-level modules are actually loadable+# (find_spec locates without importing). RECORD existence is the fallback+# for wheels without top_level.txt; 3.14+ already filters d.files to what+# exists, so an empty ftops there falls back to trusting the metadata.+tops = (d.read_text('top_level.txt') or '').split()+if tops:+ broken = not any(importlib.util.find_spec(t) for t in tops if t)+else:+ files = d.files or []+ # stem/suffix rather than the joined name: a bare filename literal inside an+ # installer reads as an invoked helper to the guard in+ # tests/test_installer_interactive_prompts.py, which resolves it against the+ # script's own directory and lands on the real package initializer.+ ftops = [f for f in files if len(f.parts) == 2 and f.stem == '__init__' and f.suffix == '.py'] \+ or [f for f in files if len(f.parts) == 1 and str(f).endswith('.py')]+ broken = bool(ftops) and not any(d.locate_file(f).exists() for f in ftops)+print('__MISSING__' if broken else d.version)+" "$_PKG_NAME" 2>/dev/null || echo "")+ _UPDATE_OK=false+ if [ -n "$LATEST_VER" ] && [ "$POST_VER" = "$LATEST_VER" ]; then+ _UPDATE_OK=true+ elif [ -n "$LATEST_VER" ] && [ -n "$POST_VER" ] && [ "$POST_VER" != "__MISSING__" ] && "$VENV_DIR/bin/python" -I -c "+import re, sys+def nums(v):+ m = re.match(r'\d+(\.\d+)*', v)+ if not m: sys.exit(1)+ return [int(x) for x in m.group(0).split('.')]+try:+ from packaging.version import Version+ ok = Version(sys.argv[1]) >= Version(sys.argv[2])+except Exception:+ ok = nums(sys.argv[1]) >= nums(sys.argv[2])+sys.exit(0 if ok else 1)+" "$POST_VER" "$LATEST_VER" 2>/dev/null; then+ # newer than announced is fine (a release can land mid-update); PEP 440+ # ordering so an installed pre/post/dev build never passes as the release+ _UPDATE_OK=true+ elif [ -n "$LATEST_VER" ] && [ -n "$POST_VER" ] && [ "$POST_VER" != "__MISSING__" ] && [ -n "${_PYPI_JSON:-}" ] && printf '%s' "$_PYPI_JSON" | "$VENV_DIR/bin/python" -I -c "+import json, sys+raw = sys.stdin.read()+try:+ from packaging.specifiers import SpecifierSet+ from packaging.version import Version, InvalidVersion+ post = Version(sys.argv[1])+ latest = Version(sys.argv[2])+ releases = json.loads(raw).get('releases') or {}+except Exception:+ sys.exit(1)+try:+ from packaging.tags import sys_tags+ from packaging.utils import parse_wheel_filename+ supported = set(str(t) for t in sys_tags())+except Exception:+ supported = None+cur = Version('.'.join(map(str, sys.version_info[:3])))+best = None+for ver, files in releases.items():+ try:+ v = Version(ver)+ except InvalidVersion:+ continue+ if v.is_prerelease:+ continue+ for f in files:+ if f.get('yanked'):+ continue+ rp = f.get('requires_python')+ try:+ if rp and cur not in SpecifierSet(rp):+ continue+ except Exception:+ pass+ pt = f.get('packagetype')+ if pt == 'bdist_wheel' and supported is not None:+ try:+ if not any(str(t) in supported for t in parse_wheel_filename(f.get('filename') or '')[3]):+ continue+ except Exception:+ pass+ elif pt and pt != 'sdist' and pt != 'bdist_wheel':+ continue+ if best is None or v > best:+ best = v+ break+sys.exit(0 if best is not None and best < latest and post >= best else 1)+" "$POST_VER" "$LATEST_VER" 2>/dev/null; then+ # the announced release cannot install on this interpreter (Requires-Python+ # bump): accept only the newest release this interpreter CAN install, so a+ # no-op pass below that bar still fails loudly+ substep "$_PKG_NAME $POST_VER kept: no $LATEST_VER artifact installs on this environment"+ _UPDATE_OK=true+ fi+ if [ "$_UPDATE_OK" = true ]; then+ substep "$_PKG_NAME $POST_VER confirmed"+ elif [ "$POST_VER" = "__MISSING__" ]; then+ # the one unambiguous failure: a "successful" pass with no package left+ # behind (no-op pass, stale dist-info) -- the case this check exists for.+ # The pass already wrote its success manifest (step 15, before this+ # check) and verify_install accepts a null recorded version, so the+ # marker must not survive: its presence means "install completed".+ _MANIFEST_STATE=$("$VENV_DIR/bin/python" -c "+import sys, time+sys.path.insert(0, sys.argv[1])+try:+ import install_manifest+except Exception:+ print('MANIFEST=gone')+ sys.exit(0)+ok = False+for _ in range(3):+ if install_manifest.remove_manifest():+ ok = True+ break+ time.sleep(0.2)+if not ok:+ # deletion blocked (AV lock, read-only): write is a different access right+ # than delete on Windows, and a schema-busted manifest also reads incomplete+ try:+ install_manifest.manifest_path().write_text('{\"schema\": -1}', encoding='utf-8')+ ok = True+ except Exception:+ pass+print('MANIFEST=' + ('gone' if ok else 'stuck'))+" "$SCRIPT_DIR" 2>/dev/null || echo "MANIFEST=stuck")+ case "$_MANIFEST_STATE" in *stuck*)+ substep "stale success manifest could not be removed or invalidated -- later checks may misread this venv as complete" "$C_WARN" ;;+ esac+ step "python" "update ran but $_PKG_NAME is not installed${LATEST_VER:+ (expected $LATEST_VER)}" "$C_ERR"+ setup_fail 1 "update ran but $_PKG_NAME is not installed${LATEST_VER:+ (expected $LATEST_VER)}"+ elif [ -z "$POST_VER" ]; then+ step "python" "could not verify $_PKG_NAME version after update${LATEST_VER:+ (expected $LATEST_VER)}" "$C_WARN"+ elif [ -z "$LATEST_VER" ]; then+ substep "$_PKG_NAME $POST_VER present (PyPI unreachable; compare skipped)"+ elif [ -n "$_CUSTOM_INDEX" ]; then+ substep "$_PKG_NAME $POST_VER present (custom package index; PyPI compare skipped)"+ else+ # older-but-successful is a resolver outcome (constraints, config-file+ # mirrors, wheels for this platform), not an install failure: pypi.org's+ # announced latest is not authoritative for what this environment can+ # run -- surface it, don't brick the update+ step "python" "update left $_PKG_NAME at $POST_VER ($LATEST_VER announced on PyPI)" "$C_WARN"+ fi+ fielsestep "python" "dependencies up to date"verbose_substep "python deps check: installed=$_PKG_NAME@${INSTALLED_VER:-unknown} latest=${LATEST_VER:-unknown}"