Repository navigation
Studio: keep the on-demand kernels install importable next to transformers - #17576
Conversation
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.
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex review |
There was a problem hiding this comment.
💡 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".
| _healed = True | ||
| try: | ||
| return _heal(logger) |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
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.
|
@codex review |
|
Codex Review: Didn't find any major issues. Bravo. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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". |
…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.
Summary
When a diffusion load picks a gated attention backend that needs the Hugging Face
kernelspackage (sage,_flash_3_hub,flash_4_hub, and since #17495 an INT8 MiniMax-H3-Image DiT routes tosageon its own), Studio installskernelson 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 buildskernels.LayerRepositoryobjects with neither a revision nor a version whiletransformers.integrations.hub_kernelsimports, and kernels 0.15 and newer reject that:The process that installed it keeps working, but every later Studio start fails
from diffusers import DiffusionPipelinefor every image model untilkernelsis removed by hand.The Studio installer already ships
kernels==0.12.3, so the on-demand install runs wherekernelsis missing: environments set up without the installer's extras step, or where that step was skipped or failed.This PR:
kernels==0.12.3. From 5.13 on (the first release whose hub_kernels mapping passesversion=to everyLayerRepository) it installskernels>=0.12.3. 0.12.3 is the release the Studio installer already ships (requirements/extras-no-deps.txt) and the floorflash_4_hubrequires. The pin is exact rather than<0.15because the install uses--no-deps, and kernels 0.14.0 to 0.16.x import a separatekernels-datapackage that would be left out, so the install could not be imported. huggingface_hub < 1.10 also gets 0.12.3.import transformers.activationsruns in a fresh interpreter. If it fails, the install is rolled back (uninstalled, or the previous version reinstalled) andkernelsis hidden from this process, so the load falls back to the default attention backend with a warning that says why.close_dynamo_import_windowand the background media import window), a once-per-process check reads thekernelsandtransformersversions 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 exactValueErrordoes it reinstallkernelsat the right spec. If installs are turned off (UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0), the repair fails, orkernelswas already imported in this process, it hideskernelsfrom this process instead. transformers' hub_kernels catches the resultingImportErrorand 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.pyfor each release from 5.5.0 to 5.17.0. In 5.12.1 the mapping still buildsLayerRepository(repo_id=..., layer_name=...)without a version. In 5.13.0 every entry passesversion=1. Real imports in a CPU venv (dependencies installed, sokernels-datais present for 0.14.x):import transformers.activationsGPU 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 withkernelsuninstalled and runs the real MiniMax-H3-Image INT8 trigger,install_checkpoint_attention(pipe, "cuda", scheme="int8")fromdiffusion_minimax_h3_image.py, which routes the DiT blocks tosageand goes through the on-demand install. The full checkpoint is 204 GB, so the DiT is a tiny randomFluxTransformer2DModel(bf16, CUDA) instead. Each arm then runs a forward pass and imports diffusers in a new process.kernels==0.12.3)sage_hubengaged, probe passed (INT8 attention (sage_hub) on 1 DiT blocks)kernels-community/sage-attentionbuild for this torch (FileNotFoundError), loggedfrom diffusers import DiffusionPipelineValueError: Either a revision or a version must be specified.Self-heal, starting from the broken state base left behind (kernels 0.18.2 with transformers 5.5.0):
close_dynamo_import_windowand then a diffusers import in the same processkernels 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.UNSLOTH_DIFFUSION_ATTENTION_INSTALL=0Which 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):
import transformers.activationson 5.5.0FileNotFoundErrorfor the build)Illegal header valuein the user agent)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.3resolves to the newest release).Tests
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 whenkernelsis 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-inkernelsthat raises this exactValueErrorbreaksimport transformers.activations, and afterhide_kernels()the import succeeds. It passes on transformers 5.5.0 and 5.17.0.kernelsargument 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 onmain.Not covered
kernelsonly applies after a restart. That process runs without hub kernels.