Skip to content

Feat/prebuiltllamacpp - #4741

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
mmathew23:feat/prebuiltllamacpp
Apr 1, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
mmathew23:feat/prebuiltllamacpp

Conversation

@mmathew23

Copy link
Copy Markdown
Contributor

Summary

This PR updates Studio's llama.cpp installer to resolve the latest usable published Unsloth release instead of relying on a fixed pinned tag, while preserving backward-compatible fallback behavior.

What changed

  • Resolve latest from the latest usable published release in unslothai/llama.cpp
  • Use the selected release's upstream_tag as the authoritative llama.cpp version
  • Prefer Unsloth-published platform assets when available
  • Fall back to same-tag upstream ggml-org/llama.cpp assets where allowed
  • Keep Linux CUDA anchored to Unsloth-published CUDA bundles only
  • Add bounded fallback across older Unsloth published releases
  • Add separate busy/in-use install handling
  • Skip reinstall when the installed bundle already matches the selected candidate
  • Skip redundant reinstall when a later fallback candidate already matches the healthy installed version
  • Remove shell/PowerShell direct releases/latest.tag_name fallback so the Python helper remains the only source of truth for published release -> upstream_tag
  • Harden env parsing so malformed installer env vars do not crash import-time fallback logic

Tests

  • Expanded installer selection and fallback coverage
  • Added cross-platform health-check coverage for Linux, Windows, and macOS skip behavior
  • Added validator tests for staged release_tag / upstream_tag handling
  • Updated shell/PowerShell bugfix tests to lock down helper-only resolution

Validated locally with:

  • 163 installer/regression tests passing
  • setup.sh syntax check
  • setup.ps1 PowerShell parse check
  • staged Linux runtime validation passing for all b8589 bundles

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

@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: 6d7e01b7a3

ℹ️ 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 +9 to +10
REPO_ROOT = Path(__file__).resolve().parents[5]
MODULE_PATH = REPO_ROOT / "validate-llama-prebuilt.py"

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 Correct repository root lookup in new validator tests

REPO_ROOT = Path(__file__).resolve().parents[5] resolves to / for this test path, so MODULE_PATH becomes /validate-llama-prebuilt.py and test collection fails with FileNotFoundError before any test runs. This breaks the installer test suite in normal repo execution contexts; use the same repo-root depth as the sibling installer tests.

Useful? React with 👍 / 👎.

sys.modules[spec.name] = module
try:
spec.loader.exec_module(module)
assert module.DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS == 3

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 Update malformed-env reload assertion to current default

This assertion expects DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS == 3, but the installer now defines the default as 2, so the test deterministically fails after module reload when UNSLOTH_LLAMA_MAX_PREBUILT_RELEASE_FALLBACKS is malformed. As written, this introduces a hard false negative in CI rather than validating the intended “no crash, use default” behavior.

Useful? React with 👍 / 👎.

- Fix REPO_ROOT in test_validate_llama_prebuilt.py (parents[5] -> parents[3])
- Add pytest.skip when validate-llama-prebuilt.py is not present
- Fix DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS assertion (3 -> 2) to match
  the actual default in install_llama_prebuilt.py

@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.

Thank you for the PR! The goal of this PR is to update Studio's llama.cpp installer to dynamically resolve the latest usable published Unsloth release instead of relying on a fixed pinned tag. As a summary, this PR adds multi-release fallback planning, install fingerprinting to skip redundant reinstalls, busy/in-use exit handling, and removes the shell/PowerShell direct releases/latest.tag_name fallback in favor of the Python helper as the sole resolver.

I ran 5 independent reviewers plus 3 additional parallel review passes. Here are the consolidated findings:

Reviewers Severity Finding
8/8 High test_validate_llama_prebuilt.py:9 uses parents[5] instead of parents[3] and imports validate-llama-prebuilt.py which does not exist in this branch
8/8 High test_selection_logic.py:1350 asserts DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS == 3 but code defaults to 2
2/8 Low setup.sh:538 and setup.ps1:1657 grep for "already matches selected release" but miss the "already matches fallback release" log path

I have already pushed a commit fixing the two high-severity test issues:

  1. Fixed REPO_ROOT path calculation (parents[5] to parents[3]) in test_validate_llama_prebuilt.py
  2. Added pytest.skip guard for when validate-llama-prebuilt.py is not present
  3. Fixed assertion to match actual default (2 instead of 3) in test_selection_logic.py

All 161 tests now pass (1 skipped for missing helper).

The low-severity cosmetic issue (grep pattern in setup.sh/ps1 not matching fallback log message) is minor and does not affect functionality -- it just shows "prebuilt installed and validated" instead of "prebuilt up to date and validated" in the fallback-match case.

@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

@gemini-code-assist

Copy link
Copy Markdown
Contributor

Warning

You have reached your daily quota limit. Please wait up to 24 hours and I will start processing your requests again!

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

ℹ️ 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 +3500 to +3502
allow_older_release_fallback = (
requested_tag == "latest" and not published_release_tag
)

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 Keep older-release fallback enabled for resolved tags

resolve_install_release_plans only enables cross-release fallback when requested_tag == "latest", but both setup entrypoints resolve latest to a concrete tag first and then invoke the installer with that resolved value (studio/setup.sh passes --llama-tag "$_RESOLVED_LLAMA_TAG", and studio/setup.ps1 passes --llama-tag $ResolvedLlamaTag). In that common path, a newest published release that is unusable on the host (missing/invalid platform asset) now fails immediately instead of trying older published releases, so users drop to source-build fallback despite an installable older prebuilt release being available.

Useful? React with 👍 / 👎.

@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.

Ran 3 rounds of review (5 parallel reviewers + 3 parallel subagents per round = 24 total review passes).

Summary of all findings across 3 rounds:

Fixed (committed da5dd86):

  1. test_validate_llama_prebuilt.py:9 - REPO_ROOT used parents[5] instead of parents[3], and validate-llama-prebuilt.py is not present in this branch. Fixed path and added pytest.skip guard.
  2. test_selection_logic.py:1350 - Assertion expected DEFAULT_MAX_PREBUILT_RELEASE_FALLBACKS == 3 but code defaults to 2. Fixed assertion.

Analyzed and determined to be intentional design / not real issues:

  • setup.sh/ps1 removing direct GitHub API releases/latest fallback: This is intentional per the PR description ("Remove shell/PowerShell direct releases/latest.tag_name fallback so the Python helper remains the only source of truth"). The PR's own tests (test_pr4562_bugfixes.py) explicitly verify this removal. The Python helper resolve_requested_llama_tag() already has its own upstream fallback path via latest_upstream_release_tag().
  • is_busy_lock_error classifying PermissionError as busy: Intentional for Windows compatibility where PermissionError is the standard signal for "file in use by another process." The function is used in activate_install_tree where this classification is appropriate.
  • resolve_requested_install_tag not being host-aware: This only affects --resolve-install-tag CLI usage and does not impact the prebuilt install path which uses install_prebuilt() directly.
  • Skip-reinstall not re-validating runtime: The fingerprint check compares SHA256 hashes of the exact installed asset plus metadata, making re-validation unnecessary for the normal case.

All 161 tests pass, 1 skipped (test_validate_llama_prebuilt.py skipped because validate-llama-prebuilt.py helper is not in this branch).

- Fix infinite loop when fallback PID-file lock finds an empty lock file
  left by a crashed process: the empty-file branch now checks the
  deadline before continuing, preventing an indefinite spin.

- Fix fd leak when os.write()/os.fsync() fails after os.open() succeeds
  in the fallback lock path: the fd is now closed and the lock file
  cleaned up before re-raising.

- Fix successful prebuilt activation being reported as EXIT_ERROR when
  rollback directory cleanup fails after a successful install: the
  remove_tree_logged call in the success path is now wrapped in a
  try/except so a cleanup failure does not mask a successful activation.

@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.

Pushed additional fixes (0946f5d) for three edge cases found in the fallback lock and rollback cleanup code:

  1. Fallback PID-file lock infinite loop on empty lock file -- When filelock is not installed and the fallback lock path is used, if a process crashed between os.open() and os.write(), it would leave an empty lock file. The empty-file handler did time.sleep(0.1); continue back to the top of the while True loop without checking the deadline, causing an infinite spin. Fixed by adding a deadline check in the empty-file branch.

  2. fd leak on write failure in fallback lock -- If os.write() or os.fsync() raised after os.open() succeeded, the file descriptor was never closed and the empty lock file was left on disk, which would trigger bug #1 for subsequent callers. Fixed by wrapping the write/fsync in a try/except that closes the fd and removes the lock file before re-raising.

  3. Successful install reported as EXIT_ERROR on rollback cleanup failure -- In activate_install_tree, the success (else) branch called remove_tree_logged() to clean up the rollback directory. Unlike remove_tree(), this function does not use ignore_errors=True, so a cleanup failure (e.g., permission issue on the old directory) would propagate as an exception, causing the successful installation to be reported as a failure. Fixed by wrapping the cleanup in try/except so a non-fatal cleanup error is logged but does not mask a successful activation.

All 161 tests continue to pass (1 skipped).

@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: 8aea29f35d

ℹ️ 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 +3515 to +3517
allow_older_release_fallback = (
requested_tag == "latest" and not published_release_tag
)

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 Allow older-release fallback for resolved latest installs

This gating makes cross-release fallback unreachable in the normal setup flow: resolve_install_release_plans only enables older-release fallback when requested_tag == "latest", but in this commit both setup entrypoints first resolve latest to a concrete tag and then call the installer with that resolved --llama-tag (studio/setup.sh and studio/setup.ps1). In that common path, if the newest published release for the resolved tag is unusable on the host (missing/incompatible asset), the installer raises immediately instead of trying older published releases, causing an unnecessary source-build fallback even when an older published prebuilt is installable.

Useful? React with 👍 / 👎.

danielhanchen and others added 5 commits April 1, 2026 11:42
Tests belong in a dedicated test PR to keep the installer changes
focused and reviewable. The 5 test files will be submitted in a
follow-up PR once the installer logic stabilizes.
…URCE

Let maintainers pin llama.cpp builds to a PR or fork by editing two
variables at the top of setup.sh / setup.ps1. Users get the right build
automatically via curl|sh with no PyPI release needed.

- _DEFAULT_LLAMA_PR_FORCE: baked-in PR number (promotes to _LLAMA_PR
  when user hasn't set UNSLOTH_LLAMA_PR)
- _DEFAULT_LLAMA_SOURCE: git clone URL (non-default forces source build)
- Both placed at the top of each file for easy editing
- Parameterized all git clone URLs to use the source variable
- Trailing .git in URLs normalized away
- 46 new tests covering promotion, overrides, edge cases
Revert all tests/studio/install/ files to upstream main to keep
this PR focused on the installer logic changes only.

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

ℹ️ 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 Outdated
Write-Host " Syncing llama.cpp to $ResolvedLlamaTag..." -ForegroundColor Gray
if ($UseConcreteRef) {
if ($LlamaPr) {
$gitFetchExit = Invoke-SetupCommand -AlwaysQuiet { git -C $LlamaCppDir fetch --depth 1 origin "pull/$LlamaPr/head:pr-$LlamaPr" }

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 Honor custom llama source when syncing existing checkout

When UNSLOTH_LLAMA_SOURCE is set, this script correctly forces source-build mode, but in the existing-repo path it still fetches from hardcoded origin instead of the configured source URL. If ~/.unsloth/llama.cpp/.git already exists (a common update path), builds can silently pull from the wrong repository or fail to fetch tags/PR heads that only exist in the custom fork, so the new custom-source override is not reliably applied.

Useful? React with 👍 / 👎.

- Fix fingerprint asymmetry: expected_install_fingerprint now handles
  missing source_archive the same way write_prebuilt_metadata does,
  preventing perpetual reinstalls when source archive metadata is absent
- Remove install_tree_is_healthy from existing_install_matches_choice
  to avoid requiring converter scripts for the skip-reinstall check;
  runtime_payload_is_healthy + fingerprint match is sufficient
- Remove ENOTEMPTY from is_busy_lock_error errno set and remove bare
  PermissionError catch; ENOTEMPTY is a cleanup issue, not a busy signal
- Pass _REQUESTED_LLAMA_TAG to installer instead of _RESOLVED_LLAMA_TAG
  in both setup.sh and setup.ps1 to preserve cross-release fallback
- Skip wasteful resolve-install-tag call when custom source already
  forces source build in setup.sh
- Update git remote URL when custom LLAMA_SOURCE is used with an
  existing checkout in setup.ps1
- Broaden "already matches" grep to catch both primary and fallback
  match messages in setup.sh and setup.ps1
@danielhanchen

Copy link
Copy Markdown
Member

Review Summary

Ran 5 independent reviewer passes + 3 independent code analysis passes on this PR. All 8 reviewers flagged REQUEST_CHANGES. The following fixes have been pushed directly to this branch.

Findings and fixes applied

Reviewers Severity Finding Status
5/8 High existing_install_matches_choice calls install_tree_is_healthy which requires converter scripts; causes perpetual reinstalls when ensure_converter_scripts fails once Fixed -- removed install_tree_is_healthy guard; runtime_payload_is_healthy + fingerprint match is sufficient
4/8 High Fingerprint asymmetry: write_prebuilt_metadata computes fingerprint with source_sha256=None but expected_install_fingerprint returns None entirely when source archive is absent Fixed -- aligned both functions to use source_sha256=None consistently
4/8 High is_busy_lock_error includes ENOTEMPTY and bare PermissionError, misclassifying cleanup failures and read-only filesystem errors as "in use" Fixed -- removed ENOTEMPTY from errno set, removed bare PermissionError catch
3/8 High Shell scripts pass _RESOLVED_LLAMA_TAG (already resolved) to installer, defeating cross-release fallback when latest published release is unusable Fixed -- pass _REQUESTED_LLAMA_TAG to --llama-tag in both setup.sh and setup.ps1
2/8 Medium Custom LLAMA_SOURCE with existing checkout: setup.ps1 sync path still fetches from old origin remote Fixed -- added git remote set-url origin before fetch when source is non-default
2/8 Medium Custom source forces _SKIP_PREBUILT_INSTALL=true but resolve-install-tag still runs, making unnecessary network calls and printing confusing warnings Fixed -- added elif guard to skip full resolve when prebuilt is already skipped
2/8 Low "already matches" grep only matches "selected release", missing "fallback release" message Fixed -- broadened to match "already matches"

Not fixed (intentional or negligible)

  • DEFAULT_LLAMA_TAG change from "b8508" to "latest" -- This is the intentional core change of the PR
  • env_int silent fallback on malformed env vars -- Acceptable; avoids noisy warnings on import
  • Lock timing allowing 0.1s overshoot -- Negligible, well within acceptable tolerance
  • existing_install_matches_plan checking only attempts[0] -- The primary attempt is the one actually installed in the normal path

@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: 8b4c0a3889

ℹ️ 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 +3750 to +3751
if not runtime_payload_is_healthy(install_dir, host, choice):
return False

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 Require full tree validation before skipping reinstall

This early-return path can now treat a broken install as up to date because existing_install_matches_choice only checks metadata plus runtime_payload_is_healthy, which verifies runtime libraries but not required executables/scripts (for example llama-server, llama-quantize, or converter files). If those files are missing or corrupted while the DLL/SO set and fingerprint remain, install_prebuilt exits success and never rehydrates or runs ensure_converter_scripts, leaving Studio with a non-functional llama.cpp install.

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 prebuilt installation and resolution logic to improve robustness and flexibility. Key enhancements include a new release resolution system that supports falling back to older releases, platform-specific asset prioritization (particularly for Windows CUDA), and the introduction of install fingerprints to perform health checks and avoid redundant reinstalls. Additionally, the update improves error handling for in-use files and adds support for building from custom GitHub PRs or forks. Review feedback highlights opportunities to optimize network usage by reusing bundle data, reduce code duplication in resolution and fingerprinting functions, and ensure that Unsloth-published linux-cpu assets are correctly prioritized.

Comment on lines +1392 to +1393
checksums = load_approved_release_checksums(repo, bundle.release_tag)
require_approved_source_hash(checksums, bundle.upstream_tag)

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 call to load_approved_release_checksums performs a redundant network request to fetch the release metadata from GitHub. Since the bundle object already contains the assets map, the checksum URL can be retrieved directly from it, saving an API call and reducing the risk of hitting rate limits.

    checksum_url = bundle.assets.get(DEFAULT_PUBLISHED_SHA256_ASSET)
    if not checksum_url:
        raise PrebuiltFallback(
            f"approved prebuilt release {repo}@{bundle.release_tag} did not expose {DEFAULT_PUBLISHED_SHA256_ASSET}"
        )
    try:
        payload = fetch_json(checksum_url)
        checksums = parse_approved_release_checksums(repo, bundle.release_tag, payload)
    except PrebuiltFallback:
        raise
    except Exception as exc:
        raise PrebuiltFallback(
            f"approved checksum asset {DEFAULT_PUBLISHED_SHA256_ASSET} in {repo}@{bundle.release_tag} was invalid"
        ) from exc
    require_approved_source_hash(checksums, bundle.upstream_tag)

Comment on lines +1401 to +1450
) -> ResolvedPublishedRelease:
repo = published_repo or DEFAULT_PUBLISHED_REPO
normalized_requested = normalized_requested_llama_tag(requested_tag)

if published_release_tag:
bundle = pinned_published_release_bundle(repo, published_release_tag)
if (
normalized_requested != "latest"
and bundle.upstream_tag != normalized_requested
):
raise PrebuiltFallback(
"published release "
f"{repo}@{published_release_tag} targeted upstream tag {bundle.upstream_tag}, "
f"but requested {normalized_requested}"
)
return ResolvedPublishedRelease(
bundle = bundle,
checksums = validated_checksums_for_bundle(repo, bundle),
)

skipped_invalid = 0
for bundle in iter_published_release_bundles(repo):
if (
normalized_requested != "latest"
and bundle.upstream_tag != normalized_requested
):
continue
try:
checksums = validated_checksums_for_bundle(repo, bundle)
except PrebuiltFallback as exc:
skipped_invalid += 1
log(
"published release ignored for install resolution: "
f"{repo}@{bundle.release_tag} ({exc})"
)
continue
return ResolvedPublishedRelease(bundle = bundle, checksums = checksums)

if normalized_requested == "latest":
if skipped_invalid:
raise PrebuiltFallback(
f"no usable published llama.cpp releases were available in {repo}"
)
raise PrebuiltFallback(
f"no published llama.cpp releases were available in {repo}"
)

raise PrebuiltFallback(
f"no published prebuilt release in {repo} matched upstream tag {normalized_requested}"
)

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

resolve_published_release and iter_resolved_published_releases share almost identical logic for resolving and validating releases. resolve_published_release can be refactored to use the iterator to reduce code duplication and improve maintainability.

def resolve_published_release(
    requested_tag: str | None,
    published_repo: str,
    published_release_tag: str = "",
) -> ResolvedPublishedRelease:
    return next(
        iter(
            iter_resolved_published_releases(
                requested_tag, published_repo, published_release_tag
            )
        )
    )

Comment on lines +2135 to +2141
published_choice: AssetChoice | None = None
if host.is_windows and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "windows-cpu")
elif host.is_macos and host.is_arm64:
published_choice = published_asset_choice_for_kind(release, "macos-arm64")
elif host.is_macos and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "macos-x64")

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

resolve_release_asset_choice does not check for Unsloth-published linux-cpu assets, falling back directly to upstream. This appears to contradict the PR's intent to prefer published platform assets when available, especially since health check logic for linux-cpu is included elsewhere in the script.

Suggested change
published_choice: AssetChoice | None = None
if host.is_windows and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "windows-cpu")
elif host.is_macos and host.is_arm64:
published_choice = published_asset_choice_for_kind(release, "macos-arm64")
elif host.is_macos and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "macos-x64")
published_choice: AssetChoice | None = None
if host.is_windows and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "windows-cpu")
elif host.is_linux and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "linux-cpu")
elif host.is_macos and host.is_arm64:
published_choice = published_asset_choice_for_kind(release, "macos-arm64")
elif host.is_macos and host.is_x86_64:
published_choice = published_asset_choice_for_kind(release, "macos-x64")

Comment on lines +3654 to +3656
return hashlib.sha256(
json.dumps(payload, sort_keys = True, separators = (",", ":")).encode("utf-8")
).hexdigest()

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 calculating the install fingerprint is duplicated between write_prebuilt_metadata and expected_install_fingerprint. This should be extracted into a shared helper function to ensure consistency and reduce maintenance overhead.

- Custom source with latest tag: skip upstream tag resolution for forks
  that may not carry bNNNN tags; use _REQUESTED_LLAMA_TAG directly
  when _LLAMA_SOURCE is not the default ggml-org repo (both .sh and .ps1)
- Add elseif guard in setup.ps1 to skip wasteful resolve-install-tag
  when custom source already forced source build (parity with setup.sh)
- Add llama-server existence check in existing_install_matches_choice
  to catch partially deleted installs with intact metadata/libraries
- Always sync git remote URL in setup.ps1 existing-checkout path so
  switching between default and fork sources works correctly
@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 enhances the llama.cpp installation and update process across Python, PowerShell, and Bash scripts. Key improvements include a more sophisticated release resolution strategy that supports falling back to older versions, the ability to build directly from GitHub Pull Requests or custom forks, and a new fingerprinting mechanism to skip redundant reinstalls. Additionally, the PR introduces robust detection for "busy" file states to prevent installation failures when llama.cpp is currently in use. My feedback focuses on refining the error-handling logic for these busy states, specifically regarding the inclusion of certain permission and file-existence errors that might be too broad or indicative of permanent configuration issues rather than transient locks.

"text file busy",
"file is in use",
"process cannot access the file",
"cannot create a file when that file already exists",

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 needle "cannot create a file when that file already exists" corresponds to Windows error ERROR_ALREADY_EXISTS (183). While this is a valid error to catch, it typically indicates a logic error or a directory conflict rather than a "busy" or "locked" state caused by another process holding a handle. Consider if this should be treated as a BusyInstallConflict or a standard PrebuiltFallback.

if exc.errno in {
errno.EACCES,
errno.EBUSY,
errno.EPERM,

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

Including errno.EPERM (Operation not permitted) in the busy check might be too broad. On Linux, EPERM usually indicates a permanent permission issue rather than a transient "busy" state. While EACCES is often returned on Windows when a file is in use, EPERM is less common for this purpose. Treating it as a busy error might lead to unnecessary retries for issues that require manual permission fixes.

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

ℹ️ 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 +245 to +250
if exc.errno in {
errno.EACCES,
errno.EBUSY,
errno.EPERM,
errno.ETXTBSY,
}:

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 Restrict busy classification to true in-use lock errors

is_busy_lock_error now classifies generic permission failures (EACCES/EPERM and any "permission denied" text) as a busy-install condition. That predicate is used by activate_install_tree to raise BusyInstallConflict, which install_prebuilt maps to exit code 3; both setup entrypoints then stop with an “active process” message. When activation fails because the install path is read-only or owned by another user (not actually in use), this misclassification gives the wrong remediation and skips the normal fallback error handling path.

Useful? React with 👍 / 👎.

- Add llama-quantize to existing_install_matches_choice health check
  alongside llama-server for more complete partial-deletion detection
- Honor UNSLOTH_LLAMA_RELEASE_TAG in all resolve steps (resolve-install-tag,
  resolve-llama-tag, and fallback) in both setup.sh and setup.ps1, so a
  pinned published release is respected even when falling back to source build
- Fix PR fetch rerun in setup.ps1: use FETCH_HEAD instead of creating a
  local branch ref that conflicts when already checked out
@danielhanchen

Copy link
Copy Markdown
Member

/gemini review

danielhanchen and others added 2 commits April 1, 2026 13:01
Superseded by runtime_payload_is_healthy + llama-server/llama-quantize
existence checks in existing_install_matches_choice. No remaining callers.

@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 enhances the llama.cpp installation process by implementing a multi-release fallback mechanism and robust detection for busy file conflicts. It introduces support for building from specific GitHub Pull Requests and custom source repositories, and improves installation health checks using metadata fingerprints. Review feedback suggests refactoring duplicated resolution logic and replacing silent exception handlers with logging to improve maintainability and debuggability.

Comment on lines +1397 to +1450
def resolve_published_release(
requested_tag: str | None,
published_repo: str,
published_release_tag: str = "",
) -> ResolvedPublishedRelease:
repo = published_repo or DEFAULT_PUBLISHED_REPO
normalized_requested = normalized_requested_llama_tag(requested_tag)

if published_release_tag:
bundle = pinned_published_release_bundle(repo, published_release_tag)
if (
normalized_requested != "latest"
and bundle.upstream_tag != normalized_requested
):
raise PrebuiltFallback(
"published release "
f"{repo}@{published_release_tag} targeted upstream tag {bundle.upstream_tag}, "
f"but requested {normalized_requested}"
)
return ResolvedPublishedRelease(
bundle = bundle,
checksums = validated_checksums_for_bundle(repo, bundle),
)

skipped_invalid = 0
for bundle in iter_published_release_bundles(repo):
if (
normalized_requested != "latest"
and bundle.upstream_tag != normalized_requested
):
continue
try:
checksums = validated_checksums_for_bundle(repo, bundle)
except PrebuiltFallback as exc:
skipped_invalid += 1
log(
"published release ignored for install resolution: "
f"{repo}@{bundle.release_tag} ({exc})"
)
continue
return ResolvedPublishedRelease(bundle = bundle, checksums = checksums)

if normalized_requested == "latest":
if skipped_invalid:
raise PrebuiltFallback(
f"no usable published llama.cpp releases were available in {repo}"
)
raise PrebuiltFallback(
f"no published llama.cpp releases were available in {repo}"
)

raise PrebuiltFallback(
f"no published prebuilt release in {repo} matched upstream tag {normalized_requested}"
)

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

There is significant code duplication between resolve_published_release and iter_resolved_published_releases. Both functions share similar logic for handling published_release_tag, iterating through release bundles, and validating them.

To improve maintainability and reduce redundancy, consider refactoring this logic. resolve_published_release could be simplified to delegate to iter_resolved_published_releases and just take the first result.

Comment on lines 1551 to 1552
except Exception:
pass

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 broad except Exception: pass here silences all errors during release resolution, which can make debugging difficult. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

Suggested change
except Exception:
pass
except Exception as exc:
log(f"failed to resolve published release for {published_repo}: {exc}")
pass
References
  1. Avoid using broad, silent exception handlers like except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging.

@danielhanchen
danielhanchen merged commit 428efc7 into unslothai:main Apr 1, 2026
1 check passed
shaneholloman pushed a commit to shaneholloman/unsloth that referenced this pull request Apr 1, 2026
…#4756)

Split out from unslothai#4741 to keep the main PR focused on installer logic.

- New test_install_llama_prebuilt_logic.py: tests for resolve logic,
  fallback behavior, env_int, busy/lock handling
- New test_validate_llama_prebuilt.py: validator tests for staged
  release_tag/upstream_tag handling
- New test_llama_pr_force_and_source.py: tests for PR_FORCE and
  LLAMA_SOURCE maintainer defaults
- Updated test_selection_logic.py: expanded selection/fallback coverage
- Updated test_pr4562_bugfixes.py: updated bugfix tests for new logic
- Updated smoke_test_llama_prebuilt.py: minor update
shibizhao pushed a commit to shibizhao/unsloth-npu that referenced this pull request Apr 7, 2026
…nned tag (unslothai#4741)

Replaces the fixed prebuilt llama.cpp tag with dynamic published-release
resolution, adds bounded fallback across older published releases, and
introduces maintainer-editable defaults for PR/source overrides.

Changes:
- Resolve latest from the latest usable published release in unslothai/llama.cpp
- Use the selected release upstream_tag as the authoritative llama.cpp version
- Prefer Unsloth-published platform assets when available
- Fall back to same-tag upstream ggml-org/llama.cpp assets where allowed
- Keep Linux CUDA anchored to Unsloth-published CUDA bundles only
- Add bounded fallback across older Unsloth published releases
- Add separate busy/in-use install handling (exit code 3)
- Skip reinstall when the installed bundle already matches the selected candidate
- Add maintainer-editable _DEFAULT_LLAMA_PR_FORCE and _DEFAULT_LLAMA_SOURCE
- Harden env parsing so malformed installer env vars do not crash import-time fallback logic
- Honor UNSLOTH_LLAMA_RELEASE_TAG in all resolve steps
- Always sync git remote URL in existing-checkout path
shibizhao pushed a commit to shibizhao/unsloth-npu that referenced this pull request Apr 7, 2026
…#4756)

Split out from unslothai#4741 to keep the main PR focused on installer logic.

- New test_install_llama_prebuilt_logic.py: tests for resolve logic,
  fallback behavior, env_int, busy/lock handling
- New test_validate_llama_prebuilt.py: validator tests for staged
  release_tag/upstream_tag handling
- New test_llama_pr_force_and_source.py: tests for PR_FORCE and
  LLAMA_SOURCE maintainer defaults
- Updated test_selection_logic.py: expanded selection/fallback coverage
- Updated test_pr4562_bugfixes.py: updated bugfix tests for new logic
- Updated smoke_test_llama_prebuilt.py: minor update
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