Skip to content

Use prebuilt llama.cpp for unsloth studio setup - #4562

Merged
danielhanchen merged 29 commits into
unslothai:mainfrom
mmathew23:feat/installprebuildllamacpp
Mar 25, 2026
Merged

danielhanchen merged 29 commits into
unslothai:mainfrom
mmathew23:feat/installprebuildllamacpp

Conversation

@mmathew23

Copy link
Copy Markdown
Contributor

Prebuilt llama.cpp install path with pinned approvals, checksum verification, and source-build fallback

Summary

This PR adds a first-class prebuilt llama.cpp install path for Studio setup while keeping source build as the safety net.

The prebuilt flow now:

  • prefers a prebuilt install before any source build
  • pins prebuilt installs to one approved upstream llama.cpp tag
  • requires an approved checksum manifest published in unslothai/llama.cpp
  • verifies the downloaded binary archive before extraction
  • verifies the hydrated llama.cpp source tarball before repo-shape hydration
  • stages and validates the install before activation
  • falls back to source build on any resolution, download, checksum, validation, or activation failure

This keeps the happy path fast while making failures debuggable and preserving the existing source-build path.

What changed

New installer helper

Added studio/install_llama_prebuilt.py, which owns:

  • host detection and prebuilt asset selection
  • Linux CUDA published-bundle selection from unslothai/llama.cpp
  • Windows and macOS upstream asset selection
  • approval loading from llama-prebuilt-sha256.json
  • archive download + SHA256 verification
  • upstream source-tree hydration into a repo-shaped install
  • staged runtime validation using llama-quantize and llama-server
  • activation, rollback, cleanup, and detailed diagnostics

Setup integration

Updated:

  • studio/setup.sh
  • studio/setup.ps1

Both setup paths now:

  • try the prebuilt helper first
  • log useful failure output instead of silently dying
  • continue to the existing source-build path when prebuilt resolution or validation fails

Security / approval model

Prebuilt installs are no longer driven by live upstream latest.

They are pinned to an approved release tag and gated by:

  • a published release existing in unslothai/llama.cpp
  • a published llama-prebuilt-sha256.json
  • an approved checksum entry for the selected prebuilt archive
  • an approved checksum entry for the source tarball used during repo hydration

If any of those are missing or mismatched, setup falls back to source build.

Validation and tests

Added test coverage under:

  • tests/studio/install/test_install_llama_prebuilt_logic.py
  • tests/studio/install/smoke_test_llama_prebuilt.py

This splits coverage into:

  • mocked logic/layout/rollback tests
  • a real machine-local smoke runner that installs into a temp directory instead of ~/.unsloth/llama.cpp

Why this is useful

  • Faster installs on supported machines
  • Cleaner recovery when prebuilt installs fail
  • Better logs for debugging platform-specific issues
  • A bounded trust model for prebuilt artifacts
  • No loss of the existing source-build path

How to test

Run these from the packages/unsloth repo root.

1. Logic tests

uv run --with pytest --with filelock python -m pytest -q tests/studio/install/test_install_llama_prebuilt_logic.py

Expected:

  • all tests pass

What this covers:

  • safe archive extraction
  • source hydration behavior
  • repo-shaped install layout
  • activation / rollback / cleanup behavior

2. Smoke test on the current machine

python3 tests/studio/install/smoke_test_llama_prebuilt.py

Useful variants:

python3 tests/studio/install/smoke_test_llama_prebuilt.py --keep-temp
python3 tests/studio/install/smoke_test_llama_prebuilt.py --work-dir /tmp/llama-smoke
python3 tests/studio/install/smoke_test_llama_prebuilt.py --llama-tag b8508

Expected:

  • PASS if the approved prebuilt path works on this machine
  • FALLBACK if prebuilt approval/download/validation fails and the helper would defer to source build

This test performs a real prebuilt install into a temp directory and does not touch ~/.unsloth/llama.cpp.

3. Shell syntax

bash -n studio/setup.sh
bash -n install.sh

4. End-to-end setup behavior on Unix

Run normal setup and confirm:

  • prebuilt install is attempted first
  • useful logs are printed if prebuilt fails
  • setup continues into source build instead of stopping silently

Example:

UNSLOTH_LLAMA_TAG=latest bash studio/setup.sh

5. Windows behavior

On Windows, run normal setup and confirm the same high-level behavior:

  • prebuilt attempt first
  • useful error output on failure
  • source-build fallback instead of abrupt termination

Also validate the helper directly if needed:

python .\studio\install_llama_prebuilt.py --resolve-install-tag latest
python .\tests\studio\install\smoke_test_llama_prebuilt.py --keep-temp

6. Optional release-side validation

If you are validating staged Linux CUDA assets from the outer release repo, you can run:

python3 /path/to/validate-llama-prebuilt.py local-artifacts --path /path/to/release-stage/<tag>

For local archives without a sibling llama-prebuilt-sha256.json, the validator now fails fast unless network source hashing is explicitly allowed:

python3 /path/to/validate-llama-prebuilt.py local-artifacts --path /path/to/out --allow-network-source-hash

Reviewer notes

  • The prebuilt installer is intentionally fail-closed.
  • Any missing approval data or checksum mismatch should result in source-build fallback, not partial install success.
  • The pinned tag can be updated later by changing the approved release constant and publishing the corresponding checksum asset.

@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 Unsloth Studio setup process by introducing a primary path for installing llama.cpp using prebuilt binaries. This change aims to accelerate installation times while bolstering reliability and security through checksum verification, pinned approvals, and a robust fallback to source compilation. The new system ensures a faster and more consistent user experience without compromising on the integrity or flexibility of the llama.cpp setup.

Highlights

  • Prebuilt llama.cpp Installation: Implemented a new, preferred installation path for llama.cpp using prebuilt binaries, significantly speeding up setup on supported machines.
  • Robust Fallback Mechanism: Designed a comprehensive fallback system that automatically reverts to source-based compilation if prebuilt resolution, download, checksum verification, validation, or activation fails.
  • Enhanced Security and Trust: Introduced a pinned approval model for prebuilt installs, requiring specific upstream llama.cpp tags, published checksum manifests, and verification of both binary archives and source tarballs.
  • New Installer Helper: Added studio/install_llama_prebuilt.py to manage host detection, asset selection, download, verification, staged validation, and activation of prebuilt llama.cpp.
  • Updated Setup Scripts: Modified studio/setup.sh and studio/setup.ps1 to integrate the new prebuilt installer, prioritizing it over source builds and providing detailed failure logs.
  • Comprehensive Testing: Included new test suites (test_install_llama_prebuilt_logic.py and smoke_test_llama_prebuilt.py) to cover mocked logic, layout, rollback, and real machine-local smoke installations.
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 significantly refactors the llama.cpp installation process within the studio setup scripts (PowerShell and Bash). The core change introduces a new phase that prioritizes the installation of prebuilt llama.cpp bundles using a dedicated Python script (install_llama_prebuilt.py). Subsequent steps, such as OpenSSL development environment setup and the llama.cpp source build, are now conditional on the success of the prebuilt installation or if a source build is explicitly enforced. The source build process itself has been made more robust with additional git operations for cleaning and checking out specific states. New Python tests (smoke_test_llama_prebuilt.py and test_install_llama_prebuilt_logic.py) have been added to thoroughly validate the prebuilt installer's logic, including archive extraction safety, correct installation structure for both Linux and Windows, and robust rollback mechanisms in case of installation failures. There is no feedback to provide on the review comments as none were supplied.

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

ℹ️ 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 on lines +1397 to +1398
elif has_physical_nvidia:
has_usable_nvidia = 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.

P1 Badge Avoid marking CUDA usable when no GPU rows are detected

When nvidia-smi is present but GPU enumeration fails (for example, driver/service issues or no accessible devices), this branch still sets has_usable_nvidia = True. That forces CUDA-only prebuilt selection and skips CPU prebuilt candidates, so installs can fail unnecessarily on hosts that are effectively non-CUDA. has_usable_nvidia should only become true after successfully detecting at least one visible GPU (or an explicit visible-device match), not just from prior physical-device heuristics.

Useful? React with 👍 / 👎.

Comment thread studio/setup.ps1 Outdated
Comment on lines +1466 to +1468
if ($LASTEXITCODE -ne 0) {
Write-Host " [WARN] git pull failed -- using existing source" -ForegroundColor Yellow
$BuildOk = $false
$FailedStep = "git fetch"

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 local source build path on git pull failure

This change turns a git pull failure into a hard build stop by setting $BuildOk = $false. In environments with intermittent/no GitHub access, users with an existing llama.cpp checkout can no longer continue rebuilding from local source, which previously worked and is important for fallback reliability. This should remain a warning and proceed with the existing tree (or a retry path) instead of aborting the source-build pipeline.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits March 25, 2026 03:25
1. Make filelock import optional -- environments without filelock
   (e.g. minimal installs) crashed at import time instead of
   gracefully skipping the lock.

2. Use already-verified converter script from the hydrated source
   tree instead of re-downloading from raw.githubusercontent.com
   with no checksum. Adds symlink with copy fallback for the
   legacy filename.

3. Initialize $SkipPrebuiltInstall in setup.ps1 before first use
   to prevent potential uninitialized variable errors.

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

ℹ️ 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/install_llama_prebuilt.py Outdated
existing = [part for part in env.get("PATH", "").split(os.pathsep) if part]
env["PATH"] = os.pathsep.join(dedupe_existing_dirs([*path_dirs, *existing]))
elif host.is_linux:
ld_dirs = [str(install_dir), *linux_runtime_dirs(binary_path)]

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 Include build/bin in Linux library search path

On Linux, install_from_archives overlays all runtime .so files into build/bin, but binary_env only prepends the repo root (install_dir) to LD_LIBRARY_PATH. If a selected prebuilt does not embed an RPATH/RUNPATH to its sibling libs, both validation (validate_quantize/validate_server) and later runtime execution will fail with missing shared libraries even though the bundle was extracted correctly, forcing unnecessary fallback/source-build behavior. The Linux env path should include the executable directory (e.g. binary_path.parent) or build/bin.

Useful? React with 👍 / 👎.

danielhanchen and others added 2 commits March 25, 2026 04:01
Prefer the local verified copy from the hydrated source tree, but
retain the original network download as a fallback if the file is
missing. Create the legacy hyphenated filename as a symlink with a
copy fallback instead of writing a second full copy.

@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: 689ff3cccc

ℹ️ 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/setup.ps1 Outdated
$BuildOk = $false
$FailedStep = "git fetch"
} else {
git -C $LlamaCppDir checkout --force FETCH_HEAD 2>&1 | Out-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.

P2 Badge Keep llama.cpp checkout on a branch after updating

After a successful git pull, forcing git checkout --force FETCH_HEAD detaches HEAD in the local llama.cpp clone. On a later setup run (once upstream advances), git pull in that detached state fails with "not currently on a branch", and this script treats that as a hard build failure, so Windows source rebuilds become brittle across repeated runs.

Useful? React with 👍 / 👎.

danielhanchen and others added 3 commits March 25, 2026 07:12
- setup.ps1: Replace git pull + checkout FETCH_HEAD with fetch + checkout -B
  to avoid detached HEAD state that breaks re-runs. Use pinned tag in both
  fetch and clone paths.
- setup.sh: Move rm -rf after cmake/git prerequisite checks so a missing
  tool no longer deletes the existing install. Add --branch tag to clone.
- install_llama_prebuilt.py: Add binary_path.parent to Linux LD_LIBRARY_PATH
  in binary_env() so bundled .so files in build/bin are found even without
  RPATH, matching the existing Windows PATH logic.
- Add test for binary_env LD_LIBRARY_PATH on Linux.
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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: 2b54733988

ℹ️ 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.sh Outdated
set -e
if [ "$_RESOLVE_UPSTREAM_STATUS" -ne 0 ] || [ -z "$_RESOLVED_LLAMA_TAG" ]; then
if [ "$_REQUESTED_LLAMA_TAG" = "latest" ]; then
_RESOLVED_LLAMA_TAG="latest"

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 Avoid falling back to literal latest for source builds

When prebuilt tag resolution fails and the requested tag is latest, this sets _RESOLVED_LLAMA_TAG to the literal string latest, but the later source fallback clones with git clone --branch "$_RESOLVED_LLAMA_TAG" .... ggml-org/llama.cpp does not publish a latest branch/tag, so the clone path fails and source fallback is lost exactly in the recovery path meant to keep setup working. Use a concrete resolved tag or omit --branch in this fallback case.

Useful? React with 👍 / 👎.

Comment thread studio/setup.ps1 Outdated
$ResolvedLlamaTag = if ($fallbackExit -eq 0 -and $fallbackOutput) {
($fallbackOutput | Select-Object -Last 1).ToString().Trim()
} elseif ($RequestedLlamaTag -eq "latest") {
"latest"

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 Prevent latest sentinel from breaking Windows git clone

This fallback assigns $ResolvedLlamaTag = "latest" when tag resolution fails, but the source-build path later runs git clone --depth 1 --branch $ResolvedLlamaTag .... Because latest is not a real branch/tag in ggml-org/llama.cpp, the recovery clone fails, so a prebuilt-resolution failure can cascade into a hard source-build failure instead of graceful fallback.

Useful? React with 👍 / 👎.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@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 a new mechanism to prioritize prebuilt llama.cpp bundles over source compilation in both Windows (PowerShell) and Linux (Bash) setup scripts. It leverages a Python helper script to determine and install the most suitable prebuilt binary based on the system's environment, such as CUDA version and compute capabilities. Source compilation is now a fallback option if prebuilt installation fails or is explicitly disabled. The changes also include new Python tests to validate the prebuilt installer's logic and selection process. A review comment highlights an inconsistency in the setup.sh script, noting that it unconditionally removes and re-clones the llama.cpp repository during a source build fallback, which is less efficient than the git fetch and checkout strategy implemented in setup.ps1 for existing repositories.

Comment thread studio/setup.sh Outdated
Comment on lines +516 to +521
rm -rf "$LLAMA_CPP_DIR"
echo ""
echo "Building llama-server for GGUF inference..."

BUILD_OK=true
run_quiet_no_exit "clone llama.cpp" git clone --depth 1 https://github.com/ggml-org/llama.cpp.git "$LLAMA_CPP_DIR" || BUILD_OK=false
run_quiet_no_exit "clone llama.cpp" git clone --depth 1 --branch "$_RESOLVED_LLAMA_TAG" https://github.com/ggml-org/llama.cpp.git "$LLAMA_CPP_DIR" || BUILD_OK=false

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 source build logic here unconditionally removes and re-clones the llama.cpp repository. This is inconsistent with setup.ps1, which attempts a more efficient git fetch and checkout if the repository already exists. Aligning the behavior would improve efficiency for users who re-run the setup, as it would avoid a full re-clone.

Please consider adopting the fetch/checkout strategy from setup.ps1 in this script as well for consistency.

When tag resolution fails and the requested tag is "latest", both
setup scripts now omit --branch from git clone so the default branch
is cloned instead of failing on a nonexistent "latest" branch/tag.
Similarly, the PS1 fetch path fetches the default ref when the tag
is "latest".

@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: 5e5e6703b8

ℹ️ 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".

if not normalized:
raise PrebuiltFallback(f"archive link used an empty target: {member_name}")

resolved = (target.parent / link_path).resolve()

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 Resolve tar hardlinks against archive root

Treating every tar link target as relative to target.parent breaks valid hardlink entries whose linkname is archive-root-relative (a common tar convention). In that case extraction never finds the referenced file and aborts with "unresolved link entries", causing prebuilt installs to fall back even though the archive is valid. This is reproducible with a tar containing a/file plus hardlink b/link -> a/file.

Useful? React with 👍 / 👎.

When both Python tag resolution attempts fail and the requested tag
is "latest", query the GitHub API for the actual latest release tag
from ggml-org/llama.cpp (e.g. b8508) instead of passing the literal
string "latest" to git clone --branch, which would fail since no
such branch/tag exists.

setup.sh uses curl + python json parsing; setup.ps1 uses
Invoke-RestMethod. Both fall back to the raw requested tag if the
API call also fails.
When falling back to the GitHub API to resolve "latest", query the
Unsloth release repo (unslothai/llama.cpp) first since it has the
prebuilt binaries pinned to tested tags. Only fall back to
ggml-org/llama.cpp if the Unsloth repo query fails.

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

ℹ️ 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".

if host.is_windows:
path_dirs = [
str(binary_path.parent),
*windows_runtime_dirs_for_runtime_line(runtime_line),

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 Use production PATH rules for Windows prebuilt validation

This validation path prepends windows_runtime_dirs_for_runtime_line(...), which can pull CUDA DLL locations from Python package directories (python_runtime_dirs) even when they are not on the normal process PATH. The prebuilt install can therefore validate successfully, but later llama-server startup in studio/backend/core/inference/llama_cpp.py only adds binary_dir and CUDA_PATH-based folders, so hosts that rely on wheel-bundled CUDA DLLs (no toolkit PATH setup) will fail at runtime with missing cudart/cublas DLLs after a reported successful setup.

Useful? React with 👍 / 👎.

ld_dirs = [
str(binary_path.parent),
str(install_dir),
*linux_runtime_dirs(binary_path),

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 Match Linux prebuilt validation to runtime loader env

Including linux_runtime_dirs(binary_path) during validation can make staged checks pass by discovering CUDA libs from nonstandard locations (including Python site-packages runtime dirs), but the production launcher in studio/backend/core/inference/llama_cpp.py does not reuse those discovered paths and only sets LD_LIBRARY_PATH to binary_dir plus a few /usr/local/cuda* directories. On systems where CUDA libs are available only via Python NVIDIA wheels, setup may mark prebuilt install as valid and still fail when serving real GGUF requests due to missing shared libraries.

Useful? React with 👍 / 👎.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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: 4370b33b53

ℹ️ 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/install_llama_prebuilt.py Outdated
Comment on lines +2724 to +2725
env["DYLD_LIBRARY_PATH"] = (
str(install_dir) + os.pathsep + env.get("DYLD_LIBRARY_PATH", "")

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 Add build/bin to macOS DYLD library path

binary_env currently sets DYLD_LIBRARY_PATH to install_dir, but this installer overlays macOS runtime binaries and .dylib files into build/bin. On macOS hosts where the prebuilt does not fully resolve via embedded loader paths, validation/runtime will fail to find sibling dylibs even though extraction succeeded, forcing unnecessary fallback behavior. Include binary_path.parent in DYLD_LIBRARY_PATH so the loader path matches the actual staged layout.

Useful? React with 👍 / 👎.

danielhanchen and others added 7 commits March 25, 2026 03:37
macOS prebuilt .dylib files are overlaid into build/bin (same as
Linux), but binary_env only added install_dir to DYLD_LIBRARY_PATH.
Add binary_path.parent so the loader can find sibling dylibs even
without embedded loader paths.

Mirrors the existing fix for Linux LD_LIBRARY_PATH and the Windows
PATH pattern.
When all API fallbacks fail and the tag stays as literal "latest",
omit --branch from git clone (clones default branch instead of
failing). Both setup.sh and setup.ps1 now check for "latest" before
passing --branch to git clone/fetch.

Also fix test_setup_ps1_clone_uses_branch_tag which used Python
tuple syntax (assert "x", "y" in z) that always passes. Changed to
assert "x" in z and "y" in z.
- binary_env macOS: use dedupe_existing_dirs instead of raw string
  concatenation. Eliminates trailing colon in DYLD_LIBRARY_PATH
  (which causes dyld to search CWD for libraries) and deduplicates
  when binary_path.parent == install_dir. Now consistent with the
  Linux and Windows branches.
- install_lock: when filelock is not installed, use os.O_CREAT|O_EXCL
  as a fallback exclusive file lock with timeout, instead of yielding
  with no locking. Prevents concurrent installs from corrupting each
  other's staging directories.
- setup.ps1: remove [DEBUG] log line that printed to every user on
  every Windows setup run.
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

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

ℹ️ 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.sh
echo "⚠️ Failed to resolve an installable prebuilt llama.cpp tag via $_HELPER_RELEASE_REPO"
cat "$_RESOLVE_LLAMA_LOG" >&2 || true
set +e
_RESOLVED_LLAMA_TAG="$(python "$SCRIPT_DIR/install_llama_prebuilt.py" --resolve-llama-tag "$_REQUESTED_LLAMA_TAG" 2>/dev/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.

P2 Badge Parse only the resolved tag from helper output

The fallback path assigns _RESOLVED_LLAMA_TAG from the full stdout of install_llama_prebuilt.py --resolve-llama-tag, but that helper logs retry messages to stdout when network calls transiently fail before eventually printing the tag. In that case _RESOLVED_LLAMA_TAG becomes multi-line text, and the later git clone --branch "$_RESOLVED_LLAMA_TAG" ... call fails, breaking source-build fallback in the very outage scenario this branch is meant to recover from. Capture only the last line (as done for --resolve-install-tag) or move helper logs to stderr.

Useful? React with 👍 / 👎.

@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 significantly refactors the llama.cpp installation process in studio/setup.ps1 and studio/setup.sh scripts by introducing a preference for prebuilt llama.cpp bundles over source compilation. The scripts now attempt to resolve and install a prebuilt bundle first, falling back to a source build only if a prebuilt option is unavailable, explicitly forced, or fails validation. Key improvements include robust tag resolution with a fallback mechanism, enhanced source build reliability by addressing detached HEAD issues and conditional rm -rf execution, and conditional OpenSSL installation. Additionally, environment variable management for library paths has been refined, and extensive new Python tests have been added to validate the new prebuilt installation logic, bug fixes, and binary selection across various operating systems and CUDA configurations. No specific feedback was provided in the review comments.

install_lock fallback (no filelock): write PID to lock file and
check if the holder process is still alive on contention. Dead PIDs
(ProcessLookupError) and unreadable lock files trigger immediate
cleanup. Live processes owned by other users (PermissionError) are
correctly recognized as alive -- the lock is not removed.

setup.sh/setup.ps1 source-build: clone into a temporary directory
first, then swap into place only on success. If git clone fails,
the existing install is preserved instead of being deleted by the
premature rm -rf.
@danielhanchen
danielhanchen force-pushed the feat/installprebuildllamacpp branch from 800a40c to cc2a4ad Compare March 25, 2026 12:02
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@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: 5666c27215

ℹ️ 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 +2763 to +2767
dyld_dirs = [str(binary_path.parent), str(install_dir)]
existing = [
part for part in env.get("DYLD_LIBRARY_PATH", "").split(os.pathsep) if part
]
env["DYLD_LIBRARY_PATH"] = os.pathsep.join(

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 Match macOS prebuilt validation with runtime env

The macOS validation path now relies on DYLD_LIBRARY_PATH during prebuilt checks, but the actual server launcher in studio/backend/core/inference/llama_cpp.py only sets LD_LIBRARY_PATH in its non-Windows branch (which macOS ignores). This means a prebuilt can validate successfully in setup and then fail at real runtime on macOS hosts where dylibs are discoverable only via DYLD_LIBRARY_PATH rather than embedded loader paths. To avoid post-setup runtime failures, validation should use the same env construction as the production launcher, or the launcher should add the same macOS DYLD_LIBRARY_PATH entries.

Useful? React with 👍 / 👎.

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

Gemini encountered an error creating the review. You can try again by commenting /gemini review.

@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 significantly refactors the llama.cpp installation process in studio/setup.ps1 and studio/setup.sh to prioritize prebuilt bundles over source compilation. This includes new logic for resolving appropriate llama.cpp tags, downloading and validating prebuilt artifacts, and falling back to a source build if prebuilt options are unavailable or forced. The OpenSSL installation is now conditional on needing a source build, and git operations for source builds have been updated to use fetch and checkout -B for better handling of detached HEAD states. Extensive new Python tests have been added to cover the prebuilt installation logic, including smoke tests, unit tests for archive handling, activation, bug fixes, and selection logic for various hardware and OS configurations. A review comment suggests removing 2>/dev/null from curl and python commands in studio/setup.sh to improve debugging of tag resolution failures.

Comment thread studio/setup.sh
Comment on lines +422 to +425
_RESOLVED_LLAMA_TAG="$(curl -fsSL "https://api.github.com/repos/${_HELPER_RELEASE_REPO}/releases/latest" 2>/dev/null | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])" 2>/dev/null)" || _RESOLVED_LLAMA_TAG=""
if [ -z "$_RESOLVED_LLAMA_TAG" ]; then
_RESOLVED_LLAMA_TAG="$(curl -fsSL https://api.github.com/repos/ggml-org/llama.cpp/releases/latest 2>/dev/null | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])" 2>/dev/null)" || _RESOLVED_LLAMA_TAG=""
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 2>/dev/null in the curl and python commands silences any potential errors (e.g., network issues, JSON parsing errors, GitHub API rate limits). This makes debugging failures in the fallback logic difficult, which contradicts the PR's goal of providing "useful failure output".

Consider removing 2>/dev/null to allow errors to be printed to stderr. The || _RESOLVED_LLAMA_TAG="" will still prevent the script from failing.

Suggested change
_RESOLVED_LLAMA_TAG="$(curl -fsSL "https://api.github.com/repos/${_HELPER_RELEASE_REPO}/releases/latest" 2>/dev/null | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])" 2>/dev/null)" || _RESOLVED_LLAMA_TAG=""
if [ -z "$_RESOLVED_LLAMA_TAG" ]; then
_RESOLVED_LLAMA_TAG="$(curl -fsSL https://api.github.com/repos/ggml-org/llama.cpp/releases/latest 2>/dev/null | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])" 2>/dev/null)" || _RESOLVED_LLAMA_TAG=""
fi
_RESOLVED_LLAMA_TAG="$(curl -fsSL "https://api.github.com/repos/${_HELPER_RELEASE_REPO}/releases/latest" | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])")" || _RESOLVED_LLAMA_TAG=""
if [ -z "$_RESOLVED_LLAMA_TAG" ]; then
_RESOLVED_LLAMA_TAG="$(curl -fsSL https://api.github.com/repos/ggml-org/llama.cpp/releases/latest | python -c "import sys,json; print(json.load(sys.stdin)['tag_name'])")" || _RESOLVED_LLAMA_TAG=""
fi

load_approved_release_checksums compared checksums.upstream_tag
against the Unsloth release_tag, which are different namespaces
(upstream ggml-org tag vs Unsloth published tag). This only worked
because both happened to be "b8508" by convention. Would break if
Unsloth ever uses a different release naming scheme.

The existing check at parse_approved_release_checksums (line 950)
already validates the release_tag field correctly.
install_lock fallback: add os.fsync(fd) after writing PID to ensure
the PID is visible to racing processes before they check. Treat
empty lock files (PID not yet written) as "wait and retry" instead
of stale, closing the window where two processes could both see an
empty file, both unlink it, and both acquire the lock.

setup.sh/setup.ps1 source-build: clone AND build in a temp directory
(LLAMA_CPP_DIR.build.$$). Only swap into the final LLAMA_CPP_DIR
after the build succeeds. If clone or cmake or build fails, the temp
dir is cleaned up and the existing working install is preserved.
Previously, rm -rf ran after clone but before build, destroying the
existing install even if the build later failed.
@danielhanchen
danielhanchen merged commit f4d8a24 into unslothai:main Mar 25, 2026
shibizhao pushed a commit to shibizhao/unsloth-npu that referenced this pull request Apr 7, 2026
* Use prebuilt llama.cpp for unsloth studio setup

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix 3 issues that cause unnecessary fallback to source build

1. Make filelock import optional -- environments without filelock
   (e.g. minimal installs) crashed at import time instead of
   gracefully skipping the lock.

2. Use already-verified converter script from the hydrated source
   tree instead of re-downloading from raw.githubusercontent.com
   with no checksum. Adds symlink with copy fallback for the
   legacy filename.

3. Initialize $SkipPrebuiltInstall in setup.ps1 before first use
   to prevent potential uninitialized variable errors.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Keep network fallback in ensure_converter_scripts

Prefer the local verified copy from the hydrated source tree, but
retain the original network download as a fallback if the file is
missing. Create the legacy hyphenated filename as a symlink with a
copy fallback instead of writing a second full copy.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix 4 bugs in source-build fallback and binary_env paths

- setup.ps1: Replace git pull + checkout FETCH_HEAD with fetch + checkout -B
  to avoid detached HEAD state that breaks re-runs. Use pinned tag in both
  fetch and clone paths.
- setup.sh: Move rm -rf after cmake/git prerequisite checks so a missing
  tool no longer deletes the existing install. Add --branch tag to clone.
- install_llama_prebuilt.py: Add binary_path.parent to Linux LD_LIBRARY_PATH
  in binary_env() so bundled .so files in build/bin are found even without
  RPATH, matching the existing Windows PATH logic.
- Add test for binary_env LD_LIBRARY_PATH on Linux.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Handle unresolved "latest" tag in source-build fallback clone

When tag resolution fails and the requested tag is "latest", both
setup scripts now omit --branch from git clone so the default branch
is cloned instead of failing on a nonexistent "latest" branch/tag.
Similarly, the PS1 fetch path fetches the default ref when the tag
is "latest".

* Resolve actual latest ggml-org tag instead of using literal "latest"

When both Python tag resolution attempts fail and the requested tag
is "latest", query the GitHub API for the actual latest release tag
from ggml-org/llama.cpp (e.g. b8508) instead of passing the literal
string "latest" to git clone --branch, which would fail since no
such branch/tag exists.

setup.sh uses curl + python json parsing; setup.ps1 uses
Invoke-RestMethod. Both fall back to the raw requested tag if the
API call also fails.

* Try Unsloth release repo before ggml-org when resolving latest tag

When falling back to the GitHub API to resolve "latest", query the
Unsloth release repo (unslothai/llama.cpp) first since it has the
prebuilt binaries pinned to tested tags. Only fall back to
ggml-org/llama.cpp if the Unsloth repo query fails.

* Add comprehensive sandbox tests for PR unslothai#4562 bug fixes

35 tests covering all fixes across platforms:
- binary_env cross-platform (Linux LD_LIBRARY_PATH, Windows PATH,
  macOS DYLD_LIBRARY_PATH) with edge cases (dedup, ordering, existing paths)
- resolve_requested_llama_tag (concrete, latest, None, empty)
- setup.sh logic via subprocess: prereq check ordering (cmake/git missing
  preserves install), pinned tag in clone, fetch+checkout -B pattern,
  fetch failure warns instead of aborting
- "latest" tag resolution fallback chain (Unsloth API -> ggml-org ->
  raw) with mock curl: success, failure, malformed JSON, empty body,
  empty tag_name, env overrides
- Source code pattern verification for both .sh and .ps1 files

All 138 tests pass in isolated uv venv.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Add binary_path.parent to macOS DYLD_LIBRARY_PATH in binary_env

macOS prebuilt .dylib files are overlaid into build/bin (same as
Linux), but binary_env only added install_dir to DYLD_LIBRARY_PATH.
Add binary_path.parent so the loader can find sibling dylibs even
without embedded loader paths.

Mirrors the existing fix for Linux LD_LIBRARY_PATH and the Windows
PATH pattern.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Guard --branch when resolved tag is "latest"; fix broken test assertion

When all API fallbacks fail and the tag stays as literal "latest",
omit --branch from git clone (clones default branch instead of
failing). Both setup.sh and setup.ps1 now check for "latest" before
passing --branch to git clone/fetch.

Also fix test_setup_ps1_clone_uses_branch_tag which used Python
tuple syntax (assert "x", "y" in z) that always passes. Changed to
assert "x" in z and "y" in z.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Fix macOS DYLD trailing colon, install_lock no-op, and debug log

- binary_env macOS: use dedupe_existing_dirs instead of raw string
  concatenation. Eliminates trailing colon in DYLD_LIBRARY_PATH
  (which causes dyld to search CWD for libraries) and deduplicates
  when binary_path.parent == install_dir. Now consistent with the
  Linux and Windows branches.
- install_lock: when filelock is not installed, use os.O_CREAT|O_EXCL
  as a fallback exclusive file lock with timeout, instead of yielding
  with no locking. Prevents concurrent installs from corrupting each
  other's staging directories.
- setup.ps1: remove [DEBUG] log line that printed to every user on
  every Windows setup run.

* Add stale-lock detection and atomic clone-then-swap

install_lock fallback (no filelock): write PID to lock file and
check if the holder process is still alive on contention. Dead PIDs
(ProcessLookupError) and unreadable lock files trigger immediate
cleanup. Live processes owned by other users (PermissionError) are
correctly recognized as alive -- the lock is not removed.

setup.sh/setup.ps1 source-build: clone into a temporary directory
first, then swap into place only on success. If git clone fails,
the existing install is preserved instead of being deleted by the
premature rm -rf.

* Remove redundant upstream_tag != release_tag check

load_approved_release_checksums compared checksums.upstream_tag
against the Unsloth release_tag, which are different namespaces
(upstream ggml-org tag vs Unsloth published tag). This only worked
because both happened to be "b8508" by convention. Would break if
Unsloth ever uses a different release naming scheme.

The existing check at parse_approved_release_checksums (line 950)
already validates the release_tag field correctly.

* Fix lock TOCTOU race and build-in-temp-dir swap

install_lock fallback: add os.fsync(fd) after writing PID to ensure
the PID is visible to racing processes before they check. Treat
empty lock files (PID not yet written) as "wait and retry" instead
of stale, closing the window where two processes could both see an
empty file, both unlink it, and both acquire the lock.

setup.sh/setup.ps1 source-build: clone AND build in a temp directory
(LLAMA_CPP_DIR.build.$$). Only swap into the final LLAMA_CPP_DIR
after the build succeeds. If clone or cmake or build fails, the temp
dir is cleaned up and the existing working install is preserved.
Previously, rm -rf ran after clone but before build, destroying the
existing install even if the build later failed.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit that referenced this pull request Aug 31, 2026
…d test coverage (#9979)

* CI: fix llama.cpp seed caching, Diffusers wheel installs, and isolated test coverage

* Keep a llama.cpp install only when its binaries actually run

* Fix the prompt-cache, Diffusers, and MCP menu CI legs

* Check the kept install's runtime payload, so Windows is not exempt

* Give the CLI launch tests a writable studio home

* Give each isolated unsloth_zoo file its own pytest process

* Require the paired cudart trio and keep an install that already runs the stored backend

* Tolerate an empty collection in the zoo rerun and re-anchor the node dir test

* Skip the inline code scan when no backtick escapes the block regions

* Answer the AppImage E2E preflight with the headers it asked for

* Ask an unreadable marker for the payload every kind of its platform needs

* Keep the mlx family out of the parallel zoo pass and run it serially

* Shorten verbose PR comments

* Reject a kept install whose binaries the OS will not execute

* Probe the launched entrypoint, read Windows loader statuses, and honour this run's selection

* Give the probe the recorded runtime line and stop reading GPU detection as a choice

* Shorten the comments added since the last pass

* Backfill the paired runtime asset when an install is reused

* Compare the seed in llama.cpp's uint32 domain and require the published payload

* allow cpu security import probe

* Treat every uint32 sentinel seed as random in the per-choice offset

_apply_seeded_llama_request compares the seed in llama.cpp's uint32 domain,
so -1, 4294967295 and 2**64-1 are all LLAMA_DEFAULT_SEED and all keep prompt
caching. _choice_seed still exempted the literal -1, so for n > 1 the two
helpers disagreed inside one request: choice 0 kept the caller's random seed
and its cache, while choice 1 was offset to ((seed & 0xFFFFFFFF) + 1) % 0xFFFFFFFF,
a fixed seed with the cache turned off. seed=4294967295 with n=3 served
[4294967295, 1, 2].

Confirmed against a real llama-server: -1, 4294967295 and 2**64-1 each varied
across repeated requests, while 4294967294 and 0 did not. llama.cpp applies the
same test at its own multi-choice offset in tools/server/server-task.h, where
the guard is seed != LLAMA_DEFAULT_SEED rather than a literal.

* Stop reporting a kept install as one that was just installed

The keep path answers a transient update failure by exiting 0 with the tree
already on disk. Both setup scripts only distinguish exit 0 by looking for
"already matches", so a kept install took the other branch and printed
"prebuilt installed and validated", naming a release that was never fetched.
setup.ps1 also went on to print the old release as the installed one.

The in-app updater had the same problem on macOS. start_update passes no
pin_release_tag there, so the "pinned release X but installer produced Y"
check that catches this on Linux and Windows does not run, and the phase
reported "Updated llama.cpp to <the tag the user already had>". It now
compares the marker before and after and says the install is already up to
date, which is what happened.

* Fail the zoo step when its mlx group glob matches nothing

mlx_group is passed to pytest unquoted so the list word-splits into file
arguments, which means an empty list passes no files at all and pytest
collects the whole rootdir serially instead: green, much slower, and no
longer the group the step describes. The glob only has to stop matching
once, upstream renaming the family for instance, for that to be what runs.

Also pass each rerun's own filename to _keep. Exit 5 stays tolerated, but a
module-level skip and a file that stopped collecting for a new reason both
produce it, and only the log says which file it was.

* Cover the kept-install path against every marker shape that has shipped

_existing_install_runs and _kept_install_payload_is_healthy decide whether an
install the user already has survives a transient update failure, and they had
no direct tests: the existing keep-path cases drive install_prebuilt with a
hand-built two-key marker. UNSLOTH_PREBUILT_INFO.json has grown twelve shapes
since #4562 with no version field and no migration, so an absent key is the
normal case for anything installed before the release that added it.

Covers each shipped shape on Linux, Windows and macOS hosts, including the
S1-S8 markers that carry no backend key and resolve through the asset name,
and the S1-S11 Windows CUDA installs that predate runtime_asset and so must
not be asked for a cudart trio they cannot record. Also pins two boundaries
that were unasserted: a source build has no marker, so confirm_install_tree
rejects it and it still falls through to the source-build fallback, while a
corrupt marker keeps the tree eligible and holds it to every kind's shared
payload. Adds the missing SIGSEGV and hang cases for the --version probe.

Platforms are simulated through HostInfo, as the rest of this suite does. That
covers the path decisions and the payload tables; it does not cover the Windows
loader or macOS dyld, which no Linux runner can answer.

* Cover the keep path across every OS and accelerator, and its exit contract

Extends the marker-shape cases with the product the installer actually has to
serve. Fifteen cells across Linux, WSL, Windows and macOS by NVIDIA, AMD, CPU
and Vulkan, each asserted three ways: a complete tree is kept, a gutted one is
refused, and an accelerator tree missing only its own backend library is
refused. That last case is the one that matters after a partial extraction,
where the binaries still start and only fail once a model is loaded. Vulkan,
windows-hip, windows-rocm, windows-arm64 and linux-arm64-cuda had no payload
coverage at all before this.

WSL is asserted to behave exactly like Linux, which is the claim worth pinning:
HostInfo carries no WSL field and the WSL2 ROCDXG handling lives in host
detection and setup.sh, upstream of the keep path.

Adds the exit contract the setup scripts branch on, driven through
install_prebuilt rather than the deciders: a transient failure returns 0 for
every shipped marker shape, a tree that is not runnable still reaches
EXIT_FALLBACK so a source build can proceed, an explicit version request is
never answered with the old install, and a marker recording a backend this
build cannot install exits EXIT_ERROR before the keep branch is reached. That
last ordering was untested and is what stops a newer marker being answered with
the tree already on disk.

Also covers a marker whose keys were grafted on by sync_marker_selection rather
than written in one go, which is the shape a long-lived install really has, and
a marker naming another platform's backend, which falls open rather than being
judged by a table that does not apply.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Trim the comments added for PR #9979

Same behaviour, fewer lines. AST comparison confirms every changed .py file is
identical once docstrings are stripped, so this is comments only. setup.sh
passes bash -n, setup.ps1 parses, the workflow YAML parses and its zoo step body
still passes bash -n.

* Report a kept llama.cpp install as an unavailable update for PR #9979

---------

Co-authored-by: mahiatlinux <[email protected]>
Co-authored-by: Daniel Han-Chen <[email protected]>
Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
rhsCZ pushed a commit to rhsCZ/unsloth that referenced this pull request Sep 7, 2026
…reads

Two fixes on top of this branch, both from review.

The progress label was answering with `import torch`. `_torch_step_label` runs before
the first pip step of its block, where `_TORCH_RUNTIME_PROBE` is cold, and on the very
host the label exists for (Windows, no NVIDIA, no rocminfo or amd-smi) none of the four
`_ensure_*` calls that follow reach the probe either: `_ensure_cuda_torch` returns on
no-NVIDIA, `_ensure_xpu_torch` on IS_WINDOWS, `_ensure_rocm_torch` at its "no AMD GPU
visible via hipinfo" guard, `_ensure_cpu_torch` unless an explicit CPU pin is set. So
the new operand was the first probe, spending up to its 90s timeout before `_progress()`
had printed anything, on exactly the wedged-driver hosts that timeout exists to rescue.
`pip_install` then invalidates the memo before the existing check at the torchao step,
so the cost was not amortised either.

`_installed_torch_is_windows_rocm_cheap` answers the same question from torch/version.py
via `find_spec`, which is the idiom `_installed_torch_version_label` and
`_installed_torch_label_on_disk` already use for this exact reason, and falls back to the
memoized probe only when something else has already paid for it. Behaviour on the
reported Strix Halo host is unchanged.

The marker reads were unguarded. `backend` has only been written since unslothai#8520
(2026-08-13); markers go back to unslothai#4562 (2026-03-25), so every install older than that has
no such property, and reading a missing property under a caller's `Set-StrictMode
-Version 2.0` or higher is a terminating error. The function's only try/catch wraps
`ConvertFrom-Json`, so it escaped and aborted setup. `tag`, `published_repo` and
`release_tag` had the same hazard, and an empty or truncated marker (an interrupted write
leaves one) made the function print "installed release: @" instead of staying quiet. All
four reads are now guarded through `PSObject.Properties`.

Both printers now share one contract for the value: string only, trimmed, and matching
`^[A-Za-z0-9._+-]{1,32}$`. Without it the twins disagree, since PowerShell renders
@(1, 2) as "1 2" and Python renders [1, 2] as "[1, 2]", and a newline in the value would
split the log line. The vocabulary is cuda, rocm, vulkan, cpu and metal, so nothing real
is rejected. The guard uses -ccontains because PowerShell property access is
case-insensitive and Python's dict lookup is not.

Tests. `test_torch_step_label.py` grows to 164 cases: the full
[Windows, Linux, WSL, macOS] x [NVIDIA, AMD with tooling, AMD bundled-runtime, Intel XPU,
CPU-only, no torch] matrix, explicit-backend precedence, the off-disk reader, and the
cost assertions. `test_installed_release_backend_line.py` is new: 498 cases driving the
real `Get-InstalledLlamaPrebuiltRelease` through pwsh and the real
`installed_llama_prebuilt_release` through bash, over a marker corpus (every backend,
null, non-string, unicode, 64KiB, quotes, backticks, subexpressions, newlines, control
characters, malformed and empty files) crossed with StrictMode off, 1.0, 2.0, 3.0 and
Latest, plus all twelve historical marker key sets from 2026-03-25 to today, and a
byte-for-byte parity assertion between the two printers on every case.

Both new assertions discriminate: the legacy-marker StrictMode case and the
zero-subprocess case pass on the merge base, fail on this branch before these fixes, and
pass after.

Recorded, not fixed here: setup.sh names a non-fork binary source ("+ ggml-org@b10715")
and setup.ps1 never has. Teaching setup.ps1 that branch changes what Windows prints for
upstream bundles, which is a separate change; the divergence is asserted in the new test
so it stays a known quantity.
danielhanchen added a commit that referenced this pull request Sep 8, 2026
…ling Windows ROCm torch as CPU (#10370)

* Studio: name the llama.cpp backend in the install log, and stop labelling Windows ROCm torch as CPU

The installer prints "installed release: <repo>@<tag>" and never says which
backend the installed bundle runs on, so a host running a Vulkan bundle and a
host running a ROCm one produce identical lines. A Strix Halo report came with
four install and update logs covering nine days that all read healthy while the
machine ran Vulkan; only the server logs, which record the backend, showed it.
The marker already carries the resolved backend, so both setup scripts now print
it.

Separately, the torch progress label falls back to GPU detection when
UNSLOTH_TORCH_BACKEND is unset, which is every standalone "unsloth studio
update". On Windows that detection probes rocminfo and amd-smi, which ship with
the HIP SDK rather than with AMD's bundled-runtime wheels, so the same run
printed "torch check (cpu)" a few lines above "dependency overrides (skipped,
Windows ROCm)". torch.version.hip is the installed build's own answer and is
already read for the torchao override, so the label uses it too.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: read the Windows ROCm verdict off disk, and guard the marker reads

Two fixes on top of this branch, both from review.

The progress label was answering with `import torch`. `_torch_step_label` runs before
the first pip step of its block, where `_TORCH_RUNTIME_PROBE` is cold, and on the very
host the label exists for (Windows, no NVIDIA, no rocminfo or amd-smi) none of the four
`_ensure_*` calls that follow reach the probe either: `_ensure_cuda_torch` returns on
no-NVIDIA, `_ensure_xpu_torch` on IS_WINDOWS, `_ensure_rocm_torch` at its "no AMD GPU
visible via hipinfo" guard, `_ensure_cpu_torch` unless an explicit CPU pin is set. So
the new operand was the first probe, spending up to its 90s timeout before `_progress()`
had printed anything, on exactly the wedged-driver hosts that timeout exists to rescue.
`pip_install` then invalidates the memo before the existing check at the torchao step,
so the cost was not amortised either.

`_installed_torch_is_windows_rocm_cheap` answers the same question from torch/version.py
via `find_spec`, which is the idiom `_installed_torch_version_label` and
`_installed_torch_label_on_disk` already use for this exact reason, and falls back to the
memoized probe only when something else has already paid for it. Behaviour on the
reported Strix Halo host is unchanged.

The marker reads were unguarded. `backend` has only been written since #8520
(2026-08-13); markers go back to #4562 (2026-03-25), so every install older than that has
no such property, and reading a missing property under a caller's `Set-StrictMode
-Version 2.0` or higher is a terminating error. The function's only try/catch wraps
`ConvertFrom-Json`, so it escaped and aborted setup. `tag`, `published_repo` and
`release_tag` had the same hazard, and an empty or truncated marker (an interrupted write
leaves one) made the function print "installed release: @" instead of staying quiet. All
four reads are now guarded through `PSObject.Properties`.

Both printers now share one contract for the value: string only, trimmed, and matching
`^[A-Za-z0-9._+-]{1,32}$`. Without it the twins disagree, since PowerShell renders
@(1, 2) as "1 2" and Python renders [1, 2] as "[1, 2]", and a newline in the value would
split the log line. The vocabulary is cuda, rocm, vulkan, cpu and metal, so nothing real
is rejected. The guard uses -ccontains because PowerShell property access is
case-insensitive and Python's dict lookup is not.

Tests. `test_torch_step_label.py` grows to 164 cases: the full
[Windows, Linux, WSL, macOS] x [NVIDIA, AMD with tooling, AMD bundled-runtime, Intel XPU,
CPU-only, no torch] matrix, explicit-backend precedence, the off-disk reader, and the
cost assertions. `test_installed_release_backend_line.py` is new: 498 cases driving the
real `Get-InstalledLlamaPrebuiltRelease` through pwsh and the real
`installed_llama_prebuilt_release` through bash, over a marker corpus (every backend,
null, non-string, unicode, 64KiB, quotes, backticks, subexpressions, newlines, control
characters, malformed and empty files) crossed with StrictMode off, 1.0, 2.0, 3.0 and
Latest, plus all twelve historical marker key sets from 2026-03-25 to today, and a
byte-for-byte parity assertion between the two printers on every case.

Both new assertions discriminate: the legacy-marker StrictMode case and the
zero-subprocess case pass on the merge base, fail on this branch before these fixes, and
pass after.

Recorded, not fixed here: setup.sh names a non-fork binary source ("+ ggml-org@b10715")
and setup.ps1 never has. Teaching setup.ps1 that branch changes what Windows prints for
upstream bundles, which is a separate change; the divergence is asserted in the new test
so it stays a known quantity.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: stop the hip-reader tests reading the runner's real torch

The four _torch_hip_version_on_disk cases built a stand-in torch package under
tmp_path and prepended it to sys.path, which is enough only when torch is absent.
importlib.util.find_spec returns sys.modules[name].__spec__ when the module is
already imported, so on any job that installs torch the real package answered, the
fixture was ignored, and the reader returned "" instead of the planted hip string.
They passed locally for the same reason they failed in CI.

_fake_torch_on_path now drops the sys.modules entry as well, so find_spec does a real
path search; monkeypatch restores the real torch at teardown. Reproduced the CI shape
locally by importing a stub torch before collection: 4 failed before this, 164 pass
after. Test-only, the reader itself is unchanged.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: cut the comments on the backend-label change down to the load-bearing ones

Opening comment-reduction pass over the lines this PR adds: 173 comment and docstring
lines to 73. Deleted first, shortened second.

Gone are the docstrings that only restated a test name, the per-row provenance comments
that repeated the dict key beside them, the corpus section banners, and the multi-line
rationales whose facts already sit one line above in code. Kept, at one line each: why
rocminfo and amd-smi are absent on the reported host, why find_spec needs the sys.modules
entry dropped, why the guard is -ccontains rather than -contains, why pip_install
invalidating the memo is what made the old probe unamortised, and the pre-existing
setup.sh upstream-source branch that setup.ps1 has never had.

Comments, docstrings and whitespace only. prepush_gate --comment-only passes on
install_python_stack.py, setup.ps1 and test_torch_step_label.py. It fails closed on
setup.sh and test_installed_release_backend_line.py because the edited comments live
inside an embedded-language string (a shell heredoc and a PowerShell harness literal),
which no Python or shell lexer can see into, so both were verified by hand instead: the
heredoc's Python AST and everything outside it are byte-identical, all 12 changed lines
in setup.sh start with #, and the single AST delta in the test file is one # line inside
the PowerShell string.

164 and 496 tests still pass, bash -n clean, setup.ps1 parses with zero errors.

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

* Studio: probe bash before using it, so the setup.sh printer test skips on Windows

The Windows staging run turned this up: 141 of the new printer cases failed with the
expected line compared against UTF-16 text reading "Windows Subsystem for Linux has no
installed distributions."

C:\Windows\System32\bash.exe is the WSL launcher, not a shell. WSL puts it on the system
PATH ahead of Git's bin, so shutil.which("bash") returns it even when no distro is
installed, and running it prints that notice to stdout instead of executing the script.
The skipif therefore believed bash was available and the harness read the notice as
printer output. Microsoft documents the launcher as deprecated in favour of wsl.exe, and
the same first-PATH-hit mistake is on record against pnpm and several editors.

_usable_bash now runs `bash -c "printf ok"` and accepts the executable only if it prints
ok, which is the fix those reports converge on: probe the candidate rather than trusting
the first PATH match. A stub that ignores -c is rejected, so the file skips instead of
asserting against garbage. Nothing is lost by skipping there: setup.sh is never executed
on Windows, since _find_setup_script picks setup.ps1.

Verified against a stub that mimics the launcher (prints the notice, ignores -c): the
guard resolves to None. 660 tests pass here, ruff clean.

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
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