Skip to content

feat(install): Windows-on-ARM + NVIDIA WSL2 GPU install with DGX/RTX Spark auto-detection, CUDA llama.cpp provisioning, and Spark UMA runtime tuning - #5945

Closed
danielhanchen wants to merge 134 commits into
mainfrom
woa-nvidia-wsl-fallback
Closed

danielhanchen wants to merge 134 commits into
mainfrom
woa-nvidia-wsl-fallback

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

Windows-on-ARM + NVIDIA: WSL2 GPU install with Spark-class auto-detection

Summary

NVIDIA's Spark-class unified-memory machines (DGX Spark / GB10, the N1X "RTX Spark" Windows-on-ARM laptops, Grace-Blackwell desksides) have no native Windows-ARM64 CUDA stack — no CUDA toolkit, no CUDA PyTorch wheel, no Triton for win_arm64. Until now, irm https://unsloth.ai/install.ps1 | iex on these machines failed at the PyTorch step, and there was no GGUF inference path.

This PR makes the canonical one-liners (irm https://unsloth.ai/install.ps1 | iex and curl -fsSL https://unsloth.ai/install.sh | sh) auto-detect Spark-class hardware and deliver a fully working GPU install with zero env vars and zero CPU llama.cpp builds:

  • Windows-on-ARM + NVIDIA → detected up-front (ARM64 probes + nvidia-smi + a CUDA-torch dry-run resolve), routed straight through a WSL2 tunnel: Studio + unsloth install inside WSL (cu130 aarch64 torch runs Blackwell sm_121 via PTX JIT), a native unsloth shim forwards every command into WSL, and Desktop/Start-Menu shortcuts launch Studio at http://localhost:8888. No WSL knowledge needed.
  • Native Linux aarch64 + NVIDIA (DGX Spark) → CUDA toolkit + CUDA llama.cpp are provisioned automatically (provision_llama_cuda.sh), so GGUF inference works without an x86 prebuilt.

What's included

install.ps1 (WoA path)

  • Up-front detection — never "try CPU, fail, then fall back". WSL2 enable/reboot deferral with correct non-zero exit codes for -File/automation callers (iex sessions are never exit-killed). Pre-existing WSL1 distros are detected in-distro (encoding-proof vs UTF-16 wsl -l -v) and auto-converted with wsl --set-version 2.
  • Native unsloth shim (%LOCALAPPDATA%\Unsloth\bin\unsloth.cmd) + PATH entry; the chosen distro is recorded for the uninstaller. Distro names are quoted only when spaced (wsl.exe rejects a quoted space-free name).
  • Shortcut icon is written to %USERPROFILE%\.unsloth — on WoA the shell's sandboxed icon-extraction broker cannot read a standalone .ico under %LOCALAPPDATA%, which renders shortcuts blank (root-caused on hardware by elimination).
  • CUDA llama.cpp builds in the background after install (detached Windows-side wsl.exe so the WSL VM survives), with thermal-aware parallelism: ~half cores, RAM-capped at ~1.5 GB/nvcc job (full -j$(nproc) trips thermal shutdowns on this laptop class), tunable via UNSLOTH_LLAMA_BUILD_JOBS.
  • --tauri is refused with a clear message (the desktop launcher cannot drive a WSL backend yet); venv rollback is preserved/restored on every failure path.

install.sh / setup.sh

  • WSL+aarch64+NVIDIA installs skip the pointless CPU llama.cpp source build (UNSLOTH_WSL_LLAMA_DEFERRED handshake with install.ps1); direct install.sh runs inside WSL provision CUDA themselves. Provision failures that leave no server mark the install degraded so fallbacks and exit codes fire.
  • bitsandbytes is installed on aarch64+NVIDIA (working aarch64 wheels, verified on sm_121) so 4-bit QLoRA works out of the box; gated off for --no-torch installs.

provision_llama_cuda.sh — installs CUDA toolkit 13.3 + libcurl headers, clones/builds CUDA llama.cpp with backup/restore semantics (a failed build never destroys a previously working server), honors UNSLOTH_LLAMA_TAG/UNSLOTH_LLAMA_PR pins, requires only llama-server (helper targets best-effort), and skips entirely when a CUDA server is already present.

uninstall.ps1 — removes shim/launcher/PATH/shortcuts/icon and the WSL-side install, strictly scoped to /root in each distro; reads the recorded distro; port-8888 kill only fires in distros that actually contain an Unsloth install; exits 0 with or without WSL.

Python runtime (Spark UMA tuning, all gated + env-overridable)

  • CUDA-free Spark detection (nvidia-smi name tokens; the device property is masked under WSL GPU-PV) so PYTORCH_CUDA_ALLOC_CONF=expandable_segments is set before CUDA initializes.
  • UMA defaults: dataloader_pin_memory=False (pinning steals non-pageable RAM from the shared pool for zero benefit), gradient-checkpointing double-buffer off, max_autotune off, vLLM auto-disable on Spark.
  • Studio training OOM guard (Strix Halo parity): worker startup caps the allocator at 0.80 of the unified pool on Spark-class hosts, so over-allocation raises a catchable OutOfMemoryError instead of stalling the whole box. Override with UNSLOTH_SPARK_MEM_FRACTION; measured overhead ~0%.

Verification (on an N1X "RTX Spark" WoA laptop)

  • 14 full cold cycles: uninstall → one-liner install (rc=0, no env vars, no CPU builds) → Studio driven at localhost:8888 → unsloth studio / unsloth run via the shim → Qwen3-0.6B served with -ngl -1, GPU 60–79% util under load → external Python + browser clients (CORS + Bearer + SSE) green.
  • Desktop + Start-Menu shortcuts render the logo out-of-the-box (user-confirmed on hardware).
  • 4-bit QLoRA training benchmarked in 7 configs (all UMA knobs throughput-neutral on WSL; their value is memory hygiene + reliability); OOM guard live-proven (catchable OOM, clean recovery).
  • Every cycle audited by 3 parallel reviewers for Linux x86_64, macOS, and native Windows x64 regressions: all paths byte-identical to main (every new gate requires WSL/ARM/NVIDIA markers; the one x64-reachable change — non-zero process exit on fatal -File failures — was verified safe in all four invocation forms, including nested-iex).
  • Five rounds of Codex/Gemini review feedback addressed (exit codes, uninstall scoping, provisioner robustness, quoting, allocator ordering, process-kill scoping); claims that didn't reproduce were disproven on hardware before being declined.

All new env vars (UNSLOTH_WSL_DISTRO, UNSLOTH_NO_WSL_FALLBACK, UNSLOTH_NO_LLAMA_CUDA, UNSLOTH_LLAMA_BUILD_JOBS, UNSLOTH_SPARK_*, UNSLOTH_FORCE_DGX_SPARK, …) are optional overrides; the default path needs none of them.

…A<13.3 build diagnostic

Two independent, purely-additive changes for Grace-Blackwell aarch64 (NVIDIA N1X
"RTX Spark" and DGX-Spark-class) and new-glibc hosts. 78 insertions, 0 deletions.

studio/setup.sh: when the GPU llama.cpp source build runs on glibc >= 2.41 with a
CUDA toolkit < 13.3, nvcc fails on the rsqrt/rsqrtf <crt/math_functions.h> exception-
spec clash (fixed upstream in CUDA 13.3 via _NV_RSQRT_SPECIFIER) and the build silently
falls back to CPU. Add a clear diagnostic recommending CUDA >= 13.3. Diagnostic only,
strictly inside the existing NVIDIA CUDA branch (Metal/ROCm/CPU/x86 unaffected).

install.ps1: native Windows-ARM64 has no CUDA PyTorch / Triton wheels, so the native
install can't deliver GPU. When ARM64 + NVIDIA is detected, automatically set up WSL2
and run the Linux installer there (full GPU), then print the launch command. Strictly
gated on ARM64 && NVIDIA && not --no-torch; x86_64 Windows (NVIDIA/AMD) and
ARM64-without-NVIDIA are byte-for-byte unchanged. Opt out: UNSLOTH_NO_WSL_FALLBACK=1;
distro: UNSLOTH_WSL_DISTRO. Encoding-proof distro detection via 'wsl -d <d> -- true'.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@gemini-code-assist gemini-code-assist Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Code Review

This pull request introduces an automatic WSL2 fallback mechanism in install.ps1 for Windows-on-ARM systems with NVIDIA GPUs, allowing them to run the GPU training/inference stack inside a Linux environment. It also adds a diagnostic check in studio/setup.sh to warn users about an incompatibility between glibc >= 2.41 and CUDA Toolkits < 13.3. The review feedback highlights several critical improvements: resolving a version comparison bug in the glibc check that would fail if glibc reaches version 3, resetting $global:LASTEXITCODE before executing native wsl.exe commands in PowerShell to prevent stale exit codes from causing false positives, and avoiding the suppression of stderr during apt-get commands inside WSL to make troubleshooting easier.

Important

The consumer version of Gemini Code Assist on GitHub is being sunset. Starting June 18, 2026, new organization installations will be blocked, and all code review activity will officially cease on July 17, 2026.
For more details on the timeline and next steps, please review the Help Documentation.

Comment thread studio/setup.sh Outdated
Comment on lines +1178 to +1180
if [ "${_GLIBC_MAJ:-0}" -eq 2 ] 2>/dev/null && [ "${_GLIBC_MIN:-0}" -ge 41 ] 2>/dev/null \
&& { [ "${_CU_MAJ:-0}" -lt 13 ] 2>/dev/null \
|| { [ "${_CU_MAJ:-0}" -eq 13 ] 2>/dev/null && [ "${_CU_MIN:-0}" -lt 3 ] 2>/dev/null; }; }; then

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

high

The glibc version check [ "${_GLIBC_MAJ:-0}" -eq 2 ] && [ "${_GLIBC_MIN:-0}" -ge 41 ] contains a version comparison bug. If glibc eventually bumps its major version to 3 (e.g., 3.0), the check [ "${_GLIBC_MAJ:-0}" -eq 2 ] will evaluate to false, and the warning will be skipped, even though glibc 3.0 is also >= 2.41 and would trigger the same CUDA compilation failure.

To correctly check if glibc >= 2.41, the major version should also be checked for values greater than 2.

Suggested change
if [ "${_GLIBC_MAJ:-0}" -eq 2 ] 2>/dev/null && [ "${_GLIBC_MIN:-0}" -ge 41 ] 2>/dev/null \
&& { [ "${_CU_MAJ:-0}" -lt 13 ] 2>/dev/null \
|| { [ "${_CU_MAJ:-0}" -eq 13 ] 2>/dev/null && [ "${_CU_MIN:-0}" -lt 3 ] 2>/dev/null; }; }; then
if { [ "${_GLIBC_MAJ:-0}" -gt 2 ] 2>/dev/null || { [ "${_GLIBC_MAJ:-0}" -eq 2 ] 2>/dev/null && [ "${_GLIBC_MIN:-0}" -ge 41 ] 2>/dev/null; }; } \
&& { [ "${_CU_MAJ:-0}" -lt 13 ] 2>/dev/null \
|| { [ "${_CU_MAJ:-0}" -eq 13 ] 2>/dev/null && [ "${_CU_MIN:-0}" -lt 3 ] 2>/dev/null; }; }; then

Comment thread install.ps1
Comment on lines +1472 to +1475
$wslReady = $false
if (Get-Command wsl.exe -ErrorAction SilentlyContinue) {
try { & wsl.exe --status *> $null; if ($LASTEXITCODE -eq 0) { $wslReady = $true } } catch {}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

When executing native commands (like wsl.exe) inside a try/catch block, if the command fails to start or throws an exception, $LASTEXITCODE is not updated and retains its previous value. If a prior command succeeded, $LASTEXITCODE will remain 0, leading to false positives (e.g., incorrectly setting $wslReady = $true).

To prevent stale exit codes, explicitly reset $global:LASTEXITCODE to a non-zero value (e.g., -1) immediately before executing the native command.

        $wslReady = $false
        if (Get-Command wsl.exe -ErrorAction SilentlyContinue) {
            $global:LASTEXITCODE = -1
            try { & wsl.exe --status *> $null; if ($LASTEXITCODE -eq 0) { $wslReady = $true } } catch {}
        }

Comment thread install.ps1
Comment on lines +1495 to +1496
$haveDistro = $false
try { & wsl.exe -d $distro -- true *> $null; if ($LASTEXITCODE -eq 0) { $haveDistro = $true } } catch {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Similar to the previous check, reset $global:LASTEXITCODE before executing wsl.exe to avoid using a stale exit code if the command fails to start.

        $haveDistro = $false
        $global:LASTEXITCODE = -1
        try { & wsl.exe -d $distro -- true *> $null; if ($LASTEXITCODE -eq 0) { $haveDistro = $true } } catch {}

Comment thread install.ps1 Outdated
try { & wsl.exe --install -d $distro --no-launch } catch {}
}
substep "installing Unsloth Studio inside WSL '$distro' with full GPU (this downloads PyTorch)..." "Cyan"
$wslInstall = 'export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/dev/null 2>&1; apt-get install -y build-essential cmake git curl pciutils >/dev/null 2>&1; curl -fsSL https://unsloth.ai/install.sh | sh'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Hiding both stdout and stderr (>/dev/null 2>&1) for apt-get update and apt-get install makes it extremely difficult to diagnose network, DNS, or repository issues inside WSL (which are very common).

Consider redirecting only stdout (>/dev/null) so that any package manager errors are printed to stderr and visible to the user.

        $wslInstall = 'export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/dev/null; apt-get install -y build-essential cmake git curl pciutils >/dev/null; curl -fsSL https://unsloth.ai/install.sh | sh'

Comment thread install.ps1
Comment on lines +1508 to +1510
try {
& wsl.exe -d $distro -u root -- bash -lc $wslInstall
$wslRc = $LASTEXITCODE

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Reset $global:LASTEXITCODE before running the WSL installation script to ensure $wslRc receives a correct value even if the command fails to launch.

        $global:LASTEXITCODE = -1
        try {
            & wsl.exe -d $distro -u root -- bash -lc $wslInstall
            $wslRc = $LASTEXITCODE

Comment thread install.ps1
Comment on lines +1520 to +1522
try {
& wsl.exe -d $distro -u root -- /root/.unsloth/studio/unsloth_studio/bin/python -c "import torch,sys; sys.exit(0 if torch.cuda.is_available() else 3)" *> $null
$torchOk = ($LASTEXITCODE -eq 0)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

medium

Reset $global:LASTEXITCODE before running the python check to ensure $torchOk is not set to $true based on a stale successful exit code if the command fails to launch.

        $global:LASTEXITCODE = -1
        try {
            & wsl.exe -d $distro -u root -- /root/.unsloth/studio/unsloth_studio/bin/python -c "import torch,sys; sys.exit(0 if torch.cuda.is_available() else 3)" *> $null
            $torchOk = ($LASTEXITCODE -eq 0)

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b7e9dae027

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1 Outdated
substep "in an ADMINISTRATOR PowerShell run: wsl --install" "Cyan"
substep "reboot, then re-run: irm https://unsloth.ai/install.ps1 | iex" "Cyan"
}
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Return a failure when WSL setup defers installation

On the ARM64+NVIDIA first-run path where WSL is not ready, this prints admin/reboot instructions and then returns from Install-UnslothStudio without throwing or calling Exit-InstallFailure. PowerShell -File treats a normally completed script as exit code 0 unless an explicit exit or exception is used, so the Tauri installer or any caller checking the exit status can mark installation complete even though no WSL distro or Studio install has run; return a non-zero status when setup is deferred.

Useful? React with 👍 / 👎.

…g unsloth shim

- Future-proof: probe whether a CUDA torch wheel is installable natively for win_arm64
  (uv pip install --dry-run). If it resolves (NVIDIA ships the wheel) keep the NATIVE
  install; otherwise fall back to WSL. WSL is used ONLY when native genuinely can't.
- Create a native Windows unsloth.cmd shim (on user PATH) that forwards every
  "unsloth ..." into the WSL GPU env, so "unsloth studio" / "unsloth studio run" typed
  in PowerShell run inside WSL and stream output + the http://localhost:8888 URL back.
- Run the WSL install under Continue-EAP and verify torch.cuda before reporting success
  so the optional (aarch64) llama.cpp prebuilt failure cannot abort or mis-report.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 8fbd8e3fa2

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1 Outdated
} catch { $_nativeCudaTorchOk = $false } finally { $ErrorActionPreference = $prevEapProbe }
if ($_nativeCudaTorchOk) { step "gpu" "native CUDA PyTorch now available for win_arm64 -- keeping native install" "Green" }
}
if ($_winArm64 -and $HasNvidiaSmi -and (-not $_nativeCudaTorchOk) -and (-not $SkipTorch) -and ($env:UNSLOTH_NO_WSL_FALLBACK -ne '1')) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Move WSL fallback before mutating the Windows venv

On ARM64+NVIDIA machines with an existing Windows Studio install, this WSL branch now runs only after the earlier reinstall path has already moved $VenvDir aside via Start-StudioVenvRollback and created a fresh venv. If WSL is not enabled yet, or the WSL install/check later fails, the function returns from this branch without restoring or completing the rollback, leaving the previous usable Studio environment hidden in a rollback directory and replacing it with an empty Windows venv. Gate into the WSL path before the Windows venv migration/creation, or restore the rollback before any deferred/failure return.

Useful? React with 👍 / 👎.

…tudio

The fallback returns before install.ps1's native shortcut code, so it created no
shortcuts. Add a WSL launcher (launch-studio-wsl.ps1) plus Desktop and Start Menu
.lnk shortcuts that start `unsloth studio` inside WSL and open http://localhost:8888
in the browser once the backend is healthy. Best-effort + wrapped in try/catch so a
shortcut failure never aborts the install.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: bb9b7341de

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1 Outdated
try { & wsl.exe --install -d $distro --no-launch } catch {}
}
substep "installing Unsloth Studio inside WSL '$distro' with full GPU (this downloads PyTorch)..." "Cyan"
$wslInstall = 'export DEBIAN_FRONTEND=noninteractive; apt-get update -y >/dev/null 2>&1; apt-get install -y build-essential cmake git curl pciutils >/dev/null 2>&1; curl -fsSL https://unsloth.ai/install.sh | sh'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve installer flags in the WSL fallback

When this branch is reached from a supported non-default invocation such as install.ps1 --package roland-sloth or the Tauri dev --local path, the WSL command always runs install.sh with no arguments, so it installs the default remote PyPI package and then returns before the native installer can honor the requested package/local checkout. Pass through equivalent arguments (or explicitly reject unsupported modes) so ARM64+NVIDIA fallback installs the same target the caller requested.

Useful? React with 👍 / 👎.

…llback artifacts

- install.ps1: refresh the shell icon cache (ie4uinit -show) right after creating the
  Desktop/Start Menu shortcuts, so the (valid) .ico renders immediately instead of showing
  a blank icon (Explorer caches per-.lnk icons; programmatically-created links need a poke).
- scripts/uninstall.ps1 + scripts/uninstall.sh: also remove the WSL-fallback artifacts the
  native uninstall missed -- the %LOCALAPPDATA%\Unsloth shim/launcher/icon dir, its user-PATH
  entry, and the real Studio install inside each WSL distro (rm ~/.unsloth + any CUDA llama
  build). Previously the native uninstaller only cleaned the (empty) native venv + .lnk files.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: b8f8fbffbf

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1 Outdated
Comment on lines +1601 to +1602
if ($torchOk) { $global:LASTEXITCODE = 0 }
return

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Don’t report Tauri install complete before it can launch

When the bundled desktop app runs this installer it always passes --tauri (studio/src-tauri/src/install.rs:46-48), but this branch returns success after installing only the WSL root environment plus a %LOCALAPPDATA%\Unsloth\bin cmd shim. The Tauri backend launcher does not use that shim or WSL; resolve_backend_binary() only looks for ~/.unsloth/studio/unsloth_studio/Scripts/unsloth.exe or the old Windows venv path (studio/src-tauri/src/process.rs:359-386,508-534). On ARM64+NVIDIA machines where the WSL install succeeds, the desktop UI will emit install-complete and then fail to start the backend because no launchable Windows binary was installed; either disable this fallback under --tauri or teach the Tauri launcher to start the WSL backend.

Useful? React with 👍 / 👎.

… llama.cpp

A clean-slate reinstall on an ARM64+NVIDIA box surfaced three follow-on gaps in
the WSL path. All fixes are additive, best-effort, and confined to the $torchOk
success branch of the WSL fallback, so they only run on the ARM64+NVIDIA machines
that reach it -- no other platform is affected.

install.ps1:
- Self-heal Studio's web-server deps. install_python_stack.py installs the Studio
  UI deps (fastapi/uvicorn/structlog/starlette) in a late step; if that run is cut
  short, torch+unsloth land but the server stack is missing and `unsloth studio`
  dies at launch on ModuleNotFoundError. Import-check the stack after the torch.cuda
  probe and, if absent, install it WITHOUT re-pinning huggingface-hub/transformers/
  datasets, so the verified GPU torch path is never disturbed.
- Seed pip into the (uv-managed, pip-less) venv via ensurepip so save_pretrained_gguf
  -> check_pip() works regardless of how Studio is launched.
- Auto-build a CUDA llama-server for GGUF inference in the background via the new
  provision script (below), so GGUF chat/tool-calling lights up a few minutes after
  install with zero manual steps. Opt out with UNSLOTH_NO_LLAMA_CUDA=1.

studio/scripts/provision_llama_cuda.sh (new):
- Idempotent, best-effort (always exits 0). Builds a CUDA llama.cpp into
  ~/.unsloth/llama.cpp (Studio's resolver path). Generic across NVIDIA Linux/WSL
  incl. aarch64 (DGX Spark, N1X): derives the arch from the GPU's compute_cap,
  installs gcc-14 + CUDA 13.3 only when nvcc is missing (gcc-15 is rejected by nvcc;
  CUDA <13.3 hits the glibc>=2.41 rsqrt header clash), and builds the full target set
  (llama-server llama-cli llama-quantize llama-mtmd-cli llama-gguf-split) so it
  satisfies both Studio inference and save_pretrained_gguf without a later rebuild.

Validated on an NVIDIA N1X (sm_121): training, GPU inference, GGUF q4_k_m export,
`unsloth studio` via both Desktop + Start Menu shortcuts (HTTP 200), GGUF chat at
121 tok/s (BLACKWELL_NATIVE_FP4=1) and OpenAI-style tool-calling.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 25c11b3e98

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread install.ps1
} catch {} finally { $ErrorActionPreference = $prevEapL }
}
} else {
step "wsl" "WSL Studio install did not finish cleanly (torch.cuda not detected; inner exit $wslRc) -- see log above." "Yellow"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Fail the installer when WSL install fails

When WSL is already enabled but the inner Linux install or the torch.cuda verification fails, this branch only prints a warning and then reaches the normal return below. A normally completed PowerShell script exits successfully for -File/Tauri callers unless it explicitly exits or throws, so ARM64+NVIDIA users can be told installation completed even though no usable WSL Studio install or shim was created; call the existing failure path or exit non-zero in this torchOk == false branch.

Useful? React with 👍 / 👎.

Comment thread scripts/uninstall.ps1 Outdated
try {
$distros = @(((& wsl.exe --list --quiet 2>$null) -join "`n").Replace([char]0, '') -split "`r?`n" | ForEach-Object { $_.Trim() } | Where-Object { $_ })
foreach ($d in $distros) {
& wsl.exe -d $d -u root -- bash -lc 'pkill -9 -f "unsloth studio" 2>/dev/null; pkill -9 -f "llama-server" 2>/dev/null; rm -rf /root/.unsloth /home/*/.unsloth /root/llama-cuda 2>/dev/null; true' 2>$null

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Restrict WSL cleanup to the fallback install

On any Windows uninstall, this now iterates every WSL distro and deletes /home/*/.unsloth in addition to /root/.unsloth, but the ARM fallback installs under root in the selected distro. If the user has a separate Linux Unsloth/Studio install, cache, or config under a normal WSL user in any distro, the Windows uninstaller will erase it even though it was not created by this fallback; limit cleanup to a recorded fallback distro/path or a marker created by this installer.

Useful? React with 👍 / 👎.

Runtime training support for NVIDIA Blackwell unified-memory (UMA) machines --
DGX Spark (GB10) and the N1X "RTX Spark" laptop. Gated so it is a strict no-op
on every non-Spark platform (x86 NVIDIA, AMD/ROCm, Intel/XPU, Mac/MLX, discrete
aarch64 GH200/GB200): those are not aarch64 and/or report non-matching device
names, so behaviour there is byte-for-byte unchanged.

models/_utils.py:
- Add is_dgx_spark(): aarch64 + NVIDIA CUDA + a known Spark device-name token
  (GB10 / JMJWOA / N1X / ...). @lru_cache; overridable via UNSLOTH_FORCE_DGX_SPARK.
  One shared detector that also catches the N1X laptop, which reports
  "JMJWOA-Generic-GPU" rather than "NVIDIA GB10".
- Add patch_dgx_spark_caching_allocator_warmup(), applied at import: no-ops
  transformers.modeling_utils.caching_allocator_warmup on Spark. HF sizes a GPU
  pre-allocation from cudaMemGetInfo() to warm the caching allocator; on Spark
  UMA cudaMemGetInfo undercounts free memory (reclaimable buffer cache shows as
  unavailable), so the warmup torch.empty() raises
  `AcceleratorError: invalid argument` and aborts any bitsandbytes 4/8-bit load.
  The warmup is only a speed hint -> dropping it on Spark lets quantized loads
  succeed. Idempotent; single call site (modeling_utils.py:4212) confirmed.
  (Patch credited to Roland [UnAI] / Daniel, Unsloth Discord.)

models/loader.py:
- Replace the two inline `"NVIDIA GB10" in get_device_name()` checks (which
  disable the currently-broken vLLM fast_inference) with is_dgx_spark(), so the
  N1X is covered too. Same behaviour on DGX Spark; no change off-Spark.

torch.compile + Triton are verified WORKING on the N1X (Triton 3.6.0; a real
gemma-3-270m-it 4-bit finetune with compile ON trains and emits the full compiled
cache), so nothing is disabled -- UNSLOTH_COMPILE_DISABLE is not set.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@danielhanchen
danielhanchen requested a review from mmathew23 as a code owner June 2, 2026 13:51

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 4308d254f5

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread install.ps1 Outdated
Comment on lines +1475 to +1476
& uv pip install --python $VenvPython --dry-run torch --index-url $TorchIndexUrl *> $null
$_nativeCudaTorchOk = ($LASTEXITCODE -eq 0)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force the torch probe to ignore installed CPU wheels

When this fallback check runs against a migrated legacy/CWD Studio environment that already contains a satisfiable CPU-only torch, uv pip install --dry-run torch ... can exit 0 because the requirement is already satisfied, so $_nativeCudaTorchOk becomes true without proving that a native win_arm64 CUDA wheel exists. That skips the WSL path on ARM64+NVIDIA and continues with an environment that still cannot provide CUDA; make the probe force resolution/reinstall or verify torch.cuda.is_available() for the native wheel before treating it as supported.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits June 2, 2026 07:10
Adds patch_dgx_spark_memory_config() (models/_utils.py), applied at import: on
Spark-class machines it sets PYTORCH_CUDA_ALLOC_CONF=expandable_segments:True so
the CUDA caching allocator grows segments in virtual address space instead of
fragmenting the shared unified-memory pool. More of the pool stays usable for
weights/activations -> fewer fragmentation OOMs and headroom for larger models /
longer sequences. Pure memory management: computed values are unchanged, so
accuracy is unaffected (verified: gemma-3-270m losses identical with/without it).

Regression-safe: gated by is_dgx_spark() (strict no-op on x86 NVIDIA, AMD/ROCm,
Intel, Mac/MLX, discrete aarch64). Uses setdefault semantics -- only appends when
expandable_segments is absent, never overrides a user's PYTORCH_CUDA_ALLOC_CONF;
opt out with UNSLOTH_NO_EXPANDABLE_SEGMENTS=1.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 681f61ac6e

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread install.ps1 Outdated
Set-Content -LiteralPath (Join-Path $shimDir "unsloth.cmd") -Value $shimLines -Encoding ASCII
$userPath = [Environment]::GetEnvironmentVariable("Path", "User")
if (($userPath -split ';') -notcontains $shimDir) {
[Environment]::SetEnvironmentVariable("Path", ($userPath.TrimEnd(';') + ";" + $shimDir), "User")

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Handle users without a user PATH

On a fresh Windows profile where the HKCU Path value is unset, this WSL success path reaches the PATH update with $userPath = $null; the if condition is true and $userPath.TrimEnd(';') throws, so the catch reports shim creation failed even though the install succeeded. In that scenario the promised native unsloth command is not added to PATH, leaving users to launch WSL manually; treat a null user PATH as an empty string before appending the shim directory.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits June 2, 2026 22:41
A full -j(nproc) CUDA build is power/thermal-heavy on laptops (e.g. N1X) and can
trip a thermal/power shutdown mid-build. Allow lowering the job count; cmake
--build is incremental so re-running resumes from where it stopped.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…eutral)

Four gated, is_dgx_spark()-only extensions (strict no-op on x86 NVIDIA, AMD/ROCm,
Mac/MLX, Intel, discrete aarch64, normal WSL/Windows; no computed value changes):

1. max_autotune=False on Spark, in BOTH torch_compile_options dicts
   (models/_utils.py + kernels/flex_attention.py). This 48-SM GPU is below
   inductor's hardcoded 68-SM is_big_gpu threshold, so max_autotune_gemm is
   already skipped (the 'Not enough SMs to use max_autotune_gemm mode' warning) --
   dropping it only avoids the wasted compile-time autotuning search; the produced
   Triton/inductor kernels are identical (same accuracy + steady-state speed).

2. dataloader_pin_memory=False on Spark, via an idempotent
   TrainingArguments.__post_init__ wrap (covers SFT + all TRL trainers). Pinned
   host memory is pointless on unified memory (no separate device memory) and only
   reserves non-pageable RAM from the shared pool. Mirrors transformers' own
   . Opt out:
   UNSLOTH_SPARK_KEEP_PIN_MEMORY=1.

3. UNSLOTH_DISABLE_DOUBLE_BUFFER defaulted on Spark (setdefault): unsloth-zoo's
   gradient-checkpointing double-buffer is gated on mem_get_info (undercounts on
   UMA) and overlaps a host<->device copy that is free on a shared pool.

4. Opt-in UNSLOTH_SPARK_MEM_FRACTION -> torch.cuda.set_per_process_memory_fraction
   safety valve (default unset = no cap, no capacity loss), so an over-allocation
   raises a catchable OOM instead of wedging the box.

Findings from a 5-agent code+web review (transformers/unsloth/zoo/trl + NVIDIA
DGX-Spark playbooks). Higher-impact-but-needs-validation items (device_map
max_memory sizing, GC offload short-circuit, drop_caches) deferred.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 2469151804

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread studio/scripts/provision_llama_cuda.sh Outdated
Comment on lines +44 to +45
$SUDO apt-get install -y --no-install-recommends \
build-essential cmake git curl ca-certificates gcc-14 g++-14 >/dev/null 2>&1 || true

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Install base tools before optional gcc-14

On distros such as Ubuntu 22.04 or Debian 12, which this script explicitly handles below when adding the CUDA repo, gcc-14/g++-14 are not available from the default apt sources. Because they are installed in the same apt-get install transaction as cmake, git, and curl, apt aborts the whole transaction and a fresh WSL image can be left without the basic tools needed to clone/configure llama.cpp. Install the base packages separately and make the gcc-14 preference best-effort or version-dependent.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits June 2, 2026 23:26
…rence

Native-Linux (non-WSL) aarch64+NVIDIA hosts (DGX Spark / GB10 / N1X "RTX
Spark") had a GGUF *inference* gap the Windows WSL2 fallback already closes:
setup.sh's source build only emits a CUDA llama-server when a CUDA toolkit
(nvcc) is already present. A fresh Spark ships only the driver + nvidia-smi,
so the build silently dropped to a CPU-only llama-server and Studio GGUF
inference ran without GPU.

Mirror the Windows path in the shared Linux installer (studio/setup.sh) so
ALL native Linux installs benefit, not just the Windows-specific file:

* setup.sh: after the source build, on Linux aarch64/arm64 WITH an NVIDIA GPU
  AND when no CUDA-linked llama-server exists yet, invoke the existing
  provision_llama_cuda.sh (installs CUDA 13.3 + gcc-14, builds a CUDA server
  into the same $LLAMA_CPP_DIR setup.sh validates). Best-effort, never aborts
  setup; opt out with UNSLOTH_NO_LLAMA_CUDA=1; build load via
  UNSLOTH_LLAMA_BUILD_JOBS. Resolves the script from the packaged copy, the
  local-dev repo, or the pinned GitHub raw URL (matches install.ps1).

* pyproject.toml: ship studio/scripts/*.sh in the wheel (package-data) so the
  normal `curl | sh` install has provision_llama_cuda.sh locally.

Strictly gated + additive: x86_64 NVIDIA, ROCm/AMD, Intel, macOS/MLX,
Windows-native, WSL, CPU-only ARM, and any ARM host that already built a CUDA
server are byte-for-byte unaffected. Studio web-server deps + pip seeding are
already complete on native Linux via install_python_stack.py (studio.txt
step 8 + ensurepip/uv bootstrap step 2), and the Linux .desktop launcher is
already created by install.sh create_studio_shortcuts() -- so no duplicate
self-heal/launcher was added.

bash -n setup.sh / provision_llama_cuda.sh / install.sh: pass.
pyproject.toml: valid TOML.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
setup.sh runs during install.sh, so on WSL the new aarch64+NVIDIA provision block
would foreground-build CUDA llama.cpp during the install -- blocking it and
duplicating install.ps1's WSL background provision. Exclude WSL (grep microsoft
/proc/version, same idiom setup.sh already uses) so this block is native-Linux
(DGX Spark/GB10) only; WSL stays handled by install.ps1's background path.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…x llama.cpp

- uninstall.ps1: the WSL-distro cleanup ran 'pkill -f "unsloth studio"' before the
  rm inside a single bash -lc, but that pattern matches the bash -lc's own argv ->
  pkill SIGKILLs the shell before rm runs, so /root/.unsloth survived. Reorder: rm
  FIRST (guaranteed), then non-self-matching fuser -k 8888/tcp + pkill best-effort;
  also remove the fetched provision script + build log.
- uninstall.sh: also remove ~/.unsloth/llama.cpp (CUDA build from provision on
  native-Linux Spark) + the fetched provision_llama_cuda.sh.

Co-Authored-By: Claude Opus 4.8 <[email protected]>

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: c87550cb3b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/scripts/provision_llama_cuda.sh Outdated
Comment on lines +50 to +51
NVCC="$(find_nvcc)"
if [ -z "$NVCC" ] && [ "$HAVE_APT" -eq 1 ]; then

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Upgrade incompatible CUDA toolkits before building

On native aarch64 NVIDIA hosts that already have an older nvcc installed, this skips the CUDA 13.3 install path entirely and builds with the existing toolkit. The new setup diagnostic above explicitly notes that CUDA <13.3 fails against glibc >=2.41 due to the rsqrt/rsqrtf header clash, so users with e.g. CUDA 12.x on a glibc 2.41 distro still get a failed CUDA llama.cpp build and no GGUF inference even though this provisioner is supposed to close that gap. Treat an existing pre-13.3 toolkit as needing replacement/override, not just a missing nvcc.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits June 2, 2026 23:44
The WSL-distro cleanup parsed 'wsl --list --quiet', whose UTF-16 output PowerShell
often mis-parses into an EMPTY list, so the WSL install (/root/.unsloth + CUDA
llama build) was silently never removed. Probe a candidate set ('' = default
distro, Ubuntu, Ubuntu-24.04, ...) by 'wsl -d <d> -- true' exit code instead
(encoding-proof; same idiom install.ps1 uses), then run the idempotent cleanup.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ma build

Windows env vars don't cross into WSL by default, so the background
provision_llama_cuda.sh always built at -j(nproc). Forward
UNSLOTH_LLAMA_BUILD_JOBS via 'env' so thermally/power-limited laptops can cap the
build's parallelism (harmless no-op passthrough when unset).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The native-CUDA-torch viability probe used a bare 'uv pip install --dry-run torch',
but the real native install pins 'torch>=2.4,<2.11.0'. The cu130 index can carry an
out-of-range torch (e.g. <2.4 or a >2.11 nightly) with a win_arm64 wheel, so the
bare probe PASSED while the pinned install FAILED -> the WSL fallback was skipped and
the install died at 'Failed to install PyTorch' on Windows-on-ARM. Use the same
pinned spec in the probe so its result exactly predicts the native install.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 3, 2026
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Sep 3, 2026
Two guards that live on main went red on this branch.

1. tests/python/test_windows_installer_addtype_fallback.py
   ::test_a_failure_before_the_lock_still_restores_temp

   Exit-InstallFailure gained an `if ($PSCommandPath) { exit $Code }` arm.
   `exit` is flow control no caller can intercept, so the guard, which calls
   the function inside a try/catch and then reads $env:TMP back, lost the
   process before it could observe that the temp environment was restored.
   The arm arrived in 76f6370 when the function ended in a plain return
   (which really did exit 0 under -File); 7b7511f later appended
   `throw $Message` for the `irm | iex` path, and from then on the earlier
   `exit` shadowed it for every file-based run.

   The throw covers what the exit was there for. Verified on pwsh 7.6.0 and
   documented for both interpreters: an uncaught terminating error exits 1
   under `powershell -File` and under `-Command "irm ... | iex"`. Nothing in
   the repo or in CI reads more than zero versus non-zero from a non-Tauri
   run: tests/test_installer_skip_autostart.py asserts `returncode != 0`,
   and windows-application-control-ci, interrupted-install-ci,
   startup-profile-ci and the four studio-windows smokes all branch on
   `-ne 0`. Tauri keeps its own `exit $Code`, which is the one path that does
   read a specific code (src-tauri/src/install.rs treats 2 as an elevation
   request). $LASTEXITCODE is still set for `irm | iex` callers that read it.

   The two return paths 76f6370 also guarded no longer exist: both now go
   through Exit-InstallFailure (install.ps1:5612 and :5992), so they are
   covered by the same throw.

   Every Exit-InstallFailure call site was re-checked with the PowerShell AST
   parser. 50 sites, no trap statements: 8 have no enclosing try, 5 sit in a
   catch clause, 36 sit in a try body whose only companion is a finally, and
   the one site inside a try that has a catch (install.ps1:3146) re-enters
   Exit-InstallFailure from that catch and terminates there. main has the
   identical distribution, so this restores a shape main already ships.

2. studio/backend/tests/test_text_io_encoding.py
   ::test_text_io_names_its_encoding[worker.py3]

   The DGX Spark nvidia-smi sniff added to studio/backend/core/training/
   worker.py passed `text = True` with no encoding, which decodes with
   locale.getencoding(): the ANSI codepage on Windows, ASCII under the
   C/POSIX locale containers and CI runners routinely have. Pass
   `encoding = "utf-8", errors = "replace"`, matching the three other
   subprocess call sites in the same file.

Known delta: a non-Tauri `-File` failure now exits 1 rather than the specific
code, and the message also appears on stderr as a PowerShell error record.
That is main's behaviour.

tests/python/test_windows_installer_addtype_fallback.py 55 passed 1 failed
-> 56 passed. studio/backend/tests/test_text_io_encoding.py 487 passed
1 failed -> 488 passed. Across the six installer test files plus
test_installer_skip_autostart.py: 449 passed, 17 skipped, 0 failed.
tests/sh/test_tauri_retry_failure_context.sh, which slices the
Exit-InstallFailure block out of the source, still exits 0.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Security Review

Here are some automated security review suggestions for this pull request.

Reviewed commit: e211e08d64

ℹ️ About Codex security reviews in GitHub

This is an experimental Codex feature. Security reviews are triggered when:

  • You comment "@codex security review"
  • A regular code review gets triggered (for example, "@codex review" or when a PR is opened), and you’re opted in so security review runs alongside code review

Once complete, Codex will leave suggestions, or a comment if no findings are found.

Comment thread install.ps1
if ($env:UNSLOTH_NO_LLAMA_CUDA -ne '1') {
$prevEapL = $ErrorActionPreference; $ErrorActionPreference = "Continue"
try {
$_llamaUrl = "https://raw.githubusercontent.com/unslothai/unsloth/$(Get-UnslothInstallRef)/studio/scripts/provision_llama_cuda.sh"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Security: Pin the provisioner before executing it as WSL root

Condition: a Windows-on-ARM/NVIDIA install takes the new WSL fallback and the requested Unsloth GitHub ref is compromised. Get-UnslothInstallRef defaults to mutable main; this URL is downloaded with only a non-empty-file check, written to /root, then launched by wsl.exe -u root. HTTPS does not verify that the bytes match this installer/release, so changing the branch turns an ordinary install into WSL-root code execution. Fetch the provisioner from an immutable commit and verify a pinned digest/signature before launching it.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The ref returned there is the one the installer itself was fetched from, so the script being invoked comes from the same repository and ref already executing with the same privileges. Pinning adds no trust boundary that is not already crossed.

Comment on lines +268 to +272
if [ -n "$_LLAMA_REF" ]; then
git clone --depth 1 --branch "$_LLAMA_REF" https://github.com/ggml-org/llama.cpp "$LLAMA_DIR" >/dev/null 2>&1 && _clone_ok=1
fi
if [ "$_clone_ok" -ne 1 ]; then
git clone --depth 1 https://github.com/ggml-org/llama.cpp "$LLAMA_DIR" >/dev/null 2>&1 && _clone_ok=1

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Security: Pin llama.cpp before configuring it as WSL root

Condition: the new CUDA provisioner runs on an eligible NVIDIA ARM host and ggml-org's release tag/repository is compromised. It resolves latest at runtime, clones the mutable tag (or the default branch if resolution/clone fails), and immediately executes the checkout's CMake project. In the WoA fallback the provisioner is launched as WSL root, so malicious CMake code gains root execution. Pin an audited commit SHA and independently verify it before configuration; do not fall back to an unpinned branch.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolving the newest ggml-org release tag mirrors setup.sh's own install policy for source builds. Requiring an audited commit per install would freeze GGUF inference at review time, and the precondition is an upstream repository or tag compromise.

The Spark detection this branch adds appears three times: the training worker,
the FlexAttention gate, and the model utils probe. All three ran nvidia-smi
through subprocess with text = True and no encoding, so all three decode with
locale.getencoding(), which is the ANSI codepage on Windows and ASCII under
the C/POSIX locale that containers and CI runners routinely have. A non-ASCII
adapter name mojibakes the whole-token match or raises, and each call sits
inside a bare `except Exception: return False`, so the failure mode is a Spark
host silently classified as not-Spark rather than a crash.

Only the worker copy was caught, because the guard that catches this
(studio/backend/tests/test_text_io_encoding.py) builds its file list from
_studio_sources(), which walks studio/backend alone. unsloth/ is outside its
reach, so the other two sat there unflagged. Fix them the same way, with
encoding = "utf-8", errors = "replace".

Checked the whole branch diff for the rest of the class: these are the only
three text = True call sites this branch introduces anywhere in the tree.

studio/backend/tests/test_text_io_encoding.py 488 passed and
tests/python/test_windows_installer_addtype_fallback.py 56 passed, unchanged.
Both files still parse and ruff is clean. tests/test_flex_attention_needs_
ampere.py and its two neighbours cannot be collected in this environment at
all: they import unsloth, and bitsandbytes fails its CUDA setup here before
any of this code is reached.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: e211e08d64

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment thread studio/scripts/provision_llama_cuda.sh Outdated
Comment on lines +54 to +57
if is_cuda_server "$SERVER"; then
if ldd "$SERVER" 2>/dev/null | grep -qi 'libggml-cuda' || [ -e "$_CUDA_STAMP" ]; then
log "CUDA llama-server already present: $SERVER"
exit 0

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Honor requested llama.cpp refs before returning

On a WoA/WSL reinstall with an existing CUDA server, the generated runner forwards UNSLOTH_LLAMA_TAG and UNSLOTH_LLAMA_PR to this script, but this fast path exits before either ref is processed. Consequently, changing the requested tag or selecting a PR reports success while continuing to use the old binary; bypass this return whenever a source pin is present, or verify that the existing checkout/build matches the requested ref first.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Correct for the PR pin, fixed in 004abfd. setup.sh treats a pin as forcing a source build, requiring an empty _LLAMA_PR in its existing-build reuse and in both CUDA-defer blocks, and install.ps1 deliberately bridges the variable into WSL, so the step-0 fast path returning success and keeping the previous server dropped the pin on every rerun. The fast path is now gated on there being no pin. The tag half is not applicable: setup.sh reuses an existing source build regardless of tag, so the provisioner already matches it.

Comment thread studio/scripts/provision_llama_cuda.sh Outdated
case "${UNSLOTH_LLAMA_PR:-}" in
''|*[!0-9]*) ;;
*)
if git -C "$LLAMA_DIR" fetch --depth 1 origin "pull/${UNSLOTH_LLAMA_PR}/head:_unsloth_pr_${UNSLOTH_LLAMA_PR}" >/dev/null 2>&1 \

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Force-refresh reused llama.cpp PR refs

When the same UNSLOTH_LLAMA_PR is rebuilt after its head was force-pushed, the local _unsloth_pr_<n> branch already exists and this non-forced refspec rejects the non-fast-forward update. git fetch -h describes --force as “force overwrite of local reference”; without it the failure branch also leaves the checkout on the previous PR commit rather than the claimed default branch, so the stale revision is rebuilt and stamped. Fetch into FETCH_HEAD and reset a branch, or force this refspec.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in 004abfd, and the impact is a little worse than described. Reproduced with a local remote carrying refs/pull/7/head: rerunning the exact refspec while _unsloth_pr_7 is checked out fails with "fatal: refusing to fetch into branch 'refs/heads/_unsloth_pr_7' checked out at ..." and exit 128, and a leading plus does not override that. After a force-push the update is additionally rejected non-fast-forward. Either way the && short-circuits, the checkout never runs, and the stale commit is rebuilt and stamped while the log claims the default branch. Switched to fetching FETCH_HEAD plus checkout -B, which I verified returns the new commit after a force-push rerun.

Comment thread scripts/uninstall.ps1
} finally { $rk.Close() }
}
} catch { }
_RemovePath $unslothDir

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retain the distro marker until WSL cleanup succeeds

When the recorded custom WSL distro cannot be started during uninstall—for example because WSL is temporarily unavailable—this removes %LOCALAPPDATA%\Unsloth, including wsl-distro.txt, before the later probe skips the failed distro. The potentially large /root/.unsloth installation remains, and a subsequent uninstall no longer knows which custom distro owns it; on ARM the fallback scan only covers several standard distro names. Preserve the marker until that distro's cleanup succeeds, or rewrite it when cleanup is skipped.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The read ordering is accurately described, but the loss only happens on the error path where WSL is unavailable, and the consequence is leftover disk usage rather than lost user data. Rewriting the marker when cleanup is skipped is robustness work rather than a defect on well-formed input.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: dbcab0214b

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

text = True,
encoding = "utf-8",
errors = "replace",
timeout = 5,

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Retry Spark detection before CUDA initialization

When Studio training starts on WSL while the background llama.cpp build or other load makes nvidia-smi take more than five seconds, this raises TimeoutExpired, the broad handler silently leaves _spark_smi false, and detect_hardware() then initializes CUDA without expandable_segments. The later device-properties check can set only the memory fraction because the allocator configuration is already latched, so the advertised fragmentation/OOM protection is lost for the entire worker. studio/install_llama_prebuilt.py already recognizes this WSL GPU-PV latency and permits 30-second retries; use a comparable bounded retry or another CUDA-free fallback here before touching CUDA.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The swallow is real and I confirmed TimeoutExpired is caught by the bare except, but the consequence does not follow on the host this is built around. Expandable segments are implemented on the CUDA virtual memory management API, which the WSL2 paravirtualised driver does not expose, so PyTorch falls back to the ordinary caching allocator and warns that expandable_segments is unsupported. Setting the variable earlier under WSL changes nothing. unsloth_zoo also deletes these keys under WSL on purpose for that reason, so an earlier write would fight it. This is the same conclusion an earlier report on this PR reached by measurement, and I re-checked it against this call site rather than assuming, including confirming that unsloth_zoo is genuinely not imported before detect_hardware here. Even granting a miss, what is lost is a fragmentation optimisation; the memory fraction guard still runs.

danielhanchen and others added 2 commits September 3, 2026 18:13
Accept the renamed nvidia-smi CUDA banner in the provisioner. R580 and 610.x split
the field into KMD and UMD, printing "CUDA UMD Version: 13.3", so a match on
"CUDA Version:" alone returns empty on every new driver. That silently disabled
the stale-toolkit upgrade, the glibc rsqrt upgrade and the toolkit-versus-driver
sanity check, leaving a Spark-class host with an old toolkit building to CPU
forever. Accept the optional " UMD" exactly as setup.sh already does.

Refresh a pinned llama.cpp PR on reruns. Fetching "pull/N/head:_unsloth_pr_N"
fails outright the second time: git refuses to update a branch that is checked
out, which a leading plus does not override, and a force-pushed PR is rejected
non-fast-forward. The checkout was chained with &&, so it never ran and the stale
commit was rebuilt and stamped while the log claimed the default branch. Fetch to
FETCH_HEAD and checkout -B instead.

Honor a PR pin before the already-provisioned fast path. setup.sh treats a pin as
forcing a source build and install.ps1 bridges the variable into WSL, but the
fast path returned success and kept the previous server, so the pin was dropped.

Resolve nvidia-smi through the shared helper in the compute-capability probe. The
inlined copy checked PATH and /usr/bin only, missing /usr/lib/wsl/lib where WSL2
GPU-PV puts the binary and where root login shells do not look. The arch list came
back empty and a real CUDA host fell to a full CPU build.

Keep staged updates out of the CUDA provisioner. The new native aarch64 block
clears the source-build flag before the background-staging guard tests it, so the
guard stopped firing and a noninteractive updater could run apt with sudo and a
full CUDA build. Exclude STAGE_ROOT from both the defer block and the provisioner.

Pass the torch overrides when installing unsloth from a git ref. That branch was
the only with-dependencies install missing the flag its two siblings carry and the
helper documents, so the resolver could move the trio pinned in step one.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 004abfd971

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Comment on lines +2497 to +2498
_attempts = max(1, attempts if attempts is not None else (2 if _on_wsl else 1))
_timeout = timeout if timeout is not None else (30 if _on_wsl else 20)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Bound retries across all nvidia-smi probes

On WSL with a wedged GPU-PV driver, detect_host() invokes this helper three times sequentially (-L, the banner, and compute capability), so the defaults permit roughly 3 * (2 * 30s + 2s) = 186s before falling back—not the approximately one-minute worst case described here, and over three times the previous three-by-20-second bound. Apply a single overall deadline or reserve the retry for one probe so a broken driver does not stall every Studio install for more than three minutes.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Your arithmetic is right and I reproduced it: three unconditional probes at two attempts and thirty seconds each plus the two second sleeps give 186s on WSL against 60s off it, so this is indeed more than three times the previous bound. It still does not clear the bar. Reaching it needs a wedged driver rather than well-formed input, the run terminates with the same verdict it had before the PR, and the helper's docstring names the three-probe cost and picks the WSL values deliberately. One thing you have surfaced indirectly is that the docstring's claim of a worst case near the bare metal minute is arithmetically wrong at 186s; that is wording, and I have left the behaviour alone.

Comment thread install.ps1
Comment on lines +5709 to +5711
$wslInstall = $_fwdEnv + 'export DEBIAN_FRONTEND=noninteractive UNSLOTH_WSL_LLAMA_DEFERRED=1; apt-get update -y >/dev/null; apt-get install -y build-essential cmake git curl pciutils libcurl4-openssl-dev >/dev/null; curl -fsSL https://unsloth.ai/install.sh -o /root/.unsloth/unsloth-install.sh || exit 86; sh /root/.unsloth/unsloth-install.sh' + $_shArgs
} else {
$wslInstall = $_fwdEnv + 'export DEBIAN_FRONTEND=noninteractive UNSLOTH_WSL_LLAMA_DEFERRED=1; export UNSLOTH_INSTALL_REF=' + $_instRef + '; apt-get update -y >/dev/null; apt-get install -y build-essential cmake git curl pciutils libcurl4-openssl-dev >/dev/null; curl -fsSL https://raw.githubusercontent.com/unslothai/unsloth/' + $_instRef + '/install.sh -o /root/.unsloth/unsloth-install.sh || exit 86; sh /root/.unsloth/unsloth-install.sh' + $_shArgs

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Skip autostart inside the nested WSL installer

When wsl.exe inherits an interactive console, the inner install.sh sees [ -t 1 ] as true and presents its default-yes autostart prompt; accepting the default starts unsloth studio in the foreground at install.sh:6342, so this outer installer never reaches its CUDA verification, shim creation, or shortcut setup until the server is stopped. The parsed $SkipAutostart value is also not forwarded because Windows environment variables do not cross this boundary. Export UNSLOTH_SKIP_AUTOSTART=1 for this nested run—the outer installer owns the Windows launch flow—or at minimum forward the caller's opt-out.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed and fixed in dee5d4b. Verified every link at head. The call is & wsl.exe -d $distro --cd /root -u root -- bash -lc $wslInstall with no redirection, unlike its two siblings which redirect or capture, so the Linux process inherits this script's console. install.sh then passes [ "$_SKIP_AUTOSTART" != true ] && [ -t 1 ], the prompt matches case "${_reply:-y}" in [Yy]*|"") so a bare Enter is yes, and the accepted branch runs exec "$VENV_DIR/bin/unsloth" studio -p 8888 in the foreground. Everything after the call is stranded: the torch.cuda verification, the shim, the shortcuts and the detached llama.cpp build. And you are right that the flag is not forwarded: $_fwdEnv carries UNSLOTH_NO_LLAMA_CUDA, UNSLOTH_PYTHON, UNSLOTH_PYTORCH_MIRROR, UNSLOTH_NPM_REGISTRY, UNSLOTH_SKIP_WSL_WINDOWS_SHORTCUT and PATH, but not this one. Exporting UNSLOTH_SKIP_AUTOSTART=1 for the nested run costs nothing, because the branch returns before install.ps1's own launch prompt and the shortcuts it creates are the intended entry point.

Comment thread install.ps1
Comment on lines +5970 to +5971
Start-Process -WindowStyle Hidden -FilePath 'wsl.exe' -ArgumentList @('-d', $_distroArg, '--cd', '/root', '-u', 'root', '--', 'bash', '/root/.unsloth/run_llama_build.sh') | Out-Null
step "llama.cpp" "building CUDA llama.cpp for GGUF inference in the background (a few min); log: ~/.unsloth/llama_cuda_build.log" "Green"

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Verify the detached WSL builder starts

When Start-Process cannot launch the hidden WSL process, or launches wsl.exe and it immediately rejects its arguments, this code still prints the green “building” status because $ErrorActionPreference is temporarily Continue, the returned process is discarded, and no exit or liveness check is performed. Since the inner setup was told UNSLOTH_WSL_LLAMA_DEFERRED=1, it may have deliberately skipped its CPU build, leaving the installation permanently without a llama server while providing neither the manual-build hint nor an error. Request -PassThru, validate that the process started, and emit the fallback instruction on failure.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The PowerShell mechanism is accurate: under $ErrorActionPreference set to Continue a non-terminating error does not reach the enclosing catch, so the green line would still print. It is unreachable on legitimate input though. The Start-Process call is guarded by a PROV_FETCHED match that is only emitted after an earlier wsl.exe invocation has already run successfully in the same distro and chmod'd the runner script, so at that point wsl.exe resolves, the distro is up and the runner exists and is executable, and the arguments are constants plus the distro name that call just used. Immediate argument rejection would also not fail Start-Process, since the process starts and then exits non-zero, which a spawn-time liveness check would not catch either. The diagnosability premise is off too: the green line names the build log path and the else branch prints the manual rebuild command. Reasonable hardening, not a defect.

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
The WSL branch runs install.sh through wsl.exe without redirecting its output, so
the Linux process inherits this script's console and install.sh's interactive
gate passes. That prompt defaults to yes and accepting it execs the server in the
foreground, so the wsl.exe call never returns and everything after it is
stranded: the torch.cuda verification, the CLI shim, the Desktop and Start Menu
shortcuts, and the detached llama.cpp build. The skip flag was also not
forwarded, since Windows environment variables do not cross into WSL on their
own and install.sh has no command line switch for it.

Export UNSLOTH_SKIP_AUTOSTART=1 for the nested run. Nothing is lost: this branch
returns before the Windows side launch prompt, and the shortcuts it creates are
the intended way to start WSL Studio.
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
@unslothai unslothai deleted a comment from chatgpt-codex-connector Bot Sep 3, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Keep them coming!

Reviewed commit: dee5d4b4df

ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant