Repository navigation
tests/studio: tighten MLX smoke gates (loss + round-trip, _on_step grad_norm) - #5537
Conversation
The MLX trainer's step callback now passes a ninth positional argument (grad_norm) per unsloth_zoo/mlx/trainer.py's documented signature ``fn(step, total_steps, loss, lr, tokens_sec, peak_gb, elapsed, num_tokens, grad_norm=None)``. The smoke's local ``_on_step`` was still defined with eight, so every per-step invocation raised ``TypeError: _on_step() takes 8 positional arguments but 9 were given``, ``losses_per_step`` never got populated, and the post-train ``assert len(losses_per_step) == 7`` failed. Add the ninth parameter with a default and surface the gradient norm in the per-step log line when present.
…wins unsloth_zoo PR #5340 added per-element gradient clipping to MLXTrainer and defaulted ``MLXTrainingConfig.max_grad_value = 5.0``. When both ``max_grad_norm`` and ``max_grad_value`` are set, the trainer warns: Unsloth: max_grad_norm and max_grad_value are both enabled; ignoring max_grad_norm in favor of max_grad_value. and silently drops the test's ``max_grad_norm=1.0``. +-5.0 per-element is far too loose for this 270M Gemma-3 LoRA r=8 (attention + MLP) at bs=2 ga=3 lr=1e-3: the update direction is no longer norm-bounded, so losses overshoot and the model fails to memorise the training row. Reproduced on a CUDA mirror (scripts/cuda_mlx_mirror_sim.py): norm_1 (max_grad_norm=1.0, no clip): losses 7.64 -> 0.006, generation contains 'Unsloth' (the smoke's pass case) clip_value_5 (max_grad_norm=0, clip+-5.0): losses 7.29 -> 8.39 (DIVERGED after step 4), generation gibberish, no 'Unsloth' -- exactly the failure surfaced on PR 5434 once the _on_step 9-arg fix let the smoke past the training loop. Pin ``max_grad_value=0.0`` so the smoke uses the same ``max_grad_norm= 1.0`` clipping it was designed against. Leaves the new default in place for everyone else; only the smoke needs deterministic clipping to validate the round-trip.
Refresh the rationale comment to reflect the new default landing in unslothai/unsloth-zoo#652 (max_grad_value=1.0, not 5.0). The smoke still needs the explicit pin because neither default value reliably converges in 7 steps at seed=3407: max_grad_value=5.0 -- diverges after step 4 (loss 7.3 -> 8.4) max_grad_value=1.0 -- stalls (loss ~3.2 plateau across seeds) max_grad_value=0.5/0.25/0.1 -- noisier still max_grad_norm=1.0 -- cleanly drops loss to <0.01, emits "Unsloth!" Mention both the historical 5.0 default and the new 1.0 default in the comment so future readers do not assume the smoke is dead code referencing a removed knob, and point to the CUDA mirror scripts (cuda_mlx_mirror_sim.py + cuda_mlx_clip1_vs_norm1.py) for the empirical evidence. No behaviour change; comment-only refresh.
…ates
The MLX smoke's three "EXPECT in completion" assertions assume the
trained model will greedy-emit the exact "Unsloth" token after the
prompt. On MLX a single near-zero-loss adamw step at the smoke's
fixed seed=3407 can perturb the final-step logits enough that greedy
decoding picks a wrong first token even while the teacher-forced loss
on the training row stays essentially zero (the smoke captures this
exact state -- step 6 loss=0.049, step 7 grad=36.7, step 7 loss=0.17;
completion goes from "Unsloth!" to "5 lbs!"). Reproduced extensively
on CUDA via scripts/cuda_mlx_step7_*.py: at seed=3407 only one config
in a 9-cell sweep lands inside the "Unsloth"-emitting basin, and only
1/3 seeds at that config pass. This is a property of the assertion,
not of save/reload correctness.
Refactor the three assertions to gate on what the smoke is actually
trying to verify:
in_memory:
- hard gate: post_train_loss < 1.0 (training memorised the row).
- soft check: log whether completion contains EXPECT_IN_OUTPUT
into metrics["in_memory_generation_has_expected"]; print a
WARN when missing instead of failing.
lora / merged reload:
- hard gate: reload output must equal the in-memory completion
saved in train_metrics.json. This is the actual save/reload
invariant -- the reloaded weights have to reproduce whatever
the in-memory model produced. Falls back to the original
gibberish gate if train_metrics.json is unavailable.
gguf reload:
- hard gate: llama.cpp produced usable, non-empty output after
the prompt (>=4 chars). llama.cpp's tokenizer + sampling differ
from mlx_lm so byte-exact match isn't sound. Log
gguf_has_expected for visibility.
Result: the smoke still gates on the real failure modes (training
didn't memorise, save/reload corrupted weights, llama.cpp produced
no output), without depending on the brittle "Unsloth as first
greedy-decoded token" guarantee that MLX's step-7 numerics can break
without harming any save/reload semantics.
Cross-version constraint: no transformers / trl API touched.
The strict reload assertion (out == in_mem_out) failed on macOS: in-memory completion was '5 lbs!' and the reloaded completion was '_________________________'. Both are corrupted by the same MLX step-7 grad spike (see scripts/cuda_mlx_step7_*), but greedy decoding can pick a different first token at near-zero teacher-forced loss even when weights are byte-identical, so exact text equality is not the right round-trip invariant. Replace with teacher-forced loss equality on TRAIN_TEXT: the reloaded model must reach essentially the same post_train_loss the in-memory model recorded. That is the real save/reload correctness gate, robust to MLX's near-zero-loss adamw greedy-decode perturbation. Falls back to a non-empty-body check when train_metrics.json is missing. CUDA mirror at this seed converges cleanly to ~0.006 loss; on MLX post_train_loss < 1.0 still holds via the existing memorisation gate. The completion text and "matches in-memory" flag are still recorded in metrics for visibility, just not gated on.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e7347643cc
ℹ️ 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".
| metrics["reload_completion_matches_in_memory"] = ( | ||
| in_mem_out is not None and out == in_mem_out | ||
| ) |
There was a problem hiding this comment.
Assert the reload generation round-trip
In the CI workflow the reload steps always follow the train step in the same mlx_workdir, so train_metrics.json exists and this boolean is only recorded, not enforced. If a reload regression preserves teacher-forced loss but changes the generation path (for example wrong tokenizer/EOS handling or adapter activation during generate), reload_completion_matches_in_memory can be false and the test still passes via the loss comparison below, so the advertised generation round-trip gate is not actually gating LoRA/merged reloads.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Code Review
This pull request enhances the MLX smoke test by adding gradient norm logging, a robust memorisation gate based on training loss, and cross-process verification of reloaded model weights. The reviewer recommended replacing a broad exception handler with specific exception types and adding logging to improve visibility when loading training metrics fails.
| try: | ||
| tm = json.loads(train_metrics_path.read_text()) | ||
| in_mem_loss = tm.get("post_train_loss") | ||
| in_mem_out = tm.get("in_memory_generation") | ||
| except Exception: | ||
| in_mem_loss = None |
There was a problem hiding this comment.
Avoid using broad, silent exception handlers. If train_metrics.json exists but fails to load (e.g., due to corruption or permission issues), the loss round-trip verification will be silently skipped in favor of a much weaker fallback check. Logging the exception provides visibility into why the stronger verification was bypassed. Additionally, catching specific exceptions like OSError and json.JSONDecodeError is preferred over a broad Exception catch to avoid suppressing unrelated errors.
| try: | |
| tm = json.loads(train_metrics_path.read_text()) | |
| in_mem_loss = tm.get("post_train_loss") | |
| in_mem_out = tm.get("in_memory_generation") | |
| except Exception: | |
| in_mem_loss = None | |
| try: | |
| tm = json.loads(train_metrics_path.read_text()) | |
| in_mem_loss = tm.get("post_train_loss") | |
| in_mem_out = tm.get("in_memory_generation") | |
| except (OSError, json.JSONDecodeError) as e: | |
| print(f" [WARN] failed to load {train_metrics_path}: {e}", flush = True) | |
| in_mem_loss = None |
References
- Avoid using broad, silent exception handlers like
except Exception: pass. Instead, log the exception, even if at a debug level, to aid in future debugging. - When handling exceptions, avoid broad
except Exception: passclauses. Instead, catch specific exceptions and log them (at least at a debug level) to aid in troubleshooting. If a failure is expected, log the specific exception type and its details.
The seven MLX smoke commits in this PR's history (_on_step grad_norm, max_grad_value pin, loss + round-trip gates) are unrelated to the FLA / tilelang work. They now live in unslothai#5537 so this PR's diff is limited to the studio worker installer changes. Net effect on tests/studio/run_real_mlx_smoke.py vs main: zero.
#5434) * studio: install flash-linear-attention and tilelang for Qwen3.5 family Studio currently only installs causal-conv1d for qwen3.5 / qwen3.6 / qwen3-next models. Without flash-linear-attention installed alongside it, transformers' Qwen3.5 fast-path gate stays False and the model falls back to a pure-PyTorch loop for the GatedDeltaNet layers. In a 60-step run on unsloth/Qwen3.5-2B on B200, this fallback costs ~2.35x vs the full fast path. On top of that, FLA dispatches its hottest GDN kernels through a TileLang backend when tilelang is importable. Adding tilelang plus a pinned apache-tvm-ffi gives another ~26% on the same workload (4.73 s/step to 3.50 s/step) and is what users have been getting indirectly when they install mamba-ssm (mamba-ssm transitively pulls tilelang and pins apache-tvm-ffi<=0.1.9, which is the last working version on sm_100; 0.1.10 and 0.1.11 crash Triton with misaligned address). Changes: * _ensure_flash_linear_attention: pure-Python PyPI install gated on the same model match set as _ensure_causal_conv1d_fast_path. * _ensure_tilelang_backend: installs apache-tvm-ffi==0.1.9 and tilelang==0.1.8 in one pip resolve so the tvm-ffi pin wins over tilelang's >=0.1.2 constraint. Gated on the Qwen3.5 family only; SSM models (Nemotron-H, Falcon-H1, Granite-H, LFM2) do not use FLA's GDN dispatch. * UNSLOTH_STUDIO_SKIP_TILELANG_INSTALL=1 escape hatch matching the flash-attn pattern. * Orchestration block reordered: causal-conv1d -> fla -> mamba-ssm -> tilelang -> flash-attn (long context). * 7 new tests covering the new helpers, including SSM-model skip, skip-env, full Qwen3 family name variants, and graceful pip install failure. Combined Qwen3.5-2B-Vision step time on B200 in our bench goes from 5.0 s/step (current Studio: causal-conv1d only) to 3.5 s/step (causal-conv1d + fla + tilelang), a 1.43x speedup with no notebook or user code changes required. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * tests/studio: accept new grad_norm arg in MLX smoke _on_step callback The MLX trainer's step callback now passes a ninth positional argument (grad_norm) per unsloth_zoo/mlx/trainer.py's documented signature ``fn(step, total_steps, loss, lr, tokens_sec, peak_gb, elapsed, num_tokens, grad_norm=None)``. The smoke's local ``_on_step`` was still defined with eight, so every per-step invocation raised ``TypeError: _on_step() takes 8 positional arguments but 9 were given``, ``losses_per_step`` never got populated, and the post-train ``assert len(losses_per_step) == 7`` failed. Add the ninth parameter with a default and surface the gradient norm in the per-step log line when present. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ci: retrigger after zoo drift + IPython fixes landed in main * tests/studio: pin max_grad_value=0 in MLX smoke so max_grad_norm=1.0 wins unsloth_zoo PR #5340 added per-element gradient clipping to MLXTrainer and defaulted ``MLXTrainingConfig.max_grad_value = 5.0``. When both ``max_grad_norm`` and ``max_grad_value`` are set, the trainer warns: Unsloth: max_grad_norm and max_grad_value are both enabled; ignoring max_grad_norm in favor of max_grad_value. and silently drops the test's ``max_grad_norm=1.0``. +-5.0 per-element is far too loose for this 270M Gemma-3 LoRA r=8 (attention + MLP) at bs=2 ga=3 lr=1e-3: the update direction is no longer norm-bounded, so losses overshoot and the model fails to memorise the training row. Reproduced on a CUDA mirror (scripts/cuda_mlx_mirror_sim.py): norm_1 (max_grad_norm=1.0, no clip): losses 7.64 -> 0.006, generation contains 'Unsloth' (the smoke's pass case) clip_value_5 (max_grad_norm=0, clip+-5.0): losses 7.29 -> 8.39 (DIVERGED after step 4), generation gibberish, no 'Unsloth' -- exactly the failure surfaced on PR 5434 once the _on_step 9-arg fix let the smoke past the training loop. Pin ``max_grad_value=0.0`` so the smoke uses the same ``max_grad_norm= 1.0`` clipping it was designed against. Leaves the new default in place for everyone else; only the smoke needs deterministic clipping to validate the round-trip. * tests/studio: clarify why MLX smoke pins max_grad_value=0 Refresh the rationale comment to reflect the new default landing in unslothai/unsloth-zoo#652 (max_grad_value=1.0, not 5.0). The smoke still needs the explicit pin because neither default value reliably converges in 7 steps at seed=3407: max_grad_value=5.0 -- diverges after step 4 (loss 7.3 -> 8.4) max_grad_value=1.0 -- stalls (loss ~3.2 plateau across seeds) max_grad_value=0.5/0.25/0.1 -- noisier still max_grad_norm=1.0 -- cleanly drops loss to <0.01, emits "Unsloth!" Mention both the historical 5.0 default and the new 1.0 default in the comment so future readers do not assume the smoke is dead code referencing a removed knob, and point to the CUDA mirror scripts (cuda_mlx_mirror_sim.py + cuda_mlx_clip1_vs_norm1.py) for the empirical evidence. No behaviour change; comment-only refresh. * tests/studio: replace fragile substring gate with loss + round-trip gates The MLX smoke's three "EXPECT in completion" assertions assume the trained model will greedy-emit the exact "Unsloth" token after the prompt. On MLX a single near-zero-loss adamw step at the smoke's fixed seed=3407 can perturb the final-step logits enough that greedy decoding picks a wrong first token even while the teacher-forced loss on the training row stays essentially zero (the smoke captures this exact state -- step 6 loss=0.049, step 7 grad=36.7, step 7 loss=0.17; completion goes from "Unsloth!" to "5 lbs!"). Reproduced extensively on CUDA via scripts/cuda_mlx_step7_*.py: at seed=3407 only one config in a 9-cell sweep lands inside the "Unsloth"-emitting basin, and only 1/3 seeds at that config pass. This is a property of the assertion, not of save/reload correctness. Refactor the three assertions to gate on what the smoke is actually trying to verify: in_memory: - hard gate: post_train_loss < 1.0 (training memorised the row). - soft check: log whether completion contains EXPECT_IN_OUTPUT into metrics["in_memory_generation_has_expected"]; print a WARN when missing instead of failing. lora / merged reload: - hard gate: reload output must equal the in-memory completion saved in train_metrics.json. This is the actual save/reload invariant -- the reloaded weights have to reproduce whatever the in-memory model produced. Falls back to the original gibberish gate if train_metrics.json is unavailable. gguf reload: - hard gate: llama.cpp produced usable, non-empty output after the prompt (>=4 chars). llama.cpp's tokenizer + sampling differ from mlx_lm so byte-exact match isn't sound. Log gguf_has_expected for visibility. Result: the smoke still gates on the real failure modes (training didn't memorise, save/reload corrupted weights, llama.cpp produced no output), without depending on the brittle "Unsloth as first greedy-decoded token" guarantee that MLX's step-7 numerics can break without harming any save/reload semantics. Cross-version constraint: no transformers / trl API touched. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * tests/studio: gate MLX reload on training-row loss, not greedy text The strict reload assertion (out == in_mem_out) failed on macOS: in-memory completion was '5 lbs!' and the reloaded completion was '_________________________'. Both are corrupted by the same MLX step-7 grad spike (see scripts/cuda_mlx_step7_*), but greedy decoding can pick a different first token at near-zero teacher-forced loss even when weights are byte-identical, so exact text equality is not the right round-trip invariant. Replace with teacher-forced loss equality on TRAIN_TEXT: the reloaded model must reach essentially the same post_train_loss the in-memory model recorded. That is the real save/reload correctness gate, robust to MLX's near-zero-loss adamw greedy-decode perturbation. Falls back to a non-empty-body check when train_metrics.json is missing. CUDA mirror at this seed converges cleanly to ~0.006 loss; on MLX post_train_loss < 1.0 still holds via the existing memorisation gate. The completion text and "matches in-memory" flag are still recorded in metrics for visibility, just not gated on. * ci: retrigger Backend CI after transient pwsh-startup timeout * ci: retrigger MLX dispatch after pytorch CDN DNS flake * studio: harden FLA + tilelang installers per reviewer feedback Addresses bot review on #5434: * Narrow `_ensure_flash_linear_attention` from `_model_wants_causal_conv1d` (which also matches Nemotron-H / Falcon-H1 / Granite-H / LFM2) to `_model_wants_tilelang` (Qwen3.5 / Qwen3.6 / Qwen3-Next only). True SSM families take the mamba_ssm path and never call FLA's GDN kernels, so installing FLA there is wasted bandwidth. * Pin both `flash-linear-attention==0.5.0` and `fla-core==0.5.0` and install with `--no-deps`. Otherwise pip resolves fla-core's declared `torch>=2.7.0` requirement and may silently upgrade the Studio venv's torch on environments running torch 2.4/2.5/2.6. * Skip both installs on Python <3.10 (FLA, fla-core, and tilelang all declare `Requires-Python: >=3.10`). On older interpreters the pip install would fail every launch and leave the worker on the slow torch fallback while still claiming to have set up the fast path. * Skip tilelang install on non-Linux platforms. `tilelang==0.1.8` only publishes Linux x86_64 / aarch64 and macOS arm64 wheels. Falling back to its 93MB sdist on a Studio worker is undesirable. * Detect an existing `apache-tvm-ffi` 0.1.10 / 0.1.11 install and force a reinstall to 0.1.9 with `--force-reinstall --no-deps`. Previously the import-only probe returned early and left the broken version in place, which crashes Triton on sm_100. * Add a 600s timeout to the tilelang and FLA subprocess.run calls, matching the existing flash-attn install pattern, so a network hang cannot block the training subprocess indefinitely. * 13 new / updated tests covering all six guards plus the pinned-spec, timeout, and force-reinstall code paths. Total: 21 passing tests (8 original + 13 new / updated). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: address reviewer.py P1/P2 findings on FLA + tilelang installers Twelve-reviewer aggregated review on this PR flagged several real correctness bugs in the first hardening pass. Fixes: P1: * Add UNSLOTH_STUDIO_SKIP_FLA_INSTALL escape hatch for symmetry with UNSLOTH_STUDIO_SKIP_TILELANG_INSTALL and the existing UNSLOTH_STUDIO_SKIP_FLASHATTN_INSTALL. * Install einops alongside fla-core. `--no-deps` was suppressing fla-core's only non-torch runtime dep, so on a clean venv `import fla.modules` raised ModuleNotFoundError even though pip exited 0. * Drop --no-deps from the tilelang force-reinstall path. tilelang needs z3-solver, ml-dtypes, cloudpickle, etc. at runtime; --force-reinstall --no-deps left libz3.so missing and `import tilelang` raised OSError on the next training subprocess. * Skip FLA install when installed torch is below 2.7.0 (fla-core declares torch>=2.7.0). Otherwise users on Studio's supported torch 2.4/2.5/2.6 stacks get an incompatible FLA installed silently. P2: * Replace bare `except ImportError` probes with helpers that catch `Exception` so a broken native package (OSError on missing .so, RuntimeError in __init__, ...) does not kill the worker before the fallback path can run. * Tighten the tilelang platform guard from "any linux" to "linux + machine in {x86_64, aarch64, ...}" so ppc64le / s390x / armv7 do not fall through and download the 93 MB tilelang sdist. * Add --only-binary=:all: to the tilelang install command. The comment already said we never want the sdist; now the pip invocation enforces it. * Verify both FLA and tilelang are importable after pip exits 0; if not, report and continue on the fallback path. 6 new tests bring the suite to 27 passing (was 21). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: pin packaging + triton with FLA --no-deps install An end-to-end install simulation in a fresh venv caught a real regression: `fla/utils.py` does `from packaging import version` and `import triton` at module load, but fla-core's METADATA only declares einops + torch. With `--no-deps` the worker would land FLA in any runtime that lacks packaging (e.g. minimal torch builds) and the post-install import probe would fall back to the torch GDN loop silently. Add `packaging` and `triton` to `_FLA_RUNTIME_DEPS` so the install spec list always carries them. Tests updated to assert both are now in the install command. * studio: hook transformers' fast-path gates for just-in-time FLA + causal-conv1d install The substring-based detection in this PR (`_model_wants_tilelang` / `_model_wants_causal_conv1d`) is brittle: it depends on what the user typed for the model name, not on what the architecture actually needs. Users typing custom model paths, future Qwen3.7 / non-Qwen GDN architectures, and any model whose author renamed it would silently fall back to the torch loop. The correct signal is the one transformers itself uses to gate the fast path. `transformers/models/qwen3_5_moe/modeling_qwen3_5_moe.py` does at module import time: if is_causal_conv1d_available(): from causal_conv1d import causal_conv1d_fn, causal_conv1d_update if is_flash_linear_attention_available(): from fla.modules import FusedRMSNormGated from fla.ops.gated_delta_rule import ( chunk_gated_delta_rule, fused_recurrent_gated_delta_rule, ) Wrap both gates so the first call (always at modeling import, before any forward pass) installs the matching kernel synchronously and delegates to the original function. Any model whose architecture queries those gates auto-triggers the install; models that never query them (Llama, Gemma, dense Qwen, ...) never pay the cost. Mechanics: - Split `_ensure_flash_linear_attention` and `_ensure_tilelang_backend` into `_unconditional` variants (no substring gate, retains python / torch / platform / skip-env guards) plus thin substring wrappers used by the legacy fallback path. - New `_install_fast_path_hooks(event_queue)` patches both gates on `transformers.utils.import_utils` AND sweeps `sys.modules` so any modeling file that already did `from ... import is_X` sees the wrapper (the local binding survives a module-level reassignment). - Wrappers clear the original's `lru_cache` before delegating, install on False, re-check, and short-circuit on subsequent calls. - Set `UNSLOTH_STUDIO_SKIP_FAST_PATH_HOOKS=1` to fall back to the substring path. Verified end-to-end against `transformers.models.qwen3_5_moe`: PRE_STATE fla=False tilelang=False causal_conv1d=False HOOK_INSTALLED Hook fired for is_causal_conv1d_available; installing kernel... Installing prebuilt causal-conv1d wheel... Hook fired for is_flash_linear_attention_available; installing kernel... Installing flash-linear-attention==0.5.0 (with fla-core==0.5.0) for the fast path... Installed flash-linear-attention for the FLA fast path Installing TileLang backend (apache-tvm-ffi==0.1.9, tilelang==0.1.8)... Installed TileLang backend for FLA fast path MODELING_IMPORT_OK FAST_PATH_SYMBOLS {"chunk_gated_delta_rule": true, "fused_recurrent_gated_delta_rule": true, "FusedRMSNormGated": true, "causal_conv1d_fn": true, "causal_conv1d_update": true} POST_STATE fla=True tilelang=True causal_conv1d=True Adds 9 new tests covering: install-on-False, skip-on-True, idempotency, install-failure handling, env-disable, lru_cache clear, sys.modules rebind, missing-transformers fallback, substring fallback. Total test count is now 36 (was 27). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: address reviewer.py n=12 findings on the FLA hook path Eight issues reproduced by parallel reviewers against 6ce495a; all fixed and covered by regression tests. 45 pytest cases pass (was 36); end-to-end Qwen3.5_MoE modeling-import drill still loads all five fast-path symbols. P1 fixes: 1. TileLang loses the Qwen-family guard on the normal FLA hook path (10/12 reviewers, reproduced with allenai/OLMo-Hybrid-1B). The hook unconditionally installed tilelang for any FLA-using model. - Threaded `model_name` through `_install_fast_path_hooks(event_queue, model_name)`. - `_fla_install` now gates tilelang on `_model_wants_tilelang(model_name)` AND a successful FLA install. 2. TileLang repair `--force-reinstall` (without `--no-deps`) could replace `torch==2.12.0+cu130` with `torch==2.12.0`. Split repair into TWO steps: step 1: `--force-reinstall --no-deps apache-tvm-ffi==0.1.9` step 2: regular install of tilelang + apache-tvm-ffi Step 1 surgically downgrades the broken package; step 2 resolves missing transitive deps (z3-solver, ml-dtypes) without --force-reinstall, so it never replaces torch. 3. Hook could return True after the installer's deep import probe failed: when pip exits 0 but `import fla.modules` raises, the old wrapper re-called `original()` (transformers' metadata check) and trusted it. Refactored: - `_ensure_flash_linear_attention_unconditional(...) -> bool` - `_ensure_tilelang_backend_unconditional(...) -> bool` The wrapper now uses the installer's bool directly. 4. SSM models (Nemotron-H, Falcon-H1, Granite-H) use `lazy_load_kernel("causal-conv1d")` and never call `is_causal_conv1d_available()`, so the hook never fires for them. The orchestrator now always runs `_ensure_causal_conv1d_fast_path` outside the hook-mode if/else. P2 fixes: 5. `_rebind_in_already_imported_modules` invoked transformers' lazy module `__getattr__` (hundreds of "Accessing X from .models..." warnings, ~3.4s overhead). Switched to `module.__dict__.get(...)` which only sees real module-level bindings. 6. TileLang installed even when FLA was skipped (Torch <2.7) or failed (timeout, post-install probe failed). Now gated on the installer's bool return. 7. TileLang repair was skipped when FLA was already True but tilelang missing or apache-tvm-ffi on the broken list. Added an optional `post_available_fn` to the wrapper; the FLA hook's `_fla_post_available` runs `_ensure_tilelang_backend_unconditional` when (model wants tilelang) AND (tilelang missing OR tvm-ffi broken). 8. `_flash_linear_attention_importable()` only checks deep import, not version. Added `_flash_linear_attention_current()` that compares against the pinned `flash-linear-attention==0.5.0` / `fla-core==0.5.0`; older versions trigger `--force-reinstall --no-deps` so torch stays untouched. Helpers extracted to keep the surface tight: - `_pip_install_cmd(*args)` builds `uv pip install` or `python -m pip install` depending on uv availability. - `_run_pip(cmd, event_queue, label)` runs a pip command with timeout / failure handling and a status emission. Regression tests added: - test_hook_does_not_install_tilelang_for_non_qwen_fla_model - test_hook_does_install_tilelang_for_qwen35 - test_tilelang_repair_does_not_touch_torch_cuda_stack - test_hook_trusts_installer_bool_not_metadata - test_rebind_does_not_trigger_module_getattr - test_hook_skips_tilelang_when_fla_install_is_skipped - test_hook_runs_tilelang_repair_when_fla_already_true - test_fla_installer_force_reinstalls_when_older_version_present - test_run_training_process_eagerly_installs_causal_conv1d_in_normal_mode Existing tests updated for the new `_install_fast_path_hooks` signature and the two-step tilelang repair flow. End-to-end re-verified against transformers.models.qwen3_5_moe: PRE_STATE fla=False, hook fires for both gates, FLA + tilelang + causal-conv1d install, all 5 fast-path symbols non-None. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: fix double-install of tilelang on the FLA hook install path Backend CI surfaced a test-isolation bug introduced by the post_available_fn mechanism for finding #7. The wrapper ran `post_available_fn` in BOTH paths (install ran AND gate already True), but `_fla_install` already chains tilelang on the install path, so the post-available step then called tilelang install AGAIN. This was masked locally because tilelang was installed in the workspace venv (post_available short-circuited on `_tilelang_importable()` returning True). CI starts with no tilelang, so the second call actually fired and the mock recorded two calls. Fix: only run `post_available_fn` when the install path did NOT run. That preserves the finding #7 semantics (tilelang repair when FLA already True but tilelang missing or tvm-ffi broken) without duplicating the chained install on the gate-was-False path. Also tightened `test_hook_skips_install_when_gate_already_true` to monkeypatch `_tilelang_importable=True` and `_installed_tvm_ffi_version=0.1.9` so it stays a pure "no install at all" test regardless of the venv's actual state. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ci: retrigger Mac Studio GGUF after transient HF DNS resolve flake * studio: skip tilelang on HIP / ROCm torch (Strix Halo crash report) h34v3nzc0dex tested PR 5434 on Strix Halo (gfx1151, ROCm 7.13, torch 2.11.0+rocm7.13.0) and hit a hard regression: File ".../fla/ops/common/backends/tilelang/__init__.py", line 92, in chunk_bwd_dqkwg File ".../tilelang/jit/kernel.py", line 137, in __init__ File ".../tilelang/tileop/gemm/__init__.py", line 143, in _select_gemm_instruction tvm.error.InternalError: Check failed: (0) is false: Unsupported target for gemm: hip -keys=hip,gpu -mcpu=gfx1151 ... `tilelang==0.1.8` ships no HIP GEMM instruction; `_select_gemm_instruction` raises at lower-time, not import-time. So: - pip install succeeds - `import tilelang` succeeds - `TileLangBackend.is_available()` returns True - FLA's dispatcher picks TileLang for `chunk_bwd_dqkwg` - training subprocess dies at first GDN backward, no graceful fallback The PR's existing platform gate (`_tilelang_platform_supported`) checked only `sys.platform == "linux"` and `platform.machine()`, both of which look identical on a ROCm box. Fix has two layers: 1. INSTALL GATE: new `_torch_has_hip()` helper checks `torch.version.hip is not None`. `_tilelang_platform_supported` now returns False on HIP torch, so the install never fires. 2. RUNTIME GATE: even with the install skipped, a user could have tilelang already present (e.g. venv carried over from a CUDA box). `_install_fast_path_hooks` now calls `os.environ.setdefault("FLA_TILELANG", "0")` when HIP is detected, which is the env-var FLA's `TileLangBackend` already honors. Users who know they have a HIP-aware tilelang fork can override by setting `FLA_TILELANG=1` explicitly. This costs nothing on CUDA (the gate is a no-op when `torch.version.hip is None`), and removes the crash for AMD users. The benchmark numbers in the PR description (1.43x on B200 sm_100) are not affected. The other halves of the PR are confirmed working on gfx1151 by the same report: - `flash-linear-attention 0.5.0` runs at production scale (B=1 T=8192 H=16 K=128 V=128 and others) with no patches. - `causal-conv1d` runs at the shapes the fast-path gate cares about. (A separate Ubuntu 24.04 `--gcc-install-dir` build workaround is needed for the source-build path; that mirrors bbf004c's llama.cpp fix and is out of scope here.) Tests added: - test_tilelang_platform_unsupported_on_hip_torch - test_tilelang_install_skipped_on_hip_torch - test_install_fast_path_hooks_sets_fla_tilelang_zero_on_hip - test_install_fast_path_hooks_respects_user_fla_tilelang_override - test_install_fast_path_hooks_does_not_set_fla_tilelang_on_cuda Total 50 passing (was 45). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * ci: retrigger Windows Studio UI after transient Playwright tab-lookup flake * studio: auto-discover FLA-using model types from installed transformers Drop the hand-maintained `_TILELANG_MODEL_SUBSTRINGS` tuple (qwen3.5 / qwen3_5 / qwen3.6 / qwen3_6 / qwen3-next / qwen3_next) and derive the allowlist by scanning the installed `transformers/models/*/modeling_*.py` for `from fla.` imports. A model "wants tilelang" iff its modeling file imports an FLA op, which is the same signal `is_flash_linear_attention_available()` is the runtime test for. The scan happens once per worker subprocess and is cached for the process lifetime; an empty result (eg transformers not importable) means "no tilelang pre-install" -- the FLA runtime hook still drives the install via the gate when the loaded model actually probes it. Verified against the live installed transformers, the auto-derived set is {qwen3_5, qwen3_5_moe, qwen3_next}, with `_model_wants_tilelang` matching the HF Hub names `unsloth/Qwen3.5-2B`, `Qwen/Qwen3.5-MoE-A3B`, `mlx-community/qwen3-next-80b`, and correctly rejecting Llama, Mistral, Nemotron-H, Falcon-H1, etc. Future GDN models (Qwen3.7, OLMo-Hybrid-FA, ...) are picked up automatically once they ship in transformers; no further worker edits needed. Also trim docstrings / comments through the FLA / tilelang / HIP / hook block: constants get 1-line trailing comments, function docstrings collapse to 1-3 lines, and the fast-path-hooks banner shrinks from a 27-line block to 4 lines. The file drops from 2847 to 2630 lines without losing the load-bearing WHY notes (--no-deps protects torch; `__dict__.get` avoids lazy-module __getattr__; two-step tvm-ffi repair keeps torch off the dep graph; HIP setdefault disables FLA's TileLang dispatch even with tilelang already installed). 7 new tests (50 -> 57 total): discovery returns only FLA-using model_types; discovery cache reuse; missing transformers handled; OSError on a modeling file is non-fatal; `_model_wants_tilelang` matches real HF repo names across separator variants; empty discovery -> always False; normalization across `-`, `.`, `/`, space. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * test: hermetize the non-allowlist hook test against transformers 5.4.0+ transformers 5.4.0 added `olmo_hybrid` as an FLA-using model_type, so the auto-discovered allowlist now includes it -- and the test's prior choice of `allenai/OLMo-Hybrid-1B` as a "non-Qwen FLA-only" example became an allowlist member. CI on Python 3.11 / 3.13 caught this. Swap to a guaranteed-not-in-allowlist fake model_name AND patch _discover_fla_model_types to a known {qwen3_5, qwen3_5_moe, qwen3_next} set so the test stays valid as upstream transformers adds new FLA-using architectures. Renames the test to reflect the actual semantic under test: "outside-allowlist -> no tilelang". * ci: retrigger Windows Studio API after llama.cpp prebuilt staging WinError 5 flake * tests: move MLX smoke gate changes to dedicated PR #5537 The seven MLX smoke commits in this PR's history (_on_step grad_norm, max_grad_value pin, loss + round-trip gates) are unrelated to the FLA / tilelang work. They now live in #5537 so this PR's diff is limited to the studio worker installer changes. Net effect on tests/studio/run_real_mlx_smoke.py vs main: zero. * studio: friendlier install banners (drop hook / gate-name jargon) User-visible status text now reads: Installing flash-linear-attention==<ver> for faster training... Installing TileLang==<ver> for faster training... Installing causal-conv1d for faster training... Installing flash-attn for faster training... Removed the transient "Hook fired for is_flash_linear_attention_available; installing kernel..." banner — the install banner that immediately follows already tells the user what is happening, in plain English. The internal logger.info messages (server-side log) still carry the gate names + "Hook fired ..." for debugging. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Two corrections to the earlier f93e918 / e05d6c7 direction: 1. max_grad_value=0.0, max_grad_norm=1.0 picked the memory-heavy norm clip. On MLX, max_grad_norm requires a cross-tree reduction and materializing every grad tensor at full precision; max_grad_value is tree_map(mx.clip) per leaf with no reduction. MLXTrainingConfig defaults to max_grad_value=1.0 for exactly this reason. Flip the smoke to max_grad_norm=0.0, max_grad_value=1.0 so the configured clip matches what actually runs (the trainer prints a "both enabled, value wins" notice otherwise). 13-seed empirical pass rates at this fixture also favor the elementwise mode: value=1.0 62%, norm=1.0 46%, value=5.0 33%, value=0.5 77%. Cheaper default = higher pass rate, no tradeoff. (See PR #5498 / staging-2#119 rounds A-AT.) 2. max_steps=7 was below the convergence horizon at every clip tested. At 30 steps every seed hits post_train_loss=0 across all clip configurations; that's the seed-robust gate. Bump max_steps 7 -> 30, tighten the memorisation gate from post_loss < 1.0 to post_loss < 0.1. 3. Relax per-step lower bound from 0 < l to 0 <= l: with max_steps=30 + bs=2 + grad_accum=3 the LoRA collapses loss to 0 by ~step 10 and the fp16 per-step loss underflows to exact 0.0 from then on. That's the success signal, not a bug. Keeps the e7ec2f5 EXPECT_IN_OUTPUT demotion-to-warning and the e734764 reload teacher-forced-loss round-trip invariant -- those are the right gates regardless of the clip / steps choice.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 44789d43d1
ℹ️ 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".
| # when the smoke probes loss/generation. At 30 steps every | ||
| # seed tested hits post_train_loss=0 across all clip | ||
| # configurations, so 30 is the seed-robust gate. | ||
| max_steps = 30, |
There was a problem hiding this comment.
Update the logged-step assertion after raising max_steps
With max_steps now set to 30 and logging_steps=1, _on_step should append one loss per training step, but the assertion below still requires exactly 7 entries. On the MLX smoke workflow this makes the train subcommand fail immediately after a successful 30-step training run with expected 7 logged steps, so none of the new loss/reload gates can run.
Useful? React with 👍 / 👎.
The prior "soft warn + metric" was a step back from the original hard assert: regressions could land silently if greedy decode happened to pass on seed=3407 but post_train_loss diverged. A true hard gate is needed. Greedy decode is empirically fragile -- a 47-round, 13-seed sweep on this fixture (see danielhanchen#119) showed contains-Unsloth lands in 46-77% across MLX clip configs even when post_train_loss is zero, because fp16 noise on the first generated token after PROMPT perturbs the argmax. Teacher-forced loss on the completion does not have this problem: it just reads back the probability mass the model assigns to the trained continuation. In every config where post_train_loss < 0.1, the completion loss is essentially zero. Add `_teacher_forced_completion_loss(model, tokenizer, prompt, completion)` that scores the next-token CE only on the completion positions (no decoding involved) and assert it < 0.5. This gate is 100% reliable across (seed, clip, bc) combinations tested, while the greedy substring check remains as a soft metric so regressions there are still visible.
* mlx: match mlx-lm's iterate_batches padding rule (1 + pad_to * ceil) create_text_batches previously padded each batch to `_PAD_MULTIPLE * ceil(max_len / _PAD_MULTIPLE)`. mlx-lm's `iterate_batches` (mlx_lm/tuner/trainer.py:158) pads to `1 + _PAD_MULTIPLE * ceil(max_len / _PAD_MULTIPLE)` -- one extra token, which after the autoregressive shift in `default_loss` (`inputs = batch[:, :-1]` / `targets = batch[:, 1:]`) gives the model exactly `_PAD_MULTIPLE * ceil(...)` attention positions. unsloth_zoo's `make_baseline_loss_fn` does the same shift, but since zoo's padded_len dropped the +1, the inputs were one token SHORTER than mlx-lm's after the shift. On small fixtures (the single-row LoRA memorization smoke against `gemma-3-270m-it`) that one-token gap moved the run into a different basin of attraction: probe 31 (manual mlx-lm loop, nl=16, no clip): 10/15 = 67% probe 33 (zoo MLXTrainer, nl=16, None silent-clip) : 8/15 = 53% probe 34 (zoo FastMLXModel + MLXTrainer, nl=16) : 7/15 = 47% probe 37 (zoo MLXTrainer, nl=16, explicit max_grad_value=0): 6/15 = 40% (See `danielhanchen/unsloth-staging-2` mlx-parity-probes matrix, Round BM run 26050214501.) Teacher-forced completion loss is 0 in 15/15 seeds across every probe -- the model fully memorizes either way. The greedy-decode basin is what shifts. cf_loss < 0.5 smoke gating per unslothai/unsloth#5537 stays green regardless, so this is not a training-quality defect -- but it IS a parity defect against mlx-lm CLI, which is the primary reference implementation for the MLX path. Tests: tests/test_mlx_batch_padding.py pins the padding rule against mlx-lm's value-for-value across 11 length boundaries plus a source-string assertion guarding against future refactor drift, plus a check that _PAD_MULTIPLE stays at 32 (mlx-lm uses the same constant). * mlx: trim verbose pad-multiple comment Per code-comment policy: keep WHY (autoregressive shift headroom), drop empirical probe results — those live in commit b265d99's message.
…thai#670) * mlx: warn on bf16 -> fp16 downcast in FastMLXModel loader `_convert_mlx_dtype` silently downcasts native bf16 weights to fp16 when the user passes `dtype="float16"`. fp16's finite range (~6.5e4) is much narrower than bf16's (~3.4e38); models with large activations (e.g. Gemma3-270m) can lose precision or overflow silently. Empirically (gemma-3-270m-it single-row LoRA memorization, n=15 seeds): - FastMLXModel(dtype=None) + last-16 layers: 47% greedy-decode pass rate - FastMLXModel(dtype="float16") + last-16 layers: 15% The 32pp drop is from the silent bf16 -> fp16 cast (`probe_32` vs `probe_34` in danielhanchen/unsloth-staging-2). Teacher-forced completion loss is 0 in both cases (memorization works), so CI smoke gating per unslothai/unsloth#5537 stays green either way — but the greedy-decode behavior diverges noticeably. This patch only adds a warning. The cast still happens (users on M1/M2 without native bf16 GPU support genuinely need fp16). The warning surfaces the trade-off so callers can switch to dtype=None / "bfloat16" on M3+ if they didn't intend to downcast. Tests: - test_mlx_dtype_downcast_warning.py — five cases: bf16->fp16 warns; bf16->fp32 / fp32->fp16 / no-cast do NOT emit the warning; cast still occurs after the warning. * mlx: trim verbose bf16->fp16 downcast docstring Per code-comment policy: keep WHY (range narrowing risk), drop the empirical numbers and probe references — those live in the commit message of 0987d27. * mlx: gate bf16->fp16 warning on FORCE_FLOAT32; centralize the list Move FORCE_FLOAT32 — the list of architectures whose activations exceed fp16's finite range — into a new dependency-free module unsloth_zoo/model_lists.py and re-export from both unsloth_zoo (top-level) and unsloth_zoo.compiler (back-compat). unsloth/models/loader.py can now 'from unsloth_zoo import FORCE_FLOAT32' and drop its local copy. Gate _convert_mlx_dtype's bf16->fp16 downcast warning on the model_type being in FORCE_FLOAT32. Llama/Mistral/Qwen2 etc. cast silently as before; only models that actually NaN/Inf in fp16 (Gemma3 family, gpt_oss, Qwen3.5) get the warning. _is_force_float32_arch normalizes -/_ and honors the 'gemma3,' trailing-comma exact-match marker. * mlx: document FORCE_FLOAT32 entries as config.json model_type strings Per maintainer feedback: the FORCE_FLOAT32 entries are HuggingFace config.json model_type values (the same strings returned by unsloth_zoo.hf_utils.get_transformers_model_type). Make that contract explicit in the module docstring with worked examples for each entry, and add a parity test that pins _is_force_float32_arch against the real-world model_type strings on the Hub.
PR unslothai#5537 bumped max_steps from 7 to 30 but the post-train assertion still hardcoded the old count, so every fresh run that reaches the post-train phase fails on `expected 7 logged steps, got [30 floats]`. Derive the expected count from `config.max_steps` and add a `train_result["train_steps"]` cross-check so the gate self-updates with future sweep changes.
MLX CI on Mac M1 + Backend CI (both Repo tests CPU and Python 3.10/11/12/13) have been red on every push to main for days. None of the underlying code is wrong; three test files have stale anchors / assertions left behind by PR #5537 (max_steps bump) and PR #5775 (composer + provision-desktop-auth). 1. tests/studio/run_real_mlx_smoke.py:393 PR #5537 bumped max_steps from 7 to 30 for seed-robust convergence but left `assert len(losses_per_step) == 7`. With logging_steps=1 the callback fires once per step; 30 entries, not 7. Track config.max_steps so the gate auto-follows future bumps. 2. tests/studio/test_composer_rtl_bidi_attribute.py:29 PR #5775 changed the composer aria-label from the literal `aria-label="Message input"` to a JSX ternary `aria-label={overlay ? "Image edit instructions" : "Message input"}`. Anchor on the inner string literal `"Message input"` instead. 3. studio/backend/tests/test_desktop_auth.py:487 The guarded_import in test_provision_desktop_auth_writes_secret_and_creates_db_without_backend_deps blocks any import whose name == "utils", including the relative `from .utils import echo` inside typer._click.decorators (typer 0.25+). Gate the block on level == 0 so only absolute imports of `utils` / `auth` / `fastapi` / `structlog` are rejected; relative imports inside third-party packages pass through. All three tests pass locally; the MLX one is a mechanical 7->config.max_steps swap and will be exercised by MLX CI on this PR.
MLX CI on Mac M1 + Backend CI (both Repo tests CPU and Python 3.10/11/12/13) have been red on every push to main for days. None of the underlying code is wrong; three test files have stale anchors / assertions left behind by PR #5537 (max_steps bump) and PR #5775 (composer + provision-desktop-auth). 1. tests/studio/run_real_mlx_smoke.py:393 PR #5537 bumped max_steps from 7 to 30 for seed-robust convergence but left `assert len(losses_per_step) == 7`. With logging_steps=1 the callback fires once per step; 30 entries, not 7. Track config.max_steps so the gate auto-follows future bumps. 2. tests/studio/test_composer_rtl_bidi_attribute.py:29 PR #5775 changed the composer aria-label from the literal `aria-label="Message input"` to a JSX ternary `aria-label={overlay ? "Image edit instructions" : "Message input"}`. Anchor on the inner string literal `"Message input"` instead. 3. studio/backend/tests/test_desktop_auth.py:487 The guarded_import in test_provision_desktop_auth_writes_secret_and_creates_db_without_backend_deps blocks any import whose name == "utils", including the relative `from .utils import echo` inside typer._click.decorators (typer 0.25+). Gate the block on level == 0 so only absolute imports of `utils` / `auth` / `fastapi` / `structlog` are rejected; relative imports inside third-party packages pass through. All three tests pass locally; the MLX one is a mechanical 7->config.max_steps swap and will be exercised by MLX CI on this PR.
…d CI) (#5803) * tests: unblock three stale assertions broken on main MLX CI on Mac M1 + Backend CI (both Repo tests CPU and Python 3.10/11/12/13) have been red on every push to main for days. None of the underlying code is wrong; three test files have stale anchors / assertions left behind by PR #5537 (max_steps bump) and PR #5775 (composer + provision-desktop-auth). 1. tests/studio/run_real_mlx_smoke.py:393 PR #5537 bumped max_steps from 7 to 30 for seed-robust convergence but left `assert len(losses_per_step) == 7`. With logging_steps=1 the callback fires once per step; 30 entries, not 7. Track config.max_steps so the gate auto-follows future bumps. 2. tests/studio/test_composer_rtl_bidi_attribute.py:29 PR #5775 changed the composer aria-label from the literal `aria-label="Message input"` to a JSX ternary `aria-label={overlay ? "Image edit instructions" : "Message input"}`. Anchor on the inner string literal `"Message input"` instead. 3. studio/backend/tests/test_desktop_auth.py:487 The guarded_import in test_provision_desktop_auth_writes_secret_and_creates_db_without_backend_deps blocks any import whose name == "utils", including the relative `from .utils import echo` inside typer._click.decorators (typer 0.25+). Gate the block on level == 0 so only absolute imports of `utils` / `auth` / `fastapi` / `structlog` are rejected; relative imports inside third-party packages pass through. All three tests pass locally; the MLX one is a mechanical 7->config.max_steps swap and will be exercised by MLX CI on this PR. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci --------- Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
…pere through Blackwell (#5748) * test_locally.sh: use docker buildx (or DOCKER_BUILDKIT=1) for the build The Dockerfile uses BuildKit-only features (the # syntax=docker/dockerfile:1.7 parser directive and RUN ... <<'PY' heredocs added in dockerfile 1.3+). The legacy builder rejects the --progress flag at the CLI level and would fail later at the heredocs anyway. Detect docker buildx and use it when available (preserves --progress=plain output). Otherwise fall back to plain `docker build` with DOCKER_BUILDKIT=1 exported, which gets the BuildKit features without buildx's nicer formatting. Reproduces the failure path seen on Docker 28.2.2 without buildx installed: unknown flag: --progress ERROR docker build exited 125 * test_locally.sh: require docker buildx, no legacy fallback Docker 28 removed the legacy image builder entirely. Setting DOCKER_BUILDKIT=1 no longer falls back to a builtin builder -- it delegates to buildx, which then errors out if buildx isn't installed: ERROR: BuildKit is enabled but the buildx component is missing or broken. The Ubuntu docker.io package omits buildx by default, so users on that path hit this immediately. Detect missing buildx up front and print exact install commands for apt / dnf / manual binary instead of attempting a fallback that cannot work. * test_locally.sh: pre-flight check for docker daemon connectivity If the user is not in the 'docker' group, every docker command after the pre-flight returns "permission denied while trying to connect to the Docker daemon socket at /var/run/docker.sock". This used to surface as a confusing buildx failure mid-Block-2, but the actual problem is a host permissions issue that's settable up front. Detect by running 'docker info' and checking its exit code (not just grep on its output -- a permission failure prints to stderr and returns non-zero, so the old grep-based check was a silent skip). Also clarify the nvidia-runtime WARN: on Docker 28+ with CDI mode this is a false positive most of the time. The real GPU-attach test is the smoke run in Block 3a, where the container entrypoint catches missing GPUs with an actionable message. * Dockerfile: drop system-python pip/uv bootstrap (PEP 668) Ubuntu 24.04 (noble) marks the system Python interpreter as externally-managed per PEP 668, so: curl get-pip.py | python python -m pip install -U pip uv fails inside the builder image with: error: externally-managed-environment This environment is externally managed The system-level pip and uv were never used: the very next RUN creates the venv at /opt/unsloth-venv, which bootstraps its own pip via the ensurepip module (provided by the python3.12-venv apt package). uv is then installed INTO the venv with the venv's pip, and used from there. Drop the two system-pip bootstrap lines. The venv path is unchanged. Reproduces on any Docker build of the unsloth-blackwell image against a noble base image (which our nvidia/cuda:12.8.1-cudnn-devel-ubuntu24.04 is). * smoke_test.py: import unsloth before unsloth_zoo / transformers / trl / peft unsloth_zoo/__init__.py guards against being imported standalone: if "UNSLOTH_IS_PRESENT" not in os.environ: raise ImportError("Please install Unsloth via `pip install unsloth`!") The env var is set by unsloth/__init__.py at import time, so importing unsloth must happen first. The old check_imports() imported xformers, bnb, transformers, trl, peft, then unsloth_zoo -- which fired the guard because unsloth had not been imported yet. Reorder check_imports() to import unsloth (and unsloth_zoo) first, then the rest. check_unsloth_import() becomes a thin re-import to keep the "FastLanguageModel reachable" banner in the output. Same fix the unsloth README has been recommending for years: "import unsloth at the top of your file, before transformers/trl/peft." * Dockerfile: install gcc + g++ + python3-dev in runtime stage Triton's nvidia backend lazily JIT-compiles a small C extension (CudaUtils, in triton/backends/nvidia/driver.py) on first GPU access. Without a C compiler and Python headers in the runtime image, the very first forward pass of any Unsloth model dies with: RuntimeError: Failed to find C compiler. Please specify via CC environment variable. The builder stage has build-essential and python3.12-dev so this worked during the build's verification step (no GPU = no Triton kernel call = no C extension build). But the runtime stage stripped those out for size, so the failure only surfaces when a real user runs training inside the container. Add gcc + g++ + python3.12-dev to the runtime stage. Increases the runtime image by ~250MB, which is the cost of letting Triton JIT correctly. Pre-compiling CudaUtils at build time would need a real CUDA device (the constructor calls cuda runtime functions), so shipping the toolchain is the right trade-off. * Expand arch list to every current x86_64 NVIDIA CC per developer.nvidia.com/cuda/gpus TORCH_CUDA_ARCH_LIST now covers the full set of compute capabilities NVIDIA publishes on https://developer.nvidia.com/cuda/gpus for x86_64 hardware, from Turing onward: sm_75 Turing T4, RTX 20-series, Quadro RTX sm_80 Ampere DC A100, A30 sm_86 Ampere A40, RTX A6000, RTX 30-series sm_89 Ada L4, L40, L40S, RTX 40-series sm_90 Hopper H100, H200, GH200 sm_100 Blackwell DC B100, B200, GB200 sm_103 Blackwell DC B300, GB300 sm_120 Blackwell RTX 50-series, RTX PRO 6000 Blackwell sm_121 Blackwell GB10 (DGX Spark) with +PTX on the highest entry so future arch revisions can JIT. Setting TORCH_CUDA_ARCH_LIST only affects nvcc invocations for any source build the user adds on top of this image (e.g. flash-attn, a custom CUDA op). The prebuilt cu128 wheels already include SASS for sm_70/75/80/86/90/100/120 (verified at build time via torch._C._cuda_getArchFlags()). Ada (sm_89), B300 (sm_103) and DGX Spark (sm_121) GPUs run via JIT-PTX from the nearest available arch. Jetson archs (sm_87 Orin, sm_110 Thor) are intentionally NOT included -- they require aarch64 wheels and this image is linux/amd64 only. Also lower the entrypoint's compute-capability gate from sm_80 to sm_75. Turing GPUs work, with the caveat that bfloat16 is unavailable; the entrypoint prints a NOTE in that case so Unsloth's fp16 fallback isn't a surprise. * Add docker/hf_{push,pull}.sh: simulate docker push/pull against HF Hub HF Hub does not act as a generic OCI registry for arbitrary Docker images -- the registry.hf.space endpoint only serves images that Spaces have built, not images pushed by `docker push`. So we cannot do `docker push huggingface.co/user/repo:tag` for an Unsloth image. For cross-host testing where we want one canonical place to pull from (and Docker Hub credentials are not yet configured), wrap the manual flow into push/pull-shaped commands: hf_push.sh: docker save | pigz | huggingface-cli upload hf_pull.sh: huggingface-cli download | gunzip | docker load This is approximation, not real OCI semantics -- every push uploads the full ~4 GB blob, no layer dedup, no manifest negotiation. Good for testing across A100 / H100 / RTX 6000 boxes; the real release should go through .github/workflows/docker-publish.yml to Docker Hub, which gets layer dedup, multi-arch manifest support, and standard `docker pull` UX for users. Usage: bash docker/hf_push.sh unsloth-blackwell:test danielhanchen/unsloth-blackwell-docker bash docker/hf_pull.sh danielhanchen/unsloth-blackwell-docker unsloth-blackwell-test.tar.gz unsloth-blackwell:test * hf_{push,pull}.sh: use new `hf` CLI, fall back to deprecated `huggingface-cli` In huggingface_hub >= 0.27 the `huggingface-cli` binary is deprecated and prints a "Use hf instead" notice then exits without doing the operation. The previous wrappers ran `huggingface-cli upload/download` silently, treated the deprecation exit as success, and uploaded nothing. Detect the new `hf` binary first and use that. If only the legacy `huggingface-cli` is on PATH (older installs), fall back with a WARN so users know the failure mode if anything goes sideways. Also: hf_pull.sh now asserts the downloaded file is non-empty (`test -s`) so we catch silent download failures before the `docker load` step. * test_locally.sh: use nbformat directly, drop fragile jupyter nbconvert call `jupyter nbconvert --to script nb.ipynb --output nb 2>/dev/null` was silently exiting 0 without producing the output file in some environments (likely because jupyter/jupyter_core wasn't on PATH or nbconvert's --output handling differed across versions). The 2>/dev/null hid the underlying error, and `set -e` did not catch the missing-output case because nbconvert itself returned 0. Switch to a direct nbformat-based conversion: pip install -q nbformat python -c "import nbformat; nb=nbformat.read('nb.ipynb', as_version=4); code='\n\n'.join(c.source for c in nb.cells if c.cell_type == 'code') open('nb.py','w').write(code + '\n')" Smaller dep set, no shell-out to a jupyter wrapper script, and an explicit `test -s nb.py` afterwards catches any silent failure before downstream steps try to read the file. Reproduces the failure on RTX PRO 6000 Blackwell (sm_120, docker 29.2.1, ubuntu 24.04) where nbconvert's CLI silently no-op'd. * test_locally.sh: skip notebook install cells, strip stray jupyter magic The previous nbformat-based conversion dumped raw cell.source for every code cell. The gpt-oss-20B notebook's first cell uses Jupyter !shell magic to install dependencies: !pip install --upgrade -qqq uv !uv pip install -qqq ... \ git+https://github.com/triton-lang/triton.git@0add68... ... Dumped verbatim, the `@0add68...` token tripped the Python parser with "SyntaxError: invalid decimal literal" before training could even start. The container already has unsloth, triton, transformers, etc. baked in, so we don't need the notebook's install cell. Skip any cell whose source contains pip/install markers, and comment out stray !cmd / %magic lines in any other cells. Then assert nb.py parses with ast.parse() before trying to run it -- catches conversion failures up front instead of at training time. Reproduces on RTX PRO 6000 Blackwell (sm_120, fresh Docker 29.2.1 host) where the previous conversion produced an invalid nb.py. * Add linux/arm64 (DGX Spark / Grace) support via QEMU at build time Make the docker image multi-arch so DGX Spark (GB10, sm_121, aarch64) and the Grace-Hopper / Grace-Blackwell SoCs (GH200 arm64, GB200 arm64) pull a natively-built arm64 child from the same manifest. Runtime emulation is NOT involved -- QEMU is used only for the cross-compile step on x86_64 CI runners; consumers on aarch64 hosts get a normal arm64 image and CUDA works as on any other host. Dockerfile: * ARG TARGETARCH; switch unsloth extras between cu128-ampere-torch2100 (amd64, with xformers) and huggingface (arm64, no xformers -- there is no cu128 aarch64 xformers wheel as of 0.0.34, so we fall back to Unsloth's native SDPA path; ~5-10% slowdown but functionally complete). * Build-time torch._C._cuda_getArchFlags() assertion: amd64 still requires sm_120, arm64 accepts sm_120 or sm_121. * Same TORCH_CUDA_ARCH_LIST on both arches; nvcc emits whatever's listed. docker/setup_qemu.sh (new): One-time host setup -- registers binfmt_misc handlers via tonistiigi/binfmt and creates a 'unsloth-multiarch' docker-container buildx builder. Required only on x86_64 build hosts targeting arm64. docker/test_locally.sh: --platform amd64|arm64 flag. Cross-builds verify QEMU is registered, then build through the in-image arch-flags assertion. Smoke + notebook blocks auto-skip when image arch != host arch (CUDA cannot run under user-space QEMU + nvidia-container-toolkit cannot bridge a QEMU guest to a real GPU). .github/workflows/docker-publish.yml: platforms: linux/amd64,linux/arm64 (single manifest, two children). Timeout bumped 60 -> 150 min for the slower arm64-under-QEMU leg. docker/setup-qemu-action@v3 with platforms: arm64 (was implicit before). * docker-publish.yml: native arm64 runner + per-arch digest merge GitHub announced free linux/arm64 hosted runners for public repos (GA Aug 2025) under labels `ubuntu-24.04-arm` / `ubuntu-22.04-arm`. Switching the arm64 leg from QEMU-on-amd64 to a native arm64 matrix runner is ~3x faster and avoids QEMU's occasional flakiness on long cu128 installs. The workflow now: * builds amd64 and arm64 in parallel on their native runners, pushing each as a single-arch image *by digest* (no tag) * stitches both digests into one multi-platform manifest in a follow-up `merge` job, using `docker buildx imagetools create` * keeps a separate buildx cache scope per platform to avoid cross-arch cache collisions Smoke-test job now needs `merge` (was `build`) so it only runs once the final manifest is published. Dockerfile header: replace the speculative aarch64 SASS list with the verified one from pytorch/pytorch v2.10.0 .ci/manywheel/build_cuda.sh (8.0;9.0;10.0;12.0 on aarch64), and note that sm_120 is forward-compatible to sm_121 per PyTorch maintainers -- which is what makes DGX Spark work without an explicit sm_121 SASS section in the wheel. setup_qemu.sh / test_locally.sh --platform stay in place: they're for the local-dev path on x86_64 boxes that don't have arm64 hardware. * Dockerfile: tighten arch-flag assertion + correct fat-binary claims Empirical reality (cuobjdump on the downloaded cu128 wheels): amd64: sm_70 sm_75 sm_80 sm_86 sm_90 sm_100 sm_120 arm64: sm_80 sm_90 sm_90a sm_100 sm_100a sm_120 sm_120a Earlier comments claimed sm_89 native and a "+PTX JIT to sm_121" fallback; both are wrong. cu128 wheels ship NO PTX. Ada (sm_89) runs on sm_86 SASS, B300/GB300 (sm_103) on sm_100, DGX Spark (sm_121) on sm_120 -- all forward-compat WITHIN a major architecture, which is the canonical CUDA rule and ptrblck (PyTorch maintainer) confirmed it directly: "the compatibility ... is also used for e.g. sm_89 with sm_86 and sm_80." Build-time assertion was `any(a in ("sm_120", "sm_121"))` on arm64. Since sm_121 is never in any cu128 wheel, the OR was misleading and could mask a real wheel regression. Tightened to just `assert "sm_120" in arches` on both arches. * Dockerfile: arm64 DGX Spark NVRTC + ptxas fix (cu13 alongside cu128) Empirically (cu128 wheel SASS list `sm_80;90;90a;100;100a;120;120a` on aarch64) the cu128 wheel covers DGX Spark sm_121 via sm_120 binary forward-compat. BUT two CPU-side compilers shipped at cu12.8 do not know sm_121 and need a cu13 swap: (1) torch's bundled libnvrtc.so.12 from CUDA 12.8 rejects sm_121 as a --gpu-architecture. Symlinks libnvrtc.so.13 over it. (2) Triton's nvidia backend runs ptxas. Wheels older than 3.6.0 bundled cu12.8 ptxas which silently downgrades sm_121 to sm_80 (see triton-lang/triton#8335). Bump pin triton>=3.6.0 (3.6 bundles cu13 ptxas) AND install cuda-nvcc-13-0 so the entrypoint can point TRITON_PTXAS_PATH at it as defense in depth. Both fixes are arm64-only (gated on TARGETARCH, ~400 MB on the arm64 image; amd64 is untouched, no sm_121 hardware exists on x86_64). Neither component talks to libcuda, so this does NOT bump the toolkit driver floor away from cu128's 570+. TRITON_PTXAS_PATH is set from the entrypoint (only when the cu13 ptxas actually exists in the image) rather than via a Dockerfile ENV, because ENV is unconditional and Triton errors out if TRITON_PTXAS_PATH points at a nonexistent file. Sources: martimramos/dgx-spark-ml-guide Challenge 14; triton-lang/triton issue #8335; ptrblck PyTorch forum thread on sm_121 fwd-compat from sm_120. * Dockerfile: switch runtime base cudnn-runtime -> base (~2.7 GB lighter) torch wheels ship their own cuDNN/cuBLAS/cuSPARSE/cuRAND/cuSOLVER/cuFFT/ NCCL/cuSparseLt inside torch/lib/, and libtorch_cuda.so's RPATH ($ORIGIN/../../nvidia/cudnn/lib:$ORIGIN/../../nvidia/cublas/lib:...) points at those wheel-bundled copies. The dynamic loader resolves through the wheel, never the system, so the libcudnn/libcublas in the system cudnn-runtime layer are unreachable code on every pull. Verified empirically via `readelf -d torch/lib/libtorch_cuda.so` and confirmed bitsandbytes' NEEDED list resolves against torch's bundled libcudart/libcublas/libcublasLt/libcusparse/libnvJitLink before bnb loads. Triton's .so files have zero CUDA NEEDED entries -- they dlopen through the host driver. Compressed image saving: ~2.7 GB (cudnn-runtime base 2.86 GB -> base 0.10 GB, on amd64; arm64 similar). Uncompressed: ~5 GB. Zero functional impact. Source: Fork 5 image-size audit, May 2026. * entrypoint.sh: correct driver-floor message (570+ unconditionally on cu128) The earlier message had per-arch driver minimums (525/535/555/570) that came from when each chip first got driver support. That's not how CUDA toolkit floors work -- cu128 imposes 570.26+ on EVERY GPU regardless of arch. Only B300 (sm_103) and DGX Spark (sm_121) need a newer driver (580+), and they ship factory with those drivers anyway. External HF README has the same correction applied in temp/hf_readme.md (updated separately when published). * Dockerfile: arm64 install cu13 nvrtc/nvcc directly without cuda-keyring deb The nvidia/cuda base image already registers the CUDA apt repo with its own Signed-By keyring. Installing cuda-keyring_1.1-1_all.deb on top adds a duplicate sources entry with a different Signed-By value, which makes `apt-get update` refuse the entire repo: E: Conflicting values set for option Signed-By regarding source https://developer.download.nvidia.com/compute/cuda/repos/ubuntu2404/sbsa/ The repo URL is monolithic (every CUDA version is served from the same path), so we can install cuda-nvrtc-13-0 + cuda-nvcc-13-0 directly without touching the keyring. Empirically reproduced on the ubuntu-24.04-arm GitHub Actions runner (staging-fork CI run 26360461375); fix verified via the same staging-fork after force-push. * Dockerfile: install vLLM nightly on amd64 for GRPO fast_inference Unsloth's GRPO notebooks (Qwen3_4B-GRPO.ipynb, Qwen3_8B_FP8_GRPO.ipynb, Llama_FP8_GRPO.ipynb, etc.) set `fast_inference=True` which requires vLLM to be importable in the same venv. Install vllm pre-release wheels from https://wheels.vllm.ai/nightly alongside the cu128 pytorch index, holding torch==2.10.0 fixed so uv refuses any vLLM build that would yank torch out from under unsloth. amd64 only -- vLLM does not publish aarch64 wheels yet (vllm-project/vllm#31128 is open). On arm64 the GRPO notebooks that need fast_inference will fail to import vllm; non-GRPO and fast_inference=False paths are unaffected. Gated by ARG INSTALL_VLLM=auto so the install can be disabled for contributors who want a smaller image or are blocked by vllm/torch resolve conflicts during iteration. * Dockerfile: arm64 build aborted by set -e in vLLM auto-gate The case-arm `auto) [ "${TARGETARCH}" = "amd64" ] && WANT_VLLM=1` exits 1 on arm64 (the [ test ] is false and nothing follows ||), which with `set -e` aborts the entire RUN. Replace with an explicit if/then/fi so each arch's auto branch returns 0. Caught by ubuntu-24.04-arm CI on the staging fork. * Dockerfile: re-upgrade numpy after vLLM install (2.2.6 wheel is broken) vLLM 0.19.1 pulls numpy down to 2.2.6 whose wheel ships numpy/_core/ without the tests/ subdir, but numpy/testing/_private/utils.py imports `from numpy._core.tests._natype import pd_NA`. Anything that hits `from numpy import *` (scipy._lib.array_api_compat does) then crashes. unsloth_zoo's gemma patch does `from transformers.processing_utils import Unpack` which touches that path, so `import unsloth` blew up on every GRPO notebook in the vLLM image. Bump numpy to >=2.4 right after the vllm install; vllm still imports fine on numpy 2.4.6 (verified locally). * Fix two upstream regressions surfaced by the Blackwell Docker validation 1. Inductor subprocess GPU invisibility in `--gpus '"device=N"'` containers. The NVIDIA container runtime sets NVIDIA_VISIBLE_DEVICES but not CUDA_VISIBLE_DEVICES; Inductor's compile worker subprocess pool then cannot enumerate the cgroup-pinned device and raises `Could not find an active GPU backend` from triton_helpers.set_driver_to_gpu. Force a single in-process compile thread on that exact fingerprint; opt out via UNSLOTH_FORCE_SINGLE_COMPILE_WORKER=0. Repros: nb/Mistral_v0.3_(7B)-CPT.ipynb, nb/gpt-oss-(20B)-Fine-tuning.ipynb. 2. unsloth_base_fast_generate injects `logits_to_keep` before transformers `_validate_model_kwargs` runs. transformers 5.0 auto-injects the same kwarg inside `GenerationMixin.generate` (utils.py:2527) AFTER the validator, so PEFT-wrapped GRPO models raise ValueError: The following `model_kwargs` are not used by the model: ['logits_to_keep'] Gate the legacy injection on transformers < 5.0 and defensively pop any leaked kwarg on 5.x. transformers 4.57.6 behaviour is preserved. Repros: nb/gpt-oss-(20B)-GRPO.ipynb, nb/gpt_oss_(20B)_RL_2048.ipynb. Both patches are gated and backwards-compatible (transformers 4.57.6 + 5.x, TRL 0.22.2 + 0.27.1 + 1.x, PEFT 0.19.x). * docker: add Dockerfile.studio extending the Blackwell image with Unsloth Studio The base unsloth-blackwell image ships the `unsloth` CLI but refuses to start `unsloth studio` until the dedicated Studio venv is laid down under UNSLOTH_STUDIO_HOME by install.sh. Build it once and commit the result as an opt-in companion tag (`:studio`) instead of bloating the base image. Build: docker buildx build --build-arg BASE_TAG=test \ -f docker/Dockerfile.studio -t unsloth-blackwell:studio docker/ Run: docker run --rm --gpus '"device=0"' -p 8888:8888 unsloth-blackwell:studio Open http://localhost:8888. Inference (llama.cpp CPU + GPU) and training are both available. First-boot admin password lands in container logs and at /opt/unsloth-studio/auth/.bootstrap_password. * Address reviewer findings on PR #5748: 4 release-path bugs Round-trip with the reviewer.py 12-persona pass surfaced four real issues. Fix all four in this PR so the new Docker release path is self-consistent. 1. docker/smoke_test.py used `import xformers` unconditionally, which guarantees a failure on arm64 (built with `[huggingface]` extras to skip xformers since it has no aarch64 cu128 wheel). Wrap the import in try/except so the same smoke script validates both arches. 2. unsloth/_gpu_init.py forced `TORCHINDUCTOR_COMPILE_THREADS=1` before `import unsloth_zoo`, but `patch_torch_compile` in unsloth_zoo main pops that env var in non-debug mode. After unsloth_zoo init the guard was effectively undone, so cgroup-pinned `docker --gpus '"device=N"'` containers still spawned the Inductor subprocess pool that cannot enumerate the GPU. Set `torch._inductor.config. compile_threads = 1` directly post-import-torch and re-populate the env var so `determine_compile_threads()` in the zoo options dict also returns 1, regardless of whether the zoo-side fix from PR #694 has shipped yet. 3. docker-publish.yml UNSLOTH_REF build-arg defaulted to `'main'` for tag pushes and scheduled runs, so a `v1.2.3` release image would contain whatever `main` happened to be at build time, not v1.2.3. Pick the tag's `github.ref_name` for tag events and `github.sha` for branch/schedule events. 4. The smoke-test job pulled `:latest` regardless of which tag the merge job had just published, so tag/schedule/sha publishes were never actually validated. Re-run docker/metadata-action with the same config the merge job used, then smoke-test the first tag from its output. All four changes are gated and backwards-compatible. * Remove async_task_outputs from repo (accidentally committed) The previous commit pulled in 51 transient async-task-output markdown files from the local workspace's reviewer.py runs. Drop them and add the directory to .gitignore so it cannot recur. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker/Dockerfile.studio: keep source for the editable install install.sh --local installs unsloth into the Studio venv as an editable package keyed to the just-cloned source tree. We were rm-rf'ing that tree in the same RUN; the resulting `unsloth_cli` import then failed at container start with `ModuleNotFoundError: No module named 'unsloth_cli'`. Clone the source directly under UNSLOTH_STUDIO_HOME/src so it persists in the image layer, and strip only .git to save ~120MB. * docker: add timm + addict to the base image Two vision-notebook deps that ship by reference rather than via unsloth extras: transformers' Gemma3N + TimmWrapperModel needs `timm`, and DeepSeek-OCR's dynamic modeling file requires `addict`. Both are tiny (~30MB combined). Including them in the base unified resolve avoids hitting `ImportError: TimmWrapperModel requires the timm library` or `ImportError: This modeling file requires the following packages that were not found in your environment: addict` after the user has already downloaded the model. Repros: nb/Gemma3N_(4B)-Vision.ipynb (timm), nb/Deepseek_OCR_(3B).ipynb (addict). * Address reviewer-2 findings on PR #5748 Round-2 of the 12-persona reviewer.py pass found 17 issues. Address the P1s + the regression-class P2s in this commit; the remaining nits are left for a follow-up cleanup pass. 1. unsloth/_gpu_init.py: the `NVIDIA_VISIBLE_DEVICES in os.environ` check triggered for every NVIDIA-runtime container including `--gpus all` (NVIDIA_VISIBLE_DEVICES=all is the default). Gate strictly on a non-special device list. Also drop the precondition that the env var was absent: if the user already pinned TORCHINDUCTOR_COMPILE_THREADS=1 we should still plant the UNSLOTH_FORCE_SINGLE_COMPILE_WORKER sentinel so the zoo-side patch knows to preserve the forcing. 2. unsloth/_gpu_init.py: after the post-`import unsloth_zoo` reassertion, monkey-patch `unsloth_zoo.temporary_patches.common.determine_compile_threads` to return 1, so any later `torch.compile` call that rebuilds the options dict still sees the single-worker forcing even if a downstream patch_torch_compile pops the env var again. 3. docker/Dockerfile: torchaudio==2.11.0 mismatched the torch==2.10.0 release pairing; pin to 2.10.0 so the ABI is correct and the audio stack matches torch/cu128. 4. docker/Dockerfile: drop `12.1+PTX` from TORCH_CUDA_ARCH_LIST. The cu128 toolkit compiler does not know about compute_121; the trailing PTX entry forced nvcc to emit a `sm_121` gencode that breaks any in-container source builds. 5. docker/smoke_test.py: the device-capability floor said `cap[0] < 8`, rejecting Turing (sm_75) while the Dockerfile + entrypoint advertise sm_75 as supported. Lower the smoke floor to sm_75 and print a hint that bf16 is not available on Turing. 6. docker/run.sh: `-it` is unconditional; CI / non-TTY invocations died with "the input device is not a TTY". Probe `[ -t 0 ] && [ -t 1 ]` first. Also remove `set -x` which echoed the forwarded HF_TOKEN / WANDB_API_KEY / UNSLOTH_LICENSE values to stdout. 7. docker/test_locally.sh: `-e HF_TOKEN="${HF_TOKEN:-}"` either pasted the secret verbatim into the process arg list or shadowed any in-container value with an empty string. Forward conditionally. 8. .github/workflows/docker-publish.yml: gate `latest` on default branch AND on `unsloth_ref` not being overridden via workflow_dispatch. Otherwise a maintainer testing a feature SHA from main could overwrite `:latest` with non-main source. 9. docker/Dockerfile.studio: add an `UNSLOTH_STUDIO_REF` build-arg so the Studio companion image is pinned to a known unsloth ref instead of cloning `main` whenever it builds. * Remove individual_reviews from repo (accidentally committed) reviewer.py drops the 12 raw per-persona review markdown files under individual_reviews/ in the current working tree. Drop them here and add the directory to .gitignore so it cannot recur. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * tests/studio: assert losses_per_step matches max_steps, not stale 7 PR #5537 bumped max_steps from 7 to 30 but the post-train assertion still hardcoded the old count, so every fresh run that reaches the post-train phase fails on `expected 7 logged steps, got [30 floats]`. Derive the expected count from `config.max_steps` and add a `train_result["train_steps"]` cross-check so the gate self-updates with future sweep changes. * Address 3 MAJOR review findings on the docker PR 1. Stop leaking secrets via docker run -e VAR=VALUE argv (run.sh, test_locally.sh) `docker run ... -e HF_TOKEN=hf_xxx ...` puts the literal token in the docker CLI's argv, which is visible to any user on the host via `ps auxe` / `/proc/<pid>/cmdline` for the lifetime of the process. Switch to the dash-only form `-e HF_TOKEN`, which tells docker to read the value from the parent shell's env and never appears in argv. Same fix for WANDB_API_KEY and UNSLOTH_LICENSE in run.sh and HF_TOKEN in test_locally.sh. 2. Stop stripping numpy/tests/ in the runtime layer (Dockerfile) The Dockerfile explicitly upgrades numpy >= 2.4 because numpy 2.2.6 shipped a stripped wheel where `from numpy._core.tests._natype import pd_NA` fails. Numpy 2.4 restores `numpy/_core/tests/`, then the existing `find ${VENV} -name tests -exec rm -rf {} +` deleted it again -- re-introducing the same broken-import state on the deployed image (the build-time verification at line 220 runs BEFORE the strip so it passed). Whitelist numpy's tests directories from the strip; keep stripping the rest. 3. Align :latest tag gate between merge and smoke-test jobs (.github/workflows/docker-publish.yml) merge job: enable = is-default-branch AND unsloth_ref == '' smoke-test job: enable = is_default_branch only On `workflow_dispatch`, `github.event.inputs.unsloth_ref` defaults to "main" (not ""), so the merge step skipped `:latest` but the smoke step still emitted `:latest` as tags[0]. The smoke step then `docker pull`-ed a prior `:latest` from Docker Hub instead of the image just merged -- so the smoke test verified the OLD image, not the new one. Copy the merge step's exact `enable=` expression into the smoke-test step so the two stay byte-identical and a workflow_ dispatch run validates whatever was actually merged. * docker: round-3 review fixes (concurrency, lockfile wording) - docker-publish.yml: add `concurrency: docker-publish-${{ github.ref }}` (cancel-in-progress: false) so two pushes to main never race the `:latest` retag. Don't cancel in-progress runs -- the build is expensive and a half-built image left around is worse than a stale :latest for a few minutes. - Dockerfile: soften the requirements.lock.txt comment. `pip freeze` captures versions but not wheel hashes, and several deps resolve from VCS / nightly indexes that float, so the file is not actually byte-reproducible. Reword as an "informational pin record". * docker-publish: pin UNSLOTH_ZOO_REF on tag pushes Previously, UNSLOTH_REF was pinned to the triggering tag (e.g. v2026.5.8) but UNSLOTH_ZOO_REF was hardcoded to main. That made release-tag images ship a zoo from whatever was on main at build time rather than the zoo release cut alongside that unsloth tag, so a 2026.5.8 tag image could install a zoo from days later. Mirror the tag branch of UNSLOTH_REF. SHA-based branch pushes still fall through to main because the unsloth SHA does not exist in the unsloth-zoo repo. workflow_dispatch still honours the unsloth_zoo_ref input. * docker/run.sh: translate UNSLOTH_GPUS index selectors to device= form The header docstring advertises UNSLOTH_GPUS values like "0" and "0,1" but Docker reads a bare integer for --gpus as a COUNT, not an INDEX. UNSLOTH_GPUS=0 was therefore exposing zero GPUs, and the entrypoint's GPU check refused to start. Wrap bare-int and comma-list inputs as "device=$GPUS" so the documented values do what they say; "all" and already-quoted device= selectors pass through unchanged. * docker/test_locally.sh: fail fast + pin notebook fetch to immutable SHA Two small fixes: 1. The fallback build-context refresh used `git pull --ff-only | tail`, which on this script (set -uo pipefail, no -e) silently masked any non-zero exit from pull. A failed refresh would then quietly build from a stale clone. Wrap both clone and pull in `if ! ...; then fail` so refresh failures abort the run with a clear message. 2. The gpt-oss-20B notebook was fetched from notebooks/main, which is mutable. Pin to the current immutable SHA (efe20c9) via NB_REPO_REF so reruns of this script don't silently change semantics when notebooks/main rolls forward. Override via env when you want to verify a newer notebook. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: ship Jupyter, Studio and prebuilt llama.cpp out of the box Base image (docker/Dockerfile): - Install JupyterLab + notebook + ipywidgets in a separate pure-Python uv pass so the cu128 pin set cannot move; EXPOSE 8888. - Bake the prebuilt llama.cpp bundle into /opt/unsloth/llama.cpp at the runtime stage using studio/install_llama_prebuilt.py from the same UNSLOTH_REF (sha256-verified, portable CUDA bundle since the build host has no GPU; arm64 resolves the linux-arm64-cuda13 bundle). Export UNSLOTH_LLAMA_CPP_PATH so unsloth_zoo's save_pretrained_gguf finds it and never reaches the interactive install prompt or a source build. - Optional github_token BuildKit secret for the resolver's API calls on shared CI runner IPs. Entrypoint: UNSLOTH_ALLOW_CPU=1 degrades a missing GPU to a warning so Docker Desktop on macOS / Windows-without-WSL2-GPU and plain CPU hosts can run Jupyter, GGUF tooling and Studio chat; with a GPU visible the normal pre-flight still runs. Full image (docker/Dockerfile.studio): now mirrors the production service set under supervisord - Studio on 8000, JupyterLab on 8888, key-only sshd on 22 (enabled only when PUBLIC_KEY/SSH_KEY is set). Points Studio's llama.cpp dir at the baked bundle to skip a duplicate download, accepts any git ref via fetch+checkout (CI passes commit SHAs), and FROMs a digest-pinned BASE_IMAGE. Publish workflow: base image moves to the base-* tag namespace; new build-studio/merge-studio jobs publish the full image as :latest (hub parity with the previous production image, which shipped Studio + Jupyter + SSH). Studio builds FROM the exact base manifest digest published by the same run. GPU smoke job now also boots the full image and probes Studio /api/health and Jupyter /api. run.sh: UNSLOTH_GPUS=none, UNSLOTH_ALLOW_CPU forwarding, UNSLOTH_PORTS publish flags, CPU-mode and Jupyter usage examples. * docker: pin the llama.cpp bake by target arch, add docker_confirm.sh The first bake attempt reused studio/install_llama_prebuilt.py, but that resolver selects a bundle for the CURRENT host: on a GPU build host /proc/driver/nvidia leaks into docker build and the resolver goes down the CUDA path with no readable driver runtime (chosen_asset=none, exit 2), while on a GPU-less CI runner it would resolve a CPU bundle instead. Both violate the image's build-host-independence rule. fetch_llama_prebuilt.py pins by build target only: amd64 takes the linux-x64-cuda12-portable bundle, arm64 the linux-arm64-cuda13-portable bundle (DGX Spark / Grace), both sha256-verified against the release's llama-prebuilt-sha256.json. convert_hf_to_gguf.py plus gguf-py/ are hydrated from the same release's source tarball so the converter's tensor mappings match the binaries, mirroring unsloth_zoo's _hydrate_converter_sources layout. LLAMA_PREBUILT_TAG build-arg overrides the pinned release. docker_confirm.sh: one-command confirmation script for any machine (Linux / WSL2 / macOS) following the staging confirm-script conventions: host + docker + GPU detection with CPU-mode auto-fallback, image pulls, in-container torch.cuda check, 5-step LoRA training smoke, baked llama.cpp verification, full-image boot probing Studio /api/health and JupyterLab /api, PASS/WARN/FAIL summary with RESULT line. * docker: whitelist new build-context files, add docker_confirm.ps1 The dockerignore uses an everything-out whitelist; fetch_llama_prebuilt.py (base bake) and supervisord.conf + studio_launch.sh (Dockerfile.studio) need explicit entries. docker_confirm.ps1 is the Windows Docker Desktop counterpart of docker_confirm.sh. * docker/studio: deterministic Studio install inside the image build Two failures from the first in-image Studio install, both rooted in install.sh probing the build host: 1. setup.sh aborted on the pre-linked llama.cpp dir: 'already exists and is not marked as a Studio-owned llama.cpp install'. The dir is the image's baked prebuilt, provisioned exclusively for Studio, so write the .unsloth-studio-owned marker next to the binaries. 2. With no GPU and no nvidia-smi in the build container, install.sh fell back to cu126 torch wheels for the Studio venv (and would pick cpu wheels on a CI runner without /proc/driver/nvidia), so the published image's Studio venv would depend on which host built it and could not train on Blackwell. get_torch_index_url now honours an explicit UNSLOTH_TORCH_INDEX_FAMILY override naming the index leaf (cu128, cu130, rocm7.2, cpu, ...). The resolved family flows into UNSLOTH_TORCH_BACKEND, which install_python_stack.py already consumes, so the whole downstream chain follows the pin. Dockerfile.studio sets cu128 on amd64 and cu130 on arm64 (DGX Spark / Grace). * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: mirror the llama.cpp bake into build/bin so Studio setup reuses it Studio's setup.sh provisioning runs install_llama_prebuilt.py, whose host-probing cannot succeed inside an image build, so it fell back to a CPU-only llama.cpp source build layered over the baked CUDA bundle. setup.sh skips that fallback when build/bin/llama-server and build/bin/llama-quantize are executable, so hardlink the installed bundle into build/bin: zero extra bytes, $ORIGIN rpath still resolves, and no symlink cycle when setup.sh later relinks the root quantizer to build/bin/llama-quantize. * docker_confirm.sh: rename unused poll counter for shellcheck SC2034 * docker: review fixes from the 8-reviewer pass and staging CI entrypoint.sh: a container started without a GPU request has no nvidia-smi at all (the toolkit injects it), so the old check 1 reported 'CUDA runtime in this image is broken, re-pull' for the most common user error. Fold the missing-binary case into the actionable 'No GPU visible' message and document the CPU-only option (UNSLOTH_ALLOW_CPU=1). run.sh / test_locally.sh: guard empty-array expansions with the ${arr[@]+...} form; bash 3.2 (macOS /bin/bash) treats "${empty[@]}" as unbound under set -u, which broke the documented macOS CPU path. studio_launch.sh: exclude *_TOKEN, *_API_KEY, *_PASSWORD, *_SECRET, *_LICENSE from the env snapshot written for SSH sessions; secrets stay in process env only, never on disk. supervisord.conf / Dockerfile.studio: pin HOME=/root for the studio and jupyter programs (jupyter would silently fall back to token auth if HOME were unset), default JUPYTER_PORT and UNSLOTH_ENABLE_SSHD at the image level so a direct supervisord invocation cannot hit a bad %(ENV_*)s expansion, and document the root-services decision (non-root parity with the previous production image is a tracked follow-up). docker_confirm.ps1: mirror the bash script's GPU selector translation so GPUS=0 / 0,1 select devices instead of silently using all GPUs. docker-publish.yml: studio cache scope moves to mode=min; a mode=max cache of a ~24GB image would evict everything else in the 10GB GHA quota for no hit-rate gain. * docker: second review pass fixes - Dockerfile: lift numba past vllm's 0.61.2 pin after the numpy>=2.4 re-upgrade; 0.61.2 refuses numpy 2.3+ at import time and the stack cannot move numpy down. Verified numba 0.65 + numpy 2.4.6 + vllm import cleanly together. - docker-publish.yml: resolve UNSLOTH_ZOO_REF in a step that mirrors the pushed tag only when the tag exists in unsloth-zoo (the zoo currently cuts no tags, so blind mirroring broke every tag publish); falls back to main. - Dockerfile.studio: Studio venv stays on cu128 for arm64 too, matching the base venv (cu130 wheels would lift the driver floor to 580+), and gets the same NVRTC cu13 swap for DGX Spark / GB10 sm_121 support. - docker_confirm.sh: do not drop to CPU mode when docker info lacks a nvidia runtime entry; CDI installs and Docker Desktop WSL2 expose GPUs without one. The phase 3 --gpus probe is now the authority. - docker_confirm.ps1: GPU selector built as an args array; comma device lists get version-aware CSV quoting (native arg passing changed in PowerShell 7.3). - studio_launch.sh: no fixed Jupyter default password; generate a random one and print it when JUPYTER_PASSWORD is unset. Env snapshot for SSH sessions now written via shlex.quote instead of sed so values with quotes or command substitution cannot break or inject into /etc/profile.d. - install.ps1: honour UNSLOTH_TORCH_INDEX_FAMILY like install.sh does. * docker ci: aggressive runner disk reclaim before image builds A staging run of the studio image build died with ENOSPC during the Studio venv install: the hosted runners' default free space does not fit the base image plus buildkit state plus the Studio layer. Drop all unused preinstalled toolchains and the runner's preloaded docker images in both build jobs. * gpu_init: satisfy the import-hoist lint in the compile-thread patch The checker does not count attribute assignment on an aliased module import as a use and flagged _zoo_common as added-but-unused. Set the attribute through importlib.import_module instead; importlib is already a module-level import here. Behaviour unchanged. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: zstd + matplotlib for out-of-the-box notebook coverage Running the published unslothai/notebooks set inside the image surfaced two gaps: the Ollama export notebook installs ollama in-container and that installer needs zstd for extraction, and DeepSeek-OCR's trust_remote_code modeling file imports matplotlib unconditionally (plotting is also simply expected in a Jupyter image). * docker: audio decode out of the box (ffmpeg + matched torchcodec bake) The TTS/STT notebooks decode datasets Audio features through torchcodec, which fails three different ways on a fresh image: the PyPI wheel pairs with the cu13 torch line and dlopens libnvrtc.so.13; builds newer than 0.10 reference torch 2.11+ symbols; and the matching +cu128 build dlopens torch and NVIDIA runtime libraries that live inside the venv where the loader cannot see them. Bake ffmpeg, torchcodec==0.10.0 from the cu128 channel, nvidia-npp-cu12, and register the venv lib dirs via ld.so.conf.d (not LD_LIBRARY_PATH, so the llama.cpp bundle keeps winning through its own RUNPATH). Verified in-container: AudioDecoder imports and llama-server still resolves its bundled libraries. * docker: split the torchcodec bake across build stages The wheel install belongs in the builder (the venv copy carries it), but the ld.so.conf.d registration and the import check belong in the runtime stage: the conf file does not survive the stage copy and the import needs ffmpeg, which only the runtime stage installs. * docker: install vLLM on the arm64 leg too and probe it in the confirm scripts PyPI has shipped aarch64 abi3 wheels for every vLLM release since 0.17, so the arm64 skip rested on a stale premise. With torch held at 2.10.0 the resolver lands on vllm 0.19.1 (the release pinning torch==2.10.0) on both arches; verified by cross-resolving the exact index set for aarch64-unknown-linux-gnu. amd64 keeps fail-loud semantics. arm64 is fail-soft because the aarch64 wheels are newer and their GPU kernels get validated on Spark hardware via docker_confirm.sh rather than in CI; on failure the fallback uninstalls vllm and restores the numpy/numba floor so a partial install cannot break import unsloth (numpy 2.2.6 ships a broken numpy.testing). The install steps form an explicit && chain instead of a set -e subshell: POSIX shells disable errexit inside condition contexts (verified on dash), so a (set -e; ...) condition would mask failures. Both confirm scripts gain a 5b vLLM phase: ok on import, bad if missing on x86_64, warn on other arches where fast_inference=True is best-effort. * docker: add wget to the runtime image Notebooks fetch sample assets with !wget; without the binary the shell prints not-found to stderr, the cell still exits zero from Jupyter's perspective, and the next cell crashes confusingly on the missing file. The Whisper notebook died exactly this way in the validation matrix. * ci: retrigger after bulk-cancelled runs * docker: unbreak standalone vllm serve (ninja-build + flashinfer-jit-cache) The notebook validation matrix caught the synthetic-data notebook dying because the vllm server SyntheticDataKit launches never came up. Two layers to the failure: 1. flashinfer's cpp_ext JIT shells out to ninja. The pip ninja lives in the venv bin, which subprocesses like vllm serve do not always inherit on PATH, so the JIT failed with exit 127. Install ninja-build so the binary is reachable from any PATH. 2. With ninja present the JIT still cannot succeed for device code: the runtime image deliberately ships no nvcc. Bake flashinfer-jit-cache (cu128) so ops missing from the cubin package (fmha_gen on sm_100a was the repro) come precompiled. In-process GRPO never hit this because unsloth-zoo blocks the FlashInfer JIT path; standalone vllm serve gets no zoo patches. Fail-soft on the jit-cache for arches without a wheel; the vLLM chain itself stays fail-loud on amd64. * dataprep: detect vllm 0.19 server readiness (renamed log line, stderr) SyntheticDataKit.from_pretrained waits for 'Starting vLLM API server on' in the child's stdout before declaring the server up. vLLM 0.19 renamed the line to 'Starting vLLM server on ...', so the regex never matched, the 1200 s readiness timeout expired with a perfectly healthy server, and the launcher tore it down; every downstream synthetic-data-kit step then failed on missing files. Accept both wordings, watch stderr too (vLLM has moved its logging between pipes across versions), and bail out of the wait early if the child exits. With this plus the ninja-build and flashinfer-jit-cache image fixes the Meta synthetic data notebook goes from a 21 min timeout-and-fail to a 3 min pass inside the container. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * studio: honor UNSLOTH_TORCH_INDEX_FAMILY in CUDA repair path, assert torch CUDA family at studio image build _detect_cuda_torch_index_url now respects the explicit family override before probing nvidia-smi, matching install.sh get_torch_index_url and install.ps1 Get-TorchIndexUrl. Without it, a GPU-less environment falls back to cu126 wheels which lack sm_100/sm_120 kernels and break training on Blackwell. ROCm repair path is intentionally unchanged. Dockerfile.studio now fails the build if the Studio venv torch local version tag does not match the pinned TORCH_FAMILY, so a studio ref whose installer ignores the override can never ship a silently wrong image. Metadata-only check so QEMU arm64 builds do not need to load torch. * Fix import on driverless hosts under UNSLOTH_ALLOW_CPU=1 unsloth_zoo.device_type.get_device_type() deliberately returns cuda when UNSLOTH_ALLOW_CPU=1 and no accelerator exists (CPU CI, Docker Desktop without GPU passthrough), but the DEVICE_TYPE == cuda import paths probed torch.cuda.get_device_capability() unconditionally and raised RuntimeError: Found no NVIDIA driver. Guard the module level probes with torch.cuda.is_available(); bf16 stays enabled in the degrade branch since CPU bf16 kernels exist while fp16 ones largely do not. Healthy GPU hosts take the original branches unchanged. Found by the cross platform CPU mode validation of the Docker images. * docker: mirror soname symlinks into llama.cpp build/bin, assert the relinked quantizer executes The build/bin hardlink mirror skipped symlinks, so the soname links (libllama-common.so.0 and friends) never reached build/bin. Studio's setup.sh relinks the root llama-quantize to build/bin/llama-quantize, whose RUNPATH is $ORIGIN, so the loader failed with libllama-common.so.0 not found and GGUF export from Studio died with No working quantizer found, then hit the interactive source-build prompt in a non-TTY export subprocess (EOFError). Mirror same-directory soname symlinks into build/bin and extend the bake sanity check to execute llama-quantize from both the install root and build/bin. Dockerfile.studio now also runs the studio-visible quantizer after install.sh so a regression fails the image build instead of runtime exports. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker/studio: make the quantizer build assertion content based llama-quantize exits nonzero on --help/--version while still printing usage, so a bare invocation fails the build even when the binary is healthy. Grep for the usage banner instead; a loader failure prints error while loading shared libraries and no usage text. * docker_confirm: accept locally built images when pull fails A locally built tag (test_locally.sh or docker build) is not on a registry, so the pull phase reported hard failures on a machine that was actually fine. Degrade to a warn when the image is present locally; missing images still fail. * docker: ship cuda-nvcc and cudart-dev in the runtime image flash-linear-attention's TileLang backend JIT-compiles CUDA kernels via nvcc at runtime for gated-delta-rule models (Qwen3.5 family). The -base image only ships runtime libraries, so Studio vision training of unsloth/Qwen3.5-2B died on the first backward pass with [Errno 2] No such file or directory: /usr/local/cuda/bin/nvcc. Install cuda-nvcc and cuda-cudart-dev matching the image CUDA version and assert nvcc is executable at build time. Found by driving a real Qwen3.5-2B training run through the Studio UI in the image. * docker: bake soundfile, evaluate, tensorboard for notebook deps The TTS notebooks (Sesame CSM, Orpheus) read audio via soundfile, the Whisper notebook computes WER via evaluate, and TrainingArguments defaults report_to to tensorboard. These are declared by notebook pip cells that the in-image notebook runner neutralises (deps are meant to be prebaked), so without them those notebooks die on import. All are pure-Python or self-contained wheels and never name torch, so the cu128 pin set is undisturbed. * docker: add jiwer, langid, easydict, protobuf to baked notebook deps Continuation of the notebook-dep prebaking: the in-image notebook runner neutralises pip cells, so declared deps must be prebaked. evaluate's WER metric imports jiwer (Whisper), DeepSeek-R1 GRPO's reward uses langid, some vision trust_remote_code files need easydict, and sentencepiece tokenizer conversion needs protobuf. All pure-Python; torch pin intact. * docker: notebook deps, image size cuts, per-notebook transformers Notebook dependency coverage (base Dockerfile): - Bake omegaconf, einx, librosa, decord, ftfy so the TTS/STT and vision notebooks stop dying on a silent No module named X. Installed in the notebook-deps layer (after the torch/vLLM resolve) with an assertion that the resolve did not move torch 2.10.0 / numpy>=2.3 / numba>=0.65. Image size (no functional change): - Base: prune npp to the two libs torchcodec actually dlopens (libnppicc + libnppc), drop link-time-only .a archives and the nvshmem device bitcode. Headers (torch/include etc) are kept so causal-conv1d / mamba-ssm still build at notebook time with --no-build-isolation. - Studio: pin the Studio venv to Python 3.12 (matches base) so its nvidia-*-cu12 wheels are byte-identical to the base venv's, then symlink the heavy arch-independent CUDA libs (cudnn/cublas/nccl/...) into the base venv copy. cuda_nvrtc and cuda_runtime are excluded (the arm64 nvrtc swap mutates nvrtc in place). Also remove the build-only frontend node_modules (runtime serves the committed dist). Studio image drops ~4.8GB. Per-notebook transformers version, run notebooks unchanged: - Bake coherent transformers sidecars (4.57.6 default + 5.3.0/5.5.0/5.10.2), each transformers==X with its matched huggingface_hub/tokenizers/ safetensors installed --no-deps into its own dir. Companion versions are resolved at build time so they satisfy each transformers' requirements. - unsloth_nb_compat.py: pick the sidecar from the notebook's pin or the model name and activate it (prepend to sys.path) before any ML import, without touching the base cu128 torch/vLLM/unsloth stack. - pip/uv shim on PATH: a notebook install cell becomes safe and idempotent inside a kernel (keeps the baked stack, records the requested transformers for its sidecar); passthrough to the real tool everywhere else. - IPython startup hook for manual JupyterLab, and unsloth-run for the headless driven path. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: pre-load unslothai/notebooks into JupyterLab, edit-safe refresh JupyterLab now opens with the unslothai/notebooks collection already present, so people can open and run a notebook directly without a git clone or wget. - Bake the repo into the image as a read-only template at /opt/unsloth-notebooks (~206MB, .git stripped, build commit recorded). Inherited by the studio image. - On boot the entrypoint populates /workspace/unsloth-notebooks from the template (instant, works offline) and best-effort refreshes from GitHub, but only when upstream has actually advanced (cheap git ls-remote gate, no download otherwise). - The user's edits always win. We record the content hash of every file we write; on refresh a file whose hash differs from what we last wrote is treated as user-modified and is left untouched, so the refresh only updates files the user has not changed and adds new ones. It never overwrites an edited notebook and never produces merge conflicts. Verified: an edited notebook stays the user's version across repeated upstream changes. - Fully best-effort and gated: UNSLOTH_SKIP_NOTEBOOK_SYNC=1 disables it, UNSLOTH_SKIP_NOTEBOOK_REFRESH=1 keeps the baked copy and never hits the network. Offline boots keep what is there and never error. base 18.45 -> 18.67GB, studio 24.88 -> 25.10GB (+~206MB baked notebooks). * docker: notebook refresh ignores header/footer-only upstream changes The boot-time refresh now compares only the tutorial body (the non-boilerplate cells) when deciding whether to update an untouched notebook. If only the install header, announcements, or footer moved upstream, the user's file is left as-is so it is not churned. Notebooks the user has edited or run are still kept untouched, and non-notebook files keep the whole-file refresh. Adds unsloth_nb_content_sig.py to segment head/middle/tail and bakes it into the image. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: heal deleted notebooks on boot + fix notebooks helper dockerignore The boot-time notebook sync now restores notebooks the user deleted, on every boot, from the baked template (offline, even when upstream has not advanced). It only restores files that are missing, so it never resurrects or overwrites an edited notebook, and the GitHub refresh still bumps a restored file to the latest upstream. Opt out with UNSLOTH_KEEP_DELETED_NOTEBOOKS=1. Also add unsloth_nb_content_sig.py to docker/.dockerignore's allowlist; it was referenced by the Dockerfile COPY but excluded from the build context, which broke the image build. * docker: track latest llama.cpp release + show its update banner in Studio Two related changes to the baked llama.cpp prebuilt. 1. Dynamically follow the newest unslothai/llama.cpp release. build.sh resolves the latest release tag (following the /releases/latest redirect, no API token) to a concrete tag and passes it as LLAMA_PREBUILT_TAG, so the layer cache busts only when upstream publishes. The Dockerfile default is now "latest" and fetch_llama_prebuilt.py resolves it the same way, so a plain `docker build .` also tracks latest. Pin LLAMA_PREBUILT_TAG to a concrete tag for a reproducible, frozen build. 2. Make the in-app "newer llama.cpp available" banner work inside the image. Studio's freshness check (utils.llama_cpp_freshness.check_prebuilt_freshness) keys off tag / release_tag / published_repo in UNSLOTH_PREBUILT_INFO.json -- the schema install_llama_prebuilt.py writes. The image bakes the bundle directly, so the marker was the release tarball's own, which only carries upstream_tag / source_repo; the freshness check then bailed with installed_tag=None and could never report "behind", hiding the banner. fetch_llama_prebuilt.py now augments the baked marker with those keys (setdefault, no build timestamp so the layer stays byte-identical). A fresh build is on latest -> no banner; once upstream publishes a newer release the banner appears, as verified against the real freshness backend. * docker: add unsloth-studio-update for in-place Studio updates Updating Studio in the container previously meant pulling a fresh ~25GB image (or at best the ~6GB fused Studio layer) for what is usually a small Python/UI change. Add a baked helper so a running container can update in place: docker exec <container> unsloth-studio-update It updates only the Studio packages -- the backend code and the pre-built frontend, which ships inside the unsloth wheel -- with `pip install -U --no-deps unsloth unsloth_zoo`, then restarts just the studio service via supervisor. The torch/CUDA stack is left untouched, so it is safe in both GPU and CPU-only containers. This deliberately avoids `unsloth studio update`, which re-runs the full installer and re-probes the GPU to pick torch wheels -- in a container started without --gpus that finds no GPU and can downgrade torch to CPU/cu126. Options: --ref <branch|tag|sha> installs from git (track main) instead of the latest PyPI release; --with-deps also updates dependencies; --no-restart defers the restart. After the swap the helper smoke-imports studio.backend.main and, if a transitive dep is now missing, points the user at --with-deps. The update lands in the container's writable layer (survives docker restart); mount -v unsloth_studio_home:/opt/unsloth-studio to keep it across a recreate. * docker: add unsloth-llama-update for in-place llama.cpp prebuilt updates Parity with unsloth-studio-update: update the baked llama.cpp prebuilt in a running container without pulling a new image. docker exec <container> unsloth-llama-update # latest release docker exec <container> unsloth-llama-update --check # report only It reuses the build-time fetcher (fetch_llama_prebuilt.py, now baked at /usr/local/lib/unsloth) rather than the host-probing installer behind the in-app banner. The fetcher resolves the latest release via the GitHub /releases/latest redirect (no API token, not rate-limited) and installs the portable CUDA bundle that runs on CPU and every supported GPU, so it works the same in a CPU-only or a --gpus container. The installer path, by contrast, scans the GitHub API (rate-limited to 403 in practice) and probes the host GPU, which falls back to a slow source build in a container started without --gpus. The fetch lands in a sibling temp dir on the same filesystem and is swapped in with an atomic rename; on any failure the existing install is left untouched. The Studio ownership marker is preserved across the swap. Verified end to end in a CPU-only container: b9596-mix-e6f2453 -> b9773-mix-1f1aaa4. * docker: optional Cloudflare tunnel for JupyterLab (UNSLOTH_JUPYTER_CLOUDFLARE) Mirror the public-link convenience Studio already has for its own UI, for JupyterLab. Off by default; opt in two ways: docker run -e UNSLOTH_JUPYTER_CLOUDFLARE=1 ... unsloth/unsloth docker exec <container> unsloth-jupyter-tunnel --force unsloth-jupyter-tunnel waits for JupyterLab, reuses a cached cloudflared (or fetches the static binary for the arch, no account needed), and starts a quick tunnel to the Jupyter port; the https://<name>.trycloudflare.com URL is printed to docker logs. supervisord runs it as the jupyter-cloudflare program, autostarted only when UNSLOTH_JUPYTER_CLOUDFLARE=1 (studio_launch.sh exports a 0 default so the autostart gate expands, matching the sshd pattern). JupyterLab still enforces its password, so the tunnel is not an open door. Verified: the helper fetches cloudflared and mints a working trycloudflare URL that reaches JupyterLab (HTTP 200) inside a running container. * docker-publish: clean build-args + add least-privilege default permissions - Move the explanatory prose out of the two `build-args:` blocks. docker/build-push-action forwards every non-empty line verbatim, so a leading-# line is passed as a bogus --build-arg; the comments now live above each block. This workflow has not run yet, so the issue was latent. - Add a top-level `permissions: contents: read` default so every job (including smoke-test, which had none) limits the GITHUB_TOKEN. The merge jobs keep their own `packages: write` blocks. Addresses the CodeQL "workflow does not contain permissions" findings. * [pre-commit.ci] auto fixes from pre-commit.com hooks for more information, see https://pre-commit.ci * docker: fix notebook pip-shim drops, first-boot overwrite, base :latest tag, arm64 decord - pip shim: count editable/local/url/vcs targets (-e ., ., git+https, wheel URLs) as install targets, not just canonical package names, so they are no longer silently skipped inside notebooks - notebook sync: never overwrite a pre-existing user notebook on first boot (match the refresh path's ownership rule); skip .unsloth_sync_state.tmp when recording state so it is not tracked as a managed file - docker-publish: set flavor latest=false on the base image metadata so a v* tag push cannot publish :latest from the base image (the Studio image owns it) - notebook deps: pin to tested versions and install decord on its own, hard on amd64 and fail-soft on arm64 (no aarch64 wheel) so the arm64 base build works * docker-publish: pin one llama.cpp prebuilt release across both arch legs The base build-args never passed LLAMA_PREBUILT_TAG, so the Dockerfile fell back to latest and each matrix leg resolved whatever unslothai/llama.cpp release was current at its own build time. If latest moved between the amd64 and arm64 legs, one published manifest could carry different GGUF binaries per arch. Resolve the release once in a new prepare job (explicit llama_prebuilt_tag dispatch input for a frozen build, else follow the /releases/latest redirect to a concrete tag, mirroring docker/build.sh) and pass that single tag to both legs. * docker: address review follow-ups (pip-shim flags, sync ownership, tags, zoo ref, arch list) - pip shim: do not treat the value of an index-url / find-links / constraint flag as an install target. A cell like 'pip install --extra-index-url <url> torch' now no-ops after keeping the baked stack instead of exec'ing a bare 'pip install --extra-index-url <url>' that fails. Positional . / url / vcs and -r/--requirement files still count as targets. - notebook sync: on first boot, record only files we actually wrote (or that are byte-identical to the template), never a kept pre-existing user file; and on the GitHub refresh, treat a file present in DEST but absent from the sync state as user-owned and keep it. Previously a bind-mounted notebook was recorded as managed and then overwritten by upstream. - docker-publish: add flavor latest=false to the Studio metadata steps too, so a v* tag push cannot emit an implicit :latest via metadata-action's latest=auto; :latest stays default-branch-only, and the smoke test pulls the published tag. - unsloth-studio-update: resolve the unsloth-zoo ref independently of --ref (new --zoo-ref, else use the ref only when the zoo repo has it, else fall back to main) so 'update --ref <unsloth-tag/sha>' does not fail on a missing zoo ref. - Dockerfile: drop 10.3 (compute_103) from TORCH_CUDA_ARCH_LIST in both the builder and runtime stages. B300 runs sm_100 SASS, and the bundled CUDA 12.8 nvcc cannot compile compute_103 (added in 12.9), which broke arch-list-honoring source / JIT builds. * docker: address review round 3 (notebook …
Summary
Moved out of #5434 so the FLA/tilelang work stays focused. Pure test-only changes to
tests/studio/run_real_mlx_smoke.py._on_stepcallback now accepts the extragrad_normarg that recent transformers / TRL pass in, so the MLX smoke stops aborting with a TypeError on the first optimizer step.max_grad_value=0somax_grad_norm=1.0is the gradient gate that actually wins (otherwise the value-clip silently dominates and we never exercise norm clipping).Test plan
tests/studio/run_real_mlx_smoke.pyruns to completion on the MLX Mac runner.