Repository navigation
Unsloth Studio: tokenize in process when the trainer is too big in host RAM to fork - #17701
Conversation
…o fork A forked child shares the trainer's pages copy-on-write, so every page the parent rewrites while the child lives is held twice. With Block Swap on a 180B MoE the 122-133 GiB trainer was OOM-killed before step 1, once by the online tokenization DataLoader workers and once by the dataset.map pool. Both fork sites now consult host_memory_fork_veto: Block Swap requested, or the trainer's RSS above the host RAM still available. Online tokenization turns off (UNSLOTH_STUDIO_ONLINE_TOKENIZATION=1 still forces it) and dataset_num_proc asks for 1 (UNSLOTH_DATASET_NUM_PROC still wins).
|
@codex review |
Codex Review Summary: ✅ CompletedThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: e3e8fd3bec
ℹ️ 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".
| """(this process's RSS, host RAM still available) in bytes, or None when unreadable.""" | ||
| try: | ||
| import psutil | ||
| return int(psutil.Process().memory_info().rss), int(psutil.virtual_memory().available) |
There was a problem hiding this comment.
Use cgroup headroom in the fork veto
In a cgroup-limited Studio/container run, psutil.virtual_memory().available reports host availability rather than the memory remaining under the process's memory.max. This repository's utils/host_memory.py::usable_host_ram_mib() accounts for both. When trainer RSS is below host availability but above cgroup headroom, this snapshot permits the DataLoader or Dataset.map fork and can still OOM-kill the training job; include cgroup headroom in the veto.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Addressed on the branch by 9c5e82f: the veto's available memory is now min(psutil available, host_memory.cgroup_headroom_mib()) (online_tokenization.py:218-225), and 57b883d29e takes that reading once per run so both fork sites agree. Inside a real 3 GiB container limit it read 2.98 GiB available instead of the host figure and vetoed the fork once the trainer held 2.2 GiB.
…uce order noise (#17896) ## Summary `tests/test_tp_eval_gloo.py::test_trainer_evaluates_a_tensor_parallel_model_like_one_process[2-2]` fails intermittently in the `Repo tests (CPU, gloo)` shard on unrelated PRs (seen on #17701 and #17840): ``` Mismatched elements: 1 / 2016000 (0.0%) Greatest absolute difference: 1.07e-05 at index ... (up to 1e-05 allowed) ``` The predictions are logits after three training steps. Under tensor parallelism the row-parallel all-reduce sums partial products in a different order than the single-process reference, so an element close to zero can land just past `atol = 1e-5` depending on the CPU and thread layout. The test was added in #15722 and the check itself is right, the absolute tolerance is just at the edge of float32 reduction noise. ## Change - Predictions `atol` goes from `1e-5` to `5e-5` (`rtol` unchanged at `1e-4`), with a comment saying why. - The training and eval losses are still compared at `rel = 1e-5`, and `label_ids` still has to match exactly, so a real sharding or gather bug (which moves logits and losses by orders of magnitude more) still fails the test. ## Testing - `pytest tests/test_tp_eval_gloo.py` on CPU (torch 2.10, transformers 5.17): 3 passed.
psutil reports the whole machine's available RAM, so in a container with a memory limit the veto let a fork through that the cgroup then OOM-killed. host_memory_snapshot now takes min(MemAvailable, cgroup headroom) via utils.host_memory, the same reading the rest of Unsloth Studio budgets with.
|
Pushed @codex review |
|
Codex Review: Didn't find any major issues. Keep it up! 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". |
…ry reading per run, cover the batched packing pool offload_layers = "auto" attaches no swapper when the model fits the card, so it held nothing in host RAM but still switched tokenizer workers and online tokenization off. The dataset_num_proc site and the online tokenization gate now share one host memory reading, and Multi-LoRA packing, which forks the same loaded base model, asks the same veto. [skip ci]
|
@codex review |
|
Codex Review: Didn't find any major issues. Already looking forward to the next diff. 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". |
#18324) ## Multi-LoRA packing: load the num_proc policy without importing unsloth `studio/backend/tests/test_dataset_map_num_proc.py::test_the_batched_packing_pool_asks_the_same_veto` fails in `(Python 3.13, a-f)` on every PR since #17701, for example #18015, #18108, #18142 and #18303: ``` core/training/multi_lora_trainer.py:686: in _pack_num_proc from unsloth_zoo.dataset_num_proc import get_dataset_num_proc E ModuleNotFoundError: No module named 'unsloth_zoo' core/training/multi_lora_trainer.py:688: in _pack_num_proc from unsloth.dataset_num_proc import get_dataset_num_proc unsloth/_gpu_init.py:241: in <module> E ImportError: Unsloth: Please install unsloth_zoo via `pip install unsloth_zoo` then retry! ``` ### Cause `_pack_num_proc`, the multi-LoRA packing pool's worker count from #15733, looks up the shared `dataset_num_proc` policy in two steps: 1. it imports `unsloth_zoo`; 2. if that fails, it falls back to `from unsloth.dataset_num_proc import ...`. That fallback runs the whole `unsloth` package `__init__`, which needs `unsloth_zoo` anyway and patches torch on the way. The rest of the backend already avoids this. `utils.hardware.hardware._shared_policy()` tries `unsloth_zoo` first and otherwise loads the stdlib-only `dataset_num_proc.py` straight off disk, precisely so that no caller runs `import unsloth`. #17701 added the first test that reaches `_pack_num_proc`, and the backend shard runs without `unsloth_zoo`, so the fallback fails there. ### Fix `_pack_num_proc` now gets the policy from `_shared_policy()`, the same loader the single-job tokenize pool uses. - **With a policy**, which is every real install: the call is unchanged, `get_dataset_num_proc(count)` on the same module. - **With no policy at all:** it keeps that function's contract, so a serial count of 1 still means `None`. ### Verification - Faithful repro of the CI state: `core.training.trainer` already imported, then `unsloth_zoo` made unimportable, then `_pack_num_proc` called with a tight host-memory snapshot. - `main`: `ModuleNotFoundError: No module named 'unsloth_zoo'`. - This PR: returns `None`, as the test expects. - With `unsloth_zoo` installed: `tests/test_dataset_map_num_proc.py` and the multi-LoRA tests pass (88 passed). - ruff is clean.
…th_zoo is absent (#18338) ## Summary A test fix for a check that fails on every PR against current main. ### 1. Trainer-backed num_proc veto tests without unsloth_zoo These tests, added in #17701, import `core.training.trainer`, which imports unsloth and so needs `unsloth_zoo`: - `test_the_batched_packing_pool_asks_the_same_veto` (through `_pack_num_proc`'s lazy import of the trainer); - the five `test_block_swap_counts_for_the_veto_only_when_it_offloads` cases. Some CPU CI buckets (Repo tests, Python 3.13 a-f) do not install the zoo, so these fail there with `ImportError: Unsloth: Please install unsloth_zoo`. Both tests now call a small `_trainer_or_skip()` helper. It skips the same way `test_dataset_preview_role_aliases.py` already does when the zoo cannot be imported. `studio/backend/tests/test_dataset_map_num_proc.py`: - with `unsloth_zoo`: 40 passed, nothing skipped; - without it: 32 passed, 8 skipped (6 failed before). The Unreal level tools encoding fix and the model picker contract update this PR also carried landed separately on main (#18344, #18372), so this branch now takes main's versions of those files.
With Block Swap on Qwen3.8-Flash-Next (180B MoE), every Unsloth Studio run with default settings was OOM-killed before step 1. Tokenizing the dataset forks the loaded trainer, through either the
dataset.map(num_proc=N)pool or the online-tokenization DataLoader workers. A forked child shares the parent's pages copy-on-write, so every page the parent rewrites while the child lives is held twice. On a Colab G4 (177 GiB host RAM) the trainer held about 133 GiB, host RAM went from 138 to 165 GiB right after the fork, and the run was killed.Both fork sites now ask
host_memory_fork_veto, which vetoes the fork when Block Swap is on, or when the trainer's RSS is above the host RAM still available:dataset_num_procasks for 1 (in-process).UNSLOTH_DATASET_NUM_PROCstill wins.UNSLOTH_STUDIO_ONLINE_TOKENIZATION=1still forces it on.The log says why:
Tokenizing in process: Block Swap keeps offloaded layers in host RAM, which a fork would duplicate.Evidence: with this branch and no env overrides, Flash-Next trains under Block Swap on one G4 at Count 32, Count 36, Count 36 batch 2 and Count 36 at ctx 4096. Runs and recordings: LeoBorcherding/unsloth-zoo#44
Host RAM over the run, main vs this PR (Count 32, same settings):
Tested stacked with the Block Swap work
The Flash-Next runs ran this branch on top of the rest of the Block Swap stack. Core was unslothai/unsloth main
211f0ee22, which already has #11832, #12996, #12998, #15159, #15632 and #15633, plus this PR. The zoo was main plus unslothai/unsloth-zoo#1619, #2269 and #2499, all merged since. With that stack, Qwen3.8-Flash-Next-FP8 (180B MoE) LoRA-trains on one RTX PRO 6000 96 GB in Unsloth Studio, with default settings and no env overrides:Without this PR, the same stack is OOM-killed before step 1. Full data, charts and recordings: LeoBorcherding/unsloth-zoo#44
Outside Block Swap: I ran the same LoRA on a Colab T4 (12.7 GiB host RAM, 2 CPUs) with Block Swap off, main and this branch side by side. Llama-3.2-1B and Llama-3.1-8B (4-bit) trained on both, with the trainer peaking at the same RSS: 3.0 vs 3.1 GiB and 6.0 vs 5.9 GiB. That's well under the free RAM, so the veto stayed off and behavior matched main. Qwen3-14B ran on main only, peaking at 6.3 GiB; the VM for this branch was reclaimed before its run.
Tests:
test_dataset_map_num_proc.py: the newtest_a_trainer_too_big_to_fork_tokenizes_in_processfails on main and passes here (34/34).test_online_tokenization.pyandtest_online_tokenization_wiring.py: new cases cover the Block Swap veto, an unreadable memory read (no veto), and the env flag overriding the gate.Hardware: Linux, RTX PRO 6000 96 GB (Colab G4). Windows and macOS already tokenize eagerly, because their workers spawn instead of forking.
Follow-up commit on this branch
57b883d29eFork veto: count Block Swap Auto only when it offloads, one host memory reading per run, cover the batched packing pool.offload_layers = "auto"attaches no swapper when the model fits the card (unsloth/models/_utils.py:_auto_block_swap_indicesreturns nothing, so no_unsloth_block_swap), so nothing sits in host RAM. As first submitted, any"auto"run lost itsdataset.mapworkers and online tokenization anyway. The veto now reads_block_swap_engaged(trainer): a fixed count stands as asked,"auto"counts only once a swapper is attached.dataset_num_procsite and the online tokenization gate each took their own RSS / available reading, so near the line they could disagree (in-process map, then forked persistent DataLoader workers). The gate now reuses the reading thedataset_num_procsite took._pack_num_procinmulti_lora_trainer.pyforks a packing pool off the same loaded base model (Block Swap is passed to itsload_modeltoo). It now goes in process under the same veto.Each new test fails with its fix reverted (negative controls below).
Evidence
Copy-on-write repro (CPU, no PR code). A process holding 1.8 GiB of touched host memory runs
Dataset.mapover 4,000 rows inside a 3 GiB cgroup (systemd-run --user --scope -p MemoryMax=3G -p MemorySwapMax=0). Unique memory = summed PSS of parent and children, sampled every 50 ms.num_proc=None(in process)num_proc=2(forked pool)num_proc=2(forked pool)memory.eventsoom_kill 1), orphaned workers hangWithout a cgroup (3 GiB buffer, 1.6 TiB host) the same writing arm grew by +1.27 GiB within 3.5 s, idle +0.05 GiB. The hazard is real, and its size is what the parent rewrites while children live: persistent online-tokenization workers live through all of training, the
dataset.mappool only through tokenization.Real cgroup reading.
host_memory_snapshot()in that 3 GiB scope reads 2.98 GiB available (1597 GiB host-wide outside it); with 2.2 GiB held it vetoes:trainer holds 2.2 GiB of host RAM with 0.8 GiB available, more than a fork can safely duplicate. Cost: 245 to 355 us per call, called once per run.Routing cells (one subprocess per platform;
dataset_num_procconfig value and the online tokenization decision; 4 Block Swap states x 4 memory states xUNSLOTH_DATASET_NUM_PROCunset / 3 = 96 cells):On Linux every moved cell with the follow-up is a veto cell: a swapper attached (fixed count or Auto that offloaded) or RSS above available. The 3 num_proc / 6 online cells only the first version moved are Auto with nothing offloaded.
UNSLOTH_DATASET_NUM_PROCwins in every cell.Tokenized dataset and training parity (Unsloth
SFTTrainer, tiny Llama, 4,000 rows, fp16 to mimic T4 numerics, 8 steps, correctness on B200):bb48fd178fb0f72cbb48fd178fb0f72cc540da4422293d57c540da4422293d57Byte-identical rows and bit-identical losses and grad norms in both modes.
Tests, main vs branch (
test_dataset_map_num_proc.py,test_online_tokenization.py,test_online_tokenization_wiring.py):num_proc+ wiring files)test_multi_lora_trainer.py)[auto-None-0],..._offloaded_nothing_still_goes_online)test_the_gate_reuses_the_reading...)test_the_batched_packing_pool_asks_the_same_veto)Cross-platform. Staging CI on the first submitted head: ubuntu-latest green. macos-15 (70 of 139 failed) and windows-latest red. These three test files pin
sys.platform = "linux"but not the multiprocessing start method, so on spawn hosts the start-method gate answers before the gates under test. Emulating spawn on Linux, main's own tests already fail 69 times. The new tests fail the same way (12 more), and none of them are production paths. In production on macOS and Windows,dataset_map_num_procreturns None and online tokenization is refused by its platform gate before the memory gate runs, so behaviour there is unchanged (64 of 64 cells identical).Not proven here: the 180B Flash-Next OOM itself (no reproduction on this host; the contributor's G4 runs are the evidence); speed numbers for in-process vs pooled tokenization (only reached on veto cells, never for runs that fit); real macOS / Windows base-arm failure IDs for the three test files.