Skip to content

Studio: precompile bytecode after setup so the first launch does not - #15646

Merged
danielhanchen merged 6 commits into
mainfrom
studio-precompile-bytecode
Oct 28, 2026
Merged

danielhanchen merged 6 commits into
mainfrom
studio-precompile-bytecode

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 28, 2026 •

Copy link
Copy Markdown
Member

uv installs packages without .pyc unless --compile-bytecode / UV_COMPILE_BYTECODE is set, and none of the installers set it. After a fresh install.sh --local, site-packages held 1,020 .pyc for 24,753 .py, so the first Studio launch compiled every module import main loads (about 2,400) before the backend could answer. That first launch cost roughly twice the CPU of every later one.

What changes

  • New studio/precompile_bytecode.py, run by studio/setup.sh and studio/setup.ps1 after the last install phase, only when a dependency pass changed the venv (fresh install, or unsloth studio update that installed something). An update that finds everything current skips it.
  • It only adds missing .pyc: a source that already has one, current or stale, is left alone, so no existing file is modified and a re-run writes nothing.
  • It can never affect the install's outcome:
    • exit 0 on every error, an unwritable directory, a missing interpreter or a crash while listing files;
    • one deadline for the whole compile (240 s by default, UNSLOTH_STUDIO_COMPILE_BYTECODE_TIMEOUT), under the Desktop installer's 5 minute silence report. On a timeout it kills the whole worker tree (taskkill /T on Windows, the process group elsewhere) and removes exactly what this run created: the .pyc it wrote, their temp files and the __pycache__ folders it made;
    • Ctrl+C is passed on as SIGINT after the same cleanup, so setup stops as it does for any other step;
    • skipped when the filesystem has less than 4 GiB free.
  • Opt out with UV_COMPILE_BYTECODE=0 or UNSLOTH_STUDIO_COMPILE_BYTECODE=0; an opted-out install prints nothing extra.
  • Setup prints one line, python precompiling bytecode..., through its existing step helper. It is a plain log line, not a [TAURI:STEP] marker, so the Desktop step counter is unchanged. The helper itself prints nothing.
  • It compiles the venv's site-packages and the editable checkout's studio, unsloth and unsloth_cli packages, never node_modules, frontend, src-tauri or tests. Package discovery ignores PYTHONPATH, the current directory and the script's own folder.
  • install.sh / install.ps1 are unchanged; nothing sets uv's own bytecode option.
  • The helper is registered in tests/test_installer_interactive_prompts.py and in the path filters of cross-platform-parity-ci.yml, which an existing test requires of every installer helper.

Results

Linux x64, CPU torch, fresh copies of a real install.sh --local venv, base and head alternating, n=5. The host was heavily loaded (load average 260 to 330 on 192 cores), so absolute times are high; an earlier quieter run showed the same ratio (8.44 s to 3.89 s CPU).

First Studio launch, import main base this PR
CPU, median (range) 12.76 s (9.90 to 13.13) 6.04 s (5.12 to 6.60)
Wall, median (range) 13.78 s (9.19 to 23.65) 5.81 s (4.50 to 6.54)

A warm launch costs 5 to 6 s CPU on either side, so the first launch now costs the same as a warm one.

Install cost of the step
First compile, 192 cores 7.4 s wall (6.2 to 10.8)
First compile, 4 cores 21.0 s wall
Re-run over a compiled tree 0.3 to 0.5 s
Disk 516 MB

A fresh head install ends with no .py lacking a .pyc; three re-runs on a real install (144,074 files) changed nothing.

Tests

  • New tests/python/test_installer_compile_bytecode.py (28): placement in both setup scripts, the real setup.sh block under bash -euo pipefail and the real setup.ps1 block under PowerShell with fake interpreters that exit 1 or 7 (setup reaches the footer, $LASTEXITCODE and the error preference are restored), read-only trees, a failing compile, a missing interpreter, a crash while planning, the timeout kill and exact undo, Ctrl+C, low disk, the opt-outs, the no-op re-run and the discovery rules. 26 fail on main.
  • Forced timeout at 2 s mid-compile, and a fully read-only venv: in both cases a 43,736-file snapshot of the venv is identical before and after, exit 0, no output.
  • Non-verbose install.sh --local on base, head and head with UV_COMPILE_BYTECODE=0: head adds only the one progress line, the opt-out run adds nothing, all exit 0.
  • The 180 installer-related test files: failing test IDs outside the new file are identical on main and this branch (all already fail on main).
  • The helper runs on Python 3.9, 3.10 and 3.13, including the spawn start method Windows and macOS use.

Follow-up fixes

  • The compile runs in its own session so a timeout can kill its pool workers, which also put it outside setup's process group. The Desktop's Stop sends SIGTERM to that group (install.rs stop_install), and a closed terminal sends SIGHUP; both killed setup but left the compiler writing into the venv. The supervisor now handles SIGTERM and SIGHUP like Ctrl+C: it kills the worker group, undoes the partial compile and dies of the same signal. On a real 6,481-file venv, a SIGTERM to setup's group 0.6 s into the compile left 194 compiler processes running and a changed tree on the previous head; with the fix none survive and the tree is byte-identical. test_a_stop_signal_kills_the_compile_and_undoes_it[SIGTERM|SIGHUP] fails on the previous head and passes now.
  • The process pool is capped at 32 workers. With one worker per core, 192 workers held 3.6 GB of RSS, which a memory-limited container on a large host may not have.
  • The setup.sh gate reads ${_COLAB_NO_VENV:-false}, so a llama-only run that inherits UNSLOTH_SETUP_RERUN=1 cannot stop on an unset variable under set -u.
  • The new test file carries the license header.

Independent check (Linux x64, Python 3.12 uv venv with fastapi, uvicorn, pydantic, transformers, datasets, no .pyc; host heavily loaded, so ratios only): first import wall time 5.1 to 6.2 s on base vs 1.9 to 2.3 s after the step, the same as a warm launch; afterwards 0 of 6,481 sources lack a .pyc, a re-run changes nothing, and a forced 0.3 s timeout leaves the tree byte-identical.

Not covered

  • setup.ps1 has not run end to end on Windows PowerShell 5.1, including Defender and the taskkill path; covered by the test that runs the real block under PowerShell 7 on Linux.
  • macOS, the Desktop app end to end and a non-editable unsloth studio update were not run.
  • CUDA and ROCm torch add more files to compile; the step stays capped at 240 s, and a run cut short is fully undone.

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 28, 2026
@danielhanchen danielhanchen self-assigned this Oct 28, 2026
danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 28, 2026
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex security review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 28, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review 🔄 Running since 2026-10-28T10:58:07.295143Z 3d1cc32 Draft marked ready
🔒 Security Review ✅ Completed 2026-10-28T09:33:51.080375Z 1571957 Manual request
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Delightful!

Reviewed commit: 1571957b7c

ℹ️ About Codex in GitHub

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

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

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

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

@chatgpt-codex-connector

Copy link
Copy Markdown

🛡️ Codex Security Review

Security review completed. No security issues were found in this pull request.

Reviewed commit: 1571957b7c

View security finding report

Only the user who started this review can view the report in Codex.

ℹ️ About Codex security reviews in GitHub

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

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

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

The compile runs in its own session, so the desktop's Stop (SIGTERM to setup's
process group) or a hangup left it compiling into the venv after setup died.
The supervisor now kills the worker group, undoes and dies of the same signal.
Workers are capped at 32 (192 held 3.6 GB RSS), and the setup gate no longer
expands an unset _COLAB_NO_VENV under set -u.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. 👍

Reviewed commit: 5e6287e473

ℹ️ About Codex in GitHub

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

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

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

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

danielhanchen added a commit to Imagineer99/unsloth that referenced this pull request Oct 28, 2026
@danielhanchen
danielhanchen marked this pull request as ready for review October 28, 2026 10:57
@danielhanchen
danielhanchen merged commit 1ba04b0 into main Oct 28, 2026
27 of 98 checks passed
@danielhanchen
danielhanchen deleted the studio-precompile-bytecode branch October 28, 2026 10:58
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ency pass (#15747)

## Summary

`Shell installer tests` fails on main, so every PR's staging CI run of
that lane is red (e.g. #15725, a frontend-only change):

```
FAIL: the rerun check directly follows that dependency pass (expected '    _setup_rerun_if_replaced', got '    _SETUP_VENV_CHANGED=true')
Results: 31 passed, 1 failed
tests/sh/test_setup_rerun_after_replace.sh exited 1
```

#15646 (precompile bytecode after setup) added
`_SETUP_VENV_CHANGED=true` between `install_python_stack` and
`_setup_rerun_if_replaced`, and pinned that order in its own
`tests/python/test_installer_compile_bytecode.py`.
`tests/sh/test_setup_rerun_after_replace.sh` pins the opposite: the
handoff to a replaced `setup.sh` must sit directly behind the dependency
pass, so no line of the old copy runs after the update has swapped the
file. The two tests now contradict each other on main.

Both intents can hold at once:
- The flag is a plain local assignment that only feeds the precompile
gate near the end of the script.
- That gate already fires on `UNSLOTH_SETUP_RERUN=1` too: `if { [
"${_SETUP_VENV_CHANGED:-false}" = true ] || [ "${UNSLOTH_SETUP_RERUN:-}"
= 1 ]; }`.

So setting it after the handoff changes nothing:
- **No replacement:** the flag is set before anything reads it.
- **Replacement:** the exec'd new copy precompiles because of
`UNSLOTH_SETUP_RERUN` (an unexported shell variable would not have
survived the `exec` anyway).

## Change

- **`studio/setup.sh`:** `_setup_rerun_if_replaced` moves back directly
behind `install_python_stack`. `_SETUP_VENV_CHANGED=true` follows it,
still inside the dependency-pass branch, with a one-line comment on why
the order is safe.
- **`tests/python/test_installer_compile_bytecode.py`:** asserts the
handoff is the line right after the dependency pass, and that the flag
is set right behind it in the same branch. It keeps the existing checks
on the gate and the `UNSLOTH_SETUP_RERUN` fallback.

## Testing

- `tests/sh/test_setup_rerun_after_replace.sh`: 31 passed, 1 failed on
main; 32 passed with this change.
- `tests/python/test_installer_compile_bytecode.py`: 30 passed, on both
main and this change.
- Every other test that pins this block passes: 12 shell suites and 4
studio pytest files, including `test_setup_full_deps_override.sh`,
`test_node_pin_update.sh`, the CUDA / XPU / AMD fast-path escapes and
`test_ci_shell_suite_coverage.py`.
- `bash -n studio/setup.sh` is clean.
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…ugh run_pwsh (#15758)

## Summary

`Repo tests (CPU, studio)` fails on main, so it is red on every recent
staging CI run (#15680, #15696, #15716, #15723 and others). Of its 6
failures, 4 are tests that no longer match intentional changes; this PR
fixes those. The other 2 are real product slips on the login screen and
are fixed separately.

**Media picker contracts (3 failures).** #15726 lined the Images, Audio
and Video model pickers up with Chat:
- The picker now uses `className="ml-1.5 max-w-full overflow-hidden
!pl-2.5 !pr-1.5 !h-[var(--studio-chat-control-height,34px)]"`.
- It no longer sets a `triggerLabelClassName` override.

`tests/studio/test_desktop_reliability_frontend_contract.py` still
pinned the old class string and the old label override, and counted two
scaled `!h-[calc(34px*var(--ui-space-scale,1))]` literals on the Images
and Video pages (and one on Audio) that are now the shared token:

```
images-page.tsx states 1 scaled !h-34px, not 2
assert 'className="!h-[34px] max-w-full gap-1 ...' in header
```

**PowerShell spawn (1 failure).**
`tests/python/test_installer_compile_bytecode.py:271` (from #15646)
starts PowerShell with `subprocess.run`.
`tests/studio/test_pwsh_calls_use_the_shared_runner.py` forbids that,
because direct spawns share one PowerShell startup cache across xdist
workers and can die at startup.

## Change

- **`test_desktop_reliability_frontend_contract.py`:**
- The Images and Audio header contracts assert the new picker class
(`_MEDIA_PICKER_CLASS`), and that the label is not overridden, so the
trigger reads like Chat's.
- The scale table's `!h-34px` counts drop to what the pages still state
literally: Images 1, Audio 0, Video 1. The "no bare `!h-[34px]`" half of
that check is unchanged.
- New test `test_the_media_pickers_take_chats_scaled_control_height`:
all three pages use the picker class, and `index.css` still defines
`--studio-chat-control-height` as `calc(Npx * var(--ui-space-scale,
1))`. This keeps the original point of the scale check, a pill that
grows with the UI scale, attached to the token the height now comes
from.
- **`test_installer_compile_bytecode.py`:** the PowerShell case runs
through `run_pwsh` from `tests/_shared/unsloth_pwsh_runner.py`, with the
same argv and keyword arguments.

## Testing

- These three files: 80 passed (pwsh is installed here, so the
PowerShell cases really ran). On main, the same tests fail 4.
- **Sabotage:** with `--studio-chat-control-height` changed to a bare
`33px`, the new scaling test fails.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 29, 2026
…5923)

## Summary

v0.1.912-beta shipped the post-install bytecode precompile from unslothai#15646.
It made `unsloth studio update` and Desktop updates slower on every
desktop OS: every update re-runs setup, which compiles a `.pyc` for
every module in the Studio venv (about 25,000 files, including packages
whose versions did not change). On Windows, Defender real-time
protection also scans each newly written file. Python already compiles
each module lazily the first time it is imported and caches it in
`__pycache__`, which spreads the same work over only the modules a
launch actually loads.

This turns the precompile off by default on every OS and keeps it as an
opt-in.

## What changes

- `studio/setup.ps1` and `studio/setup.sh`: the "Precompile bytecode"
step runs only when `UNSLOTH_STUDIO_COMPILE_BYTECODE` (or
`UV_COMPILE_BYTECODE`) is true (`1`, `true`, `yes`, `on`, case and
whitespace insensitive). A false value on either name still wins.
Without the opt-in the step prints nothing and starts no process.
- `studio/precompile_bytecode.py`: the helper itself also defaults to
off with the same opt-in, so a direct call behaves the same way as
setup.

## Opt-in

```bash
UNSLOTH_STUDIO_COMPILE_BYTECODE=1 unsloth studio update
```

```powershell
$env:UNSLOTH_STUDIO_COMPILE_BYTECODE = "1"
unsloth studio update
```

## Results: 911 to 912 Desktop update, precompile on (main) vs off (this
PR)

Same update command and environment the 911 Desktop app runs, on the
staging runners (CPU torch). "Net saved" is the update time saved minus
the extra time of the first backend `import main` afterwards, which now
compiles on demand.

| runner | update time saved | first `import main`, precompiled / lazy |
net saved |
|---|---|---|---|
| windows-latest | 53.0 s | 4.3 / 14.9 s | 42.4 s |
| windows-11-arm | 93.5 s | 7.4 / 18.4 s | 82.5 s |
| macos-15 | 31.1 s | 4.2 / 7.3 s | 27.9 s |
| ubuntu-latest | 20.4 s | 2.7 / 4.5 s | 18.7 s |
| ubuntu-24.04-arm | 14.4 s | 3.1 / 6.3 s | 11.1 s |

The precompile phase was 41 to 52% of the whole update on every runner,
and 20 to 30% of a fresh install. Modules imported later in a session
also compile on first use and are not counted in the import column.

## What is unchanged

- uv is still never asked to compile (`UV_COMPILE_BYTECODE` is not set
by any installer), and `UV_COMPILE_BYTECODE_TIMEOUT` in `install.sh` /
`install.ps1` stays as is.
- Nothing reads the `.pyc` as a readiness signal: unslothai#15646 only added the
helper, its two call sites, tests and the parity workflow path filter.
No launch timeout, health check or `verify-install` step depends on it.
- Read-only installs: when Python cannot write `__pycache__` (for
example a per-machine install under Program Files), the import still
succeeds and the module is compiled in memory on each launch, the same
behaviour as before unslothai#15646.

## Tests

`tests/python/test_installer_compile_bytecode.py`:
- the `setup.ps1` block (under PowerShell) and the `setup.sh` block
(under bash) do not call the helper with no switch set or after no
dependency pass, and do call it for `UNSLOTH_STUDIO_COMPILE_BYTECODE=1`
/ ` On ` and `UV_COMPILE_BYTECODE=true` / `1`; a false on either name
wins over a true;
- the helper writes nothing without the opt-in and compiles with it; the
existing compile, idempotence and stop-signal tests run with the opt-in
set.

The new default-off cases fail on `main`; on this branch
`test_installer_compile_bytecode.py`,
`test_installer_interactive_prompts.py` (143 passed together) and
`tests/python/test_cross_platform_parity.py` (119 passed) pass.

## Windows detail: Defender exclusions removed (911 to 912 Desktop
update)

Same update command and environment the 911 Desktop app runs, then the
912 installer with `/S /UPDATE`; two runs per arm. "Defender on" = the
runner's drive exclusions removed and real-time protection enabled
before the update. `import main` timed twice from the installed backend
afterwards. Runner speed varies between jobs, so compare within a row
pair.

| Defender real-time | precompile | update total (s) | precompile phase
(s, share) | first / second `import main` (s) |
|---|---|---|---|---|
| off | on (main) | 159.6 / 94.2 | 79.6 / 43.1 (50% / 46%) | 3.8 / 3.4
and 3.2 / 3.2 |
| off | off (this PR) | 70.5 / 66.7 | none | 10.7 / 11.4 and 4.4 / 4.5 |
| on | on (main) | 237.8 / 274.2 | 130.4 / 150.5 (55% / 55%) | 4.6 / 6.1
and 4.1 / 5.5 |
| on | off (this PR) | 124.3 / 122.4 | none | 23.6 / 20.7 and 5.4 / 5.4
|

The precompile writes about 25,000 `.pyc` files for the whole venv on
every update, including packages whose versions did not change. Skipping
it moves about 7 s (Defender off) or 16 to 18 s (Defender on) to the
first backend import after the update, for a net saving of about 36 to
73 s (off) and 60 to 130 s (on). Modules imported later in a session
also compile on first use and are not counted here.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant