Skip to content

PR: Fix/cuda minimum check and abort - #4517

Merged
danielhanchen merged 7 commits into
unslothai:mainfrom
LeoBorcherding:fix/cuda-minimum-check-and-abort
Mar 22, 2026
Merged

danielhanchen merged 7 commits into
unslothai:mainfrom
LeoBorcherding:fix/cuda-minimum-check-and-abort

Conversation

@LeoBorcherding

Copy link
Copy Markdown
Collaborator

PR: Fix/cuda minimum check and abort

Branch: fix/cuda-minimum-check-and-abort
Files changed: studio/setup.ps1, studio/setup.sh
Closes: #4437


Summary

Three setup reliability fixes aimed at eliminating silent failures during llama.cpp CUDA builds and venv reuse across driver updates.


Changes

1. CUDA minimum version check (setup.ps1 + setup.sh)

Problem: setup.ps1/setup.sh already rejected CUDA toolkits too new for the driver, but had no lower-bound check. A user with CUDA 12.1 (< 12.4, the minimum llama.cpp requires) passed the existing check, setup continued, and cmake failed deep in the build with a generic, unrelated-looking error. The real cause only became visible after manually re-running cmake from the llama.cpp folder.

Fix: Immediately after nvcc is confirmed present (and before any cmake invocation), run nvcc --version, parse the release X.Y field, and abort with a clear red error + link to the CUDA archive if the version is below 12.4.

[ERROR] CUDA Toolkit 12.1 is too old for llama.cpp.
        llama.cpp requires CUDA >= 12.4.
  Install: https://developer.nvidia.com/cuda-toolkit-archive

Placement:

  • setup.ps1 — after the if (-not $NvccPath) { exit 1 } guard, before CUDA env vars are set.
  • setup.sh — inside if [ -n "$NVCC_PATH" ], after -DGGML_CUDA=ON is appended to CMAKE_ARGS.

2. CUDA VS integration copy hardened (setup.ps1)

Problem: Copying the CUDA .targets/.props files into Visual Studio's MSBuild customizations folder requires elevation. The previous catch block printed a yellow warning and continued; cmake then failed with the cryptic "No CUDA toolset found" MSBuild error.

Fix: Changed from a soft [WARN] + continue to a red [ERROR] box + exit 1, clearly indicating admin rights are needed and pointing to the CUDA archive for a clean reinstall.

[ERROR] Could not copy CUDA VS integration files (admin required).
        cmake cannot find the CUDA toolset without these files.
  Re-install CUDA Toolkit (or Visual Studio Build Tools, then CUDA):
  https://developer.nvidia.com/cuda-toolkit-archive

3. Stale venv detection and rebuild (setup.ps1)

Problem: If a user updated their NVIDIA driver after the initial setup (e.g. driver now supports CUDA 13.0, previously 12.4), the existing .venv still contained a cu124-tagged torch. Setup would silently reuse it, and the UI would fail at runtime because torch's CUDA library was mismatched.

Fix: Before creating the venv, if .unsloth/studio/.venv already exists, import torch inside it and read torch.__version__ to extract the installed CUDA tag (e.g. cu124). Compare against the tag the current driver requires (via Get-PytorchCudaTag). If they differ, wipe the venv with Remove-Item -Recurse -Force so a clean install follows.

[INFO] Stale venv detected (torch cu124 != required cu130) -- rebuilding...

Test scenarios

Scenario Expected behaviour
CUDA 12.1 installed Aborts immediately with version error, before cmake runs
CUDA 12.4 installed Passes check, build proceeds normally
CUDA 13.x installed Passes check (>= 12.4)
No nvcc found Existing "no nvcc" error path fires first; version check is not reached
CUDA VS integration copy fails Aborts with red error + reinstall link
Venv exists with matching cu tag No change, setup continues as normal
Venv exists with mismatched cu tag Venv wiped, rebuilt with correct torch

LeoBorcherding and others added 3 commits March 19, 2026 17:15
- setup.ps1/setup.sh: abort with clear error if CUDA toolkit < 12.4
  (llama.cpp requirement); link to cuda-toolkit-archive for upgrade
- setup.ps1: promote CUDA VS integration copy failure from WARN to
  ERROR + exit 1; remove manual-copy hack instructions per Roland —
  correct fix is re-installing CUDA/MSBuild, not a manual workaround

Fixes: unslothai#4437
Reported by: Sebastien
When the NVIDIA driver is updated, the required PyTorch CUDA tag changes
(e.g. cu124 -> cu130) but setup.ps1 was silently reusing the existing
.venv, leaving the old torch wheel in place and breaking the UI for
everyone on the next setup run.

Before creating/reusing the venv, inspect the installed torch version
string. If its CUDA tag does not match what the current driver requires,
wipe the venv so we always get a clean, correct install.
@gemini-code-assist

Copy link
Copy Markdown
Contributor

Summary of Changes

Hello, I'm Gemini Code Assist1! I'm currently reviewing this pull request and will post my feedback shortly. In the meantime, here's a summary to help you and other reviewers quickly get up to speed!

This pull request significantly enhances the reliability of the setup scripts ("setup.ps1" and "setup.sh") by addressing common failure points related to CUDA builds and Python virtual environments. It introduces robust checks for minimum CUDA toolkit versions, improves error reporting for Visual Studio integration, and intelligently manages virtual environments to prevent issues arising from driver updates.

Highlights

  • CUDA Minimum Version Check: Implemented a check in both "setup.ps1" and "setup.sh" to ensure the installed CUDA Toolkit is at least version 12.4, which is required by llama.cpp. This prevents silent failures during builds by aborting early with a clear error message if the version is too old.
  • Hardened CUDA VS Integration Copy: Modified "setup.ps1" to change the error handling for copying CUDA Visual Studio integration files. Previously a warning, it now results in an immediate error and exit if admin rights are insufficient, providing clearer guidance to the user.
  • Stale Virtual Environment Detection: Added logic to "setup.ps1" to detect if an existing Python virtual environment (".venv") has a PyTorch CUDA tag that no longer matches the current NVIDIA driver. If a mismatch is found, the stale venv is automatically removed and rebuilt, preventing runtime issues caused by mismatched CUDA libraries.
Using Gemini Code Assist

The full guide for Gemini Code Assist can be found on our documentation page, here are some quick tips.

Invoking Gemini

You can request assistance from Gemini at any point by creating a comment using either /gemini <command> or @gemini-code-assist <command>. Below is a summary of the supported commands on the current page.

Feature Command Description
Code Review /gemini review Performs a code review for the current pull request in its current state.
Pull Request Summary /gemini summary Provides a summary of the current pull request in its current state.
Comment @gemini-code-assist Responds in comments when explicitly tagged, both in pull request comments and review comments.
Help /gemini help Displays a list of available commands.

Customization

To customize Gemini Code Assist for GitHub experience, repository maintainers can create a configuration file and/or provide a custom code review style guide (such as PEP-8 for Python) by creating and adding files to a .gemini/ folder in the base of the repository. Detailed instructions can be found here.

Limitations & Feedback

Gemini Code Assist may make mistakes. Please leave feedback on any instances where its feedback is incorrect or counter productive. You can react with 👍 and 👎 on @gemini-code-assist comments. If you're interested in giving your feedback about your experience with Gemini Code Assist for GitHub and other Google products, sign up here.

Footnotes

  1. Review the Privacy Notices, Generative AI Prohibited Use Policy, Terms of Service, and learn how to configure Gemini Code Assist in GitHub here. Gemini can make mistakes, so double check it and use code with caution. ↩

@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 several reliability improvements to the setup scripts. My review focuses on enhancing the code's readability and maintainability. I've suggested using more idiomatic PowerShell constructs for version comparison and simplifying a shell script conditional for better clarity. Overall, the changes are solid and improve the robustness of the setup process.

Comment thread studio/setup.ps1 Outdated
Comment on lines +632 to +645
$MIN_CUDA_MAJOR = 12; $MIN_CUDA_MINOR = 4
$nvccVerOut = & $NvccPath --version 2>&1 | Out-String
if ($nvccVerOut -match 'release\s+(\d+)\.(\d+)') {
$tkMaj = [int]$Matches[1]; $tkMin = [int]$Matches[2]
if ($tkMaj -lt $MIN_CUDA_MAJOR -or ($tkMaj -eq $MIN_CUDA_MAJOR -and $tkMin -lt $MIN_CUDA_MINOR)) {
Write-Host "" -ForegroundColor Red
Write-Host "================================================================" -ForegroundColor Red
Write-Host "[ERROR] CUDA Toolkit $tkMaj.$tkMin is too old for llama.cpp." -ForegroundColor Red
Write-Host " llama.cpp requires CUDA >= $MIN_CUDA_MAJOR.$MIN_CUDA_MINOR." -ForegroundColor Red
Write-Host " Install: https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow
Write-Host "================================================================" -ForegroundColor Red
exit 1
}
}

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

The current CUDA version check is implemented by manually comparing major and minor version numbers. This can be simplified and made more idiomatic by using PowerShell's [version] type accelerator, which natively supports version comparisons. This improves readability and maintainability.

$MIN_CUDA_VERSION = [version]'12.4'
$nvccVerOut = & $NvccPath --version 2>&1 | Out-String
if ($nvccVerOut -match 'release\s+(\d+\.\d+)') {
    $tkVer = [version]$Matches[1]
    if ($tkVer -lt $MIN_CUDA_VERSION) {
        Write-Host "" -ForegroundColor Red
        Write-Host "===============================================================" -ForegroundColor Red
        Write-Host "[ERROR] CUDA Toolkit $tkVer is too old for llama.cpp." -ForegroundColor Red
        Write-Host "        llama.cpp requires CUDA >= $MIN_CUDA_VERSION." -ForegroundColor Red
        Write-Host "  Install: https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow
        Write-Host "===============================================================" -ForegroundColor Red
        exit 1
    }
}

Comment thread studio/setup.sh Outdated
Comment on lines +440 to +446
if [ "$_nvcc_maj" -lt 12 ] || \
{ [ "$_nvcc_maj" -eq 12 ] && [ "$_nvcc_min" -lt 4 ]; }; then
echo ""
echo "❌ ERROR: CUDA Toolkit $_nvcc_ver is too old for llama.cpp (requires >= 12.4)."
echo " Install CUDA >= 12.4: https://developer.nvidia.com/cuda-toolkit-archive"
exit 1
fi

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

The version comparison logic using [ ... ] || { ... } is correct but a bit verbose. Since this is a bash script (#!/usr/bin/env bash), you can use the more concise and readable arithmetic expansion ((...)) for integer comparisons.

Suggested change
if [ "$_nvcc_maj" -lt 12 ] || \
{ [ "$_nvcc_maj" -eq 12 ] && [ "$_nvcc_min" -lt 4 ]; }; then
echo ""
echo "❌ ERROR: CUDA Toolkit $_nvcc_ver is too old for llama.cpp (requires >= 12.4)."
echo " Install CUDA >= 12.4: https://developer.nvidia.com/cuda-toolkit-archive"
exit 1
fi
if (( _nvcc_maj < 12 || (_nvcc_maj == 12 && _nvcc_min < 4) )); then
echo ""
echo "❌ ERROR: CUDA Toolkit $_nvcc_ver is too old for llama.cpp (requires >= 12.4)."
echo " Install CUDA >= 12.4: https://developer.nvidia.com/cuda-toolkit-archive"
exit 1
fi

@danielhanchen danielhanchen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Review Summary

The PR is directionally correct -- all three changes address real user pain points. However, the new protections have gaps that should be addressed before merge.

Reviewers Severity Finding
8/8 High Stale venv misses CPU/untagged torch installs (+cpu or plain 2.x.y); broken torch imports also silently reuse the old venv
8/8 High grep -oP in setup.sh uses Perl regex unavailable on macOS -- version check silently bypassed
7/8 High exit 1 in setup.sh is a backwards-compat regression -- existing design treats llama.cpp build failures as non-fatal
6/8 Medium Version check is fail-open in both scripts -- unparseable nvcc output silently skips the guard
6/8 Medium VS integration error lost manual fix paths ($cudaExtras / $vsCustomizations)
5/8 Medium Error message gives impossible remediation when driver < 12.4
4/8 Medium Remove-Item $VenvDir -Recurse -Force is unguarded under $ErrorActionPreference = "Stop"
3/8 Low setup.sh check placed after rm -rf "$LLAMA_CPP_DIR" and CMAKE_ARGS mutation
3/8 Low No stale venv detection parity in setup.sh
2/8 Low Error message style inconsistency (PS1 [ERROR] box vs SH emoji)

Comment thread studio/setup.sh Outdated

# Minimum CUDA version check for llama.cpp (requires >= 12.4)
_nvcc_ver=$("$NVCC_PATH" --version 2>/dev/null \
| grep -oP 'release \K[\d]+\.[\d]+' || true)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[8/8 reviewers] grep -oP uses Perl-compatible regex (\K lookbehind) which is only available in GNU grep. macOS ships BSD grep with no -P flag. The || true guard silently swallows the error, _nvcc_ver stays empty, and the entire version check is bypassed on macOS without any warning.

The script already has macOS fallbacks elsewhere (e.g. sysctl -n hw.ncpu), confirming macOS is a supported platform.

Suggested change
| grep -oP 'release \K[\d]+\.[\d]+' || true)
_nvcc_ver=$("$NVCC_PATH" --version 2>/dev/null \
| sed -n 's/.*release \([0-9][0-9]*\.[0-9][0-9]*\).*/\1/p' || true)

Alternatively, use bash-native [[ =~ ]] with BASH_REMATCH to avoid external tool portability issues entirely.

Comment thread studio/setup.sh Outdated
echo ""
echo "❌ ERROR: CUDA Toolkit $_nvcc_ver is too old for llama.cpp (requires >= 12.4)."
echo " Install CUDA >= 12.4: https://developer.nvidia.com/cuda-toolkit-archive"
exit 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[7/8 reviewers] exit 1 here aborts the entire Studio setup, but the existing design treats llama.cpp build failures as non-fatal (the script says "everything else works" when GGUF build fails). This is a backwards-compatibility regression: users with CUDA < 12.4 can no longer complete Studio setup at all, even for non-GGUF use cases.

Recommended: fall back to CPU-only llama.cpp build instead of aborting. Clear NVCC_PATH and remove -DGGML_CUDA=ON from CMAKE_ARGS:

echo ""
echo "Warning: CUDA Toolkit $_nvcc_ver is too old for llama.cpp CUDA builds (requires >= 12.4)."
echo "   Falling back to CPU-only llama.cpp build."
echo "   Install CUDA >= 12.4 to enable GPU GGUF support: https://developer.nvidia.com/cuda-toolkit-archive"
NVCC_PATH=""
CMAKE_ARGS="${CMAKE_ARGS% -DGGML_CUDA=ON}"

Note: the version check also runs after CMAKE_ARGS already has -DGGML_CUDA=ON appended and after rm -rf "$LLAMA_CPP_DIR" wiped any previous build. Moving the check before the CMAKE_ARGS mutation would be cleaner.

Comment thread studio/setup.ps1 Outdated
Write-Host "================================================================" -ForegroundColor Red
exit 1
}
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[6/8 reviewers] The version check is fail-open: if nvcc --version output is unparseable (broken install, unexpected format, localized string), the regex does not match, the if body is skipped, and a sub-12.4 toolkit proceeds unchecked -- the same bad experience this PR is trying to prevent.

Add an else branch:

} else {
    Write-Host "[WARN] Could not parse CUDA Toolkit version from nvcc -- proceeding at your own risk" -ForegroundColor Yellow
    Write-Host "       llama.cpp requires CUDA >= $MIN_CUDA_MAJOR.$MIN_CUDA_MINOR" -ForegroundColor Yellow
}

Also consider using PowerShell's [version] type accelerator for cleaner comparison:

$MinCudaVersion = [version]'12.4'
if ($nvccVerOut -match 'release\s+(\d+\.\d+)') {
    $tkVer = [version]$Matches[1]
    if ($tkVer -lt $MinCudaVersion) { ... }
}

[5/8 reviewers] Additionally, when $DriverMaxCuda is known and < 12.4, the error message tells the user to install CUDA >= 12.4, which is impossible with their current driver. Check $DriverMaxCuda and recommend a driver update instead.

Comment thread studio/setup.ps1 Outdated
Write-Host " Re-install CUDA Toolkit (or Visual Studio Build Tools, then CUDA):" -ForegroundColor Yellow
Write-Host " https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Cyan
Write-Host "================================================================" -ForegroundColor Red
exit 1

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[6/8 reviewers] The old [WARN] block printed the exact source ($cudaExtras) and destination ($vsCustomizations) paths so users could manually copy the files. The new error only says "Re-install CUDA Toolkit" -- this is a UX regression for power users on locked corporate machines who cannot re-install.

The hard exit 1 is correct (cmake will fail anyway), but the manual fix info and the "run as admin" suggestion should be preserved:

Write-Host "" -ForegroundColor Red
Write-Host "================================================================" -ForegroundColor Red
Write-Host "[ERROR] Could not copy CUDA VS integration files (admin required)." -ForegroundColor Red
Write-Host "        cmake cannot find the CUDA toolset without these files." -ForegroundColor Red
Write-Host "  Fix: re-run setup as Administrator, or manually copy:" -ForegroundColor Yellow
Write-Host "    $cudaExtras" -ForegroundColor Cyan
Write-Host "  into:" -ForegroundColor Yellow
Write-Host "    $vsCustomizations" -ForegroundColor Cyan
Write-Host "  Or re-install CUDA Toolkit (after Visual Studio Build Tools):" -ForegroundColor Yellow
Write-Host "  https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Cyan
Write-Host "================================================================" -ForegroundColor Red
exit 1

Comment thread studio/setup.ps1 Outdated
Comment on lines +997 to +1008
$installedCuTag = $null
if (Test-Path $VenvPyExe) {
try {
$torchVer = & $VenvPyExe -c "import torch; print(torch.__version__)" 2>$null
if ($torchVer -match '\+(cu\d+)') { $installedCuTag = $Matches[1] }
} catch { }
}
$expectedCuTag = if ($HasNvidiaSmi) { Get-PytorchCudaTag } else { "cpu" }
if ($installedCuTag -and $installedCuTag -ne $expectedCuTag) {
Write-Host " [INFO] Stale venv detected (torch $installedCuTag != required $expectedCuTag) -- rebuilding..." -ForegroundColor Yellow
Remove-Item $VenvDir -Recurse -Force
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[7/8 reviewers] The stale-venv detection has several gaps:

  1. CPU torch not detected as stale -- \+(cu\d+) only matches CUDA wheels. CPU wheels (+cpu or plain 2.x.y from PyPI) leave $installedCuTag = $null. The if ($installedCuTag -and ...) guard skips the wipe, so a user who had CPU-only torch and then added a GPU silently reuses the wrong venv. pip install later may not force-replace an already-satisfied package.

  2. Broken torch imports silently reused -- If import torch fails (corrupted venv), catch {} swallows the error and the venv is reused -- exactly the broken state a re-run should repair.

  3. Remove-Item unguarded [4/8] -- Under $ErrorActionPreference = "Stop", a locked file (e.g. running python.exe) throws a terminating error and crashes setup. Wrap in try/catch.

Suggested fix: normalize installed torch tag to cuNNN | cpu | unknown, rebuild on any mismatch or when torch can't be imported. Match \+(cu\d+|cpu), treat untagged versions as cpu. Wrap Remove-Item in try/catch.

@danielhanchen danielhanchen left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Concrete suggestions for each finding below.

Comment thread studio/setup.ps1 Outdated
Write-Host "================================================================" -ForegroundColor Red
Write-Host "[ERROR] CUDA Toolkit $tkMaj.$tkMin is too old for llama.cpp." -ForegroundColor Red
Write-Host " llama.cpp requires CUDA >= $MIN_CUDA_MAJOR.$MIN_CUDA_MINOR." -ForegroundColor Red
Write-Host " Install: https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[5/8 reviewers] The error message always says "Install: https://developer.nvidia.com/cuda-toolkit-archive" -- but if the user's NVIDIA driver only supports e.g. CUDA 12.3, installing CUDA >= 12.4 is impossible without first upgrading the driver. On Windows, the script can even auto-install a driver-compatible toolkit via winget, then immediately abort telling the user to install an incompatible one.

$DriverMaxCuda is already available at this point. Check it and give actionable guidance:

if ($DriverMaxCuda -and ([version]$DriverMaxCuda) -lt [version]"$MIN_CUDA_MAJOR.$MIN_CUDA_MINOR") {
    Write-Host "        Your NVIDIA driver only supports CUDA $DriverMaxCuda." -ForegroundColor Red
    Write-Host "  Update the NVIDIA driver first, then re-run setup." -ForegroundColor Yellow
} else {
    Write-Host "  Install: https://developer.nvidia.com/cuda-toolkit-archive" -ForegroundColor Yellow
}

The same issue exists in setup.sh at line 444 -- the Linux error message should also check the driver's max CUDA version via nvidia-smi output before recommending a toolkit install.

Comment thread studio/setup.ps1 Outdated
$expectedCuTag = if ($HasNvidiaSmi) { Get-PytorchCudaTag } else { "cpu" }
if ($installedCuTag -and $installedCuTag -ne $expectedCuTag) {
Write-Host " [INFO] Stale venv detected (torch $installedCuTag != required $expectedCuTag) -- rebuilding..." -ForegroundColor Yellow
Remove-Item $VenvDir -Recurse -Force

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[4/8 reviewers] Remove-Item $VenvDir -Recurse -Force is called bare, outside any try/catch. The script has $ErrorActionPreference = "Stop" set at the top, so any locked file (e.g. a running python.exe from the Studio backend still attached to the venv) will throw a terminating error and crash the entire setup with a cryptic "Access Denied" message -- before the venv can be recreated.

try {
    Remove-Item $VenvDir -Recurse -Force -ErrorAction Stop
} catch {
    Write-Host "   [WARN] Could not remove stale venv: $_" -ForegroundColor Yellow
    Write-Host "          Close any running Studio/Python processes and re-run setup." -ForegroundColor Yellow
}

Comment thread studio/setup.sh Outdated
echo " Building with CUDA support (nvcc: $NVCC_PATH)..."
CMAKE_ARGS="$CMAKE_ARGS -DGGML_CUDA=ON"

# Minimum CUDA version check for llama.cpp (requires >= 12.4)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

[3/8 reviewers] The version check is placed after two irreversible operations have already occurred:

  1. rm -rf "$LLAMA_CPP_DIR" (line 390, above this block) has already wiped any previously-built llama.cpp -- including a working CPU build.
  2. CMAKE_ARGS="$CMAKE_ARGS -DGGML_CUDA=ON" (line 432, two lines above) has already committed to a CUDA build.

When exit 1 fires, the user on CUDA 12.3 who had a working CPU-built llama.cpp loses it and gets no rebuild. If the check silently passes (regex fail), CMAKE_ARGS already has CUDA=ON set with an unsupported toolkit.

Moving the version check before both the rm -rf and the CMAKE_ARGS mutation would prevent both issues. If falling back to CPU-only (per the suggestion on line 445), the check should happen before -DGGML_CUDA=ON is appended so it can cleanly skip the CUDA path.

@danielhanchen

Copy link
Copy Markdown
Member

[3/8 reviewers] Missing stale venv detection parity in setup.sh

The stale venv detection (checking torch CUDA tag vs. driver) is only added to setup.ps1 (Windows). The Linux setup.sh has no equivalent logic -- its venv creation at lines 258-276 unconditionally wipes and recreates the venv on every run (rm -rf "$VENV_DIR"), which sidesteps staleness but at the cost of a full reinstall every time.

If setup.sh is ever changed to reuse an existing venv (like setup.ps1 does), the same driver-mismatch problem will surface on Linux. Consider adding equivalent stale-venv detection to setup.sh, or document this as a known platform difference / follow-up.

…etection

- setup.sh: Replace grep -oP with POSIX sed for macOS compatibility
- setup.sh: Replace exit 1 with NVCC_PATH="" to fall back to CPU-only build
- setup.sh: Move version check before -DGGML_CUDA=ON append
- setup.sh: Add else branch warning when nvcc version is unparseable
- setup.ps1: Replace exit 1 with $NvccPath=$null for non-fatal CUDA fallback
- setup.ps1: Add driver vs toolkit guidance in version warning
- setup.ps1: Guard CUDA env/VS integration setup with if ($NvccPath)
- setup.ps1: VS integration catch: downgrade to WARN, restore source/dest paths
- setup.ps1: Stale venv: detect CPU torch and untagged wheels, not just +cuNNN
- setup.ps1: Stale venv: rebuild on failed torch import
- setup.ps1: Stale venv: wrap Remove-Item in try/catch for locked files
llama.cpp has no hard minimum CUDA version -- it builds with CUDA as old
as 11.2 and degrades features gracefully via #if CUDART_VERSION guards.
The 12.4 figure was the default Docker/CI baseline, not a build requirement.

Reverted:
- CUDA version check in setup.sh (entirely removed)
- CUDA version check in setup.ps1 (entirely removed)
- VS integration catch block cosmetic changes (restored to main)
- if ($NvccPath) guard around CUDA env setup (not needed without version check)

Kept:
- Stale venv detection in setup.ps1: detects torch CUDA tag mismatch
  (cu124 vs cu130, cpu vs cuXXX, broken torch import) and rebuilds venv
…lure

- Add 30s timeout for torch import probe via ProcessStartInfo/WaitForExit
- Use Test-Path -PathType Container to reject files masquerading as venv dir
- Trigger rebuild when python.exe is missing (incomplete venv)
- Make Remove-Item failure fatal ([ERROR] + exit 1) instead of warn-and-continue
- Move $expectedTorchTag computation inside -not $shouldRebuild guard
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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 several valuable reliability fixes to the setup scripts, focusing on CUDA version validation and virtual environment management. The addition of stale venv detection in setup.ps1 is a solid improvement to prevent runtime errors from mismatched dependencies. I've suggested a minor refactoring to this new logic to enhance its clarity and provide more specific logging messages. The other changes described, such as the minimum CUDA version check and hardening the Visual Studio integration step, are also sensible improvements, though their code was not part of the provided patch for review.

Comment thread studio/setup.ps1
Comment on lines +975 to +1031
if (Test-Path $VenvDir -PathType Container) {
$VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"
$installedTorchTag = $null
$shouldRebuild = $false

if (Test-Path $VenvPyExe) {
try {
$psi = New-Object System.Diagnostics.ProcessStartInfo
$psi.FileName = $VenvPyExe
$psi.Arguments = '-c "import torch; print(torch.__version__)"'
$psi.RedirectStandardOutput = $true
$psi.RedirectStandardError = $true
$psi.UseShellExecute = $false
$psi.CreateNoWindow = $true
$proc = [System.Diagnostics.Process]::Start($psi)
$torchVer = $proc.StandardOutput.ReadToEnd().Trim()
$finished = $proc.WaitForExit(30000)
if ($finished -and $proc.ExitCode -eq 0 -and $torchVer) {
if ($torchVer -match '\+(cu\d+)') {
$installedTorchTag = $Matches[1]
} elseif ($torchVer -match '\+cpu') {
$installedTorchTag = "cpu"
} else {
# Untagged wheel (plain "2.x.y" from PyPI) -- treat as cpu
$installedTorchTag = "cpu"
}
} else {
if (-not $finished) { try { $proc.Kill() } catch {} }
$shouldRebuild = $true
}
} catch {
$shouldRebuild = $true
}
} else {
# Missing python.exe means the venv is incomplete -- rebuild it.
$shouldRebuild = $true
}

if (-not $shouldRebuild) {
$expectedTorchTag = if ($HasNvidiaSmi) { Get-PytorchCudaTag } else { "cpu" }
if ($installedTorchTag -and $installedTorchTag -ne $expectedTorchTag) {
$shouldRebuild = $true
}
}

if ($shouldRebuild) {
$reason = if ($installedTorchTag) { "torch $installedTorchTag != required $expectedTorchTag" } else { "torch could not be imported" }
Write-Host " [INFO] Stale venv detected ($reason) -- rebuilding..." -ForegroundColor Yellow
try {
Remove-Item $VenvDir -Recurse -Force -ErrorAction Stop
} catch {
Write-Host " [ERROR] Could not remove stale venv: $($_.Exception.Message)" -ForegroundColor Red
Write-Host " Close any running Studio/Python processes and re-run setup." -ForegroundColor Red
exit 1
}
}
}

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

The logic for detecting a stale virtual environment is sound. However, using a boolean flag ($shouldRebuild) and then constructing a generic reason string later makes the code slightly harder to follow and the log messages less specific.

Consider refactoring this block to use a single string variable (e.g., $rebuildReason) to track the need for a rebuild. This would make the logic clearer and allow for more precise logging about why the venv is being rebuilt (e.g., 'venv is incomplete' vs. 'torch version mismatch').

if (Test-Path $VenvDir -PathType Container) {
    $VenvPyExe = Join-Path $VenvDir "Scripts\python.exe"
    $installedTorchTag = $null
    $rebuildReason = ""

    if (Test-Path $VenvPyExe) {
        try {
            $psi = New-Object System.Diagnostics.ProcessStartInfo
            $psi.FileName = $VenvPyExe
            $psi.Arguments = '-c "import torch; print(torch.__version__)"'
            $psi.RedirectStandardOutput = $true
            $psi.RedirectStandardError = $true
            $psi.UseShellExecute = $false
            $psi.CreateNoWindow = $true
            $proc = [System.Diagnostics.Process]::Start($psi)
            $torchVer = $proc.StandardOutput.ReadToEnd().Trim()
            $finished = $proc.WaitForExit(30000)
            if ($finished -and $proc.ExitCode -eq 0 -and $torchVer) {
                if ($torchVer -match '\+(cu\d+)') {
                    $Matches[1]
                } elseif ($torchVer -match '\+cpu') {
                    $installedTorchTag = "cpu"
                } else {
                    # Untagged wheel (plain "2.x.y" from PyPI) -- treat as cpu
                    $installedTorchTag = "cpu"
                }
            } else {
                if (-not $finished) { try { $proc.Kill() } catch {} }
                $rebuildReason = "torch could not be imported from venv"
            }
        } catch {
            $rebuildReason = "torch could not be imported from venv"
        }
    } else {
        # Missing python.exe means the venv is incomplete -- rebuild it.
        $rebuildReason = "venv is incomplete (missing python.exe)"
    }

    if (-not $rebuildReason) {
        $expectedTorchTag = if ($HasNvidiaSmi) { Get-PytorchCudaTag } else { "cpu" }
        if ($installedTorchTag -and $installedTorchTag -ne $expectedTorchTag) {
            $rebuildReason = "torch $installedTorchTag != required $expectedTorchTag"
        }
    }

    if ($rebuildReason) {
        Write-Host "   [INFO] Stale venv detected ($rebuildReason) -- rebuilding..." -ForegroundColor Yellow
        try {
            Remove-Item $VenvDir -Recurse -Force -ErrorAction Stop
        } catch {
            Write-Host "   [ERROR] Could not remove stale venv: $($_.Exception.Message)" -ForegroundColor Red
            Write-Host "           Close any running Studio/Python processes and re-run setup." -ForegroundColor Red
            exit 1
        }
    }
}

@danielhanchen
danielhanchen marked this pull request as ready for review March 22, 2026 11:42

@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: a1d79867c6

ℹ️ 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/setup.ps1
Comment on lines +989 to +992
$proc = [System.Diagnostics.Process]::Start($psi)
$torchVer = $proc.StandardOutput.ReadToEnd().Trim()
$finished = $proc.WaitForExit(30000)
if ($finished -and $proc.ExitCode -eq 0 -and $torchVer) {

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 Enforce timeout before reading torch version output

This probe can hang indefinitely because ReadToEnd() is called before the timeout check: if python -c "import torch..." stalls (or blocks on redirected streams), execution never reaches WaitForExit(30000), so stale-venv detection can freeze setup instead of rebuilding or continuing. The timeout logic only works if process completion is checked before any blocking full-stream read.

Useful? React with 👍 / 👎.

@danielhanchen
danielhanchen merged commit 96edad9 into unslothai:main Mar 22, 2026
shibizhao pushed a commit to shibizhao/unsloth-npu that referenced this pull request Apr 7, 2026
* fix: add CUDA minimum version check and abort for llama.cpp (>= 12.4)

- setup.ps1/setup.sh: abort with clear error if CUDA toolkit < 12.4
  (llama.cpp requirement); link to cuda-toolkit-archive for upgrade
- setup.ps1: promote CUDA VS integration copy failure from WARN to
  ERROR + exit 1; remove manual-copy hack instructions per Roland —
  correct fix is re-installing CUDA/MSBuild, not a manual workaround

Fixes: unslothai#4437
Reported by: Sebastien

* fix: wipe stale studio venv when torch CUDA tag changes

When the NVIDIA driver is updated, the required PyTorch CUDA tag changes
(e.g. cu124 -> cu130) but setup.ps1 was silently reusing the existing
.venv, leaving the old torch wheel in place and breaking the UI for
everyone on the next setup run.

Before creating/reusing the venv, inspect the installed torch version
string. If its CUDA tag does not match what the current driver requires,
wipe the venv so we always get a clean, correct install.

* Fix CUDA version check: portability, non-fatal fallback, stale venv detection

- setup.sh: Replace grep -oP with POSIX sed for macOS compatibility
- setup.sh: Replace exit 1 with NVCC_PATH="" to fall back to CPU-only build
- setup.sh: Move version check before -DGGML_CUDA=ON append
- setup.sh: Add else branch warning when nvcc version is unparseable
- setup.ps1: Replace exit 1 with $NvccPath=$null for non-fatal CUDA fallback
- setup.ps1: Add driver vs toolkit guidance in version warning
- setup.ps1: Guard CUDA env/VS integration setup with if ($NvccPath)
- setup.ps1: VS integration catch: downgrade to WARN, restore source/dest paths
- setup.ps1: Stale venv: detect CPU torch and untagged wheels, not just +cuNNN
- setup.ps1: Stale venv: rebuild on failed torch import
- setup.ps1: Stale venv: wrap Remove-Item in try/catch for locked files

* Remove incorrect CUDA >= 12.4 check, keep only stale venv detection

llama.cpp has no hard minimum CUDA version -- it builds with CUDA as old
as 11.2 and degrades features gracefully via #if CUDART_VERSION guards.
The 12.4 figure was the default Docker/CI baseline, not a build requirement.

Reverted:
- CUDA version check in setup.sh (entirely removed)
- CUDA version check in setup.ps1 (entirely removed)
- VS integration catch block cosmetic changes (restored to main)
- if ($NvccPath) guard around CUDA env setup (not needed without version check)

Kept:
- Stale venv detection in setup.ps1: detects torch CUDA tag mismatch
  (cu124 vs cu130, cpu vs cuXXX, broken torch import) and rebuilds venv

* Fix stale venv detection: incomplete venvs, timeout, fatal delete failure

- Add 30s timeout for torch import probe via ProcessStartInfo/WaitForExit
- Use Test-Path -PathType Container to reject files masquerading as venv dir
- Trigger rebuild when python.exe is missing (incomplete venv)
- Make Remove-Item failure fatal ([ERROR] + exit 1) instead of warn-and-continue
- Move $expectedTorchTag computation inside -not $shouldRebuild guard

---------

Co-authored-by: LeoBorcherding <[email protected]>
Co-authored-by: Daniel Han <[email protected]>
pull Bot pushed a commit to steelburn-forked/unsloth that referenced this pull request May 29, 2026
)

* Studio setup.sh: cope with fresh CUDA toolkits like 13.3

CUDA 13.3 shipped today. Three loose ends in studio/setup.sh surfaced
during the llama.cpp build path:

1. setup.ps1 already aborts cleanly when the CUDA toolkit is below
   llama.cpp's minimum (12.4) via unslothai#4517, but setup.sh still hit the
   generic cmake failure described in unslothai#4437. Added a min-version check
   that downgrades to a CPU build for nvcc < 12.4 with a clear message
   pointing to the toolkit archive.
2. The first day a new CUDA toolkit ships, its host-compiler whitelist
   lags whatever gcc/clang the distro is on, so nvcc rejects the host
   compiler with a wall of "#error -- unsupported GNU version" before
   any real compile runs. NVCC_PREPEND_FLAGS now carries
   -allow-unsupported-compiler so the build moves on instead.
3. The Linux CUDA/ROCm configure failure path had no symmetry with the
   macOS Metal fallback: a single nvcc failure left BUILD_OK=false and
   no llama.cpp at all. Generalised the existing Metal -> CPU fallback
   to cover any GPU_BACKEND, so a CUDA configure or build failure now
   transparently retries with the CPU args and the user still ends up
   with a working llama-server.

Pulled the version probe out into _nvcc_meets_llama_minimum so it can
be unit-tested. Added tests/sh/test_nvcc_meets_llama_minimum.sh and two
extra cases in tests/sh/test_get_torch_index_url.sh covering the legacy
"CUDA Version: 13.3" header (driver-reported) and the future 13.7
case. Wired the new test into tests/run_all.sh and the studio-backend
CI workflow.

* tests: relax pr4562 regression to allow generic GPU fallback label

* studio tests: assert setup.sh exports NVCC_PREPEND_FLAGS=-allow-unsupported-compiler

The -allow-unsupported-compiler flag is the core of the fresh-CUDA-toolkit fix
(it lets nvcc accept a host gcc/clang newer than its release-time whitelist, so
CUDA 13.3 day-one builds do not abort on '#error -- unsupported GNU version'),
but it had no automated coverage. Add a source-pattern test asserting the flag
is present, delivered via NVCC_PREPEND_FLAGS so it also covers cmake's CUDA
compiler-id probe, and kept out of CMAKE_ARGS for bash word-splitting safety.

* studio/setup.ps1: allow unsupported host compiler for CUDA build (Windows parity)

Mirror the Linux setup.sh headline fix from this PR on Windows. A freshly
released CUDA toolkit ships with a host-compiler whitelist that lags the
installed toolchain, so nvcc can reject the host with
"#error -- unsupported Microsoft Visual Studio version!" before any real
compile runs (the MSVC analogue of the gcc wall the Linux side hit on
CUDA 13.3). Set NVCC_PREPEND_FLAGS=-allow-unsupported-compiler in the CUDA
build branch so both cmake's configure-time CUDA compiler-id probe and the
cmake --build step proceed. The flag disables the host version check only and
is a no-op when the compiler is already supported.

Set via the process environment (not the $CmakeArgs array), after the
Refresh-Environment calls that re-sanitize CUDA env vars, and appended
idempotently to any value the user already set.

Validated with PowerShell 7.6.2: full setup.ps1 AST parse is clean and the
snippet is idempotent (empty -> set, existing -> append once, no duplicate).
Needs real Windows + CUDA CI to exercise the actual nvcc/MSVC build.

Adds test_setup_ps1_exports_allow_unsupported_compiler asserting the flag is
present, env-delivered, kept out of $CmakeArgs, and scoped to the CUDA-on branch.

* studio: tighten code comments added in this PR

Shorten the verbose multi-line comments and test docstrings introduced by
this PR (setup.sh, setup.ps1, and the shell/python tests) to be succinct
while preserving the rationale. No code or test-assertion changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants