Skip to content

Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.

Run the Mac GGUF inference phases in the Mac UI job, not on a second runner (#9213)

Daniel Han566272b721d0
diff --git a/.github/workflows/studio-mac-inference-smoke.yml b/.github/workflows/studio-mac-inference-smoke.yml
deleted file mode 100644
index 10db2e2488a..00000000000
--- a/.github/workflows/studio-mac-inference-smoke.yml
+++ /dev/null
@@ -1,1170 +0,0 @@
-# SPDX-License-Identifier: AGPL-3.0-only
-# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved.
-
-# One end-to-end smoke job, three phases, that boots a freshly-installed
-# Unsloth and exercises the surfaces real users hit through the OpenAI /
-# Anthropic SDKs and curl. Each phase picks the smallest model that
-# exercises the behaviour under test and primes its own model cache via
-# actions/cache; all three share a single install.sh --local --no-torch.
-#
-# 1. OpenAI, Anthropic API tests
-# gemma-3-270m-it UD-Q4_K_XL (~254 MiB).
-# Password rotation via /api/auth/change-password (old fails,
-# new works), then OpenAI + Anthropic Python SDKs against /v1/*
-# with temperature=0 and a fixed seed. Asserts the four-turn
-# conversation is deterministic across two runs.
-#
-# 2. Tool calling Tests
-# Qwen3.5-2B UD-IQ3_XXS (~890 MiB). OpenAI function calling,
-# server-side tools (python, terminal, web_search) via
-# enable_tools / enabled_tools, and enable_thinking on/off.
-#
-# 3. JSON, images
-# gemma-4-E2B-it UD-IQ3_XXS (~2.4 GiB) + mmproj-F16 (~986 MiB).
-# response_format JSON-schema decoding and OpenAI image_url
-# (data URI) plus Anthropic source/base64 image inputs.
-#
-# The phases run in sequence on one runner. Wall time is dominated by
-# phase 3 on a cold cache; a warm cache cuts that phase to ~3 min. They
-# used to be three parallel jobs, which held 3 of the 5 macOS slots
-# available account-wide and repeated the same install three times.
-
-name: Mac Studio GGUF CI
-
-on:
- pull_request:
- paths:
- - 'studio/**'
- - 'unsloth/**'
- - 'unsloth_cli/**'
- - 'install.sh'
- - 'pyproject.toml'
- - '.github/workflows/studio-mac-inference-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- - '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- - '.github/scripts/wait-for-health.sh'
- # The install step in this workflow is `uses:` on that composite action,
- # so an edit to the action changes what this workflow actually runs.
- - '.github/actions/install-unsloth-local/action.yml'
- # Executed directly by this workflow: the load assertion, every model
- # download, and the multi-turn chat driver. A change to any of them changes
- # what this workflow actually runs.
- - '.github/scripts/assert-llama-loads.sh'
- - '.github/scripts/hf-download-with-retry.sh'
- - '.github/scripts/studio_smoke/multi_turn_chat.py'
- push:
- branches: [main]
- # Same list as the PR filter. Without it this workflow ran on EVERY commit to
- # main: a README-only commit fired all four unfiltered macOS workflows, seven
- # macOS legs, against an account-wide cap of five concurrent macOS jobs. The
- # post-merge backstop is unchanged, because a commit that cannot touch what
- # this workflow tests has nothing here to back up.
- # clean-machine-install-ci.yml and mlx-ci.yml already do exactly this.
- paths:
- - 'studio/**'
- - 'unsloth/**'
- - 'unsloth_cli/**'
- - 'install.sh'
- - 'pyproject.toml'
- - '.github/workflows/studio-mac-inference-smoke.yml'
- # Every server boot in this workflow shells out to that script, so an edit
- # to it changes what this workflow actually runs.
- - '.github/scripts/boot-studio-api-only.sh'
- # Same for the /api/health wait that runs after a boot.
- - '.github/scripts/wait-for-health.sh'
- # The install step in this workflow is `uses:` on that composite action,
- # so an edit to the action changes what this workflow actually runs.
- - '.github/actions/install-unsloth-local/action.yml'
- # Executed directly by this workflow: the load assertion, every model
- # download, and the multi-turn chat driver. A change to any of them changes
- # what this workflow actually runs.
- - '.github/scripts/assert-llama-loads.sh'
- - '.github/scripts/hf-download-with-retry.sh'
- - '.github/scripts/studio_smoke/multi_turn_chat.py'
- # Manual trigger for pre-warming model caches on main, or re-running
- # against an arbitrary branch without pushing a no-op commit.
- workflow_dispatch:
-
-concurrency:
- group: ${{ github.workflow }}-${{ github.ref }}-${{ github.ref == 'refs/heads/main' && github.sha || '' }}
- # Latest-only on a PR branch. On main this does less than it reads like: it stops
- # a RUNNING main job being killed, but GitHub cancels any PENDING run in the group
- # the moment a newer one is queued, so a merge burst still leaves only the tip.
- # See studio-backend-ci.yml, which is grouped per commit on main for that reason.
- cancel-in-progress: ${{ github.ref != 'refs/heads/main' }}
-
-permissions:
- contents: read
-
-jobs:
- # One job, three phases. These were three separate macOS jobs that differed
- # only in model, port and test body: the checkout, setup-node, setup-python,
- # `install.sh --local --no-torch` and assert-llama-loads.sh preamble was
- # byte-identical in all three, so every triggering PR did the same install on
- # three macOS runners at once. Concurrent macOS jobs are capped at 5 per
- # account (shared with unslothai/unsloth-zoo), so that burst took 3 of the 5
- # slots to re-derive the same install twice.
- #
- # The phases now share one install. Each keeps its own model cache, server
- # port, server log, uploaded artifact and step timeouts, and each is gated on
- # the shared preamble rather than on the phase before it, so a failure still
- # points at one phase, the logs of the earlier phases survive it, and the
- # later phases still run -- the same independence the three jobs had.
- inference-smoke:
- name: GGUF inference smoke (API, tools, vision)
- runs-on: macos-15
- # Was 25 for the first phase alone; the three were 25 + 25 + 30 across three
- # runners. Sequentially they share one install, so the sum is less than 80,
- # but a cold model cache on the vision phase is the slow case. 90 covers it
- # without letting a hang sit for hours on one of the 5 macOS slots.
- #
- # 90 is the outer guard only. Every step that can block also carries its own
- # `timeout-minutes`, because the job cap alone is not a substitute for the
- # 25/25/30 caps the three jobs used to have: hf-download-with-retry.sh
- # retries forever by design and named the job timeout as its bound, so
- # without step caps one stalled download would hold a macOS slot for the
- # full 90 minutes and starve the phases behind it.
- timeout-minutes: 90
- env:
- # Only what every phase shares. Model, GGUF file and port are set per
- # phase via $GITHUB_ENV instead of here: if a phase-specific key were also
- # declared at job level, whether the later $GITHUB_ENV write wins is not
- # something the Actions docs pin down, and a phase silently talking to the
- # previous phase's port would be a nasty way to find out.
- HF_HOME: ${{ github.workspace }}/hf-cache
- # GitHub's macOS runners expose a PARAVIRTUAL Metal device, and Unsloth refuses to
- # offload to it because paravirtual Apple GPUs return corrupt output. Every phase
- # here therefore launches with `--gpu-layers 0 --device none`, which puts the WHOLE
- # model in host RAM rather than the partial spill the host-offload guard was written
- # for. #8883 prices that correctly and declines the load:
- #
- # "About 3 GB of this model does not fit in GPU memory and would run from system
- # RAM. Only about 4 GB is available and 2 GB of that is kept free for the rest of
- # the system, leaving about 2 GB usable."
- #
- # The guard is right: the runner cannot host gemma-4-E2B UD-Q4_K_XL (~2.4 GB) plus
- # mmproj-F16 (~780 MB) in 2 GB. This job ran green for weeks before the guard existed
- # because the prompts are tiny and the mapping is paged -- which is exactly the
- # gamble the guard stops taking on a user's machine. Here we take it knowingly. The
- # alternative is silently swapping the model this phase covers for a smaller one,
- # which changes what mac vision inference is tested against.
- #
- # Job-level, not on the vision phase alone: every phase is CPU-only for the same
- # reason, so a runner image with a little less free RAM takes out the tool-calling
- # phase next. Set on the job so each booted server inherits it.
- #
- # This removes no coverage of the guard itself, which is tested in
- # studio/backend/tests/test_host_offload_ram_guard.py and test_llama_cpp_placement.py.
- UNSLOTH_ALLOW_HOST_OFFLOAD: '1'
- steps:
- - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
- with:
- persist-credentials: false
-
- - uses: actions/setup-node@820762786026740c76f36085b0efc47a31fe5020 # v7.0.0
- with:
- node-version: '22'
-
- - uses: actions/setup-python@5fda3b95a4ea91299a34e894583c3862153e4b97 # v7.0.0
- with:
- python-version: '3.12'
-
-
- # Shared preamble, but it sits below phase 1's model priming because the
- # install probe (stories260K) rides along in that same step. `!cancelled()`
- # Deliberately NO `if:`, so this rides the implicit success(). Nothing
- # phase-local runs before it any more, so the only thing the implicit check
- # can see is a genuine shared-preamble failure -- checkout, setup-node or
- # setup-python -- and those SHOULD stop the job rather than install onto a
- # runner that never got its pinned toolchain.
- - name: Install Unsloth (--local, --no-torch)
- id: install
- timeout-minutes: 20
- uses: ./.github/actions/install-unsloth-local
- with:
- gh-token: ${{ secrets.GITHUB_TOKEN }}
- # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
- hf-token: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
-
- # Last step of the shared preamble. Phases 2 and 3 gate on its outcome:
- # once checkout, install and this check have passed, a failure inside one
- # phase says nothing about the others, so the others should still run.
- # Gates on `install` explicitly rather than on the implicit `success()` so
- # that it keeps holding if a phase-local step is ever moved back above it.
- # A broken install still skips this step, so its outcome stays non-success
- # and the phases below correctly stay out.
- - name: Assert llama.cpp loads on this macOS
- id: assert-llama
- if: ${{ !cancelled() && steps.install.outcome == 'success' }}
- timeout-minutes: 5
- run: bash .github/scripts/assert-llama-loads.sh
-
- # Phase 1's environment and model cache sit HERE, after the shared preamble,
- # not before it. Ordering them first was what forced the installer onto an
- # explicit `!cancelled()`: a phase-1 GGUF download failure would otherwise
- # skip the install under the implicit success() and take phases 2 and 3
- # down with it. That gate bought phase independence at the cost of running
- # the installer on a runner whose setup-node or setup-python had failed.
- # Moving the block is strictly better than either gate, because it makes
- # the two failure classes structural: everything above is genuinely
- # shared, everything from here down is phase 1's own.
- - name: Phase 1 environment
- run: |
- echo "GGUF_REPO=unsloth/gemma-3-270m-it-GGUF" >> "$GITHUB_ENV"
- echo "GGUF_VARIANT=UD-Q4_K_XL" >> "$GITHUB_ENV"
- echo "GGUF_FILE=gemma-3-270m-it-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
- echo "STUDIO_PORT=18888" >> "$GITHUB_ENV"
-
- # Cross-OS shared entry. The tree under `hf-cache` is byte-identical on
- # Linux, macOS and Windows, so the key carries no `runner.os`, and
- # enableCrossOsArchive lets Windows (which tars with --force-local) join it.
- - name: Restore HF_HOME for unsloth/gemma-3-270m-it-GGUF
- id: cache-hf
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- continue-on-error: true
- timeout-minutes: 15
- with:
- path: hf-cache
- key: hf-unsloth/gemma-3-270m-it-GGUF-UD-Q4_K_XL-v3
- enableCrossOsArchive: true
-
- - name: Prime HF_HOME with the GGUF
- id: prime-hf
- if: steps.cache-hf.outputs.cache-hit != 'true' || steps.cache-hf.outcome != 'success'
- timeout-minutes: 15
- env:
- # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
- HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- run: |
- python -m pip install --upgrade huggingface_hub
- mkdir -p hf-cache
- bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE"
- bash .github/scripts/hf-download-with-retry.sh ggml-org/models tinyllamas/stories260K.gguf
-
- # Save partial caches on cancel/timeout -- hf download resumes by
- # content hash. `outcome != skipped` keeps cache-hit a no-op.
- - name: Save HF_HOME for unsloth/gemma-3-270m-it-GGUF
- # Save on main only. Caches created on a PR ref are scoped to that
- # merge ref -- per GitHub's docs they "can only be restored by re-runs
- # of the pull request" -- while every PR *can* restore from the default
- # branch. So a PR-scoped save helps almost nothing and competes for the
- # per-repo cache budget, and when that budget is exceeded GitHub evicts
- # by least-recently-used, which deletes main's copies that all PRs share.
- # This repo's budget is 50 GiB, not GitHub's 10GB default, and it was
- # measured at 49.63 GiB across 258 entries -- 99.3% full, so eviction runs
- # at the margin. 20.74 GiB of that (42%) is the SAME key held on several
- # refs, and every one of those keys already has a copy on main, so the
- # PR-scoped duplicates are redundant by construction. That is the thrash
- # loop: PR misses -> downloads -> saves its own copy -> evicts main's ->
- # next PR misses.
- if: always() && github.ref == 'refs/heads/main' && steps.prime-hf.outcome != 'skipped' && hashFiles('hf-cache/**/*.gguf') != ''
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- timeout-minutes: 15
- with:
- path: hf-cache
- key: hf-unsloth/gemma-3-270m-it-GGUF-UD-Q4_K_XL-v3
- enableCrossOsArchive: true
- - name: Install OpenAI + Anthropic Python SDKs
- timeout-minutes: 5
- run: pip install 'openai>=1.50' 'anthropic>=0.40'
-
- - name: Reset auth + boot Unsloth (API-only)
- timeout-minutes: 2
- run: |
- # Wipe (not reset-password): the boot below must re-seed a fresh .bootstrap_password.
- bash .github/scripts/boot-studio-api-only.sh --port "$STUDIO_PORT"
-
- - name: Wait for /api/health
- timeout-minutes: 5
- run: |
- bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT"
-
- - name: Password rotation (old must fail, new must work)
- timeout-minutes: 3
- run: |
- OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
- NEW="CIRotated-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
- echo "::add-mask::$OLD"
- echo "::add-mask::$NEW"
- # 1. Login with the bootstrap password.
- OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
- [ -n "$OLD_TOKEN" ] && [ "$OLD_TOKEN" != "null" ] || { echo "bootstrap login failed"; exit 1; }
- # 2. Rotate to a fresh random password.
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
- -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
- -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
- # 3. Old password must now be rejected (HTTP 401).
- OLD_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
- -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}")
- if [ "$OLD_STATUS" != "401" ]; then
- echo "::error::Login with old password returned $OLD_STATUS, expected 401"
- exit 1
- fi
- # 4. New password must succeed; capture the JWT for downstream steps.
- NEW_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
- [ -n "$NEW_TOKEN" ] && [ "$NEW_TOKEN" != "null" ] || { echo "new login failed"; exit 1; }
- echo "TOKEN=$NEW_TOKEN" >> "$GITHUB_ENV"
- echo "password rotation OK (old=401, new=200)"
-
- - name: Load the GGUF (HF repo + variant, served from HF_HOME cache)
- # curl already caps itself at --max-time 600; +2 for process overhead.
- timeout-minutes: 12
- run: |
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
- -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
- --max-time 600 \
- -d "{\"model_path\":\"$GGUF_REPO\",\"gguf_variant\":\"$GGUF_VARIANT\",\"is_lora\":false,\"max_seq_length\":2048}" \
- | jq '{status, display_name, is_gguf, context_length}'
-
- - name: Multi-turn determinism via OpenAI + Anthropic SDKs
- timeout-minutes: 15
- env:
- BASE_URL: http://127.0.0.1:18888
- run: |
- python3 .github/scripts/studio_smoke/multi_turn_chat.py
-
- - name: Stop Unsloth
- if: always()
- run: |
- kill "${STUDIO_PID}" 2>/dev/null || true
- sleep 2
- ss -tln | grep ":${STUDIO_PORT}" || true
-
- - name: Upload logs
- # Always upload so green runs are still reviewable.
- if: always()
- # Diagnostic only: a transient artifact-service drop must not fail a green job.
- continue-on-error: true
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- with:
- name: openai-anthropic-log
- path: |
- logs/studio.log
- logs/install.log
- retention-days: 7
-
- # ==============================================================
- # Phase 2: tool calling + server-side tools.
- # Reuses the install and llama.cpp check done once above rather than
- # repeating them on a second runner. Ids, cache dir and server log are
- # suffixed -tools so the phases cannot collide inside one job.
- #
- # Every step below carries the same `if:`. A step with no `if:` gets an
- # implicit `success()`, which is job-wide rather than per-step, so a
- # single failed phase-1 step would otherwise skip phases 2 and 3
- # outright -- exactly the coverage the three independent jobs used to
- # give us when one of them went red. `!cancelled()` runs the phase after
- # a phase-1 failure while still honouring a cancel, and the
- # assert-llama gate keeps it from running when the SHARED preamble
- # broke (a failed checkout or install skips assert-llama, so its outcome
- # is not 'success' and phases 2 and 3 correctly stay out). The job still
- # ends red, because the failed phase-1 step already set the job status.
- # ==============================================================
- - name: Phase 2 environment
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' }}
- run: |
- echo "GGUF_REPO=unsloth/Qwen3.5-2B-GGUF" >> "$GITHUB_ENV"
- echo "GGUF_FILE=Qwen3.5-2B-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
- echo "STUDIO_PORT=18898" >> "$GITHUB_ENV"
-
- # Cross-OS shared entry with the Linux tool-calling job in
- # studio-inference-smoke.yml: same repo, same file, same flat
- # --local-dir payload, byte-identical on all three runners. The key
- # therefore carries no `runner.os`, and enableCrossOsArchive is what
- # lets Windows -- which tars with --force-local -- join it.
- #
- # The suffix is bumped v2 -> v3 because the Linux side moves its
- # directory to gguf-cache-tools in the same commit, and that is not
- # cosmetic: actions/cache identifies an entry by key AND a version hash
- # derived from the `path` input, while key uniqueness is global per ref.
- # Move the path without bumping the key and the restore misses on
- # version while the save is refused with "Unable to reserve cache with
- # key ... another job may be creating this cache" -- measured on staging
- # during the Mac consolidation: two consecutive runs both logged "Cache
- # not found for input keys" and both failed to save.
- - name: Restore GGUF model file
- id: cache-gguf-tools
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' }}
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- continue-on-error: true
- timeout-minutes: 15
- with:
- path: gguf-cache-tools
- key: gguf-unsloth/Qwen3.5-2B-GGUF-Qwen3.5-2B-UD-Q4_K_XL.gguf-v3
- enableCrossOsArchive: true
-
- - name: Download GGUF if cache miss
- id: download-gguf-tools
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && (steps.cache-gguf-tools.outputs.cache-hit != 'true' || steps.cache-gguf-tools.outcome != 'success') }}
- # hf-download-with-retry.sh retries forever; this is its real bound.
- timeout-minutes: 20
- env:
- # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
- HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- run: |
- python -m pip install --upgrade huggingface_hub
- mkdir -p gguf-cache-tools
- bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache-tools
-
- # Save partial caches on cancel; next run resumes via content hash.
- - name: Save GGUF model file
- if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-tools.outcome != 'skipped' && hashFiles('gguf-cache-tools/**/*.gguf') != ''
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- timeout-minutes: 15
- with:
- path: gguf-cache-tools
- key: gguf-unsloth/Qwen3.5-2B-GGUF-Qwen3.5-2B-UD-Q4_K_XL.gguf-v3
- enableCrossOsArchive: true
-
- - name: Reset auth + boot Unsloth (API-only, default tool policy)
- id: boot-tools
- # Phase-local prerequisite on top of the shared gate. The phase stays
- # independent of EARLIER phases, which is what the shared assert-llama
- # gate buys, but it is not independent of its own download: without this
- # clause a failed download still boots a server with no model and runs
- # the test against it. `!= 'failure'` and not `== 'success'`, because a
- # cache hit skips the download.
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.download-gguf-tools.outcome != 'failure' }}
- timeout-minutes: 2
- # We deliberately use the API-only mode rather than
- # `unsloth studio run` because the latter calls
- # `set_tool_policy(...)` with a resolved bool: on loopback the
- # default resolves to True, which forces every request through
- # the server-side agentic loop and breaks the standard
- # function-calling test below. API-only mode leaves
- # tool_policy=None so each request's `enable_tools` field is
- # honoured.
- run: |
- bash .github/scripts/boot-studio-api-only.sh \
- --port "$STUDIO_PORT" --log logs/studio_tools.log
-
- - name: Wait for /api/health, log in, change password, load model
- id: ready-tools
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.boot-tools.outcome == 'success' }}
- # 180s health wait + curl's own --max-time 600, with headroom.
- timeout-minutes: 15
- run: |
- for i in $(seq 1 180); do
- if curl -fs "http://127.0.0.1:${STUDIO_PORT}/api/health" > /tmp/health.json; then
- jq -e '.status == "healthy"' /tmp/health.json && break
- fi
- sleep 1
- done
- jq -e '.status == "healthy"' /tmp/health.json
- OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
- NEW="CITool-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
- echo "::add-mask::$OLD"
- echo "::add-mask::$NEW"
- OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
- -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
- -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
- TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
- echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- GGUF_PATH="$GITHUB_WORKSPACE/gguf-cache-tools/${GGUF_FILE}"
- ls -lh "$GGUF_PATH"
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
- -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
- --max-time 600 \
- -d "{\"model_path\":\"$GGUF_PATH\",\"is_lora\":false,\"max_seq_length\":2048}" \
- | jq '{status, display_name}'
-
- - name: Tool calling, server-side tools, thinking on/off
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.ready-tools.outcome == 'success' }}
- timeout-minutes: 20
- env:
- BASE_URL: http://127.0.0.1:18898
- run: |
- python - <<'PY'
- import json
- import os
- import time
- import urllib.error
- import urllib.request
-
- BASE = os.environ["BASE_URL"]
- KEY = os.environ["API_KEY"]
- SEED = 3407
-
- def post(path, body, *, timeout = 240):
- """Plain JSON POST. For requests that don't go through
- the server-side agentic loop, the response is one JSON
- object."""
- data = json.dumps(body).encode()
- req = urllib.request.Request(
- f"{BASE}{path}",
- data = data,
- method = "POST",
- headers = {
- "Authorization": f"Bearer {KEY}",
- "Content-Type": "application/json",
- },
- )
- # Shared CI runners stall sporadically, so retry transport-level
- # failures only; HTTP status errors surface immediately. Bounded
- # to fit the job's timeout-minutes: short probes get 3 full
- # attempts, long probes one retry capped at 300s (a healthy
- # server answers a retry quickly; a stalled one never does).
- attempts = 3 if timeout <= 300 else 2
- for attempt in range(attempts):
- try:
- t = timeout if attempt == 0 else min(timeout, 300)
- with urllib.request.urlopen(req, timeout = t) as resp:
- return resp.status, json.loads(resp.read().decode())
- except urllib.error.HTTPError:
- raise
- except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
- if attempt == attempts - 1:
- raise
- print(f"[retry] {path}: {exc!r}", flush = True)
- time.sleep(15)
-
- def post_sse(path, body, *, timeout = 600, retries = 1, soft = False):
- """POST a streaming request and accumulate the assistant
- text deltas. The server-side agentic loop ALWAYS returns
- SSE regardless of the request's `stream` field, so any
- call with enable_tools=true must use this helper.
-
- A shared CI runner can stall the stream transport (the
- connection opening, or a mid-stream read) even when Unsloth
- is healthy, so harden the read three ways: retry a stall
- once with a fresh request capped at 300s; return any text
- already streamed before a stall (a stall on the trailing
- tokens, after the answer arrived, still counts); and when
- every attempt yields nothing, a hard call re-raises while a
- soft call (the best-effort server-side tool probes) returns
- None so the caller can WARN instead of sinking the whole
- job. HTTP status errors always surface immediately."""
- body = {**body, "stream": True}
- data = json.dumps(body).encode()
- req = urllib.request.Request(
- f"{BASE}{path}",
- data = data,
- method = "POST",
- headers = {
- "Authorization": f"Bearer {KEY}",
- "Content-Type": "application/json",
- },
- )
- for attempt in range(retries + 1):
- parts = []
- t = timeout if attempt == 0 else min(timeout, 300)
- try:
- with urllib.request.urlopen(req, timeout = t) as resp:
- for raw in resp:
- line = raw.decode().strip()
- if not line.startswith("data: "):
- continue
- payload = line[6:]
- if payload == "[DONE]":
- break
- try:
- chunk = json.loads(payload)
- except json.JSONDecodeError:
- continue
- for choice in chunk.get("choices", []):
- delta = choice.get("delta", {}) or {}
- if delta.get("content"):
- parts.append(delta["content"])
- return "".join(parts)
- except urllib.error.HTTPError:
- raise
- except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
- # Text already streamed is a valid signal -- keep it
- # rather than re-running a heavy generation.
- if parts:
- joined = "".join(parts)
- print(f"[retry-sse] {path}: {exc!r}; keeping {len(joined)} partial chars", flush = True)
- return joined
- if attempt == retries:
- if soft:
- print(f"[tools] WARN {path}: SSE transport stalled with no data ({exc!r}) -- non-blocking", flush = True)
- return None
- raise
- print(f"[retry-sse] {path}: {exc!r}", flush = True)
- time.sleep(15)
-
- # ── 1. Standard OpenAI function calling ──────────────────────
- weather_tool = {
- "type": "function",
- "function": {
- "name": "get_weather",
- "description": "Get current weather for a city.",
- "parameters": {
- "type": "object",
- "properties": {"city": {"type": "string"}},
- "required": ["city"],
- },
- },
- }
-
- # Mac Metal at temperature=0 is pathological for these small
- # quants (Qwen3.5-2B emits ',,,,,,...' or 'The The The...'),
- # gemma-4-E2B emits '<unused5>' tokens). The Linux CPU
- # backend hides the issue. Use a small non-zero temperature
- # with a fixed seed so we stay deterministic but escape the
- # degenerate sampling trap.
- TEMP = 0.2
-
- status, data = post("/v1/chat/completions", {
- "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
- "tools": [weather_tool],
- "tool_choice": "required",
- "stream": False,
- "temperature": TEMP,
- "seed": SEED,
- # tool_choice='required' constrains the grammar so the
- # model emits a tool_call quickly when it works at all;
- # 128 tokens is enough for `{"city":"Paris"}` plus the
- # JSON envelope.
- "max_tokens": 128,
- }, timeout = 180)
- assert status == 200, f"tool call status {status}: {data}"
- choice = data["choices"][0]
- tool_calls = (choice.get("message") or {}).get("tool_calls") or []
- # Unsloth's contract: when tool_choice='required', llama.cpp's
- # grammar should force a tool_calls payload. On Mac that
- # contract is sometimes broken by the underlying quant; the
- # PASS path is "tool_calls present + correct schema", the
- # WARN path documents Unsloth still returned 200 with a
- # well-formed choices[] envelope.
- if tool_calls:
- tc = tool_calls[0]
- assert tc["function"]["name"] == "get_weather", (
- f"unexpected tool name: {tc['function']['name']!r}"
- )
- args = json.loads(tc["function"]["arguments"])
- assert args.get("city"), f"missing city arg: {args}"
- print(f"[tools] PASS function calling -> {tc['function']['name']}({args}) finish={choice.get('finish_reason')!r}")
- else:
- # Infrastructure path is correct; model output drifted.
- print(
- f"[tools] WARN function calling: no tool_calls (finish_reason="
- f"{choice.get('finish_reason')!r}); HTTP path OK, this is a "
- f"Mac Metal quant degeneracy."
- )
-
- # ── 2. Server-side python tool ───────────────────────────────
- # 123 * 456 = 56088. The agentic loop streams SSE; we
- # accumulate the assistant text and look for the answer. On
- # Mac the model often loses the tool calling contract before
- # producing the answer; accept either the answer OR a
- # non-empty SSE stream as proof the path completes.
- # macOS free runner is ~10 tok/s on Qwen3.5-2B Q4_K_XL;
- # cap max_tokens tightly so each SSE round stays under ~30s
- # even when the model stalls in a degenerate output state.
- # retries=0 on the best-effort probes: this step's 20-minute cap
- # also has to cover the thinking checks, so a no-data stall must be a
- # single 180s attempt (not 180+15+180s) to leave room for the
- # thinking checks. A soft/best-effort probe only WARNs anyway.
- content = post_sse("/v1/chat/completions", {
- "messages": [{"role": "user", "content": "What is 123 * 456? Use the python tool to compute it and tell me the number."}],
- "enable_tools": True,
- "permission_mode": "full",
- "enabled_tools": ["python"],
- "session_id": "ci-tool-calling-py",
- "temperature": TEMP,
- "seed": SEED,
- "max_tokens": 128,
- }, timeout = 180, retries = 0, soft = True)
- if content is None:
- print("[tools] WARN python tool: SSE transport stalled after retries -- non-blocking")
- elif "56088" in content or "56,088" in content:
- print(f"[tools] PASS python tool ({len(content)} chars, found 56088)")
- else:
- # Empty stream is a known Mac-quant degeneracy too; log
- # but do not fail.
- print(
- f"[tools] WARN python tool: SSE OK ({len(content)} chars) but "
- f"model didn't return 56088 -- Mac quant drift"
- )
-
- # NOTE: the dedicated "Server-side bash (terminal) tool" axis
- # was dropped in favour of the python axis above. Both share
- # the SAME server-side agentic loop wiring (only the registry
- # entry differs); the python axis is the canonical proof. On
- # macOS the duplicated SSE round was the dominant cost in
- # this step, so collapsing the two saves ~30-60 s wallclock
- # without losing distinct coverage.
-
- # ── 3. Server-side web_search tool ───────────────────────────
- # DuckDuckGo is flaky from CI runners and small Qwen3.5-2B
- # may not actually search. Only assert that the SSE stream
- # opens and yields any data; HTTP / parser failures already
- # raise above.
- try:
- content = post_sse("/v1/chat/completions", {
- "messages": [{"role": "user", "content": "Search the web for 'unsloth ai github' and summarise."}],
- "enable_tools": True,
- "permission_mode": "full",
- "enabled_tools": ["web_search"],
- "session_id": "ci-tool-calling-web",
- "temperature": TEMP,
- "seed": SEED,
- "max_tokens": 96,
- }, timeout = 180, retries = 0)
- print(f"[tools] PASS web_search stream ({len(content)} chars)")
- except Exception as exc:
- print(f"[tools] WARN web_search probe failed (non-blocking): {exc}")
-
- # ── 4. Thinking on / off ─────────────────────────────────────
- # Unsloth strips think blocks from message.content for tools-mode
- # responses, so we toggle plain chat (no enable_tools) and look
- # at the surfaced reasoning_content / message.thinking field.
- def thinking_call(enable):
- status, data = post("/v1/chat/completions", {
- "messages": [{"role": "user", "content": "Briefly: is 17 prime?"}],
- "stream": False,
- "enable_thinking": enable,
- "temperature": TEMP,
- "seed": SEED,
- # 80 tokens lands within this step's 20-minute cap
- # on the macOS free runner. 17 is small; this is
- # plenty of room for either "Yes" + brief reasoning
- # or a degenerate empty completion.
- "max_tokens": 80,
- }, timeout = 180)
- assert status == 200
- msg = data["choices"][0]["message"]
- # Unsloth surfaces thinking via reasoning_content (OpenAI
- # extension). Fall back to inline <think> markers for
- # robustness across template versions.
- raw = (msg.get("content") or "") + (msg.get("reasoning_content") or "")
- return raw
-
- on_text = thinking_call(True)
- off_text = thinking_call(False)
- # Mac quant drift: the model may produce empty / degenerate
- # output regardless of enable_thinking. Assert ONLY that the
- # endpoint returned 200 (already enforced inside thinking_call)
- # and that toggling the flag doesn't surface a hard <think>
- # marker when off.
- had_think_on = ("<think>" in on_text) or len(on_text) > 80
- if not had_think_on:
- print(
- f"[tools] WARN enable_thinking=True produced no thinking signal: "
- f"{on_text[:200]!r} -- Mac quant drift"
- )
- # Off-mode should not contain the literal <think> marker.
- assert "<think>" not in off_text, (
- f"enable_thinking=False but <think> still present: {off_text!r}"
- )
- print(f"[tools] PASS thinking on/off (on={len(on_text)} chars, off={len(off_text)} chars)")
- PY
-
- - name: Stop Unsloth
- if: always()
- run: |
- kill "${STUDIO_PID}" 2>/dev/null || true
- sleep 2
- ss -tln | grep ":${STUDIO_PORT}" || true
-
- - name: Upload logs
- # Always upload so green runs are still reviewable.
- if: always()
- # Diagnostic only: a transient artifact-service drop must not fail a green job.
- continue-on-error: true
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- with:
- name: tool-calling-log
- path: |
- logs/studio_tools.log
- logs/install.log
- retention-days: 1
-
- # ==============================================================
- # Phase 3: JSON schema decoding + image input.
- # Reuses the install and llama.cpp check done once above rather than
- # repeating them on a second runner. Ids, cache dir and server log are
- # suffixed -vision so the phases cannot collide inside one job.
- # Same `if:` as phase 2, for the same reason: a phase-1 or phase-2
- # failure must not silently skip this phase's coverage.
- # ==============================================================
- - name: Phase 3 environment
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' }}
- run: |
- echo "GGUF_REPO=unsloth/gemma-4-E2B-it-GGUF" >> "$GITHUB_ENV"
- echo "GGUF_VARIANT=UD-Q4_K_XL" >> "$GITHUB_ENV"
- echo "GGUF_FILE=gemma-4-E2B-it-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
- echo "MMPROJ_FILE=mmproj-F16.gguf" >> "$GITHUB_ENV"
- echo "STUDIO_PORT=18899" >> "$GITHUB_ENV"
-
- - name: Restore GGUF + mmproj files
- id: cache-gguf-vision
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' }}
- uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- continue-on-error: true
- timeout-minutes: 20
- with:
- path: gguf-cache-vision
- key: ${{ runner.os }}-gguf-unsloth/gemma-4-E2B-it-GGUF-gemma-4-E2B-it-UD-Q4_K_XL.gguf-mmproj-F16.gguf-v3
-
- - name: Verify cache contains BOTH gguf + mmproj
- id: verify-cache
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.cache-gguf-vision.outputs.cache-hit == 'true' }}
- run: |
- if [[ -f "gguf-cache-vision/$GGUF_FILE" && -f "gguf-cache-vision/$MMPROJ_FILE" ]]; then
- echo "ok=true" >> "$GITHUB_OUTPUT"
- else
- echo "Partial cache hit -- forcing re-download."
- echo "ok=false" >> "$GITHUB_OUTPUT"
- fi
-
- - name: Download GGUF + mmproj if cache miss or partial
- id: download-gguf-vision
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && (steps.cache-gguf-vision.outputs.cache-hit != 'true' || steps.verify-cache.outputs.ok != 'true') }}
- # Authenticated + parallel: shared macOS NAT egress stalls
- # multi-GB anonymous downloads. hf-download-with-retry.sh retries
- # forever, so this cap is what actually bounds a permanent stall --
- # 30 matches the old json-images job timeout, the slowest of the three.
- timeout-minutes: 30
- env:
- # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
- HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
- run: |
- python -m pip install --upgrade huggingface_hub
- mkdir -p gguf-cache-vision
- bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache-vision &
- MODEL_PID=$!
- bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$MMPROJ_FILE" gguf-cache-vision &
- MMPROJ_PID=$!
- wait "$MODEL_PID"
- wait "$MMPROJ_PID"
- # Fail loud on a partial download instead of in the next step.
- ls -lh "gguf-cache-vision/$GGUF_FILE" "gguf-cache-vision/$MMPROJ_FILE"
-
- # Save partial caches on cancel. hashFiles guard avoids a hard
- # save failure when the download step exits with no files. The
- # additional mmproj-presence check stops a partial save from
- # poisoning the cache for the next run.
-
- - name: Save GGUF + mmproj files
- if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-vision.outcome != 'skipped' && hashFiles('gguf-cache-vision/**/*.gguf') != '' && hashFiles(format('gguf-cache-vision/{0}', 'mmproj-F16.gguf')) != ''
- uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
- timeout-minutes: 20
- with:
- path: gguf-cache-vision
- key: ${{ runner.os }}-gguf-unsloth/gemma-4-E2B-it-GGUF-gemma-4-E2B-it-UD-Q4_K_XL.gguf-mmproj-F16.gguf-v3
-
- - name: Install OpenAI + Anthropic Python SDKs
- id: sdks-vision
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' }}
- timeout-minutes: 5
- run: pip install 'openai>=1.50' 'anthropic>=0.40'
-
- - name: Reset auth + boot Unsloth (API-only)
- id: boot-vision
- # Same phase-local prerequisite as phase 2. The SDK clause is here and
- # not in phase 2 because only this phase imports openai/anthropic.
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.sdks-vision.outcome == 'success' && steps.download-gguf-vision.outcome != 'failure' }}
- timeout-minutes: 2
- # See phase 2's comment: API-only mode keeps tool_policy=None so
- # response_format requests aren't routed through the agentic
- # tool loop.
- run: |
- bash .github/scripts/boot-studio-api-only.sh \
- --port "$STUDIO_PORT" --log logs/studio_vision.log
-
- - name: Wait for /api/health, log in, change password, load model
- id: ready-vision
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.boot-vision.outcome == 'success' }}
- # 180s health wait + curl's own --max-time 900, with headroom.
- timeout-minutes: 20
- run: |
- for i in $(seq 1 180); do
- if curl -fs "http://127.0.0.1:${STUDIO_PORT}/api/health" > /tmp/health.json; then
- jq -e '.status == "healthy"' /tmp/health.json && break
- fi
- sleep 1
- done
- jq -e '.status == "healthy"' /tmp/health.json
- OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
- NEW="CIJson-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
- echo "::add-mask::$OLD"
- echo "::add-mask::$NEW"
- OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
- -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
- -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
- TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
- -H 'content-type: application/json' \
- -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
- echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
- # Load via local file path; mmproj sibling auto-detected by
- # detect_mmproj_file (model_config.py). gguf_variant omitted
- # -- it routes through _find_local_gguf_by_variant which
- # expects a directory, not a file path.
- GGUF_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${GGUF_FILE}"
- MMPROJ_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${MMPROJ_FILE}"
- ls -lh "$GGUF_PATH" "$MMPROJ_PATH"
- curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
- -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
- --max-time 900 \
- -d "{\"model_path\":\"$GGUF_PATH\",\"is_lora\":false,\"max_seq_length\":2048}" \
- | jq '{status, display_name, is_vision}'
-
- - name: JSON schema decoding + image input
- if: ${{ !cancelled() && steps.assert-llama.outcome == 'success' && steps.ready-vision.outcome == 'success' }}
- timeout-minutes: 20
- env:
- BASE_URL: http://127.0.0.1:18899
- run: |
- python - <<'PY'
- import base64
- import json
- import os
- import time
- import urllib.error
- import urllib.request
- from openai import OpenAI
- from anthropic import Anthropic
-
- BASE = os.environ["BASE_URL"]
- KEY = os.environ["API_KEY"]
- SEED = 3407
- # Mac Metal degenerates these gemma-4 quants at temperature=0
- # (any prompt yields '<unused5>...' padding tokens). Use a
- # small non-zero temperature with the same seed so we stay
- # deterministic-enough but escape the trap.
- TEMP = 0.2
-
- def post(path, body, *, timeout = 240):
- req = urllib.request.Request(
- f"{BASE}{path}",
- data = json.dumps(body).encode(),
- method = "POST",
- headers = {
- "Authorization": f"Bearer {KEY}",
- "Content-Type": "application/json",
- },
- )
- # Shared CI runners stall sporadically, so retry transport-level
- # failures only; HTTP status errors surface immediately. Bounded
- # to fit the job's timeout-minutes: short probes get 3 full
- # attempts, long probes one retry capped at 300s (a healthy
- # server answers a retry quickly; a stalled one never does).
- attempts = 3 if timeout <= 300 else 2
- for attempt in range(attempts):
- try:
- t = timeout if attempt == 0 else min(timeout, 300)
- with urllib.request.urlopen(req, timeout = t) as resp:
- return resp.status, json.loads(resp.read().decode())
- except urllib.error.HTTPError:
- raise
- except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
- if attempt == attempts - 1:
- raise
- print(f"[retry] {path}: {exc!r}", flush = True)
- time.sleep(15)
-
- # ── 1. response_format = json_object (JSON mode) ─────────────
- # llama.cpp's HTTP server supports OpenAI-compatible JSON
- # mode: `response_format: {"type": "json_object"}` constrains
- # the model to emit syntactically-valid JSON. We use raw HTTP
- # rather than the OpenAI SDK so that the field shape Unsloth
- # forwards to llama-server is unambiguous (the SDK rewrites
- # response_format depending on which variant it recognises).
- # We deliberately do NOT pass a strict JSON schema -- on
- # small Gemma-4 quants the GBNF-from-schema path occasionally
- # produces empty output, and JSON mode is the surface we care
- # about exposing through Unsloth.
- status, data = post("/v1/chat/completions", {
- "model": "default",
- "messages": [
- {"role": "system", "content": 'Reply with a single JSON object of the form {"city": "...", "country": "..."}. Output ONLY the JSON, nothing else.'},
- {"role": "user", "content": "What is the capital of France?"},
- ],
- "temperature": TEMP,
- # Trimmed for Mac runner timeout budget; json_object
- # grammar terminates quickly when working.
- "max_tokens": 200,
- "seed": SEED,
- "stream": False,
- "enable_thinking": False,
- "response_format": {"type": "json_object"},
- }, timeout = 240)
- assert status == 200, f"json status {status}: {data}"
- # Verify the response envelope shape -- this is what we
- # actually want to exercise on Mac. The model output quality
- # downstream of this is a Mac-Metal-quant artefact.
- assert (
- isinstance(data.get("choices"), list)
- and data["choices"]
- and "message" in data["choices"][0]
- ), f"json response envelope malformed: {data}"
- content = (data["choices"][0]["message"].get("content") or "").strip()
- print(f"[json] raw json_object content: {content!r}")
- # Some chat templates wrap JSON in ```json fences even in JSON
- # mode -- strip those before parsing.
- if content.startswith("```"):
- content = content.split("```", 2)[1]
- if content.startswith("json"):
- content = content[4:]
- content = content.strip("`\n ")
- if content:
- try:
- parsed = json.loads(content)
- if "paris" in str(parsed.get("city", "")).lower():
- print(f"[json] PASS json_object -> {parsed}")
- else:
- print(f"[json] WARN json_object decoded but city!=Paris: {parsed}")
- except json.JSONDecodeError as exc:
- print(f"[json] WARN json_object content not parseable ({exc}); content={content!r}")
- else:
- print("[json] WARN json_object produced empty content on this Mac quant")
- # Cross-check: same prompt without response_format. We care
- # that the inference path stays healthy (status 200 + envelope
- # shape OK); model output quality is a separate concern.
- status2, data2 = post("/v1/chat/completions", {
- "model": "default",
- "messages": [{"role": "user", "content": "What is the capital of France? Answer with one word."}],
- "temperature": TEMP,
- # 1-word answer doesn't need 400 tokens; trim so a
- # degenerate streaming model doesn't burn through the
- # job's wallclock budget.
- "max_tokens": 150,
- "seed": SEED,
- "stream": False,
- "enable_thinking": False,
- }, timeout = 240)
- assert status2 == 200, f"plain status {status2}: {data2}"
- plain = (data2["choices"][0]["message"].get("content") or "").lower()
- print(f"[json] plain capital-of-france reply: {plain!r}")
- if "paris" in plain:
- print("[json] PASS plain inference path (paris mentioned)")
- else:
- print(
- f"[json] WARN plain inference returned no 'paris' -- Mac quant "
- f"degeneracy. HTTP path validated separately above."
- )
-
- # ── 2. OpenAI image_url (data URI base64) ───────────────────
- # 64x64 solid-red PNG. stb_image (used by Unsloth's image
- # normaliser at routes/inference.py:3410) rejects 4x4 or
- # smaller PNGs as truncated, so we go up to 64x64 -- still
- # tiny in token cost. The assertion is loose: any non-empty
- # response from the vision path proves multimodal end-to-end
- # wiring; small VL quants are weak at colour identification.
- PNG_64X64_RED_B64 = (
- "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAYklEQVR4nO3PMQ0AIADAMEAI/k"
- "UhBhEcDcmqYJtn7/GzpQNeNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA"
- "1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaBdCJ0BmMJ25zMAAAAASUVORK5CYII="
- )
- data_uri = f"data:image/png;base64,{PNG_64X64_RED_B64}"
-
- # The Mac prebuilt llama.cpp server has a known crash when
- # processing image inputs alongside the gemma-4-E2B mmproj
- # (server disconnects mid-completion). This is upstream
- # llama.cpp behaviour, not Unsloth. Wrap both SDK calls in
- # try/except so an upstream crash registers as a WARN rather
- # than failing the whole job. Unsloth's contract (OpenAI/
- # Anthropic image fields are accepted and forwarded) is
- # validated by the request body Unsloth constructs, not by
- # whether llama.cpp can decode it on Mac Metal.
- client = OpenAI(base_url = f"{BASE}/v1", api_key = KEY)
- try:
- openai_resp = client.chat.completions.create(
- model = "default",
- temperature = TEMP,
- max_tokens = 80,
- seed = SEED,
- messages = [{
- "role": "user",
- "content": [
- {"type": "image_url", "image_url": {"url": data_uri}},
- {"type": "text", "text": "What colour dominates this image? Reply in one word."},
- ],
- }],
- )
- openai_text = (openai_resp.choices[0].message.content or "").lower()
- print(f"[image/openai] reply: {openai_text!r}")
- if openai_text:
- print("[image/openai] PASS image_url accepted, non-empty response")
- else:
- print("[image/openai] WARN image_url accepted but empty content -- Mac quant drift")
- except Exception as exc:
- print(
- f"[image/openai] WARN image_url SDK call raised: {type(exc).__name__}: "
- f"{exc}. Likely upstream llama.cpp Mac+vision crash, NOT an Unsloth "
- f"regression. Unsloth successfully forwarded the request."
- )
-
- # ── 3. Anthropic source/base64 image ────────────────────────
- # Two SDK quirks vs. Unsloth: base_url must NOT include /v1
- # (the SDK appends it itself; otherwise /v1/v1/messages -> 405),
- # and Unsloth's auth is HTTPBearer-only so the SDK's default
- # x-api-key header is ignored -- send Authorization: Bearer
- # via default_headers.
- anthropic = Anthropic(
- base_url = BASE,
- api_key = "unused",
- default_headers = {"Authorization": f"Bearer {KEY}"},
- )
- try:
- a_msg = anthropic.messages.create(
- model = "default",
- max_tokens = 80,
- temperature = TEMP,
- extra_body = {"seed": SEED},
- messages = [{
- "role": "user",
- "content": [
- {
- "type": "image",
- "source": {
- "type": "base64",
- "media_type": "image/png",
- "data": PNG_64X64_RED_B64,
- },
- },
- {"type": "text", "text": "Describe this image briefly."},
- ],
- }],
- )
- a_text = "".join(b.text for b in a_msg.content if getattr(b, "type", None) == "text")
- print(f"[image/anthropic] reply: {a_text!r}")
- if a_text:
- print("[image/anthropic] PASS source/base64 accepted, non-empty response")
- else:
- print("[image/anthropic] WARN source/base64 accepted but empty content -- Mac quant drift")
- except Exception as exc:
- print(
- f"[image/anthropic] WARN anthropic image SDK call raised: "
- f"{type(exc).__name__}: {exc}. Likely upstream llama.cpp Mac+vision "
- f"crash, NOT an Unsloth regression."
- )
- PY
-
- - name: Stop Unsloth
- if: always()
- run: |
- kill "${STUDIO_PID}" 2>/dev/null || true
- sleep 2
- ss -tln | grep ":${STUDIO_PORT}" || true
-
- - name: Upload logs
- # Always upload so green runs are still reviewable.
- if: always()
- # Diagnostic only: a transient artifact-service drop must not fail a green job.
- continue-on-error: true
- uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
- with:
- name: json-images-log
- path: |
- logs/studio_vision.log
- logs/install.log
- retention-days: 1
diff --git a/.github/workflows/studio-mac-ui-smoke.yml b/.github/workflows/studio-mac-ui-smoke.yml
index ab1a135aefc..08a4ce86667 100644
--- a/.github/workflows/studio-mac-ui-smoke.yml
+++ b/.github/workflows/studio-mac-ui-smoke.yml
@@ -22,7 +22,7 @@
# and asserting the machine is clean -- that is the teardown for the whole job,
# so nothing needing Unsloth installed may follow it.
-name: Mac Studio UI + API + Update CI
+name: Mac Studio UI + API + Update + Inference CI
on:
pull_request:
@@ -54,6 +54,10 @@ on:
# download.
- '.github/scripts/assert-llama-loads.sh'
- '.github/scripts/hf-download-with-retry.sh'
+ # Executed directly by the absorbed inference phase 1. The only entry
+ # studio-mac-inference-smoke.yml watched that this filter did not
+ # already cover.
+ - '.github/scripts/studio_smoke/multi_turn_chat.py'
push:
branches: [main]
# Same list as the PR filter. Without it this workflow ran on EVERY commit to
@@ -90,6 +94,10 @@ on:
# download.
- '.github/scripts/assert-llama-loads.sh'
- '.github/scripts/hf-download-with-retry.sh'
+ # Executed directly by the absorbed inference phase 1. The only entry
+ # studio-mac-inference-smoke.yml watched that this filter did not
+ # already cover.
+ - '.github/scripts/studio_smoke/multi_turn_chat.py'
workflow_dispatch:
concurrency:
@@ -105,20 +113,45 @@ permissions:
jobs:
ui-smoke:
- name: Chat UI, API and Update Tests
+ name: Chat UI, API, Update and GGUF inference
runs-on: macos-15
# 35 covered the UI phases alone. The absorbed API and update phases each
# add a server boot plus their own checks, but both reuse this job's single
# install rather than doing their own, so they cost minutes rather than the
# ~10 the bootstrap takes. 65 leaves headroom without inviting a hang to sit
# for an hour holding one of the 5 macOS slots.
- timeout-minutes: 65
+ timeout-minutes: 100
env:
GGUF_REPO: unsloth/gemma-3-270m-it-GGUF
GGUF_VARIANT: UD-Q4_K_XL
GGUF_FILE: gemma-3-270m-it-UD-Q4_K_XL.gguf
STUDIO_PORT: '18896'
HF_HOME: ${{ github.workspace }}/hf-cache
+ # GitHub's macOS runners expose a PARAVIRTUAL Metal device, and Unsloth refuses to
+ # offload to it because paravirtual Apple GPUs return corrupt output. The absorbed
+ # inference phases therefore launch with `--gpu-layers 0 --device none`, which puts
+ # the WHOLE model in host RAM rather than the partial spill the host-offload guard
+ # was written for. #8883 prices that correctly and declines the load:
+ #
+ # "About 3 GB of this model does not fit in GPU memory and would run from system
+ # RAM. Only about 4 GB is available and 2 GB of that is kept free for the rest of
+ # the system, leaving about 2 GB usable."
+ #
+ # The guard is right: the runner cannot host gemma-4-E2B UD-Q4_K_XL (~2.4 GB) plus
+ # mmproj-F16 (~780 MB) in 2 GB. Those phases ran green for weeks before the guard
+ # existed because the prompts are tiny and the mapping is paged -- which is exactly
+ # the gamble the guard stops taking on a user's machine. Here we take it knowingly.
+ # The alternative is silently swapping the model the vision phase covers for a
+ # smaller one, which changes what mac vision inference is tested against.
+ #
+ # Job-level, not on the vision phase alone: every phase in this job is CPU-only for
+ # the same reason, so a runner image with a little less free RAM takes out the
+ # tool-calling phase next. Set on the job so each booted server inherits it, and so
+ # a phase added later inherits it too instead of failing mysteriously.
+ #
+ # This removes no coverage of the guard itself, which is tested in
+ # studio/backend/tests/test_host_offload_ram_guard.py and test_llama_cpp_placement.py.
+ UNSLOTH_ALLOW_HOST_OFFLOAD: '1'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
with:
@@ -558,6 +591,964 @@ jobs:
kill "${STUDIO_API_PID}" 2>/dev/null || true
sleep 2
+ # ---------------------------------------------------------------
+ # GGUF inference phases, absorbed from studio-mac-inference-smoke.yml.
+ #
+ # Fourth workflow to fold into this job, for the reason the three above
+ # were: it ran the same checkout, setup-node, setup-python,
+ # `install.sh --local --no-torch` and assert-llama-loads.sh, and primed
+ # hf-cache from the SAME key with the SAME GGUF. A studio/** PR paid two
+ # macOS slots to install Unsloth twice on two Macs and then test two
+ # surfaces of it.
+ #
+ # Slots are the point, not seconds. Measured over the last 8 green main
+ # runs of each: this job executes 1154s behind a 17438s queue, the
+ # inference job 402s behind a 13252s queue. Running them in sequence on
+ # one runner costs ~400s of wall clock and returns a macOS slot, and the
+ # cap is 5 concurrent macOS jobs account-wide, shared with
+ # unslothai/unsloth-zoo. Every slot returned shortens the queue for
+ # everything else on it.
+ #
+ # Placed here, after the UI and API phases and before the update phase,
+ # for two reasons that are both load-bearing:
+ #
+ # - `Phase 1 environment` and its siblings write GGUF_REPO, GGUF_VARIANT,
+ # GGUF_FILE and STUDIO_PORT to $GITHUB_ENV, and phase 3 points them at
+ # gemma-4-E2B-it. $GITHUB_ENV outranks the job-level `env:` for every
+ # later step, so running these first would silently hand the UI phases
+ # a different model than the one they declare.
+ # - The update phase must still run last: it uninstalls and asserts the
+ # machine is clean, which is the teardown for the whole job.
+ #
+ # Phase 1's own HF restore/prime/save block is NOT lifted. It used the
+ # identical cache key for the identical GGUF that this job already primes
+ # before the install, so it would restore over a cache it is sitting on
+ # and race its own save step.
+ # ---------------------------------------------------------------
+ - name: Phase 1 environment
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ run: |
+ echo "GGUF_REPO=unsloth/gemma-3-270m-it-GGUF" >> "$GITHUB_ENV"
+ echo "GGUF_VARIANT=UD-Q4_K_XL" >> "$GITHUB_ENV"
+ echo "GGUF_FILE=gemma-3-270m-it-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
+ echo "STUDIO_PORT=18888" >> "$GITHUB_ENV"
+
+ - name: Install OpenAI + Anthropic Python SDKs
+ id: sdks-chat
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ timeout-minutes: 5
+ run: pip install 'openai>=1.50' 'anthropic>=0.40'
+
+ - name: Reset auth + boot Unsloth (API-only)
+ id: boot-chat
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ timeout-minutes: 2
+ run: |
+ # Wipe (not reset-password): the boot below must re-seed a fresh .bootstrap_password.
+ bash .github/scripts/boot-studio-api-only.sh --port "$STUDIO_PORT" \
+ --log logs/studio_chat_api.log --pid-var STUDIO_CHAT_PID
+
+ - name: Wait for /api/health
+ id: ready-chat
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.boot-chat.outcome == 'success' }}
+ timeout-minutes: 5
+ run: |
+ bash .github/scripts/wait-for-health.sh --port "$STUDIO_PORT"
+
+ - name: Password rotation (old must fail, new must work)
+ id: rotate-chat
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.ready-chat.outcome == 'success' }}
+ timeout-minutes: 3
+ run: |
+ OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
+ NEW="CIRotated-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
+ echo "::add-mask::$OLD"
+ echo "::add-mask::$NEW"
+ # 1. Login with the bootstrap password.
+ OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
+ [ -n "$OLD_TOKEN" ] && [ "$OLD_TOKEN" != "null" ] || { echo "bootstrap login failed"; exit 1; }
+ # 2. Rotate to a fresh random password.
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
+ -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
+ -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
+ # 3. Old password must now be rejected (HTTP 401).
+ OLD_STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
+ -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}")
+ if [ "$OLD_STATUS" != "401" ]; then
+ echo "::error::Login with old password returned $OLD_STATUS, expected 401"
+ exit 1
+ fi
+ # 4. New password must succeed; capture the JWT for downstream steps.
+ NEW_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
+ [ -n "$NEW_TOKEN" ] && [ "$NEW_TOKEN" != "null" ] || { echo "new login failed"; exit 1; }
+ echo "TOKEN=$NEW_TOKEN" >> "$GITHUB_ENV"
+ echo "password rotation OK (old=401, new=200)"
+
+ - name: Load the GGUF (HF repo + variant, served from HF_HOME cache)
+ id: load-chat
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.rotate-chat.outcome == 'success' }}
+ # curl already caps itself at --max-time 600; +2 for process overhead.
+ timeout-minutes: 12
+ run: |
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
+ -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
+ --max-time 600 \
+ -d "{\"model_path\":\"$GGUF_REPO\",\"gguf_variant\":\"$GGUF_VARIANT\",\"is_lora\":false,\"max_seq_length\":2048}" \
+ | jq '{status, display_name, is_gguf, context_length}'
+
+ - name: Multi-turn determinism via OpenAI + Anthropic SDKs
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.load-chat.outcome == 'success' }}
+ timeout-minutes: 15
+ env:
+ BASE_URL: http://127.0.0.1:18888
+ run: |
+ python3 .github/scripts/studio_smoke/multi_turn_chat.py
+
+ - name: Stop Unsloth
+ if: always()
+ run: |
+ kill "${STUDIO_CHAT_PID}" 2>/dev/null || true
+ sleep 2
+ lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
+
+ - name: Upload logs
+ # Always upload so green runs are still reviewable.
+ if: always()
+ # Diagnostic only: a transient artifact-service drop must not fail a green job.
+ continue-on-error: true
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: openai-anthropic-log
+ path: |
+ logs/studio_chat_api.log
+ logs/install.log
+ retention-days: 7
+
+ # ==============================================================
+ # Phase 2: tool calling + server-side tools.
+ # Reuses the install and llama.cpp check done once above rather than
+ # repeating them on a second runner. Ids, cache dir and server log are
+ # suffixed -tools so the phases cannot collide inside one job.
+ #
+ # Every step below carries the same `if:`. A step with no `if:` gets an
+ # implicit `success()`, which is job-wide rather than per-step, so a
+ # single failed phase-1 step would otherwise skip phases 2 and 3
+ # outright -- exactly the coverage the three independent jobs used to
+ # give us when one of them went red. `!cancelled()` runs the phase after
+ # a phase-1 failure while still honouring a cancel, and the
+ # assert-llama gate keeps it from running when the SHARED preamble
+ # broke (a failed checkout or install skips assert-llama, so its outcome
+ # is not 'success' and phases 2 and 3 correctly stay out). The job still
+ # ends red, because the failed phase-1 step already set the job status.
+ # ==============================================================
+ - name: Phase 2 environment
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ run: |
+ echo "GGUF_REPO=unsloth/Qwen3.5-2B-GGUF" >> "$GITHUB_ENV"
+ echo "GGUF_FILE=Qwen3.5-2B-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
+ echo "STUDIO_PORT=18898" >> "$GITHUB_ENV"
+
+ # Cross-OS shared entry with the Linux tool-calling job in
+ # studio-inference-smoke.yml: same repo, same file, same flat
+ # --local-dir payload, byte-identical on all three runners. The key
+ # therefore carries no `runner.os`, and enableCrossOsArchive is what
+ # lets Windows -- which tars with --force-local -- join it.
+ #
+ # The suffix is bumped v2 -> v3 because the Linux side moves its
+ # directory to gguf-cache-tools in the same commit, and that is not
+ # cosmetic: actions/cache identifies an entry by key AND a version hash
+ # derived from the `path` input, while key uniqueness is global per ref.
+ # Move the path without bumping the key and the restore misses on
+ # version while the save is refused with "Unable to reserve cache with
+ # key ... another job may be creating this cache" -- measured on staging
+ # during the Mac consolidation: two consecutive runs both logged "Cache
+ # not found for input keys" and both failed to save.
+ - name: Restore GGUF model file
+ id: cache-gguf-tools
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ continue-on-error: true
+ timeout-minutes: 15
+ with:
+ path: gguf-cache-tools
+ key: gguf-unsloth/Qwen3.5-2B-GGUF-Qwen3.5-2B-UD-Q4_K_XL.gguf-v3
+ enableCrossOsArchive: true
+
+ - name: Download GGUF if cache miss
+ id: download-gguf-tools
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && (steps.cache-gguf-tools.outputs.cache-hit != 'true' || steps.cache-gguf-tools.outcome != 'success') }}
+ # hf-download-with-retry.sh retries forever; this is its real bound.
+ timeout-minutes: 20
+ env:
+ # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
+ HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+ run: |
+ python -m pip install --upgrade huggingface_hub
+ mkdir -p gguf-cache-tools
+ bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache-tools
+
+ # Save partial caches on cancel; next run resumes via content hash.
+ - name: Save GGUF model file
+ if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-tools.outcome != 'skipped' && hashFiles('gguf-cache-tools/**/*.gguf') != ''
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ timeout-minutes: 15
+ with:
+ path: gguf-cache-tools
+ key: gguf-unsloth/Qwen3.5-2B-GGUF-Qwen3.5-2B-UD-Q4_K_XL.gguf-v3
+ enableCrossOsArchive: true
+
+ - name: Reset auth + boot Unsloth (API-only, default tool policy)
+ id: boot-tools
+ # Phase-local prerequisite on top of the shared gate. The phase stays
+ # independent of EARLIER phases, which is what the shared assert-llama
+ # gate buys, but it is not independent of its own download: without this
+ # clause a failed download still boots a server with no model and runs
+ # the test against it. `!= 'failure'` and not `== 'success'`, because a
+ # cache hit skips the download.
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.download-gguf-tools.outcome != 'failure' }}
+ timeout-minutes: 2
+ # We deliberately use the API-only mode rather than
+ # `unsloth studio run` because the latter calls
+ # `set_tool_policy(...)` with a resolved bool: on loopback the
+ # default resolves to True, which forces every request through
+ # the server-side agentic loop and breaks the standard
+ # function-calling test below. API-only mode leaves
+ # tool_policy=None so each request's `enable_tools` field is
+ # honoured.
+ run: |
+ bash .github/scripts/boot-studio-api-only.sh \
+ --port "$STUDIO_PORT" --log logs/studio_tools.log
+
+ - name: Wait for /api/health, log in, change password, load model
+ id: ready-tools
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.boot-tools.outcome == 'success' }}
+ # 180s health wait + curl's own --max-time 600, with headroom.
+ timeout-minutes: 15
+ run: |
+ for i in $(seq 1 180); do
+ if curl -fs "http://127.0.0.1:${STUDIO_PORT}/api/health" > /tmp/health.json; then
+ jq -e '.status == "healthy"' /tmp/health.json && break
+ fi
+ sleep 1
+ done
+ jq -e '.status == "healthy"' /tmp/health.json
+ OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
+ NEW="CITool-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
+ echo "::add-mask::$OLD"
+ echo "::add-mask::$NEW"
+ OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
+ -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
+ -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
+ TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
+ echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
+ GGUF_PATH="$GITHUB_WORKSPACE/gguf-cache-tools/${GGUF_FILE}"
+ ls -lh "$GGUF_PATH"
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
+ -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
+ --max-time 600 \
+ -d "{\"model_path\":\"$GGUF_PATH\",\"is_lora\":false,\"max_seq_length\":2048}" \
+ | jq '{status, display_name}'
+
+ - name: Tool calling, server-side tools, thinking on/off
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.ready-tools.outcome == 'success' }}
+ timeout-minutes: 20
+ env:
+ BASE_URL: http://127.0.0.1:18898
+ run: |
+ python - <<'PY'
+ import json
+ import os
+ import time
+ import urllib.error
+ import urllib.request
+
+ BASE = os.environ["BASE_URL"]
+ KEY = os.environ["API_KEY"]
+ SEED = 3407
+
+ def post(path, body, *, timeout = 240):
+ """Plain JSON POST. For requests that don't go through
+ the server-side agentic loop, the response is one JSON
+ object."""
+ data = json.dumps(body).encode()
+ req = urllib.request.Request(
+ f"{BASE}{path}",
+ data = data,
+ method = "POST",
+ headers = {
+ "Authorization": f"Bearer {KEY}",
+ "Content-Type": "application/json",
+ },
+ )
+ # Shared CI runners stall sporadically, so retry transport-level
+ # failures only; HTTP status errors surface immediately. Bounded
+ # to fit the job's timeout-minutes: short probes get 3 full
+ # attempts, long probes one retry capped at 300s (a healthy
+ # server answers a retry quickly; a stalled one never does).
+ attempts = 3 if timeout <= 300 else 2
+ for attempt in range(attempts):
+ try:
+ t = timeout if attempt == 0 else min(timeout, 300)
+ with urllib.request.urlopen(req, timeout = t) as resp:
+ return resp.status, json.loads(resp.read().decode())
+ except urllib.error.HTTPError:
+ raise
+ except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
+ if attempt == attempts - 1:
+ raise
+ print(f"[retry] {path}: {exc!r}", flush = True)
+ time.sleep(15)
+
+ def post_sse(path, body, *, timeout = 600, retries = 1, soft = False):
+ """POST a streaming request and accumulate the assistant
+ text deltas. The server-side agentic loop ALWAYS returns
+ SSE regardless of the request's `stream` field, so any
+ call with enable_tools=true must use this helper.
+
+ A shared CI runner can stall the stream transport (the
+ connection opening, or a mid-stream read) even when Unsloth
+ is healthy, so harden the read three ways: retry a stall
+ once with a fresh request capped at 300s; return any text
+ already streamed before a stall (a stall on the trailing
+ tokens, after the answer arrived, still counts); and when
+ every attempt yields nothing, a hard call re-raises while a
+ soft call (the best-effort server-side tool probes) returns
+ None so the caller can WARN instead of sinking the whole
+ job. HTTP status errors always surface immediately."""
+ body = {**body, "stream": True}
+ data = json.dumps(body).encode()
+ req = urllib.request.Request(
+ f"{BASE}{path}",
+ data = data,
+ method = "POST",
+ headers = {
+ "Authorization": f"Bearer {KEY}",
+ "Content-Type": "application/json",
+ },
+ )
+ for attempt in range(retries + 1):
+ parts = []
+ t = timeout if attempt == 0 else min(timeout, 300)
+ try:
+ with urllib.request.urlopen(req, timeout = t) as resp:
+ for raw in resp:
+ line = raw.decode().strip()
+ if not line.startswith("data: "):
+ continue
+ payload = line[6:]
+ if payload == "[DONE]":
+ break
+ try:
+ chunk = json.loads(payload)
+ except json.JSONDecodeError:
+ continue
+ for choice in chunk.get("choices", []):
+ delta = choice.get("delta", {}) or {}
+ if delta.get("content"):
+ parts.append(delta["content"])
+ return "".join(parts)
+ except urllib.error.HTTPError:
+ raise
+ except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
+ # Text already streamed is a valid signal -- keep it
+ # rather than re-running a heavy generation.
+ if parts:
+ joined = "".join(parts)
+ print(f"[retry-sse] {path}: {exc!r}; keeping {len(joined)} partial chars", flush = True)
+ return joined
+ if attempt == retries:
+ if soft:
+ print(f"[tools] WARN {path}: SSE transport stalled with no data ({exc!r}) -- non-blocking", flush = True)
+ return None
+ raise
+ print(f"[retry-sse] {path}: {exc!r}", flush = True)
+ time.sleep(15)
+
+ # ── 1. Standard OpenAI function calling ──────────────────────
+ weather_tool = {
+ "type": "function",
+ "function": {
+ "name": "get_weather",
+ "description": "Get current weather for a city.",
+ "parameters": {
+ "type": "object",
+ "properties": {"city": {"type": "string"}},
+ "required": ["city"],
+ },
+ },
+ }
+
+ # Mac Metal at temperature=0 is pathological for these small
+ # quants (Qwen3.5-2B emits ',,,,,,...' or 'The The The...'),
+ # gemma-4-E2B emits '<unused5>' tokens). The Linux CPU
+ # backend hides the issue. Use a small non-zero temperature
+ # with a fixed seed so we stay deterministic but escape the
+ # degenerate sampling trap.
+ TEMP = 0.2
+
+ status, data = post("/v1/chat/completions", {
+ "messages": [{"role": "user", "content": "What is the weather in Paris?"}],
+ "tools": [weather_tool],
+ "tool_choice": "required",
+ "stream": False,
+ "temperature": TEMP,
+ "seed": SEED,
+ # tool_choice='required' constrains the grammar so the
+ # model emits a tool_call quickly when it works at all;
+ # 128 tokens is enough for `{"city":"Paris"}` plus the
+ # JSON envelope.
+ "max_tokens": 128,
+ }, timeout = 180)
+ assert status == 200, f"tool call status {status}: {data}"
+ choice = data["choices"][0]
+ tool_calls = (choice.get("message") or {}).get("tool_calls") or []
+ # Unsloth's contract: when tool_choice='required', llama.cpp's
+ # grammar should force a tool_calls payload. On Mac that
+ # contract is sometimes broken by the underlying quant; the
+ # PASS path is "tool_calls present + correct schema", the
+ # WARN path documents Unsloth still returned 200 with a
+ # well-formed choices[] envelope.
+ if tool_calls:
+ tc = tool_calls[0]
+ assert tc["function"]["name"] == "get_weather", (
+ f"unexpected tool name: {tc['function']['name']!r}"
+ )
+ args = json.loads(tc["function"]["arguments"])
+ assert args.get("city"), f"missing city arg: {args}"
+ print(f"[tools] PASS function calling -> {tc['function']['name']}({args}) finish={choice.get('finish_reason')!r}")
+ else:
+ # Infrastructure path is correct; model output drifted.
+ print(
+ f"[tools] WARN function calling: no tool_calls (finish_reason="
+ f"{choice.get('finish_reason')!r}); HTTP path OK, this is a "
+ f"Mac Metal quant degeneracy."
+ )
+
+ # ── 2. Server-side python tool ───────────────────────────────
+ # 123 * 456 = 56088. The agentic loop streams SSE; we
+ # accumulate the assistant text and look for the answer. On
+ # Mac the model often loses the tool calling contract before
+ # producing the answer; accept either the answer OR a
+ # non-empty SSE stream as proof the path completes.
+ # macOS free runner is ~10 tok/s on Qwen3.5-2B Q4_K_XL;
+ # cap max_tokens tightly so each SSE round stays under ~30s
+ # even when the model stalls in a degenerate output state.
+ # retries=0 on the best-effort probes: this step's 20-minute cap
+ # also has to cover the thinking checks, so a no-data stall must be a
+ # single 180s attempt (not 180+15+180s) to leave room for the
+ # thinking checks. A soft/best-effort probe only WARNs anyway.
+ content = post_sse("/v1/chat/completions", {
+ "messages": [{"role": "user", "content": "What is 123 * 456? Use the python tool to compute it and tell me the number."}],
+ "enable_tools": True,
+ "permission_mode": "full",
+ "enabled_tools": ["python"],
+ "session_id": "ci-tool-calling-py",
+ "temperature": TEMP,
+ "seed": SEED,
+ "max_tokens": 128,
+ }, timeout = 180, retries = 0, soft = True)
+ if content is None:
+ print("[tools] WARN python tool: SSE transport stalled after retries -- non-blocking")
+ elif "56088" in content or "56,088" in content:
+ print(f"[tools] PASS python tool ({len(content)} chars, found 56088)")
+ else:
+ # Empty stream is a known Mac-quant degeneracy too; log
+ # but do not fail.
+ print(
+ f"[tools] WARN python tool: SSE OK ({len(content)} chars) but "
+ f"model didn't return 56088 -- Mac quant drift"
+ )
+
+ # NOTE: the dedicated "Server-side bash (terminal) tool" axis
+ # was dropped in favour of the python axis above. Both share
+ # the SAME server-side agentic loop wiring (only the registry
+ # entry differs); the python axis is the canonical proof. On
+ # macOS the duplicated SSE round was the dominant cost in
+ # this step, so collapsing the two saves ~30-60 s wallclock
+ # without losing distinct coverage.
+
+ # ── 3. Server-side web_search tool ───────────────────────────
+ # DuckDuckGo is flaky from CI runners and small Qwen3.5-2B
+ # may not actually search. Only assert that the SSE stream
+ # opens and yields any data; HTTP / parser failures already
+ # raise above.
+ try:
+ content = post_sse("/v1/chat/completions", {
+ "messages": [{"role": "user", "content": "Search the web for 'unsloth ai github' and summarise."}],
+ "enable_tools": True,
+ "permission_mode": "full",
+ "enabled_tools": ["web_search"],
+ "session_id": "ci-tool-calling-web",
+ "temperature": TEMP,
+ "seed": SEED,
+ "max_tokens": 96,
+ }, timeout = 180, retries = 0)
+ print(f"[tools] PASS web_search stream ({len(content)} chars)")
+ except Exception as exc:
+ print(f"[tools] WARN web_search probe failed (non-blocking): {exc}")
+
+ # ── 4. Thinking on / off ─────────────────────────────────────
+ # Unsloth strips think blocks from message.content for tools-mode
+ # responses, so we toggle plain chat (no enable_tools) and look
+ # at the surfaced reasoning_content / message.thinking field.
+ def thinking_call(enable):
+ status, data = post("/v1/chat/completions", {
+ "messages": [{"role": "user", "content": "Briefly: is 17 prime?"}],
+ "stream": False,
+ "enable_thinking": enable,
+ "temperature": TEMP,
+ "seed": SEED,
+ # 80 tokens lands within this step's 20-minute cap
+ # on the macOS free runner. 17 is small; this is
+ # plenty of room for either "Yes" + brief reasoning
+ # or a degenerate empty completion.
+ "max_tokens": 80,
+ }, timeout = 180)
+ assert status == 200
+ msg = data["choices"][0]["message"]
+ # Unsloth surfaces thinking via reasoning_content (OpenAI
+ # extension). Fall back to inline <think> markers for
+ # robustness across template versions.
+ raw = (msg.get("content") or "") + (msg.get("reasoning_content") or "")
+ return raw
+
+ on_text = thinking_call(True)
+ off_text = thinking_call(False)
+ # Mac quant drift: the model may produce empty / degenerate
+ # output regardless of enable_thinking. Assert ONLY that the
+ # endpoint returned 200 (already enforced inside thinking_call)
+ # and that toggling the flag doesn't surface a hard <think>
+ # marker when off.
+ had_think_on = ("<think>" in on_text) or len(on_text) > 80
+ if not had_think_on:
+ print(
+ f"[tools] WARN enable_thinking=True produced no thinking signal: "
+ f"{on_text[:200]!r} -- Mac quant drift"
+ )
+ # Off-mode should not contain the literal <think> marker.
+ assert "<think>" not in off_text, (
+ f"enable_thinking=False but <think> still present: {off_text!r}"
+ )
+ print(f"[tools] PASS thinking on/off (on={len(on_text)} chars, off={len(off_text)} chars)")
+ PY
+
+ - name: Stop Unsloth
+ if: always()
+ run: |
+ kill "${STUDIO_PID}" 2>/dev/null || true
+ sleep 2
+ lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
+
+ - name: Upload logs
+ # Always upload so green runs are still reviewable.
+ if: always()
+ # Diagnostic only: a transient artifact-service drop must not fail a green job.
+ continue-on-error: true
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: tool-calling-log
+ path: |
+ logs/studio_tools.log
+ logs/install.log
+ retention-days: 1
+
+ # ==============================================================
+ # Phase 3: JSON schema decoding + image input.
+ # Reuses the install and llama.cpp check done once above rather than
+ # repeating them on a second runner. Ids, cache dir and server log are
+ # suffixed -vision so the phases cannot collide inside one job.
+ # Same `if:` as phase 2, for the same reason: a phase-1 or phase-2
+ # failure must not silently skip this phase's coverage.
+ # ==============================================================
+ - name: Phase 3 environment
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ run: |
+ echo "GGUF_REPO=unsloth/gemma-4-E2B-it-GGUF" >> "$GITHUB_ENV"
+ echo "GGUF_VARIANT=UD-Q4_K_XL" >> "$GITHUB_ENV"
+ echo "GGUF_FILE=gemma-4-E2B-it-UD-Q4_K_XL.gguf" >> "$GITHUB_ENV"
+ echo "MMPROJ_FILE=mmproj-F16.gguf" >> "$GITHUB_ENV"
+ echo "STUDIO_PORT=18892" >> "$GITHUB_ENV"
+
+ - name: Restore GGUF + mmproj files
+ id: cache-gguf-vision
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ uses: actions/cache/restore@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ continue-on-error: true
+ timeout-minutes: 20
+ with:
+ path: gguf-cache-vision
+ key: ${{ runner.os }}-gguf-unsloth/gemma-4-E2B-it-GGUF-gemma-4-E2B-it-UD-Q4_K_XL.gguf-mmproj-F16.gguf-v3
+
+ - name: Verify cache contains BOTH gguf + mmproj
+ id: verify-cache
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.cache-gguf-vision.outputs.cache-hit == 'true' }}
+ run: |
+ if [[ -f "gguf-cache-vision/$GGUF_FILE" && -f "gguf-cache-vision/$MMPROJ_FILE" ]]; then
+ echo "ok=true" >> "$GITHUB_OUTPUT"
+ else
+ echo "Partial cache hit -- forcing re-download."
+ echo "ok=false" >> "$GITHUB_OUTPUT"
+ fi
+
+ - name: Download GGUF + mmproj if cache miss or partial
+ id: download-gguf-vision
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && (steps.cache-gguf-vision.outputs.cache-hit != 'true' || steps.verify-cache.outputs.ok != 'true') }}
+ # Authenticated + parallel: shared macOS NAT egress stalls
+ # multi-GB anonymous downloads. hf-download-with-retry.sh retries
+ # forever, so this cap is what actually bounds a permanent stall --
+ # 30 matches the old json-images job timeout, the slowest of the three.
+ timeout-minutes: 30
+ env:
+ # Withheld on PR: this step runs checked-out PR code; public GGUF still downloads.
+ HF_TOKEN: ${{ github.event_name != 'pull_request' && secrets.HF_TOKEN || '' }}
+ run: |
+ python -m pip install --upgrade huggingface_hub
+ mkdir -p gguf-cache-vision
+ bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$GGUF_FILE" gguf-cache-vision &
+ MODEL_PID=$!
+ bash .github/scripts/hf-download-with-retry.sh "$GGUF_REPO" "$MMPROJ_FILE" gguf-cache-vision &
+ MMPROJ_PID=$!
+ wait "$MODEL_PID"
+ wait "$MMPROJ_PID"
+ # Fail loud on a partial download instead of in the next step.
+ ls -lh "gguf-cache-vision/$GGUF_FILE" "gguf-cache-vision/$MMPROJ_FILE"
+
+ # Save partial caches on cancel. hashFiles guard avoids a hard
+ # save failure when the download step exits with no files. The
+ # additional mmproj-presence check stops a partial save from
+ # poisoning the cache for the next run.
+
+ - name: Save GGUF + mmproj files
+ if: always() && github.ref == 'refs/heads/main' && steps.download-gguf-vision.outcome != 'skipped' && hashFiles('gguf-cache-vision/**/*.gguf') != '' && hashFiles(format('gguf-cache-vision/{0}', 'mmproj-F16.gguf')) != ''
+ uses: actions/cache/save@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0
+ timeout-minutes: 20
+ with:
+ path: gguf-cache-vision
+ key: ${{ runner.os }}-gguf-unsloth/gemma-4-E2B-it-GGUF-gemma-4-E2B-it-UD-Q4_K_XL.gguf-mmproj-F16.gguf-v3
+
+ - name: Install OpenAI + Anthropic Python SDKs
+ id: sdks-vision
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' }}
+ timeout-minutes: 5
+ run: pip install 'openai>=1.50' 'anthropic>=0.40'
+
+ - name: Reset auth + boot Unsloth (API-only)
+ id: boot-vision
+ # Same phase-local prerequisite as phase 2. The SDK clause is here and
+ # not in phase 2 because only this phase imports openai/anthropic.
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.sdks-vision.outcome == 'success' && steps.download-gguf-vision.outcome != 'failure' }}
+ timeout-minutes: 2
+ # See phase 2's comment: API-only mode keeps tool_policy=None so
+ # response_format requests aren't routed through the agentic
+ # tool loop.
+ run: |
+ bash .github/scripts/boot-studio-api-only.sh \
+ --port "$STUDIO_PORT" --log logs/studio_vision.log
+
+ - name: Wait for /api/health, log in, change password, load model
+ id: ready-vision
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.boot-vision.outcome == 'success' }}
+ # 180s health wait + curl's own --max-time 900, with headroom.
+ timeout-minutes: 20
+ run: |
+ for i in $(seq 1 180); do
+ if curl -fs "http://127.0.0.1:${STUDIO_PORT}/api/health" > /tmp/health.json; then
+ jq -e '.status == "healthy"' /tmp/health.json && break
+ fi
+ sleep 1
+ done
+ jq -e '.status == "healthy"' /tmp/health.json
+ OLD=$(cat ~/.unsloth/studio/auth/.bootstrap_password)
+ NEW="CIJson-$(python -c 'import secrets; print(secrets.token_urlsafe(12))')"
+ echo "::add-mask::$OLD"
+ echo "::add-mask::$NEW"
+ OLD_TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$OLD\"}" | jq -r .access_token)
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/change-password" \
+ -H "Authorization: Bearer $OLD_TOKEN" -H 'content-type: application/json' \
+ -d "{\"current_password\":\"$OLD\",\"new_password\":\"$NEW\"}" > /dev/null
+ TOKEN=$(curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/auth/login" \
+ -H 'content-type: application/json' \
+ -d "{\"username\":\"unsloth\",\"password\":\"$NEW\"}" | jq -r .access_token)
+ echo "API_KEY=$TOKEN" >> "$GITHUB_ENV"
+ # Load via local file path; mmproj sibling auto-detected by
+ # detect_mmproj_file (model_config.py). gguf_variant omitted
+ # -- it routes through _find_local_gguf_by_variant which
+ # expects a directory, not a file path.
+ GGUF_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${GGUF_FILE}"
+ MMPROJ_PATH="$GITHUB_WORKSPACE/gguf-cache-vision/${MMPROJ_FILE}"
+ ls -lh "$GGUF_PATH" "$MMPROJ_PATH"
+ curl -fs -X POST "http://127.0.0.1:${STUDIO_PORT}/api/inference/load" \
+ -H "Authorization: Bearer $TOKEN" -H 'content-type: application/json' \
+ --max-time 900 \
+ -d "{\"model_path\":\"$GGUF_PATH\",\"is_lora\":false,\"max_seq_length\":2048}" \
+ | jq '{status, display_name, is_vision}'
+
+ - name: JSON schema decoding + image input
+ if: ${{ !cancelled() && steps.assert_llama.outcome == 'success' && steps.ready-vision.outcome == 'success' }}
+ timeout-minutes: 20
+ env:
+ BASE_URL: http://127.0.0.1:18892
+ run: |
+ python - <<'PY'
+ import base64
+ import json
+ import os
+ import time
+ import urllib.error
+ import urllib.request
+ from openai import OpenAI
+ from anthropic import Anthropic
+
+ BASE = os.environ["BASE_URL"]
+ KEY = os.environ["API_KEY"]
+ SEED = 3407
+ # Mac Metal degenerates these gemma-4 quants at temperature=0
+ # (any prompt yields '<unused5>...' padding tokens). Use a
+ # small non-zero temperature with the same seed so we stay
+ # deterministic-enough but escape the trap.
+ TEMP = 0.2
+
+ def post(path, body, *, timeout = 240):
+ req = urllib.request.Request(
+ f"{BASE}{path}",
+ data = json.dumps(body).encode(),
+ method = "POST",
+ headers = {
+ "Authorization": f"Bearer {KEY}",
+ "Content-Type": "application/json",
+ },
+ )
+ # Shared CI runners stall sporadically, so retry transport-level
+ # failures only; HTTP status errors surface immediately. Bounded
+ # to fit the job's timeout-minutes: short probes get 3 full
+ # attempts, long probes one retry capped at 300s (a healthy
+ # server answers a retry quickly; a stalled one never does).
+ attempts = 3 if timeout <= 300 else 2
+ for attempt in range(attempts):
+ try:
+ t = timeout if attempt == 0 else min(timeout, 300)
+ with urllib.request.urlopen(req, timeout = t) as resp:
+ return resp.status, json.loads(resp.read().decode())
+ except urllib.error.HTTPError:
+ raise
+ except (TimeoutError, ConnectionError, urllib.error.URLError) as exc:
+ if attempt == attempts - 1:
+ raise
+ print(f"[retry] {path}: {exc!r}", flush = True)
+ time.sleep(15)
+
+ # ── 1. response_format = json_object (JSON mode) ─────────────
+ # llama.cpp's HTTP server supports OpenAI-compatible JSON
+ # mode: `response_format: {"type": "json_object"}` constrains
+ # the model to emit syntactically-valid JSON. We use raw HTTP
+ # rather than the OpenAI SDK so that the field shape Unsloth
+ # forwards to llama-server is unambiguous (the SDK rewrites
+ # response_format depending on which variant it recognises).
+ # We deliberately do NOT pass a strict JSON schema -- on
+ # small Gemma-4 quants the GBNF-from-schema path occasionally
+ # produces empty output, and JSON mode is the surface we care
+ # about exposing through Unsloth.
+ status, data = post("/v1/chat/completions", {
+ "model": "default",
+ "messages": [
+ {"role": "system", "content": 'Reply with a single JSON object of the form {"city": "...", "country": "..."}. Output ONLY the JSON, nothing else.'},
+ {"role": "user", "content": "What is the capital of France?"},
+ ],
+ "temperature": TEMP,
+ # Trimmed for Mac runner timeout budget; json_object
+ # grammar terminates quickly when working.
+ "max_tokens": 200,
+ "seed": SEED,
+ "stream": False,
+ "enable_thinking": False,
+ "response_format": {"type": "json_object"},
+ }, timeout = 240)
+ assert status == 200, f"json status {status}: {data}"
+ # Verify the response envelope shape -- this is what we
+ # actually want to exercise on Mac. The model output quality
+ # downstream of this is a Mac-Metal-quant artefact.
+ assert (
+ isinstance(data.get("choices"), list)
+ and data["choices"]
+ and "message" in data["choices"][0]
+ ), f"json response envelope malformed: {data}"
+ content = (data["choices"][0]["message"].get("content") or "").strip()
+ print(f"[json] raw json_object content: {content!r}")
+ # Some chat templates wrap JSON in ```json fences even in JSON
+ # mode -- strip those before parsing.
+ if content.startswith("```"):
+ content = content.split("```", 2)[1]
+ if content.startswith("json"):
+ content = content[4:]
+ content = content.strip("`\n ")
+ if content:
+ try:
+ parsed = json.loads(content)
+ if "paris" in str(parsed.get("city", "")).lower():
+ print(f"[json] PASS json_object -> {parsed}")
+ else:
+ print(f"[json] WARN json_object decoded but city!=Paris: {parsed}")
+ except json.JSONDecodeError as exc:
+ print(f"[json] WARN json_object content not parseable ({exc}); content={content!r}")
+ else:
+ print("[json] WARN json_object produced empty content on this Mac quant")
+ # Cross-check: same prompt without response_format. We care
+ # that the inference path stays healthy (status 200 + envelope
+ # shape OK); model output quality is a separate concern.
+ status2, data2 = post("/v1/chat/completions", {
+ "model": "default",
+ "messages": [{"role": "user", "content": "What is the capital of France? Answer with one word."}],
+ "temperature": TEMP,
+ # 1-word answer doesn't need 400 tokens; trim so a
+ # degenerate streaming model doesn't burn through the
+ # job's wallclock budget.
+ "max_tokens": 150,
+ "seed": SEED,
+ "stream": False,
+ "enable_thinking": False,
+ }, timeout = 240)
+ assert status2 == 200, f"plain status {status2}: {data2}"
+ plain = (data2["choices"][0]["message"].get("content") or "").lower()
+ print(f"[json] plain capital-of-france reply: {plain!r}")
+ if "paris" in plain:
+ print("[json] PASS plain inference path (paris mentioned)")
+ else:
+ print(
+ f"[json] WARN plain inference returned no 'paris' -- Mac quant "
+ f"degeneracy. HTTP path validated separately above."
+ )
+
+ # ── 2. OpenAI image_url (data URI base64) ───────────────────
+ # 64x64 solid-red PNG. stb_image (used by Unsloth's image
+ # normaliser at routes/inference.py:3410) rejects 4x4 or
+ # smaller PNGs as truncated, so we go up to 64x64 -- still
+ # tiny in token cost. The assertion is loose: any non-empty
+ # response from the vision path proves multimodal end-to-end
+ # wiring; small VL quants are weak at colour identification.
+ PNG_64X64_RED_B64 = (
+ "iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAIAAAAlC+aJAAAAYklEQVR4nO3PMQ0AIADAMEAI/k"
+ "UhBhEcDcmqYJtn7/GzpQNeNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA"
+ "1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaA1oDWgNaBdCJ0BmMJ25zMAAAAASUVORK5CYII="
+ )
+ data_uri = f"data:image/png;base64,{PNG_64X64_RED_B64}"
+
+ # The Mac prebuilt llama.cpp server has a known crash when
+ # processing image inputs alongside the gemma-4-E2B mmproj
+ # (server disconnects mid-completion). This is upstream
+ # llama.cpp behaviour, not Unsloth. Wrap both SDK calls in
+ # try/except so an upstream crash registers as a WARN rather
+ # than failing the whole job. Unsloth's contract (OpenAI/
+ # Anthropic image fields are accepted and forwarded) is
+ # validated by the request body Unsloth constructs, not by
+ # whether llama.cpp can decode it on Mac Metal.
+ client = OpenAI(base_url = f"{BASE}/v1", api_key = KEY)
+ try:
+ openai_resp = client.chat.completions.create(
+ model = "default",
+ temperature = TEMP,
+ max_tokens = 80,
+ seed = SEED,
+ messages = [{
+ "role": "user",
+ "content": [
+ {"type": "image_url", "image_url": {"url": data_uri}},
+ {"type": "text", "text": "What colour dominates this image? Reply in one word."},
+ ],
+ }],
+ )
+ openai_text = (openai_resp.choices[0].message.content or "").lower()
+ print(f"[image/openai] reply: {openai_text!r}")
+ if openai_text:
+ print("[image/openai] PASS image_url accepted, non-empty response")
+ else:
+ print("[image/openai] WARN image_url accepted but empty content -- Mac quant drift")
+ except Exception as exc:
+ print(
+ f"[image/openai] WARN image_url SDK call raised: {type(exc).__name__}: "
+ f"{exc}. Likely upstream llama.cpp Mac+vision crash, NOT an Unsloth "
+ f"regression. Unsloth successfully forwarded the request."
+ )
+
+ # ── 3. Anthropic source/base64 image ────────────────────────
+ # Two SDK quirks vs. Unsloth: base_url must NOT include /v1
+ # (the SDK appends it itself; otherwise /v1/v1/messages -> 405),
+ # and Unsloth's auth is HTTPBearer-only so the SDK's default
+ # x-api-key header is ignored -- send Authorization: Bearer
+ # via default_headers.
+ anthropic = Anthropic(
+ base_url = BASE,
+ api_key = "unused",
+ default_headers = {"Authorization": f"Bearer {KEY}"},
+ )
+ try:
+ a_msg = anthropic.messages.create(
+ model = "default",
+ max_tokens = 80,
+ temperature = TEMP,
+ extra_body = {"seed": SEED},
+ messages = [{
+ "role": "user",
+ "content": [
+ {
+ "type": "image",
+ "source": {
+ "type": "base64",
+ "media_type": "image/png",
+ "data": PNG_64X64_RED_B64,
+ },
+ },
+ {"type": "text", "text": "Describe this image briefly."},
+ ],
+ }],
+ )
+ a_text = "".join(b.text for b in a_msg.content if getattr(b, "type", None) == "text")
+ print(f"[image/anthropic] reply: {a_text!r}")
+ if a_text:
+ print("[image/anthropic] PASS source/base64 accepted, non-empty response")
+ else:
+ print("[image/anthropic] WARN source/base64 accepted but empty content -- Mac quant drift")
+ except Exception as exc:
+ print(
+ f"[image/anthropic] WARN anthropic image SDK call raised: "
+ f"{type(exc).__name__}: {exc}. Likely upstream llama.cpp Mac+vision "
+ f"crash, NOT an Unsloth regression."
+ )
+ PY
+
+ - name: Stop Unsloth
+ if: always()
+ run: |
+ kill "${STUDIO_PID}" 2>/dev/null || true
+ sleep 2
+ lsof -nP -iTCP:"${STUDIO_PORT}" -sTCP:LISTEN || true
+
+ - name: Upload logs
+ # Always upload so green runs are still reviewable.
+ if: always()
+ # Diagnostic only: a transient artifact-service drop must not fail a green job.
+ continue-on-error: true
+ uses: actions/upload-artifact@043fb46d1a93c77aae656e7c1c64a875d1fc6a0a # v7.0.1
+ with:
+ name: json-images-log
+ path: |
+ logs/studio_vision.log
+ logs/install.log
+ retention-days: 1
+
+
# ---------------------------------------------------------------
# Update + uninstall phase, absorbed from studio-mac-update-smoke.yml.
# Same install, same assert-llama-loads.sh, so it was a third macOS
diff --git a/.github/workflows/workflow-trigger-lint.yml b/.github/workflows/workflow-trigger-lint.yml
index e21d23bb80a..ecc4d6410a5 100644
--- a/.github/workflows/workflow-trigger-lint.yml
+++ b/.github/workflows/workflow-trigger-lint.yml
@@ -121,6 +121,7 @@ jobs:
tests/studio/test_gguf_smoke_phases_stay_independent.py \
tests/studio/test_indicator_browsers_run_in_parallel.py \
tests/studio/test_install_phase_timing.py \
+ tests/studio/test_mac_bundled_job_phases.py \
tests/studio/test_mac_host_offload_optin.py \
tests/studio/test_macos_slots_per_commit.py \
tests/studio/test_main_runs_survive_merge_bursts.py \
diff --git a/tests/studio/playwright_chat_ui.py b/tests/studio/playwright_chat_ui.py
index cee0d64f1cb..a44fb2c9f12 100644
--- a/tests/studio/playwright_chat_ui.py
+++ b/tests/studio/playwright_chat_ui.py
@@ -183,10 +183,29 @@ def exercise_permission_mode_controls(page, shoot):
else:
route.continue_()
+ # Every reload in this block used to be followed by a bare
+ # `expect(pill).to_be_visible()` on the default 5s expect timeout.
+ # `domcontentloaded` fires long before React has mounted the composer, and on
+ # a 3-core macOS runner with a paravirtual GPU that gap is regularly wider
+ # than 5s. That is the failure that took studio-mac-ui-smoke red at 35672fc9b
+ # and again at bfcaea465, both times on this exact locator, with green runs on
+ # either side -- a race, not a regression.
+ #
+ # The composer-mount step already settles the network before waiting, for the
+ # same reason and with the same note about macOS. This does the same after
+ # each reload. It asserts exactly what it asserted before; it just stops
+ # asking before the answer can exist.
+ def reload_and_wait_for_pill():
+ page.reload(wait_until = "domcontentloaded")
+ try:
+ page.wait_for_load_state("networkidle", timeout = 30_000)
+ except Exception:
+ pass # best-effort -- proceed even if network never idles
+ expect(pill).to_be_visible(timeout = 30_000)
+
page.route("**/api/chat/settings", refuse_settings_hydration)
set_legacy_confirm(None)
- page.reload(wait_until = "domcontentloaded")
- expect(pill).to_be_visible()
+ reload_and_wait_for_pill()
# Fresh profiles default to Approve for me.
expect_mode("Approve for me")
@@ -230,8 +249,7 @@ def exercise_permission_mode_controls(page, shoot):
try:
for legacy_value, expected_label in migration_cases:
set_legacy_confirm(legacy_value)
- page.reload(wait_until = "domcontentloaded")
- expect(pill).to_be_visible()
+ reload_and_wait_for_pill()
expect_mode(expected_label)
finally:
page.unroute("**/api/chat/settings", refuse_settings_hydration)
@@ -242,8 +260,7 @@ def exercise_permission_mode_controls(page, shoot):
choose("Ask for approval")
expect_mode("Ask for approval")
set_legacy_confirm("false")
- page.reload(wait_until = "domcontentloaded")
- expect(pill).to_be_visible()
+ reload_and_wait_for_pill()
expect_mode("Ask for approval")
cached = page.evaluate("() => localStorage.getItem('unsloth_chat_permission_mode')")
if cached != "ask":
@@ -282,8 +299,7 @@ def exercise_permission_mode_controls(page, shoot):
if stored != "off":
fail(f"Full access overwrote persisted mode with {stored!r}")
- page.reload(wait_until = "domcontentloaded")
- expect(pill).to_be_visible()
+ reload_and_wait_for_pill()
expect_mode("Run automatically")
# Leave the full chat smoke in the fresh-install default.
diff --git a/tests/studio/test_mac_bundled_job_phases.py b/tests/studio/test_mac_bundled_job_phases.py
new file mode 100644
index 00000000000..4dd918d68fb
--- /dev/null
+++ b/tests/studio/test_mac_bundled_job_phases.py
@@ -0,0 +1,243 @@
+# SPDX-License-Identifier: AGPL-3.0-only
+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0
+"""
+The Mac bundle now carries four workflows' worth of phases in one job.
+
+Concurrent macOS jobs are capped at 5 account-wide and that pool is shared with
+unslothai/unsloth-zoo, so the queue, not the execution, is what a macOS slot
+costs: measured over the last 8 green main runs, the UI job executed 1154s
+behind a 17438s queue and the inference job 402s behind a 13252s queue. Folding
+the second into the first returns a slot.
+
+What that buys in queue it risks in isolation. Four phases that used to be four
+runners are now steps in one job, sharing a filesystem, a port space, an
+`$GITHUB_ENV` and a step-outcome graph. Each of the tests below is a way two
+phases can quietly stop testing what their name says while the job stays green:
+
+ - two phases on one port, where the second talks to the first's server;
+ - two phases on one log file, where the second erases the evidence of the
+ first's failure before the artifact upload runs;
+ - a phase with no `if:`, which inherits an implicit `success()` that now means
+ "every step of every earlier phase passed" rather than "the install worked";
+ - the uninstall phase stopping being last, which would leave the phases after
+ it with no Unsloth installed.
+
+None of those is loud. Ports and logs collide silently, an implicit `success()`
+reports as a skip rather than a failure, and a phase running after the uninstall
+fails with an error that names neither the uninstall nor the ordering.
+"""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from pathlib import Path
+
+import pytest
+import yaml
+
+REPO = Path(__file__).resolve().parents[2]
+WORKFLOW = REPO / ".github" / "workflows" / "studio-mac-ui-smoke.yml"
+BOOT_SCRIPT = REPO / ".github" / "scripts" / "boot-studio-api-only.sh"
+
+
+def _boot_defaults() -> tuple[str, str]:
+ """
+ The log path and PID variable boot-studio-api-only.sh uses when not told.
+
+ Read from the script rather than written down here, because the whole point
+ of the scan below is that an omitted `--log` is invisible: the collision this
+ guard exists to catch was two phases both taking this default, and neither
+ workflow line mentioned a file at all.
+ """
+ src = BOOT_SCRIPT.read_text(encoding = "utf-8")
+ log = re.search(r'^LOG="([^"]+)"', src, flags = re.M)
+ pid = re.search(r'^PID_VAR="([^"]+)"', src, flags = re.M)
+ assert log, f"{BOOT_SCRIPT.name} no longer sets a default LOG; this scan is blind"
+ return log.group(1), pid.group(1) if pid else "STUDIO_PID"
+
+
+# The phases, in the order they must run. The update phase is last because it
+# ends by uninstalling and asserting the machine is clean.
+PHASE_MARKERS = (
+ "Drive the chat UI with Playwright",
+ "Run Unsloth API & Auth tests",
+ "Multi-turn determinism via OpenAI + Anthropic SDKs",
+ "Tool calling, server-side tools, thinking on/off",
+ "JSON schema decoding + image input",
+ "Uninstall and verify clean",
+)
+
+
[email protected](scope = "module")
+def job() -> dict:
+ doc = yaml.safe_load(WORKFLOW.read_text(encoding = "utf-8"))
+ jobs = doc["jobs"]
+ assert len(jobs) == 1, f"expected one bundled job, got {list(jobs)}"
+ return next(iter(jobs.values()))
+
+
[email protected](scope = "module")
+def steps(job: dict) -> list[dict]:
+ return job["steps"]
+
+
+def _script(step: dict) -> str:
+ return step.get("run") or ""
+
+
+def _phase_starts(steps: list[dict]) -> list[int]:
+ """
+ Indices of the steps that boot a server, which is what delimits a phase.
+
+ Matched on "boot Unsloth" rather than "boot": several steps in this job are
+ named "Pass bootstrap password ...", and treating one of those as a phase
+ boundary splits a phase in half and reports its own port as a collision.
+ """
+ names = [str(s.get("name") or "") for s in steps]
+ boots = [i for i, n in enumerate(names) if "boot unsloth" in n.lower()]
+ assert boots, "no server boot step found; every scan below would be vacuous"
+
+ # The absorbed phases declare their port and model in a "Phase N environment"
+ # step several steps ahead of the boot, so a boundary drawn at the boot alone
+ # files that port under the PREVIOUS phase and reports a collision against
+ # itself. Where such a step exists, pull the boundary back to it.
+ declarations = [i for i, n in enumerate(names) if re.fullmatch(r"Phase \d+ environment", n)]
+
+ starts: list[int] = []
+ previous = -1
+ for boot in boots:
+ candidates = [d for d in declarations if previous < d < boot]
+ starts.append(candidates[0] if candidates else boot)
+ previous = boot
+ return starts
+
+
+def _phase_of(starts: list[int], index: int) -> int:
+ return max([b for b in starts if b <= index], default = -1)
+
+
+def test_the_bundle_still_carries_every_phase(steps: list[dict]) -> None:
+ """A scan that found no phases would pass every check below."""
+ names = [str(s.get("name") or s.get("uses") or "") for s in steps]
+ blob = "\n".join(names)
+ for marker in PHASE_MARKERS:
+ assert marker in blob, (
+ f"{WORKFLOW.name} no longer runs {marker!r}. Four workflows were folded "
+ f"into this job; a phase that quietly leaves takes its whole surface with "
+ f"it and nothing else covers it."
+ )
+
+
+def test_the_uninstall_phase_runs_last(steps: list[dict]) -> None:
+ """
+ It uninstalls Unsloth and asserts the machine is clean, which is the teardown
+ for the whole job. Anything needing an install after it fails for a reason
+ that names neither the uninstall nor the ordering.
+ """
+ names = [str(s.get("name") or "") for s in steps]
+ uninstall = next(i for i, n in enumerate(names) if n == "Uninstall and verify clean")
+ after = [n for n in names[uninstall + 1 :] if n]
+ # Artifact upload is the only legitimate follower: it needs no install.
+ assert all("Upload" in n for n in after), (
+ f"steps run after the uninstall phase: {after}. That phase removes Unsloth, so "
+ f"anything below it that needs an install now runs against a machine it just "
+ f"deleted."
+ )
+
+
+def test_no_two_phases_bind_the_same_port(steps: list[dict]) -> None:
+ """
+ The phases boot servers in sequence and each kills its own, so a shared port
+ is harmless only for as long as the step order stays exactly as it is. That
+ is a property of the ordering, and the ordering is the thing an edit changes.
+ A phase that finds a previous phase's server still listening does not error:
+ it connects, and tests the wrong model.
+ """
+ # A port legitimately appears several times inside ONE phase: the boot step,
+ # the health wait and the stop step all name it. So group by phase, not by
+ # step, and fail only when two phases share one.
+ starts = _phase_starts(steps)
+ by_phase: dict[str, set[int]] = defaultdict(set)
+ for i, step in enumerate(steps):
+ text = _script(step) + "\n" + yaml.safe_dump(step.get("env") or {})
+ for found in re.findall(r"\b(188\d\d)\b", text):
+ by_phase[found].add(_phase_of(starts, i))
+
+ assert by_phase, "no ports found; this scan would be vacuous"
+ collisions = {port: sorted(phases) for port, phases in by_phase.items() if len(phases) > 1}
+ assert not collisions, (
+ f"these ports are used by more than one phase of the bundled job "
+ f"(values are the index of each phase's boot step): {collisions}. Give each "
+ f"phase its own port; a phase that reaches a server another phase left behind "
+ f"reports a pass against the wrong model."
+ )
+
+
+def test_no_two_phases_write_the_same_server_log(steps: list[dict]) -> None:
+ """
+ The artifact upload publishes these by name. Two phases sharing one path means
+ the later phase truncates the earlier one's log, so a run that went red in an
+ early phase uploads the log of a later phase that passed.
+ """
+ # Grouped by phase for the same reason the port scan is: within one phase the
+ # health wait is *given* the log path so it can tail it on failure, which is a
+ # read, not a second writer.
+ starts = _phase_starts(steps)
+ default_log, _ = _boot_defaults()
+ logs: dict[str, set[int]] = defaultdict(set)
+ for i, step in enumerate(steps):
+ script = _script(step)
+ for pattern in (r"--log (logs/[\w.\-]+)", r"> (?:\")?(logs/[\w.\-]+)"):
+ for found in re.findall(pattern, script):
+ logs[found].add(_phase_of(starts, i))
+ # An invocation with no --log is the case that actually bit: neither
+ # workflow line named a file, so a text scan saw no collision while both
+ # phases wrote the same one.
+ # Checked over the whole step rather than the matched call: the
+ # invocations are backslash-continued across lines, and a regex that
+ # tries to follow the continuation quietly stops at the first line and
+ # then reports every boot as taking the default.
+ if "boot-studio-api-only.sh" in script and "--log" not in script:
+ logs[default_log].add(_phase_of(starts, i))
+
+ assert logs, "no server log targets found; this scan would be vacuous"
+ collisions = {path: sorted(phases) for path, phases in logs.items() if len(phases) > 1}
+ assert not collisions, (
+ f"more than one phase writes these server logs (values are the index of each "
+ f"phase's boot step): {collisions}. The second truncates the first, so the "
+ f"uploaded artifact describes the wrong phase."
+ )
+
+
+def test_every_absorbed_phase_step_says_when_it_runs(steps: list[dict]) -> None:
+ """
+ A step with no `if:` gets an implicit `success()`, which is job-wide. When these
+ phases were their own workflows that meant "the install worked". Bundled behind
+ the UI and API phases it means "and every Playwright test passed", so one flaky
+ browser run silently drops all the inference coverage -- as a skip, which reads
+ green.
+ """
+ names = [str(s.get("name") or "") for s in steps]
+ start = names.index("Phase 1 environment")
+ end = names.index("First update should be a no-op (prebuilt already validated)")
+
+ ungated = [n for s, n in zip(steps[start:end], names[start:end]) if not s.get("if")]
+ assert not ungated, (
+ f"absorbed inference steps with no `if:`: {ungated}. Each inherits a job-wide "
+ f"implicit success(), so a failure in any earlier phase skips them and the run "
+ f"still reports green."
+ )
+
+
+def test_the_absorbed_phases_keep_the_host_offload_opt_out(job: dict) -> None:
+ """
+ Set at job level so a phase added later inherits it. Without it the load
+ returns HTTP 400 and the probe reports an unexpected status several layers
+ from the cause -- which is how the first draft of this bundle broke.
+ """
+ assert (job.get("env") or {}).get("UNSLOTH_ALLOW_HOST_OFFLOAD") == "1", (
+ "the bundled Mac job no longer opts out of the #8883 host-offload guard. "
+ "GitHub's macOS runners have a paravirtual Metal device, so every phase here "
+ "runs the whole model from host RAM and the guard declines the load."
+ )
diff --git a/tests/studio/test_mac_host_offload_optin.py b/tests/studio/test_mac_host_offload_optin.py
index 8817e5aa981..02636e2539e 100644
--- a/tests/studio/test_mac_host_offload_optin.py
+++ b/tests/studio/test_mac_host_offload_optin.py
@@ -34,7 +34,10 @@ REPO = Path(__file__).resolve().parents[2]
WORKFLOWS = REPO / ".github" / "workflows"
ENV_VAR = "UNSLOTH_ALLOW_HOST_OFFLOAD"
-MAC_GGUF = "studio-mac-inference-smoke.yml"
+# The mac GGUF phases were absorbed into the Mac UI job, which is why this is
+# not the file the docstring above was written against. The opt-out moved with
+# them, to that job's env, and is still the only place in the repo it appears.
+MAC_GGUF = "studio-mac-ui-smoke.yml"
OTHER_GGUF = ["studio-inference-smoke.yml", "studio-windows-inference-smoke.yml"]
TRUTHY = ("1", 1, "true", "True", "yes")
diff --git a/tests/studio/test_macos_slots_per_commit.py b/tests/studio/test_macos_slots_per_commit.py
index 0216900e090..bdbd2f70a06 100644
--- a/tests/studio/test_macos_slots_per_commit.py
+++ b/tests/studio/test_macos_slots_per_commit.py
@@ -87,7 +87,6 @@ def test_the_scan_finds_the_macos_workflows_it_claims_to():
names = {name for name, _, _ in _macos_workflows()}
for expected in (
"studio-mac-ui-smoke.yml",
- "studio-mac-inference-smoke.yml",
"studio-mac-install-matrix.yml",
"studio-tauri-smoke.yml",
"mlx-ci.yml",
@@ -117,7 +116,6 @@ def test_no_macos_workflow_runs_on_every_push_to_main():
"name",
[
"studio-mac-ui-smoke.yml",
- "studio-mac-inference-smoke.yml",
"studio-mac-install-matrix.yml",
"studio-tauri-smoke.yml",
"clean-machine-install-ci.yml",
@@ -161,7 +159,6 @@ def _covered(path: str, patterns) -> bool:
"name",
[
"studio-mac-ui-smoke.yml",
- "studio-mac-inference-smoke.yml",
"studio-mac-install-matrix.yml",
"studio-tauri-smoke.yml",
],
@@ -211,7 +208,6 @@ def test_every_helper_a_workflow_executes_is_in_its_trigger(name):
"name",
[
"studio-mac-ui-smoke.yml",
- "studio-mac-inference-smoke.yml",
"studio-mac-install-matrix.yml",
"studio-tauri-smoke.yml",
],
diff --git a/tests/studio/test_smoke_workflows_share_one_script.py b/tests/studio/test_smoke_workflows_share_one_script.py
index e4c7d8ecd97..855a346461b 100644
--- a/tests/studio/test_smoke_workflows_share_one_script.py
+++ b/tests/studio/test_smoke_workflows_share_one_script.py
@@ -23,7 +23,7 @@ REPO = Path(__file__).resolve().parents[2]
SCRIPT = REPO / ".github" / "scripts" / "studio_smoke" / "multi_turn_chat.py"
LEGS = (
"studio-inference-smoke.yml",
- "studio-mac-inference-smoke.yml",
+ "studio-mac-ui-smoke.yml",
"studio-windows-inference-smoke.yml",
)