Skip to content

Studio: keep the on-demand kernels install importable next to transformers - #17576

Merged
danielhanchen merged 4 commits into
mainfrom
studio-kernels-install-pin
Nov 12, 2026
Merged

danielhanchen merged 4 commits into
mainfrom
studio-kernels-install-pin

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

Summary

When a diffusion load picks a gated attention backend that needs the Hugging Face kernels package (sage, _flash_3_hub, flash_4_hub, and since #17495 an INT8 MiniMax-H3-Image DiT routes to sage on its own), Studio installs kernels on demand with no version. pip takes the newest release (0.18.2 today). With Studio's pinned transformers 5.5.0 that breaks the next process: transformers before 5.13 builds kernels.LayerRepository objects with neither a revision nor a version while transformers.integrations.hub_kernels imports, and kernels 0.15 and newer reject that:

ValueError: Either a revision or a version must be specified.

The process that installed it keeps working, but every later Studio start fails from diffusers import DiffusionPipeline for every image model until kernels is removed by hand.

The Studio installer already ships kernels==0.12.3, so the on-demand install runs where kernels is missing: environments set up without the installer's extras step, or where that step was skipped or failed.

This PR:

  1. Pins the on-demand install to the installed transformers. Next to transformers < 5.13 it installs kernels==0.12.3. From 5.13 on (the first release whose hub_kernels mapping passes version= to every LayerRepository) it installs kernels>=0.12.3. 0.12.3 is the release the Studio installer already ships (requirements/extras-no-deps.txt) and the floor flash_4_hub requires. The pin is exact rather than <0.15 because the install uses --no-deps, and kernels 0.14.0 to 0.16.x import a separate kernels-data package that would be left out, so the install could not be imported. huggingface_hub < 1.10 also gets 0.12.3.
  2. Checks the install before keeping it. After pip, import transformers.activations runs in a fresh interpreter. If it fails, the install is rolled back (uninstalled, or the previous version reinstalled) and kernels is hidden from this process, so the load falls back to the default attention backend with a warning that says why.
  3. Self-heals installs an older Studio already broke. Before diffusers is imported (close_dynamo_import_window and the background media import window), a once-per-process check reads the kernels and transformers versions from package metadata. Only when they predict the conflict does it run the import check in a subprocess, and only when that fails with this exact ValueError does it reinstall kernels at the right spec. If installs are turned off (UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0), the repair fails, or kernels was already imported in this process, it hides kernels from this process instead. transformers' hub_kernels catches the resulting ImportError and imports without hub kernels, and the log gives the one-line pip command that fixes it. A healthy install costs two metadata reads.

There are no UI or flow changes. The FA4 dependency upgrade (kernels==0.12.3) is unchanged and already below the ceiling.

How the transformers boundary was found

I fetched transformers/integrations/hub_kernels.py for each release from 5.5.0 to 5.17.0. In 5.12.1 the mapping still builds LayerRepository(repo_id=..., layer_name=...) without a version. In 5.13.0 every entry passes version=1. Real imports in a CPU venv (dependencies installed, so kernels-data is present for 0.14.x):

transformers kernels import transformers.activations
5.5.0 0.12.3 OK
5.5.0 0.14.1 OK
5.5.0 0.18.2 ValueError
5.12.1 0.14.1 OK
5.12.1 0.15.1 ValueError
5.13.0 0.15.1 OK
5.13.0 0.18.2 OK
5.17.0 0.14.1 OK
5.17.0 0.18.2 OK

GPU evidence (Colab L4, transformers 5.5.0, diffusers 0.42.1)

Base is the merge base d6841bbe96. Head is this branch. Colab L4 (sm89), torch 2.14.1+cu130, Python 3.13, transformers 5.5.0, diffusers 0.42.1, huggingface_hub 1.33.0. Each arm starts with kernels uninstalled and runs the real MiniMax-H3-Image INT8 trigger, install_checkpoint_attention(pipe, "cuda", scheme="int8") from diffusion_minimax_h3_image.py, which routes the DiT blocks to sage and goes through the on-demand install. The full checkpoint is 204 GB, so the DiT is a tiny random FluxTransformer2DModel (bf16, CUDA) instead. Each arm then runs a forward pass and imports diffusers in a new process.

Step Base Head
kernels installed on demand 0.18.2 (unpinned) 0.12.3 (kernels==0.12.3)
sage backend in the installing process sage_hub engaged, probe passed (INT8 attention (sage_hub) on 1 DiT blocks) falls back to the default backend: the 0.12.3 hub loader cannot install the current kernels-community/sage-attention build for this torch (FileNotFoundError), logged
forward pass finite finite
NEW process from diffusers import DiffusionPipeline fails: ValueError: Either a revision or a version must be specified. imports

Self-heal, starting from the broken state base left behind (kernels 0.18.2 with transformers 5.5.0):

Case Result
Head, installs allowed: close_dynamo_import_window and then a diffusers import in the same process imports. Logged kernels 0.18.2 cannot be imported by transformers 5.5.0; reinstalled kernels==0.12.3 (now 0.12.3). The next process imports too.
Head, UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0 imports. kernels stays 0.18.2 and is hidden for that process, with a log line giving the pip command that repairs it.

Which kernels release can load the sage hub build here and still keep transformers 5.5.0 importable (same L4, each release installed with its dependencies):

kernels Studio sage hub load import transformers.activations on 5.5.0
0.12.3 no (FileNotFoundError for the build) OK
0.13.0, 0.14.0 no (Illegal header value in the user agent) OK
0.14.1 no (publisher trust check) OK
0.15.1, 0.16.2, 0.17.3 no (publisher trust check) ValueError
0.18.2 yes, probe passed ValueError

On this stack no kernels release does both. Next to transformers < 5.13, the hub sage backend therefore falls back to the default backend instead of breaking every later start. On transformers >= 5.13 the install is unchanged in practice (kernels>=0.12.3 resolves to the newest release).

Tests

  • New tests/test_kernels_compat.py (CPU, no network, 30 tests): spec selection per transformers version (including pre-releases, an unknown version, and an old hub), conflict prediction against the measured matrix, the on-demand install passing the pinned spec and then running the import check, rollback (uninstall, or reinstall of the previous version) plus hiding when the check fails, keeping the install when the check cannot run, and every self-heal branch: metadata only with no conflict, repair, hide with installs off, hide when kernels is already imported, and leaving a working pair alone. It also checks that the hook runs in both diffusers import windows. One test uses the real transformers: a stand-in kernels that raises this exact ValueError breaks import transformers.activations, and after hide_kernels() the import succeeds. It passes on transformers 5.5.0 and 5.17.0.
  • Updated the existing install tests that expected the bare kernels argument and a single subprocess call.
  • tests/test_diffusion_attention.py, tests/test_diffusion_attention_install.py, tests/test_diffusion_attention_rocm_flash.py, and the torch_warmup / diffusers prewarm tests pass. The one failure, test_an_imported_old_kernels_is_not_papered_over (it expects "after Studio restarts" but the message says "after Unsloth restarts"), also fails on main.

Not covered

  • Other transformers import paths outside the diffusers import windows (for example a text model load in a process that never imports diffusers) are not repaired here. They get repaired the next time an image load runs in that environment.
  • A repair inside a process that has already imported kernels only applies after a restart. That process runs without hub kernels.
  • With Studio's transformers 5.5.0, the hub sage / FA3 / FA4 backends do not engage after this change on the stack tested above (torch 2.14.1, cu130). They fall back to the default backend. Getting them to engage on transformers < 5.13 needs a transformers bump to 5.13 or later, which this PR does not do. Older torch builds with kernels 0.12.3 were not tested.
  • Windows, macOS and ROCm were not run. The change is pip plus import logic with no platform branches.

An unpinned on-demand kernels install for the sage / FA3 / FA4 hub backends takes
the newest kernels (0.18.2). transformers before 5.13 builds kernels LayerRepository
objects without a revision or version while importing hub_kernels, which kernels
0.15+ rejects, so every later process failed `import transformers.activations`
and with it every diffusers pipeline import.

- Install kernels>=0.12.3,<0.15 next to transformers < 5.13, kernels>=0.12.3 after.
- After the install, check `import transformers.activations` in a fresh process;
  on failure roll the install back and hide kernels so the load uses the default
  backend.
- Before a diffusers import, repair (or hide for this process) a kernels install
  that an older Studio left in this state.
kernels 0.14.0 to 0.16.x import a separate kernels-data package that the
--no-deps install leaves out, so kernels<0.15 resolved to an install that cannot
import and the hub sage backend fell back to the default. Use the release the
Studio installer already ships.
@danielhanchen danielhanchen self-assigned this Nov 12, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 12, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-12T05:58:06.392546Z 80fc286 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7ef413d5f8

ℹ️ About Codex in GitHub

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

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

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

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

Comment thread studio/backend/utils/kernels_compat.py Outdated
Comment on lines +215 to +217
_healed = True
try:
return _heal(logger)

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Publish the healed flag only after the repair finishes

When a foreground image load arrives while a background media warmup is repairing an incompatible kernels installation, _healed is already true even though _heal() is still running. The foreground caller therefore returns through the unlocked fast path and can import diffusers against the broken or partially replaced installation. The media-import lock does not prevent this: background_media_import() calls the healer before acquiring that lock, so close_dynamo_import_window() can claim the window first. A deterministic two-thread check confirms that the second caller returns while the repair remains in progress. Set the completion flag after _heal() finishes so concurrent callers wait on _heal_lock before importing.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Fixed in 80fc286: the healed flag is now set in a finally after the repair returns, so a second caller waits on the lock until it finishes. Added a two-thread test that fails on the previous head.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 80fc28640d

ℹ️ 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
danielhanchen merged commit 9c4e41c into main Nov 12, 2026
@danielhanchen
danielhanchen deleted the studio-kernels-install-pin branch November 12, 2026 07:07
danielhanchen added a commit that referenced this pull request Nov 13, 2026
…ttention on current torch (#17589)

## Summary

Three changes to Studio's transformers tiers and diffusion attention:

1. **Default transformers 5.5.0 -> 5.5.4.** The main env pin moves in
`extras-no-deps.txt`, `no-torch-runtime.txt`,
`single-env/constraints.txt` and
`single-env/overrides-darwin-arm64.txt`, and
`TRANSFORMERS_DEFAULT_VERSION` follows. The Gemma 4 sidecar
(`.venv_t5_550`) moves to 5.5.4 with it, so a Gemma 4 / DiffusionGemma /
LLaDA load never steps back below the main env.
2. **Highest sidecar 5.10.2 -> 5.13.1.** `.venv_t5_510` is the highest
pre-installed tier and now holds 5.13.1 (`setup.sh`, `setup.ps1`,
`TRANSFORMERS_510_VERSION`). The directory name and the `"510"` tier key
stay as they are, so existing installs rebuild that sidecar in place on
the next update and nothing that stores a tier key changes. Custom-code
models saved by 5.11 to 5.13 now route to this tier instead of needing
the opt-in latest sidecar. 5.13.1 checks `safetensors>=0.8.0` at import
and the sidecar installs `--no-deps` over the main env, so `studio.txt`
now asks for `safetensors>=0.8.0` on every platform (it was Windows
only).
3. **SageAttention works again in the diffusion path.** See below.

The opt-in `.venv_t5_latest` sidecar is unchanged: it still installs
whatever PyPI's latest release is when the user consents. There is no
other transformers ceiling in Studio; the `<=5.17.0` cap in
`pyproject.toml` is Unsloth Core's and is untouched.

## Why sage never engaged

transformers before 5.13 can only be imported next to `kernels` < 0.15,
so the installer ships `kernels==0.12.3` and #17576 keeps it there.
kernels 0.12.3 downloads from the model-type copy of
`kernels-community/sage-attention`. That copy's newest builds are for
torch 2.12. The current builds (torch 2.10 to 2.15) live in the
kernel-type repo, which newer kernels releases read (0.18.2 does, 0.12.3
does not). On the cu130 / Python 3.13 route the installer takes on
Colab, which installs torch 2.13, every `sage` request therefore falls
back to native:

```
version 2: FileNotFoundError: Cannot install kernel from repo kernels-community/sage-attention
version 1: FileNotFoundError: Cannot install kernel from repo kernels-community/sage-attention
version 3: ValueError: Version 3 not found, available versions: 1, 2
```

No kernels release both reads the kernel-type repo and keeps
transformers 5.5 importable, so this PR does not change the kernels pin.
Instead `core/inference/diffusion_sage_hub.py` loads the build without
the `kernels` package:

- It works out the build variant names this torch can load (both
`torch213-cxx11-cu130-x86_64-linux` and the newer
`torch213-cu130-x86_64-linux`, plus older CUDA minors of the same
major).
- It lists the kernel-type repo (version 2 first, since it also covers
sm100, then version 3) and falls back to the model-type copy.
- It downloads `metadata.json` first and checks the build's CUDA archs
against the card, so a T4 or an RTX PRO 6000 never downloads the build.
- It downloads that one variant, checks every file against the sha256
digests in `metadata.json`, refuses builds that declare Python
dependencies, and imports it under a private module name.

`_load_sage_hub_kernel` tries this first and keeps `kernels.get_kernel`
as the fallback. transformers' own `kernels` import is never touched,
and the existing accuracy probe, dispatch guard and opaque custom op are
unchanged.

`kernels_compat` now pins the on-demand kernels install on the oldest
transformers that will import it, which is the main env or any sidecar
(they install `--no-deps` over the same env). With this PR the 5.3.0 and
5.5.4 sidecars and the 5.5.4 main env all keep it at `kernels==0.12.3`.
A future main env on 5.13+ would still get 0.12.3 while an older sidecar
exists.

## GPU evidence (Colab L4 and A100 40GB)

Each VM did a fresh `install.sh --local` of this branch (exit 0, 180 s
on both), which picked Python 3.13, torch 2.13.0+cu130, transformers
5.5.4, tokenizers 0.22.2, kernels 0.12.3, diffusers 0.42.1,
huggingface_hub 1.33.0 and safetensors 0.8.0.

transformers import in the main env and in each sidecar (`import
transformers.activations` and `transformers.integrations.hub_kernels`,
with the installed kernels 0.12.3), on both VMs:

| Env | transformers | Imports | `gemma4_unified` in CONFIG_MAPPING |
|---|---|---|---|
| main env (`unsloth_studio`) | 5.5.4 | OK, plus `from diffusers import
DiffusionPipeline` OK | no |
| `.venv_t5_530` | 5.3.0 | OK | no |
| `.venv_t5_550` | 5.5.4 | OK | no (`gemma4` yes) |
| `.venv_t5_510` | 5.13.1 | OK | yes |

Sage, base vs head. Same VM and same installed env for both arms. Only
the Studio backend tree differs: base is the merge base `c6712db78f` and
head is this branch. The render is FLUX.2 [klein] 4B (bf16, 768x768, 4
steps, seed 1234) through `apply_attention_backend(pipe, "sage",
target=pipe.transformer)`. The call counter wraps the `sage_hub` kernel
function after the backend is applied:

| | L4 base | L4 head | A100 base | A100 head |
|---|---|---|---|---|
| hub build loads | no (`FileNotFoundError`) | yes, 10.4 s cold | no
(`FileNotFoundError`) | yes, 6.5 s cold |
| probe, head_dim 64 (cos / rel L1) | not reached | 0.99939 / 0.0351
PASS | not reached | 0.99994 / 0.0105 PASS |
| probe, head_dim 128 (cos / rel L1) | not reached | 0.99939 / 0.0347
PASS | not reached | 0.99994 / 0.0109 PASS |
| backend engaged | native | `sage_hub` | native | `sage_hub` |
| sage kernel calls in the render | 0 | 100 (25 attention blocks x 4
steps) | 0 | 100 |
| masked calls rerouted to native | 0 | 0 | 0 | 0 |
| LPIPS vs the native render | 0.0 (it is the native render) | 0.0178
(PSNR 29.7 dB) | 0.0 | 0.0040 (PSNR 37.8 dB) |
| peak VRAM | 16.28 GiB | 16.28 GiB | 16.28 GiB | 16.28 GiB |

The probe gate is cosine >= 0.99 and relative L1 <= 0.08 against fp32
SDPA. Two native renders with the same seed are bit-identical (LPIPS
0.0), so the sage deltas are the kernel's quantization and not
run-to-run noise. Both are well inside the 0.10 LPIPS bar Studio uses
for lossy diffusion paths. These are single-render smoke timings on
shared VMs, so no speed claim is made.

Default-tier training on the same L4 install: Unsloth LoRA SFT,
Qwen2.5-0.5B-Instruct 4-bit, 20 steps, transformers 5.5.4 loaded from
the main env. Loss went from 2.778 to 0.280, and greedy decoding of a
held-out prompt gives the right answer.

The 5.5.0 -> 5.5.4 change itself was checked separately on the Core jobs
matrix (T4 and L4, everything else pinned identically): sft, dpo, orpo,
moe_sft and inference_smoke are bit-identical, vision_sft is within
tolerance, and vLLM 0.28 runs on 5.5.4, which it does not on 5.5.0 (vLLM
0.19.1 to 0.23 exclude 5.5.0 and 0.24+ require >= 5.5.3).

## Tests

- New `tests/test_diffusion_sage_hub.py` (CPU, no network): variant
names, CUDA arch compatibility for A100 / L4 / H100 / B200 / RTX PRO
6000 / T4, digest tampering, refused Python dependencies, kernel-repo
then model-copy order, metadata-only fetch on an unsupported card, the
offline cache path, a real import with relative submodules, and the
order inside `_load_sage_hub_kernel` (the direct build wins,
`get_kernel` is the fallback, and nothing downloads while `kernels` is
not importable).
- `tests/test_kernels_compat.py`: sidecar scan (skips `.staging` /
`.old`), oldest-version keying, pre-release ordering.
- `tests/studio/install/test_transformers_tokenizers_pair.py`: windows
for 5.5.4 and 5.13.1, and a new check that every sidecar release
declares the same tokenizers window the main env installs.
- Tier routing tests updated to read the version constants; added a case
where 5.12 and 5.13 custom code now fits the 5.13.1 sidecar without the
latest-tier offer.
- The Studio backend tier, kernels, diffusion attention, sage gate,
export, LTX-2.5, MOSS and native audio suites pass. One failure,
`test_an_imported_old_kernels_is_not_papered_over`, fails the same way
on `main`.

## Not covered

- T4 (sm75) and RTX PRO 6000 / G4 (sm120): neither hub build lists these
archs, so sage declines with the reason logged and nothing beyond
`metadata.json` is downloaded. This is covered by unit tests and by the
archs read from the live hub metadata, but was not run on those GPUs.
- H100 and B200 were not run.
- Windows and macOS: the direct loader is Linux only, and other
platforms keep the `kernels.get_kernel` path they had. `setup.ps1`
sidecar bumps were not run on Windows.
- Updating an existing install, where the 550 and 510 sidecars rebuild
and safetensors moves up, was not exercised. Only fresh installs were.
- No Gemma 4 Unified or other 510-tier model was loaded or trained on
5.13.1. That sidecar was checked only by import and its config mapping.
Custom-code models that ran on 5.10.2 now run on 5.13.1 and were not
tested.
- The render was driven through `apply_attention_backend` with a
diffusers pipeline, not through the Studio UI.
- The kernel-type `kernels-community/sage-attention` repo currently
redirects to `SageAttention/sage-attention`. The loader follows that
redirect and verifies digests, but does not check the sigstore
signature.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant