Repository navigation
python_scripts: end the Installation section without an Unsloth heading so 38 mirrors no longer start with a live get_ipython call - #417
Conversation
remove_unwanted_section only commented the install cells out when a later # Unsloth heading closed the section. 38 python_scripts mirrors (18 base notebooks and their AMD, Kaggle and HuggingFace Course copies) have none, so their %%capture cell stayed live and the script died with NameError: get_ipython. Without that heading, end the section at the next markdown heading of any level or the first code cell that is not an install cell. A %%capture cell that also does setup the script needs (%cd, sys.path, file edits, a name read later) stays live; a mixed boundary cell loses only its pip lines. Notebooks with the heading keep the old path byte for byte. Adds tests/test_python_scripts_no_live_install_magic.py with a commented allowlist and a CI step.
|
@codex review |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
@codex security review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
🛡️ Codex Security ReviewSecurity review completed. No security issues were found in this pull request. Reviewed commit: Only the user who started this review can view the report in Codex. ℹ️ About Codex security reviews in GitHubThis is an experimental Codex feature. Security reviews are triggered when:
Once complete, Codex will leave suggestions, or a comment if no findings are found. |
…othai#404) * Correct the config table: gemma-4 does not fit two T4s The table claimed gemma-4 PASSES on a Kaggle 2x T4 at 14.3 GB. It does not, and a user picking it would hit an OOM. Four runs on real 2x T4 hardware, all with gpus=2 and two Tesla T4s confirmed in the executed notebooks: gemma-4 seq 1024 OOM, 256 MiB short on the training card gemma-4 seq 512 OOM, 256 MiB short muse-glimmer seq 1024 OOM muse-glimmer seq 384 OOM, 208 MiB short The muse-glimmer figure reproduces the old note exactly, down to the 208 MiB. The gemma-4 PASS was measured before the chunked loss and the current notebook, and no longer holds. The reason is placement, not the sequence length. Unsloth trains on one GPU, so the second T4 can hold the teacher but not the student's activations, and the 14.56 GiB training card is exhausted either way. Dropping the sequence length from 1024 to 512 does not change the outcome, so these configs need one bigger card rather than more cards, and the table now says that. I tried giving the teacher a zero budget on the training card so the whole teacher lands on the second one. Placement worked (teacher budget 0.00 GiB on the training card, 12.42 GiB on the other, teacher loaded), but accelerate then refuses the run: "You can't train a model that has been loaded in 8-bit or 4-bit precision on a different device than the one you're training on." That trades an OOM for a ValueError, so it is not in this change. qwen3 is unaffected and still passes on a single free T4. * Muse Glimmer / Qwen3.8 Conversational: run on a single large GPU (unslothai#406) The Colab versions of Muse_Glimmer_(30B)-Conversational and Qwen3.8_(27B)-Conversational fail on a single large GPU (A100 40GB). The Kaggle T4 x2 versions pass. Both templates are fixed and regenerated; only those two templates and their generated notebooks and scripts change. ## Muse_Glimmer_(30B)-Conversational - `KeepEmbeddingOffloaded` moved the input embedding to the CPU at `on_train_begin` whenever accelerate did not own placement. - Unsloth now offloads that embedding only when the GPU is short of memory, and marks the model with `_unsloth_embedding_offloaded`. On an A100 nothing is offloaded and no hooks are installed. Moving the table anyway split the forward across devices: `Expected all tensors to be on the same device ... index is on cuda:0 ... cpu`. - The callback now only moves the embedding when that marker is set. Kaggle T4 x2 is unaffected: accelerate owns placement there, so the callback still returns early. ## Qwen3.8_(27B)-Conversational - Cell 3 asserted `torch.cuda.device_count() >= 2`, so the Colab version failed on any single-GPU VM, including a 40 GB A100. - The load cell printed `model.hf_device_map`, which does not exist on a single-GPU load. - The check is now total GPU memory of at least 28 GB. The model peaks near 22.5 GB on one A100, and about 11.4 GB per card on two T4s. The print falls back to one device. ## Validation Run as written (PyPI install), trainers capped at 5 steps: | Notebook | Before | After | |---|---|---| | Muse_Glimmer_(30B)-Conversational, Colab A100 | `trainer.train()` device mismatch | trains 5 steps, generates, saves | | Qwen3.8_(27B)-Conversational, Colab A100 | AssertionError at cell 3 | trains 5 steps, generates, saves; 1 device, peak 23.6 GB | | Kaggle-Muse_Glimmer_(30B)-Conversational, Kaggle T4 x2 | pass | pass (all 24 cells, 5 steps) | | Kaggle-Qwen3.8_(27B)-Conversational, Kaggle T4 x2 | pass | pass (all 21 cells, 5 steps, 2 devices) | Not changed here: both Colab headers say "free Tesla T4", but neither model fits one T4 (Muse_Glimmer also does not fit Colab's L4: 22.24 GB checkpoint, 21.76 GB free). * Fix the notebook static gate: AMD tool-use install from main, vLLM find_spec false positive (unslothai#407) The `notebook static checks (HARD GATE)` job fails on main (678bfaa and b6d3465). The gate runs its test files in order and stops at the first red one, so three broken files hide behind each other. The first: ``` FAILED tests/test_amd_git_main_unsloth_install.py::test_generated_amd_notebooks_match_their_source[AMD-Qwen3_(4B)-GRPO-Tool_Use.ipynb-Qwen3_(4B)-GRPO-Tool_Use.ipynb] AssertionError: AMD-Qwen3_(4B)-GRPO-Tool_Use.ipynb lost git+https://github.com/unslothai/unsloth-zoo ``` ## Cause - The CUDA and Kaggle tool-use installs end with `TOOL_USE_UNSLOTH_MAIN`, a forced reinstall of unsloth and unsloth_zoo from main. The comment there says tool calling GRPO needs the TRL chat template fallback and the tokenizer save fix. - For AMD GRPO notebooks the generator gives `_compose_amd_installation` the plain `installation_extra_grpo_content`, so the tool-use variant never saw the git main specs. The AMD notebook stayed on the released wheels. ## Change - `update_all_notebooks.py`: tool-use AMD notebooks are composed from `installation_extra_grpo_tool_use_content`. - The regenerated `nb/AMD-Qwen3_(4B)-GRPO-Tool_Use.ipynb` gains a single line, the same `--upgrade --force-reinstall --no-deps` git main line the other AMD notebooks that track main already carry (for example `AMD-Granite4.0`, `AMD-Falcon_H1-Alpaca`). Its vllm / transformers / trl pins are unchanged. - `python_scripts/AMD-Qwen3_(4B)-GRPO-Tool_Use.py` gets the same line. - `tests/test_notebook_vllm_pin.py`: with the AMD test passing, the same gate reaches this file, which also fails on main (10 cases, all tool-use notebooks). Their install cell sets `fast_inference = importlib.util.find_spec("vllm") is not None`, and the quoted-requirement regex read `"vllm"` there as an unpinned install. A module lookup (`find_spec(` / `import_module(`) is no longer read as a requirement, and both forms are added to the not-a-requirement test. Real installs are unaffected: every case the gate checked before is still checked. - `python_scripts/`: the seven Qwen3 (4B) tool-use and tool-calling mirrors (CUDA, Kaggle, AMD, HuggingFace Course) were committed in the raw-magic form, so `test_python_scripts_regen_parity.py` reported drift for all seven. They are regenerated with the generator's own `convert_notebook_to_script`, the `get_ipython()` form every other mirror already uses. No notebook changes for this. ## Validation - A full regeneration changes only this notebook beyond the existing drift on main. - `pytest tests/`: on main, 18 failures (1 AMD install, 10 vLLM pin, 7 mirror parity); on this branch, 0 (15337 passed). - Not run on AMD hardware. The change is an install line, and it is identical to the one the other AMD notebooks already use. * add tool calling notebooks (unslothai#10) Co-authored-by: oliveirabruno01 <[email protected]> * Whisper notebook: transformers pin (superseded, no changes) (unslothai#109) Co-authored-by: enesbol <[email protected]> * Strix Halo Dockerfile and gpt-oss (20B) notebook (superseded, no changes) (unslothai#126) Co-authored-by: 0xrushi <[email protected]> * Add news section to fine-tuning notebook (superseded, no changes) (unslothai#191) Co-authored-by: Aditya Tiwari <[email protected]> * Add support to AMD Dev Cloud (superseded, no changes) (unslothai#111) Co-authored-by: vivienfanghua <[email protected]> * Add image token budget example to Gemma 4 vision notebook (superseded, no changes) (unslothai#250) Co-authored-by: siddhantoon <[email protected]> * Add Modal notebooks (superseded, no changes) (unslothai#116) Co-authored-by: Aniket Maurya <[email protected]> * Add trackio experiment tracking to gpt-oss-(20B)-Fine-tuning notebook (superseded, no changes) (unslothai#110) Co-authored-by: Abubakar Abid <[email protected]> * Add SmolLM3 (3B) Conversational finetuning notebook (superseded, no changes) (unslothai#306) Co-authored-by: gowtham-sai-yadav <[email protected]> * Use re.DOTALL in GRPO format rewards (unslothai#96) The format rewards in the Llama3.1 (8B), Mistral v0.3 (7B), Phi-4 (14B) and Qwen2.5 (3B) GRPO notebooks call `re.match` without `re.DOTALL`, so `.` never crosses a newline: - `soft_format_reward_func` pays 0 even for the exact `<reasoning>\n...\n</reasoning>\n<answer>\n...\n</answer>\n` format the system prompt asks for. - `strict_format_reward_func` pays 0 whenever the reasoning spans more than one line. This adds `flags = re.DOTALL` to both calls in the four `original_template` notebooks and regenerates their `nb/`, Kaggle, HuggingFace Course and `python_scripts` copies. Reward functions from the generated Qwen2.5 script (strict, soft): | completion | before | after | |---|---|---| | expected format, multi-line reasoning | 0.0, 0.0 | 0.5, 0.5 | | expected format, one-line reasoning | 0.5, 0.0 | 0.5, 0.5 | | no tags | 0.0, 0.0 | 0.0, 0.0 | * Qwen3-VL (8B) Vision: SFTTrainer processing_class and eos_token (unslothai#253) Co-authored-by: Saad1926Q <[email protected]> * Whisper: pass processing_class instead of removed tokenizer kwarg (unslothai#290) * Whisper: pass processing_class instead of removed tokenizer kwarg transformers 5.x removed the deprecated tokenizer argument from Seq2SeqTrainer (4.x already warned: use processing_class instead), so the notebook dies at trainer construction on current installs. processing_class accepts the feature extractor on 4.57.6 and 5.x alike. Applied in original_template and synced to the generated nb, kaggle and python_scripts copies; a full regeneration was avoided on purpose since it rewrites unrelated notebooks. * Whisper: apply processing_class rename to AMD notebook * Gemma 4 Text notebooks: keep <bos> in the training text (unslothai#383) * Gemma4 Text: keep <bos> in the formatted training text The Gemma-4 chat template already starts with <bos>, and Unsloth's SFT path tokenizes text that starts with <bos> without adding special tokens. removeprefix('<bos>') therefore left training with no <bos> at all, unlike inference (unslothai#251). * Gemma4 Text notebooks: keep <bos> in the formatted training text (E2B, E4B, 26B A4B, 31B, AMD and Kaggle copies) * Keep <bos> in the Gemma 4 Text kaggle/ and molab/ copies too --------- Co-authored-by: Antigravity Reviewer <[email protected]> * Gemma3 (270M): optional export to LiteRT-LM (.litertlm) for phones (unslothai#411) Fixes unslothai#97 Users asked how to take a LoRA finetuned Gemma 3 270M from our notebook onto an Android phone through Google's on-device stack (MediaPipe `.task`). MediaPipe's LLM Inference API is now in maintenance-only mode and Google points to LiteRT-LM and its `.litertlm` files instead (Android and iOS through its Kotlin and Swift APIs), so this adds an optional LiteRT-LM export section to the Gemma 3 (270M) notebook, right after the GGUF cells. It is off by default (`if False:`), like the other saving cells, so the notebook runs exactly as before unless a user turns it on. **What the cell does** - Merges the LoRA adapters with `save_pretrained_merged(..., save_method = "merged_16bit")` into `gemma_3_finetune_16bit` (the folder name the generator already uses for 16bit merges). - Makes a separate `litert_env` virtual environment with uv and installs Google's converter and runtime there on the CPU (`litert-torch==0.10.0`, `litert-lm==0.18.1`, `tensorflow-cpu==2.21.0`, `transformers<5.21`, CPU torch via `--torch-backend cpu`). The training stack in the notebook kernel is not touched. - Runs `litert-torch export_hf gemma_3_finetune_16bit gemma_3_finetune_litertlm`, Google's documented path for finetuned checkpoints, which writes an int8 `model.litertlm`. - Repacks the file with `litert-lm unpack` / `pack` so the prefill/decode model declares `prefer_activation_type = "fp32"`. Gemma 3 270M bundles only print `<pad>` on LiteRT-LM's GPU backend with its default fp16 activations, and declaring fp32 is the workaround confirmed in google-ai-edge/LiteRT-LM#3280. The edit is guarded, so repacking twice adds the hint once. - Asks the file one question from the dataset on the CPU with `litert-lm run`. The prompt is the system prompt plus the user turn joined the way the Gemma 3 chat template joins them. `--cache no` stops LiteRT-LM from writing a 270MB XNNPACK cache file next to the model on every run. Re-running the cell is safe: `uv venv --allow-existing` reuses the environment, the install is a no-op once satisfied, and the export overwrites `model.litertlm`. **Tests change** `tests/test_no_torch_import_before_torch_pin.py` matched `litert-torch==0.10.0` as a torch pin (`\btorch==` also matches after a `-`). That install goes into a separate interpreter and never moves the kernel's torch, so the regex now requires that the name is not preceded by a word character or `-`, with a case for it. Every pin the test caught before is still caught. **Tested** - Local CPU (Linux x86-64, Python 3.12, the same pins): `export_hf` on `unsloth/gemma-3-270m-it` took 4m02s at a peak RSS of 6.6GB and wrote a 285,572,672 byte `model.litertlm`; `litert-lm run` answered "Paris" to a capital question. Re-exporting into the same folder overwrote the file cleanly. - The chat template stored in the file renders the same prompts as `tokenizer.apply_chat_template` for a user turn, a system plus user turn, and a three turn conversation (LiteRT-LM adds `<bos>` itself). - Colab T4, 2026-10-22: `nb/Gemma3_(270M).ipynb` run top to bottom (5 training steps) with the cell turned on and then run a second time. The export took 164s and 142s at a peak RSS of 6.4GB (the free tier has 12.7GB), both wrote a 285,572,672 byte `model.litertlm`, and the finetuned file answered the dataset's chess prompt in the trained format (`{"missing move": "b1c2"}`) both times. Nothing else was left in the output folder. - The fp32 hint: after the repack the file carries `prefer_activation_type = fp32` on the prefill/decode section (checked with `litert-lm unpack`), repacking a second time leaves one entry, and the CPU answers are the same with and without it (3s for a 256 token cap either way). - `python update_all_notebooks.py` (with `--amd`) regenerates `nb/Gemma3_(270M).ipynb`, `nb/Kaggle-Gemma3_(270M).ipynb`, `nb/AMD-Gemma3_(270M).ipynb` and the three `python_scripts`; running it again leaves them unchanged. Only these files are included, the rest of the generator's output on main is unrelated drift. - `pytest tests`: 15310 passed, 594 skipped, 0 failed. **Not covered** - Kaggle: not run, the GPU quota on our Kaggle accounts is used up for this week. The cell does not depend on Kaggle's Python having `ensurepip`, since uv makes the environment. - A phone: the file was run with LiteRT-LM on the CPU only, not on an Android device. * Move Orpheus token constants to top and use symbolic names (unslothai#81) Defines the Orpheus special token ids once, in their own cell before the tokenization step, and uses those names in tokenization and inference instead of the hardcoded values (128257, 128258, 128259, 128260, 128263, 128266). Fine-tuning another Orpheus-style model with a different base tokenizer, for example https://huggingface.co/OpenSpeechHub/Emilia-All-Ja-Qwen3-0.6B, now only needs that one cell edited. The change is made in `original_template/Orpheus_(3B)-TTS.ipynb` and carried into the generated Colab, Kaggle and AMD notebooks and their `python_scripts` copies. Every name resolves to the same value as the literal it replaces, so the default notebook behaves exactly as before. * Llasa TTS: fix XCodec2 encoding all-zero speech codes (unslothai#410) * Llasa TTS: load XCodec2 SnakeBeta biases and pin vector_quantize_pytorch * Tighten Llasa XCodec2 comments * Add OmniVoice (0.6B) TTS fine-tuning notebook (unslothai#412) * Add OmniVoice (0.6B) TTS fine-tuning notebook * Test that OmniVoice notebooks load the backbone with SDPA and install transformers >= 5.3 * OmniVoice notebook: tell readers to remove max_steps or set -1, not None * OmniVoice notebook: install torchaudio when absent, upload whole folders to the Hub * OmniVoice notebook: save only the merged, reloadable checkpoint * OmniVoice install: take torchaudio from torch's own index when torch has a local tag * Tighten the OmniVoice install comment * python_scripts: keep UNSLOTH_VLLM_STANDBY from the commented install cell (unslothai#413) * python_scripts: keep UNSLOTH_VLLM_STANDBY from the commented install cell The .py conversion comments out the Installation section, and the GRPO notebooks set os.environ["UNSLOTH_VLLM_STANDBY"] = "1" inside that %%capture cell, so the scripts ran without vLLM standby and the vLLM GRPO scripts OOM on a 15 GB T4 where the notebook fits. remove_unwanted_section now re-emits that assignment live right after the commented section, unless the script already sets it at top level later. * tests: license header for the standby env test * python_scripts: regenerate, keeping UNSLOTH_VLLM_STANDBY live * CI: run the standby env script test * OmniVoice: install audioop-lts on Python 3.13 so pydub imports (unslothai#414) OmniVoice imports pydub, whose utils module imports the stdlib audioop that Python 3.13 removed. pydub 0.25.1 does not declare the audioop-lts backport, and omnivoice is installed with --no-deps, so a clean Python 3.13 environment on the local/cloud install branch fails at 'from omnivoice import OmniVoice' with No module named 'pyaudioop'. Colab and Kaggle are unaffected today only because their images ship gradio, which pulls audioop-lts in. * python_scripts: end the Installation section without an Unsloth heading so 38 mirrors no longer start with a live get_ipython call (unslothai#417) * Scripts: end the installation section without a # Unsloth heading remove_unwanted_section only commented the install cells out when a later # Unsloth heading closed the section. 38 python_scripts mirrors (18 base notebooks and their AMD, Kaggle and HuggingFace Course copies) have none, so their %%capture cell stayed live and the script died with NameError: get_ipython. Without that heading, end the section at the next markdown heading of any level or the first code cell that is not an install cell. A %%capture cell that also does setup the script needs (%cd, sys.path, file edits, a name read later) stays live; a mixed boundary cell loses only its pip lines. Notebooks with the heading keep the old path byte for byte. Adds tests/test_python_scripts_no_live_install_magic.py with a commented allowlist and a CI step. * Trim comments in install section terminator * fsdp2_scripts: one multi-GPU FSDP2 launcher per python_scripts file, generated by update_all_notebooks.py (unslothai#416) * Generate fsdp2_scripts/: one multi-GPU launcher per python_scripts file update_all_notebooks.py gains generate_fsdp2_scripts and render_fsdp2_launcher. After each python_scripts conversion (the full pass and the AMD-only pass) it writes fsdp2_scripts/<name>.py for every python_scripts/<name>.py, copies scripts/fsdp2_launch.py to fsdp2_scripts/unsloth_fsdp2_launch.py and renders fsdp2_scripts/README.md. Files are staged before anything is replaced, only changed files are written, and launchers with no script are removed (scoped to AMD-* in the AMD-only pass). _assert_fsdp2_mirror checks both directions. tests/test_fsdp2_scripts_mirror.py gates the committed tree against the generator and exercises idempotence, stale cleanup and the AMD-only scope. fsdp2_scripts is added to the exec-literal lint targets, the CI paths filter and the CODEOWNERS notes. * CI: run the fsdp2 launcher helper tests tests/test_fsdp2_launch.py needs CPU torch, so it runs in the api-drift job; tests/test_fsdp2_adapter_covers_scripts.py runs with the no-torch static checks. * Regenerate fsdp2_scripts/ for the current python_scripts * Add fsdp2 launcher runtime and get_ipython adapter scripts/fsdp2_launch.py runs a python_scripts/<name>.py mirror on every visible GPU with Unsloth native FSDP2: it counts GPUs in a child process, re-execs itself under torch.distributed.run --standalone for 2+ ranks and runs the target in-process for 0 or 1. Inside torchrun the target runs via runpy with a narrow get_ipython stand-in: shell steps and file writes run once per node on local rank 0 while the other local ranks wait on a marker carrying the return code, %env and %cd apply on every rank, and package installs are skipped unless UNSLOTH_FSDP2_RUN_INSTALLS=1. tests/test_fsdp2_launch.py covers the argv, count precedence, refusal, worker mode and a real two-rank CPU torchrun. tests/test_fsdp2_adapter_covers_scripts.py checks every live get_ipython() call in python_scripts/ is supported. * fsdp2_scripts: add the generated launcher helper copy and record its two dynamic-execution call sites * fsdp2 launcher: per-launch markers, install checks, safer launch detection - Marker folders are unique per launch: the parent sets UNSLOTH_FSDP2_RUN_ID before starting torchrun, other launchers fall back to the parent pid. Local rank 0 removes the folder at exit once the other ranks have read the last marker or exited. - A LOCAL_RANK left in the shell without WORLD_SIZE / LOCAL_WORLD_SIZE is ignored, shell steps only synchronise with 2+ local ranks, and a waiting rank gives up after UNSLOTH_FSDP2_WAIT_TIMEOUT (default 6 hours) with a clear error. - Installs: by default a pip / uv pip / apt-get / ollama install is skipped only when everything it asks for is already present (versions checked), otherwise it runs once per node. Installs into another environment always run. UNSLOTH_FSDP2_RUN_INSTALLS=1 / 0 force either way, and the single process path follows the same rules. - Refuse to start torchrun from each of several SLURM / MPI tasks. - Under IPython / Jupyter (%run) torchrun runs as a child process. - multiprocessing spawn / forkserver children re-import the script with get_ipython defined and without repeating its shell steps. - %cd prints the error and continues on a missing folder, like IPython. - The single-process note names what was requested, and a failing GPU count prints the child's error. * fsdp2_scripts generator and CI: robust replace, permissions, own test job - Replacing or removing a read-only launcher clears the read-only bit and retries, as _rmtree_robust does. - Unchanged launchers still get their permissions reset. - The generate_fsdp2_scripts docstring says what a failure leaves behind. - Ignore the .fsdp2_scripts.staging-* folder. - The git diff summary counts only the root README.md as a README change. - tests/test_fsdp2_launch.py runs once in its own CPU torch job instead of in every api-drift matrix cell. - fsdp2_scripts/README.md describes the new install rules and variables. * fsdp2 launcher: private markers, step handshake, shared output and errors - The marker folder is created 0700 and refused when it is a symlink, owned by another uid, or group / world writable. Markers are written to an exclusive, no-follow temp file and then os.replace'd, and their JSON content is validated before it is believed. - Every shell / file step is a handshake: the other local ranks record their arrival with a hash of the unexpanded step, local rank 0 waits for all of them, then records its return code, output, install decision and any error. Ranks that reach different steps fail with a divergence error. - x = !cmd runs once per node under the same install rules and every rank gets local rank 0's output. Only local rank 0 decides whether an install runs; the others follow its record. - %%file errors on local rank 0 are raised on every rank. - Workers always use the adapter, even where an IPython get_ipython exists. - Log lines name a step by its unexpanded text with URL user info, index URLs, header values and token-like strings masked. - Shell steps refuse to run without bash, and on Windows refuse WSL's bash. - main() takes single_process / reason: such a script runs single process with a note, and more processes are refused unless UNSLOTH_FSDP2_FORCE=1. - --dry-run names the get_ipython adapter in use. * fsdp2_scripts: single-process list for scripts that are not multi-rank safe - FSDP2_SINGLE_PROCESS in update_all_notebooks.py names, by base name across the AMD- / Kaggle- / HuggingFace Course- variants, the scripts that start servers on fixed ports, clone or install through Python subprocess calls, or share temporary files between ranks, each with its reason. Their launchers pass single_process=True and say so in their header. - A static scan of python_scripts/ flags subprocess.Popen, os.system, vllm serve and --port outside get_ipython() calls in any script missing from the list, and stale entries in the list. - Launchers import os and sys on separate lines. - _assert_fsdp2_mirror also requires README.md. - The README documents shell step ordering, single-process scripts and UNSLOTH_FSDP2_FORCE. * fsdp2: Oute_TTS runs single process, URL installs need an explicit name - Oute_TTS_(1B) and its AMD- / Kaggle- copies join FSDP2_SINGLE_PROCESS: its install cell clones OuteTTS and then deletes files from that one checkout with os.remove, which fails on the second rank. - The single-process scan now also reads live %%capture bodies and flags os.remove / os.unlink / shutil.rmtree / shutil.move / os.rename, besides servers and Python-side process launches. - The install check no longer guesses a distribution from a repository URL. A #subdirectory= requirement (for example triton's python/triton_kernels) or a URL without an explicit name (#egg= or name @ url) cannot be checked, so the install runs. Only the unslothai/unsloth and unsloth-zoo repos map to their names, and only without a subdirectory. * fsdp2: trim redundant comments in launcher, generator and adapter test * Run Meta_Synthetic_Data_Llama3_2_(3B) single process (cherry picked from commit 0faf739) * Run shell-step installs with the launcher's own Python (cherry picked from commit 588e516) * Run unsloth with the launcher's Python and never skip PIP_* / UV_PYTHON redirects (cherry picked from commit de9feb7) * Skip an install only when it plainly targets the checked interpreter (cherry picked from commit 1cee870) * fsdp2: stop pinned shell functions recursing through a wrapper interpreter; document sharded load and generate memory The exported python / python3 / pip / pip3 / unsloth functions call $UNSLOTH_FSDP2_PYTHON. When that is a bash wrapper (sys.executable is the wrapper under `exec -a "$0"`, as in Nix-style wrappers) which runs `python3` or `pip` by name, the wrapper imports the exported functions and calls itself again without end. The pinned call now sets _UNSLOTH_FSDP2_PINNED, and below it the names resolve to PATH. _shell_env() clears the variable so a launcher started from another launcher's shell step pins again. README: document UNSLOTH_FSDP2_SHARDED_LOAD (read by Unsloth, 16-bit only) and that model.generate under native FSDP2 gathers the full model on every process, so it can run out of memory on a small GPU after training. * Run OmniVoice_(0.6B)-TTS single process The notebook builds its outer model with OmniVoice.from_pretrained and then calls model.merge_and_unload() and omnivoice.save_pretrained() directly, so the export never goes through Unsloth's collective FSDP2 path. On several ranks the merge fails with "aten.add_.Tensor got mixed torch.Tensor and DTensor" when the model fits one GPU, and the save fails with "invalid python storage" when it is sharded. Run it (and its Kaggle variant) in one process, and teach the mirror test to flag OmniVoice.from_pretrained so a new script with the same pattern must be listed. * Run Llasa_TTS_(1B) and Llasa_TTS_(3B) single process preprocess_and_save opens processed_data_memmap/input_ids.memmap with mode w+ and rewrites input_ids_shape.npy after every example. On several ranks each process truncates and rewrites the same files while another may already be reading the shape back, so np.load can fail or ranks can see different dataset lengths. Run both scripts (and their AMD- and Kaggle- copies) in one process, and teach the mirror test to flag np.memmap opened for writing so a new script with the same pattern must be listed. * fsdp2: wait on torchrun as a child on Windows instead of os.execv On Windows os.execv starts a detached process, joins the arguments without quoting (a path with a space splits) and exits with code 0 at once, so the shell got its prompt back while torchrun ran on and never saw its exit code. Use the same subprocess path as the IPython case there. * fsdp2: keep pinned python / pip working in shell steps under set -u The recursion guard read $_UNSLOTH_FSDP2_PINNED bare, so a !cmd or %%bash step that turns on nounset (set -u, set -euo pipefail) and then calls python, pip or unsloth stopped with 'unbound variable' (exit 127), where the notebook itself runs fine. Read it as ${...:-}. * Run the EmbeddingGemma2 audio, image and multimodal scripts single process EmbeddingGemma2_(300M)-Audio, -Image_Text and -Multimodal_Search write their media files with open(path, "wb").write(...) and read them back for training or encoding. On several ranks each process truncates and rewrites the same paths, and Multimodal_Search's MSR-VTT loop skips a video that already exists, so a rank can decode a file another rank has created but not yet filled (zero bytes, "moov atom not found"). Run the three scripts and their Kaggle copies in one process, and teach the mirror test to flag open(..., "wb").write(...) so a new script with the same pattern must be listed. * fsdp2: refuse SLURM / MPI multi-task steps before any single-process run _launcher_env_problem() ran only when two or more processes were about to be launched. In a SLURM step with one visible GPU per task (or with --nproc-per-node 1, no GPU, or a single-process script) every task fell through to a plain single-process run, so SLURM_STEP_NUM_TASKS=2 without torchrun rank variables quietly started independent training runs that write the same output paths. Check the scheduler environment once the process is known not to be a worker, before the single-process branch and the GPU-count choice. Workers with LOCAL_RANK and WORLD_SIZE / LOCAL_WORLD_SIZE still run. * Run the DeepSeek OCR and OpenEnv 2048 scripts single process A sweep of every python_scripts base for plain-Python writes that all ranks make to one path found two more groups: - Deepseek_OCR_(3B), Deepseek_OCR_(3B)-Eval and Deepseek_OCR_2_(3B) save a dataset image to your_image.jpg and pass that path to model.infer. One process can open the JPEG while another is truncating it, and the model's loader then fails with AttributeError. - OpenEnv_gpt_oss_(20B)_Reinforcement_Learning_2048_Game and its _BF16 copy start a uvicorn OpenEnv server through launch_openenv on a random port. The RNG is seeded the same on every rank, so all ranks pick the same port; the later ones fail to bind, pass the health check against the first rank's server and play its single game. Run them and their AMD- / Kaggle- copies in one process. The mirror test now flags launch_openenv( and PIL saves to a fixed image path, and a new AST check flags any literal path written from Python (open w/a/x, .save, sf.write, to_json, copy, ...) that the same run names again, leaving out Unsloth's collective saves and rewrites of the same path, so a new script that writes a file and reads it back must be listed. * fsdp2: run an install step that also does something else install_decision() ignored every segment that was not an install, so a step such as "pip install x" followed by printf, git clone, wget, mkdir or python -c was skipped whole once x was installed, and its other commands never ran. Now a step is skipped only when the rest is read-only (apt's index refresh, `command -v`, an output filter like tail / grep, or ollama's own curl | sh); pip subcommands other than install / uninstall / list / show / freeze / check also keep it running. * Run Llama3.2_(1B)-RAFT single process Every process generates its own dataset through the OpenAI API and then writes it to raft_train.jsonl with Dataset.to_json. The exports can differ in length, so interleaved writes can leave bytes of a longer export after a shorter one and an invalid JSONL file. Run it (and its AMD- and Kaggle- copies) in one process, and teach the mirror test to flag to_json / to_csv to a fixed path. * fsdp2: multiprocess spawn children and node-local counts from other launchers datasets' Dataset.map(num_proc = N) starts its workers through the multiprocess package, whose spawn module was not patched, so a spawned child re-imported the script without get_ipython and died with NameError. Patch multiprocess.spawn the same way as multiprocessing.spawn when it is installed. The node-local process count fell back to the global WORLD_SIZE when LOCAL_WORLD_SIZE was missing, so under DeepSpeed's launcher (LOCAL_SIZE) on two nodes with one GPU each the first shell step waited for a local rank that does not exist. Read LOCAL_SIZE and the Open MPI / MPICH local counts first. * fsdp2: skip an install with extras only when the extras' dependencies are here The install check parsed `pkg[extra]` down to `pkg`, so `pip install "requests[socks]"` was skipped whenever requests was installed, even without PySocks. Read each requested extra's dependencies from the installed distribution's metadata and skip only when every one of them is installed at a matching version; an extra the distribution does not declare, or metadata that cannot be read, keeps the step running. * fsdp2: an activated environment in a shell step gets its own python and pip The pinned python / python3 / pip / pip3 / unsloth functions always ran the launcher's interpreter, also after a step activated another virtualenv or conda environment, so `source other/bin/activate; pip install ...` installed into the launcher's environment (Unsloth Studio's setup script activates its own venv this way). The functions now fall back to PATH once VIRTUAL_ENV or CONDA_PREFIX differs from the launcher's, in the step and in any bash it starts. * Run the TTS, Minesweeper, Wordle and Qwen3 tool calling scripts single process Under native FSDP2 model.generate runs inside native_fsdp2_unsharded, which all-gathers on every rank, so every rank has to make the same number of generate calls. A sweep of every python_scripts base for loops and retries whose generate count follows each rank's own output found four scripts that break that: - gpt_oss_(20B)_Reinforcement_Learning_GRPO_Minesweeper_Game_BF16: the eval callback and play_full_game sample a move per turn and stop when a rank's move does not parse or its game ends. GRPO seeds per device, so ranks stop after different numbers of calls. - Spark_TTS_(0_5B): samples again after a codec shape error, which can hit one rank only. - Openenv_wordle_grpo: play_wordle and the training rollouts stop when each rank's own Wordle game is done. - Qwen3_(4B)-Tool_Calling and Qwen3_(4B)-GRPO-Tool_Use: run_tools samples a reply and returns once a rank's reply has no tool call. Sesame_CSM_(1B)-TTS and Spark_TTS_(0_5B) also write each rank's own sampled speech to the same WAV files with sf.write, which can mix samples from several ranks. Run them and their AMD- / Kaggle- / HuggingFace Course- copies in one process. The mirror test gains two AST checks: one flags audio / image writes to a path the script spells out (literal, f-string or a name bound to one; in-memory buffers are left out), and one flags a generate, fast_generate, infer or generate_rollout_completions call, followed through the script's own helpers, inside a while loop, a loop with a break / continue / return, or a try whose handler generates again. A for loop over a fixed list with no early exit stays allowed. Each check has its own self-test. * Trim comments in the FSDP2 launcher, generator and tests --------- Co-authored-by: oobabooga <[email protected]> * LFM2.5 (1.2B) GRPO: escape the backslashes in the regex demo strings (unslothai#424) * Add Qwen3 (1.7B) classification notebook for many labels (unslothai#425) * Add Qwen3 (1.7B) classification notebook for many labels Fine-tunes Qwen3 (1.7B) with a sequence-classification head on Banking77 (77 intents) instead of trimming the LM head to single-token labels, so the same recipe scales to hundreds of classes and multi-token label names. Shows class_encode_column for string labels, tracks accuracy and macro F1, and prints top-k predictions. Closes unslothai#192 * Classification notebook: fix script export, label map and head check - Put the "### Unsloth" heading above data prep. The script export comments out everything between Installation and that heading, so the Python scripts and FSDP2 launchers failed with NameError: num_labels. - Custom CSV tip: encode the train split and cast the test split to its ClassLabel, so ids stay right when a class is missing from test. - Check the classification head is trainable after get_peft_model and unfreeze it if not (older Unsloth, e.g. 2026.9.6, left it frozen). - Save the labels to labels.json next to the adapters and add a reload cell that passes num_labels, id2label and label2id. * Classification notebook: upload labels.json with Hub adapter * Classification notebook: cap top-k at the number of classes, fix CSV test-label mapping * Qwen3 classification: compute macro F1 with numpy, drop the scikit-learn import pip install unsloth and the AMD install cell do not install scikit-learn, so the metrics cell raised ModuleNotFoundError outside Colab and Kaggle. The numpy version matches sklearn.metrics.f1_score(average='macro'). * Qwen3 classification: assert the head is trainable instead of patching it Current Unsloth already trains the score head through PEFT's SEQ_CLS modules_to_save (17,590,272 trainable on a T4 run, head included), so the unfreeze branch never ran. Fail loudly instead of silently re-casting it. * Qwen3 classification: run classify under autocast so the reload cell works After trainer.train(), accelerate leaves model.forward wrapped in fp16 autocast, so classify only worked in the training session. Reloading the saved adapter upcasts the score head to float32 with no wrapper, and on a T4 the reload cell raised 'expected mat1 and mat2 to have the same dtype ... Half != float'. * Qwen3 classification: drop an inaccurate comment on the head dtype * Run CI on the converged head --------- Co-authored-by: Daniel Han <[email protected]> * fsdp2_scripts: run Unsloth_Studio single process (unslothai#422) * fsdp2_scripts: run Unsloth_Studio single process The Studio launcher started the Studio server from Python on every rank. List it in FSDP2_SINGLE_PROCESS like the other fixed-port servers, regenerate, and make the multi-rank safety scan catch the colab start() call. * Tighten Studio single-process test comment * Update OpenEnv links to openenv/OpenEnv (unslothai#415) OpenEnv moved from meta-pytorch/OpenEnv and huggingface/OpenEnv to the openenv GitHub organization. The old URLs redirect for now, but only while nothing is created under the old names. Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Daniel Han <[email protected]> * Add Gemma 4 (E4B) DPO notebook (unslothai#428) * Add Gemma 4 (E4B) DPO notebook Text-only DPO on unsloth/gemma-4-E4B-it (4-bit LoRA, ref_model=None, beta=0.1) with UltraFeedback pairs in conversational format, so DPOTrainer applies the Gemma-4 chat template and adds no extra EOS. Gemma 4 DPO notebooks install transformers 5.10.1 instead of 5.5.0. On 5.5.0-5.5.1, unsloth_zoo carries E2B/E4B shared K/V in a module-scoped carrier that DPOTrainer's no-grad reference forward deletes between the policy forward and its backward, so the first backward raises torch.utils.checkpoint.CheckpointError. tests/test_gemma4_dpo_notebook.py guards the pin. Fixes unslothai#254. Co-Authored-By: Claude Opus 5.5 <[email protected]> * Trim Gemma 4 DPO pin comments --------- Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: Daniel Han <[email protected]> * Add Intel generation logic for Intel notebooks (unslothai#408) * Add Intel generation logic for Intel notebooks * Add 2 generated Intel notebooks * Update README with Intel section * Intel notebooks: keep later source pins, match the default run's fixed point, list all four in README * Trim comments in the Intel generator and tests * Intel install: pin the +xpu torch and torchvision builds so an installed CPU or CUDA build is replaced * Intel: pin vllm +xpu and keep the PYTORCH_ALLOC_CONF override live in the script mirrors * Intel install: point uv at the kernel's interpreter via UV_PYTHON * Trim Intel generator comments --------- Co-authored-by: Daniel Han <[email protected]> * Knowledge distillation: all four configs pass on a Kaggle 2x T4 Re-measured every config on a Kaggle 2x T4, 30 steps at seq 1024. gemma-4 fits with the current release (12.5 + 8.2 GB); muse-glimmer and qwen3.8 self-distil across both cards once the wrapper exposes the student's output head, so the chunked loss runs instead of TRL's dense one, and with unslothai/unsloth#17876. The qwen3.8 BFloat16 != Half note no longer reproduces and is dropped. --------- Co-authored-by: Bruno De Oliveira <[email protected]> Co-authored-by: Enes Bol <[email protected]> Co-authored-by: enesbol <[email protected]> Co-authored-by: Rushi Chaudhari <[email protected]> Co-authored-by: Aditya Tiwari <[email protected]> Co-authored-by: vivienfanghuagood <[email protected]> Co-authored-by: Siddhant Verma <[email protected]> Co-authored-by: Aniket Maurya <[email protected]> Co-authored-by: Abubakar Abid <[email protected]> Co-authored-by: Gowtham Sai G <[email protected]> Co-authored-by: gowtham-sai-yadav <[email protected]> Co-authored-by: Edd <[email protected]> Co-authored-by: Saad Ahmed Siddiqui <[email protected]> Co-authored-by: Saad1926Q <[email protected]> Co-authored-by: Antigravity Reviewer <[email protected]> Co-authored-by: Kadir Nar <[email protected]> Co-authored-by: oobabooga <[email protected]> Co-authored-by: Noah Sabbavarapu <[email protected]> Co-authored-by: Arihan Varanasi <[email protected]> Co-authored-by: Sergio Paniego Blanco <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]> Co-authored-by: claire-fang <[email protected]> Co-authored-by: JoshuaL3000 <[email protected]>
Summary
remove_unwanted_sectioncomments out the Installation section of eachpython_scripts/mirror, but only when a later# Unslothheading closes it. 38 scripts (18 base notebooks plus their AMD, Kaggle and HuggingFace Course copies) have no such heading, so their%%captureinstall cell stayed live asget_ipython().run_cell_magic(...)andpython python_scripts/X.pystopped at once withNameError: name 'get_ipython' is not defined.Affected base notebooks: Whisper, Falcon_H1-Alpaca, FunctionGemma_(270M)-LMStudio, Muse_Glimmer_(30B)-GRPO, NeMo-Gym-Multi-Environment, NeMo-Gym-Sudoku, OpenEnv 2048 (and BF16), Openenv_wordle_grpo, Qwen3_(0.6B)-Knowledge_Distillation, Qwen3_5_(4B)Vision_GRPO, Qwen3.8(27B)-GRPO (Kaggle), Meta_Synthetic_Data_Llama3_2_(3B) (Kaggle), Synthetic_Data_Hackathon, and the four gpt_oss_(20B) RL notebooks.
Change
When no
# Unslothheading follows the Installation heading, the section now ends at whichever comes first:An install cell is one whose every top-level statement is a
get_ipython()call (%%capture,%%bash,!pip). Two exceptions keep code live:%%capturecell that also does setup the script needs (%cd,os.chdir,sys.path, deleting or writing files, or binding a name later code reads) stays live and ends the section. Commenting it would drop the setup silently; left live it fails loudly. This applies to the OpenEnv clone cells, which%cdinto the clone, extendsys.pathand bindworking_directory.get_ipython().system("pip install ...")lines are commented.UNSLOTH_VLLM_STANDBYlines are still lifted out of the commented cell, as on the existing path.The start heading also matches
Install Unsloth and other dependencies, the FunctionGemma LM Studio title, which the old pattern missed.Every notebook that already has the
# Unslothheading (428 of 467) takes the old code path unchanged, and their scripts are byte-identical.Results
get_ipythoncall in the installation sectionThe 6 remaining are the OpenEnv clone cells (2048, 2048 BF16, wordle, and their AMD copies), listed with reasons in the new test's allowlist.
Running each of the 38 with plain
python(CPU, heavy imports stubbed): all 38 stop atget_ipythonon main; 32 now reachimport unsloth, and the 6 OpenEnv mirrors stop at their clone +%cdsetup cell one cell later, as intended. The 428 notebooks that already have the# Unslothheading produce byte-identical mirrors, and the set of liveos.environassignments (includingUNSLOTH_VLLM_STANDBY) is unchanged in all 467.Tests
tests/test_python_scripts_no_live_install_magic.py: no mirror may keep a live installation-sectionget_ipythoncall unless it is on a commented allowlist; the allowlist is checked for stale entries; unit cases cover each terminator, the setup cell, the mixed cell, the standby lift, and pin the old path's output. Fails on all 38 scripts at the current main. Added as a step innotebooks-tests-ci.yml.test_python_scripts_regen_parity.py,test_every_test_runs_in_ci.py,test_python_scripts_keep_standby_env.py,test_amd_install_heading_adjacency.pyand every other test that readspython_scripts/or the generator pass.python_scripts/was regenerated withconvert_folderonly; the 38 changed scripts all parse.Not covered
Some scripts still have
!cells after the installation section (for example!wgetin Whisper,!pip install langidin the DeepSeek R1 GRPO notebook,%envin the CPT notebooks). Those sit outside the installation section and are left for a follow-up. OuteTTS keeps the old behaviour, so its clone andos.removepatches stay commented out as before.