Skip to content

Block Swap: get_peft_model crashes on MoE models with offload_layers (evicted expert weights read as empty) - #15159

Merged
danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/issue-bsmoe
Nov 3, 2026
Merged

danielhanchen merged 16 commits into
unslothai:mainfrom
LeoBorcherding:night-shift-tester/issue-bsmoe

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 24, 2026 •

Copy link
Copy Markdown
Collaborator

Loading fused-expert MoE layers with offload_layers replaces evicted weights with empty tensors before PEFT reads their dimensions. This change exposes each evicted parameter's original shape while adapters are created or reloaded, then restores the offloaded state on success or failure.

Both fresh-adapter entry points and both saved-adapter loader paths use the context. Core uses BlockSwap.shaped() when available and retains a fallback for older Zoo versions. Companion: unslothai/unsloth-zoo#2070.

Weight-reading modes receive explicit protection:

  • DoRA and KaSA reject evicted target weights before initialization; unrelated evicted layers do not prevent resident-only targets.
  • Fresh modules_to_save copies reject overlapping evicted weights. Saved-adapter reloads restore those copies from the checkpoint, covered by a real PEFT round-trip test.
  • Other base-weight-dependent initializers retain their existing failure behavior rather than reading placeholder zeros.

Validation uses a locally constructed random tiny Qwen3-MoE and tokenizer, without downloading checkpoint weights. On a Kaggle T4 with torch 2.14.1, Transformers 5.5.0 and PEFT 0.21.2, main fails with the one-dimensional ParamWrapper error when four layers are swapped. Core alone with baseline Zoo, both PRs together, and the non-swapped control complete three optimizer steps with 86,016 trainable parameters and identical losses [4.89938736, 4.87631130, 4.82817984] and gradient norms [0.34580228, 0.32452196, 0.29609376]. Expert adapters update, host weights remain unchanged, and generated tokens match after both plain PEFT and Unsloth reloads. Unsloth promotes this model to float32 on the T4.

Removing the Core context calls or replacing the Zoo context body with a no-op restores the original error. The CPU suites pass 75 tests; PEFT 0.18.0, 0.19.0 and 0.20.0 each pass 11 helper tests with the unavailable KaSA test skipped, and PEFT 0.21.2 passes all 12. Transformers 4.57.6 with PEFT 0.18.0 and Transformers 5.22.1 with PEFT 0.21.2 also pass their helper/load corners. Targeted Linux, macOS and Windows checks passed, and the final regression smoke, SFT and inference comparisons report no regression on d073807.

The existing main swap-after-PEFT control and the new load-time-swap path each capture 28 graphs and 529 calls with zero graph breaks. Non-swapped base/head each capture 26 graphs. No performance improvement is claimed.

Broader staging has four pre-existing test-harness failures: three no-torch installer progress cases and one PowerShell call-policy check. Each fails identically on staging main fa2a5e7 and the PR integration f9e1356, with the relevant source and test files unchanged. The failure logs are https://github.com/Etherll/unsloth/actions/runs/41597600133/job/125788500767 and https://github.com/Etherll/unsloth/actions/runs/41597600133/job/125788500751.

This is a setup and reload fix, with no forward, kernel, GPU detection, prompt or UI changes. Broader offloading support, including Studio batched expert adapters, text-diffusion training and Qwen3.8 placement integration, is outside this patch. Related feature request: #16512.

@LeoBorcherding
LeoBorcherding marked this pull request as draft October 24, 2026 20:17
@LeoBorcherding LeoBorcherding changed the title Block Swap: get_peft_model crashes on every MoE model with offload_layers (evicted expert weights read as empty) Block Swap: get_peft_model crashes on MoE models with offload_layers (evicted expert weights read as empty) Oct 24, 2026
danielhanchen added a commit that referenced this pull request Oct 24, 2026
…15165)

## Summary

`tests/test_studio_root_resilience.py` fails in the `Repo tests (CPU,
rest)` shard (#15159, #15161) but passes on its own:

```
studio/backend/loggers/handlers.py:22: in <module>
    from utils.native_path_leases import redact_native_paths
E   ModuleNotFoundError: No module named 'utils.native_path_leases'
```

`storage_roots.py` imports the backend's `loggers` and `utils` by bare
name. A dozen test modules in `tests/` (the `test_grpo_*` family,
`test_nvfp4_loader.py` and others) put `tests/` at `sys.path[0]` when
they are imported. After that, any bare `import utils` in the worker
resolves to `tests/utils`. Logging `sys.modules["utils"]` after every
test of a local run of the shard, on the same command line as CI (`-n 4
--dist loadgroup`), showed it switching to `tests/utils/__init__.py`
partway through on two workers. Every later `from
utils.native_path_leases import ...` then fails. The local run
reproduced all three CI failures. The product code is fine. The test
inherited whatever `utils` the worker had cached.

## Change

- `_load()` now takes `monkeypatch`. Before loading `storage_roots.py`
it puts `studio/backend` first on `sys.path` and drops any cached
`utils*` / `loggers*` module that does not live under `studio/backend`.
`monkeypatch` puts everything back after the test, so the rest of the
worker sees what it had before.
- `test_a_foreign_utils_left_by_another_test_does_not_answer`: registers
a stray `utils` package the way the shard does and checks that
`storage_roots.py` still loads against the backend's own `utils`.

## Verification

- With this change: `8 passed` alone, and `17 passed` with
`test_cli_export_unpacking.py` run between two copies of the file.
- Sabotage: skipping the new isolation step makes the new test fail with
CI's exact error (`ModuleNotFoundError: No module named
'utils.native_path_leases'`).
- The whole rest shard, run locally the way CI runs it, reproduced the
three failures before the change.
danielhanchen added a commit that referenced this pull request Oct 24, 2026
#15162)

## Summary

`tests/test_return_logits_survives_for_training.py` fails on main (8 of
9 tests) since #15137:

```
unsloth/models/vision.py:5506: in for_inference
    _refuse_tensor_parallel_for_inference(model)
E   TypeError: 'NoneType' object is not callable
```

The test pulls `FastBaseModel.for_inference` / `for_training` out of
`vision.py` with `ast` and runs them in a namespace where unknown names
resolve to `None`. It only lifts a hand-kept list of `_utils.py`
helpers. #15137 added the tensor parallel refusal at the top of
`for_inference` (`_refuse_tensor_parallel_for_inference`, which calls
`_is_unsloth_tensor_parallel`). Neither helper is on that list, so the
call hits `None`. The product code is correct: the refusal is intended,
and the real import in `vision.py` resolves fine. This shows up on any
PR whose `Repo tests (CPU, rest)` shard runs on current main, for
example #15159.

## Change

- Keep the explicit list. Then follow the lifted functions into any
other top-level `_utils.py` function they name, transitively. Today that
adds exactly the two tensor parallel helpers. The next helper either
method gains gets lifted automatically instead of turning into the same
`NoneType` error.
- `test_lifted_for_inference_runs_its_real_helpers`: a model carrying
`_unsloth_tp` must make the lifted `for_inference` raise the real tensor
parallel `RuntimeError`. This proves the harness runs the real guard,
not a stand-in.

## Verification

- On main: `8 failed, 1 passed`. With this change: `10 passed`.
- Sabotage 1: turning off the helper walk makes 9 tests fail again,
including the new one.
- Sabotage 2: reverting the #3071 fix in `for_training`
(`os.environ.setdefault(...)` back to a forced `"0"`) fails 3 tests. The
file still guards what it was written for.
danielhanchen added a commit that referenced this pull request Oct 25, 2026
…d copy (#15264)

`tests/test_tp_native_gloo.py::test_tp2_x_fsdp2_dp2_matches_one_process[llama-True-lora_kwargs4]`
fails now and then in `Repo tests (CPU, rest)` on unrelated PRs (#15159,
#15174, #15217, #15218, #15222, #15225) with only `AssertionError:
base_model.model.lm_head.weight`. Gradients, losses and norms all match
in those runs. Only the saved `lm_head` copy differs.

## Cause

The test, not the product. That case trains a full `lm_head` copy
(`modules_to_save`, 512000 entries) with AdamW at lr 1e-2 and the
default eps of 1e-8. At g = 0, Adam's `g / (sqrt(v) + eps)` has slope lr
/ eps = 1e6. Measured on main on this host:

| | value |
| --- | --- |
| median step-0 lm_head grad | 5.7e-6 |
| entries with step-0 grad below 1e-8 | 313 |
| step-0 grad of the 10 worst saved-weight entries | 4e-11 to 7e-9 |
| worst saved-weight diff / tolerance | 0.46 |

So reduction-order noise of about 1e-12 on a near-zero gradient becomes
about 5e-6 of weight. That is already half the `atol = 1e-5` here. A
runner whose CPU kernels sum in a different order goes over it.

## Fix

- Both arms use `AdamW(eps = 1e-6)`. The optimizer is still identical on
both sides, and 1e-6 is small next to the typical gradient, so the head
still trains. The worst entry drops to 0.0075 of the tolerance (60x
headroom).
- The saved-weight assert now keeps `assert_close`'s mismatch detail. It
used to print only the key, which is why the CI logs never showed how
far off the weight was.

## Verification

- `tests/test_tp_native_gloo.py`: 38 passed.
- Sabotage on the last step, after the norms are taken, so only the
saved weight can catch it:
- TP arm skips the lm_head update: fails, 511627 / 512000 mismatched,
max abs diff 1.0e-2.
- Each dp half's lm_head gradient scaled by +/-15% (a stand-in for a
missing dp reduction): fails, 493693 / 512000 mismatched, max abs diff
8.1e-4.
  - No sabotage: passes.
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

CI is clean at ea233c52 apart from four failures that come from main, not this diff:

  • The three Core zoo jobs fail test_quantized_decode_keeps_each_rows_padding_mask[batch|engine] (zoo's MLX shim has no BatchQuantizedKVCache). The same two tests fail on unrelated PRs from the same hour, e.g. runs 41544307510 and 41543929887.
  • Repo tests (CPU, studio) fails test_no_raw_pixel_text_utilities on the text-[10px] at studio/frontend/src/features/settings/components/composer-settings.tsx:149, which is on main. This PR doesn't touch the frontend.

@danielhanchen danielhanchen self-assigned this Nov 3, 2026
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 3, 2026
@danielhanchen

danielhanchen commented Nov 3, 2026 •

Copy link
Copy Markdown
Member

Review record for #15159, carried over from the mirror it was reviewed on: danielhanchen/unsloth-staging-review#712.

Findings are quoted as posted and attributed to the account that posted them. The reactions shown are the triage recorded on the mirror; none were re-applied here. Commits are named as the mirror's, with this PR's equivalent where one was found.

Round 1: reviewed mirror cf1a01021 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on unsloth/models/_utils.py (on the mirror)

@@ -10532,6 +10532,38 @@ def planned_prefetch_depth(device_map_planner_kwargs):
     return depth if depth == "auto" else int(depth)
 
 
+def block_swap_shaped(model, init_lora_weights = True):
+    """PEFT wraps MoE expert weights by their shape, which reads as empty on a layer offload_layers evicted."""
+    swapper = getattr(model, "_unsloth_block_swap", None)
+    # PiSSA, OLoRA, LoftQ, CorDA, MiCA... read the weights: a placeholder would silently init them from zeros.
+    # EVA only zeroes lora_B here; its activation pass runs after get_peft_model, through the swap.
+    if swapper is None or init_lora_weights not in (True, False, "gaussian", "eva"):
+        return contextlib.nullcontext()
+    shaped = getattr(swapper, "shaped", None)
+    return shaped() if shaped is not None else _block_swap_shaped_fallback(swapper)

P1 Badge Exclude DoRA initialization from zero-weight placeholders

When a model loaded with offload_layers is passed to get_peft_model(..., use_dora=True), the default init_lora_weights=True passes this guard and exposes zero placeholders for every evicted layer, including dense Linear targets. PEFT's DoraLinearVariant.init calls DoraLinearLayer.update_layer, which reads the base weights to initialize the trainable magnitude vector. With the default zero-initialized LoRA B, this initializes the magnitude to zero rather than the real weight norm, so those projections produce zero output once the actual base weights are fetched. Restoring the empty tensors on context exit does not repair the magnitude vector. Pass the DoRA configuration into this guard and reject this combination or initialize its magnitudes using the real offloaded weights.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Reproduced zero DoRA magnitudes from the evicted-weight placeholders. Fixed in 454a2d277: reject DoRA setup only when blocks are evicted, and keep ordinary and resident-weight DoRA initialization unchanged.

Round 2: reviewed mirror db3253421 (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] on unsloth/models/_utils.py (on the mirror)

@@ -10532,6 +10532,47 @@ def planned_prefetch_depth(device_map_planner_kwargs):
     return depth if depth == "auto" else int(depth)
 
 
+def block_swap_shaped(
+    model,
+    init_lora_weights = True,
+    use_dora = False,
+):
+    """PEFT wraps MoE expert weights by their shape, which reads as empty on a layer offload_layers evicted."""
+    swapper = getattr(model, "_unsloth_block_swap", None)
+    if use_dora and any(not block.resident for block in getattr(swapper, "blocks", ())):
+        raise ValueError(
+            "Unsloth: DoRA needs the real base weights to initialize its magnitudes, "
+            "so it cannot be initialized after offload_layers evicted them. "
+            "Load without offload_layers or disable use_dora."
+        )
+    # PiSSA, OLoRA, LoftQ, CorDA, MiCA... read the weights: a placeholder would silently init them from zeros.
+    # EVA only zeroes lora_B here; its activation pass runs after get_peft_model, through the swap.
+    if swapper is None or init_lora_weights not in (True, False, "gaussian", "eva"):
+        return contextlib.nullcontext()
+    shaped = getattr(swapper, "shaped", None)
+    return shaped() if shaped is not None else _block_swap_shaped_fallback(swapper)
+
+
+@contextlib.contextmanager
+def _block_swap_shaped_fallback(swapper):
+    held = []
+    try:
+        try:
+            for b in swapper.blocks:
+                if not b.resident:
+                    for p, e, sig in zip(b.params, b.empties, b.sig):
+                        held.append((b, p, e))
+                        p.data = e.new_zeros(()).expand(sig[0])

P1 Badge Protect modules_to_save from zero-weight placeholders

When a model loaded with offload_layers uses modules_to_save for an evicted module (for example, input_layernorm, explicitly supported by FastLlamaModel.get_peft_model), this replaces its weights with zeros while PEFT constructs the trainable copy. PEFT's ModulesToSaveWrapper.update deep-copies the original module, so the trainable normalization weights become zero instead of preserving the pretrained values. Restoring p.data on context exit only repairs the original parameters tracked by the swapper, not those copies, silently corrupting the model's outputs and training initialization. Pass the module-save configuration into this guard and either initialize those copies from the real weights or reject overlapping evicted modules before exposing placeholders.

Useful? React with 👍 / 👎.

Accepted on the mirror

Reply from danielhanchen:

Reproduced a zeroed trainable copy with modules_to_save on an evicted module. Fixed in 0cf573802: reject only saved modules that contain evicted parameters, with a regression and a resident-module control.

Round 3: reviewed mirror 6ce28900b (no equivalent commit found on this PR)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Breezy!

Reviewed commit: 6ce28900b2

No triage reaction was recorded on the mirror

Round 4: reviewed mirror 9cd186c2a9 (this PR's c2bf82ca4)

chatgpt-codex-connector[bot] (on the mirror)

Codex Review: Didn't find any major issues. Hooray!

Reviewed commit: 9cd186c2a9

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 9cd186c2a9 (this PR's c2bf82ca4).

This is the review as it stood at that commit. Anything pushed to this PR afterwards was not part of it.

danielhanchen added a commit that referenced this pull request Nov 3, 2026
## Summary

Since #16157 (`95aae40bb4`), `Repo tests (CPU, studio)` fails on
unrelated PRs. It reproduces on current main, and on staging CI it hit
#15159 at 07:09Z, after the other studio guard fixes landed:

```
tests/studio/test_pwsh_calls_use_the_shared_runner.py::TestEveryPwshCallUsesTheSharedRunner::test_no_test_file_spawns_powershell_directly
E   AssertionError: these test files start PowerShell through subprocess instead of run_pwsh from tests/_shared/unsloth_pwsh_runner.py ...
E       tests/python/test_desktop_unsloth_spec_no_deps_pair.py:175: subprocess.run(...)
```

#16157 added `test_desktop_unsloth_spec_no_deps_pair.py`. Its
`installer_pair` fixture runs the real `install.sh` and `install.ps1`
pair resolvers, and the PowerShell leg called `subprocess.run` directly.
The guard is right. Under `-n 4`, a direct spawn shares one PowerShell
startup cache with every other xdist worker and can die at startup with
`Stack overflow.`. The installer change in #16157 is fine and nothing in
it changes here.

## Change

`tests/python/test_desktop_unsloth_spec_no_deps_pair.py` only. The
PowerShell leg now goes through `run_pwsh`, which gives it a per-worker
startup cache and retries an interpreter crash. The `sh` leg still uses
`subprocess.run`. Arguments, timeout and env (including the empty `PATH`
for the selected-uv case) are unchanged.

## Testing

- `tests/studio/test_pwsh_calls_use_the_shared_runner.py`:
  - main: 1 failed, 5 passed (the error above);
  - this branch: 6 passed.
- `tests/python/test_desktop_unsloth_spec_no_deps_pair.py` with `pwsh`
installed: 22 passed, 2 skipped (the two skips are the non-PowerShell
params of the selected-uv test). All six PowerShell cases run and pass
through `run_pwsh`.
danielhanchen pushed a commit to unslothai/unsloth-zoo that referenced this pull request Nov 3, 2026
Evicted decoder weights have shape `(0,)`, so PEFT cannot determine fused-expert dimensions during adapter construction. `BlockSwap.shaped()` temporarily exposes the saved shapes through zero-stride views backed by one scalar per parameter, then restores the empty tensors unless a block was fetched during the context.

Core integration and weight-reading initialization guards are in unslothai/unsloth#15159. That PR also works with older Zoo versions through its fallback.

Validation:

- Fifty block-swap tests passed on a real Colab L4, including the CUDA expert shape and PEFT check. CPU test counts alone do not establish that CUDA coverage.
- The partial-setup cleanup test now injects its error deterministically, avoiding an invalid-shape assumption that failed on Windows. The updated suite passes on Linux, macOS and Windows: danielhanchen#886.
- A random tiny Qwen3-MoE on Kaggle T4 completes loading, expert adapter setup, three optimizer steps, generation, saving and both plain PEFT and Unsloth reloads with the companion Core. Losses and gradient norms are bit-identical to the non-swapped control, and authoritative host weights remain unchanged.
- Replacing only the context body with a no-op brings back the original one-dimensional `ParamWrapper` error, proving the context is engaged.

The final Zoo regression smoke, SFT and inference A/B selection reports no regression. The compile control matches the existing swapped path at 28 graphs, 529 calls and zero graph breaks.

No kernel, scheduler, GPU detection or user-flow changes are included. This does not establish support for every MoE family or adapter variant. Related feature request: unslothai/unsloth#16512.
@danielhanchen
danielhanchen marked this pull request as ready for review November 3, 2026 13:24
@danielhanchen
danielhanchen merged commit 810c932 into unslothai:main Nov 3, 2026
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-11-03T13:25:00.395528Z
We couldn’t complete this review. Comment @codex review to try again.
d073807 Draft marked ready
ℹ️ About Codex in GitHub

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

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

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 7, 2026
…t, the CPU-kept n-gram table makes the map look like two devices (unslothai#15633)

<img
src="https://raw.githubusercontent.com/LeoBorcherding/unsloth/3e9bad0671b803245f8bea0d6010cf0cb09d9537/block-swap-thick/unsloth-15633.png"
width="900">

Line numbers are at main `a595688`. Companions: unslothai#15632 (FP8 n-gram table
scale), unslothai/unsloth-zoo#2268 (table kept out of Block Swap's slot
pool). **Merge unslothai/unsloth-zoo#2268 first:** without it, the table
Block Swap now engages on lands in the GPU slot pool, which turns
Count's clean refusal into an out-of-memory error.

**What's broken**

Load `unsloth/Qwen3.8-Flash-Next-FP8` (transformers `qwen4_exp`) with
`offload_layers` set, either as a Count or as Auto. Block Swap never
turns on, so the 172.8 GiB checkpoint goes straight at the GPU.

The order is the problem.
[`vision.py:3913`](https://github.com/unslothai/unsloth/blob/a5956882f64caa31e49fbe6bd7c5e12c71823cc0/unsloth/models/vision.py#L3913)
runs `exclude_no_placement_params` first, which rewrites `{"": 0}` into
`{"": 0, <ngram_embedding>: "cpu"}`. That keeps the model's 48.9 GiB
n-gram table off the GPU. Every Block Swap decision after that sees two
devices:

- **Auto.** `resolve_auto_block_swap` only plans a bare `{"": N}`. It
logs "loads every layer onto the GPU", and the load runs out of GPU
memory. Measured on a Colab G4: RTX PRO 6000, 95 GiB VRAM, 177 GiB host
RAM.
- **Count.** The load doesn't refuse; it runs out of GPU memory instead.
Measured on the same G4 with core main + unslothai#15159 + unslothai#15632 (so only this
PR is missing), transformers 5.22.1, Count 32: transformers tries to put
the n-gram table on the card while concatenating its shards ("Tried to
allocate 47.69 GiB ... 41.67 GiB is free") and reports it as a
`CONVERSION` failure on `ngram_embedding.weight`. An earlier version of
this body called this a refusal ("needs every layer on one GPU") from a
code read; the run shows the load gets past that check.

**Fix**

Call `exclude_no_placement_params` after the Block Swap decisions, right
after the load collapses to the one-card map. The Block Swap checks see
`{"": N}`, and the table still lands on CPU. Nothing changes for models
without `_no_placement_params`.

`tests/test_block_swap_no_placement_order.py` pins the order. It's red
on main and green here.

**What it unlocks**

With this PR, unslothai#15632 and unslothai/unsloth-zoo#2268, Flash-Next trains
on one 95 GiB GPU. That run used Count 32 and an 8-bit paged AdamW: 10
steps, loss 1.19 to 0.75, 6.9 s/step, 82.8 GiB VRAM peak. The chart
shows where each run stopped before each fix:

<img
src="https://raw.githubusercontent.com/LeoBorcherding/unsloth/62007dc8f4a7f5db167b5711a83b406ad063e5c4/block-swap-flash-next/flash-next-stages.png"
width="900">

**Known gap: Auto now engages and can overrun host RAM**

Once this fix lets Auto plan, it plans for GPU memory only. On the G4 it
put 42 of 48 layers on the host, and with the 48.9 GiB table also there,
the cgroup killed it at about 170 GiB. Fixed Counts 24 to 34 peaked at
149 to 157 GiB. The host-RAM guard in unslothai/unsloth-zoo#1619 would
refuse that Auto plan up front.

<img
src="https://raw.githubusercontent.com/LeoBorcherding/unsloth/62007dc8f4a7f5db167b5711a83b406ad063e5c4/block-swap-flash-next/flash-next-host-ram.png"
width="900">

**Tested**

| Machine | What ran | Result |
|---|---|---|
| Colab G4, transformers 5.20.2, main + zoo #2268 (then fork #36) | Auto
| OOM at load, Block Swap never engaged |
| Colab G4, transformers 5.21.0, this PR + zoo #2268 (then fork #36) +
unslothai#15632 | Counts 24, 28, 32, 34, then Count 32 with paged AdamW | Block
Swap engages on every run; Count 32 + paged AdamW trains |
| Mac, CPU | `pytest tests/test_block_swap_no_placement_order.py` | 2
pass |
| Colab G4, transformers 5.22.1, core main + unslothai#15159 + unslothai#15632, zoo with
every open Block Swap PR | Count 32, Auto | without this PR: Count runs
the GPU out converting the table (47.69 GiB asked), Auto loads every
layer and OOMs |
| same, plus this PR (core `c730ae13`) | Count 32 + paged AdamW, Auto |
Count 32 trains 10 steps, loss 1.19 to 0.76, 6.8 s/step, 82.8 GiB VRAM;
Auto refused up front by the host-RAM guard (199.8 GiB asked, 142.5 GiB
free) |
| Colab T4, same stacks | `tests/test_block_swap_no_placement_order.py`
with the unslothai#15159 and unslothai#15632 tests | 18 failed against main, 19 passed on
the stack |

---------

Co-authored-by: Daniel Han <[email protected]>
danielhanchen added a commit to Etherll/unsloth that referenced this pull request Nov 18, 2026
…st RAM to fork (unslothai#17701)

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_proc` asks for 1 (in-process). `UNSLOTH_DATASET_NUM_PROC`
still wins.
- Online tokenization turns off with that reason.
`UNSLOTH_STUDIO_ONLINE_TOKENIZATION=1` still 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):

![host RAM over
time](https://github.com/LeoBorcherding/unsloth-zoo/raw/8b83a943/flash-next-sweep/charts/pr-17701-host-ram.png)

![peak host RAM and steps
finished](https://github.com/LeoBorcherding/unsloth-zoo/raw/8b83a943/flash-next-sweep/charts/pr-17701-outcome.png)

**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
unslothai#11832, unslothai#12996, unslothai#12998, unslothai#15159, unslothai#15632 and unslothai#15633, plus this PR. The zoo
was main plus unslothai/unsloth-zoo#1619, unslothai#2269 and unslothai#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:

| Block Swap setting | VRAM | s/step | tokens/s |
|---|---|---|---|
| Count 32, ctx 1024 | 82.8 GiB | 6.05 | 169 |
| Count 36, ctx 1024 | 75.4 GiB | 9.07 | 113 |
| Count 36, ctx 1024, batch 2 | 76.0 GiB | 9.07 | 226 |
| Count 36, ctx 4096 | 77.4 GiB | 39.3 | 104 |

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 new
`test_a_trainer_too_big_to_fork_tokenizes_in_process` fails on main and
passes here (34/34).
- `test_online_tokenization.py` and
`test_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

`57b883d29e` Fork veto: count Block Swap Auto only when it offloads, one
host memory reading per run, cover the batched packing pool.

1. **Block Swap Auto that offloads nothing no longer turns workers
off.** `offload_layers = "auto"` attaches no swapper when the model fits
the card (`unsloth/models/_utils.py`: `_auto_block_swap_indices` returns
nothing, so no `_unsloth_block_swap`), so nothing sits in host RAM. As
first submitted, any `"auto"` run lost its `dataset.map` workers 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.
2. **One host memory reading per run.** The `dataset_num_proc` site 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
the `dataset_num_proc` site took.
3. **Multi-LoRA packing asks the same veto.** `_pack_num_proc` in
`multi_lora_trainer.py` forks a packing pool off the same loaded base
model (Block Swap is passed to its `load_model` too). 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.map` over 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.

| arm | parent rewrites its memory while the pool lives | extra host RAM
| outcome |
|---|---|---|---|
| `num_proc=None` (in process) | yes | +0.01 GiB | finishes, rc 0 |
| `num_proc=2` (forked pool) | no | +0.05 GiB | finishes, rc 0 |
| `num_proc=2` (forked pool) | yes | climbs to the limit | OOM-killed,
rc 137 (`memory.events` oom_kill 1), orphaned workers hang |

Without 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.map` pool 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_proc`
config value and the online tokenization decision; 4 Block Swap states x
4 memory states x `UNSLOTH_DATASET_NUM_PROC` unset / 3 = 96 cells):

| platform | cells | moved vs main, as first submitted | moved vs main,
with follow-up |
|---|---|---|---|
| macOS (darwin) | 32 | 0 | 0 |
| Windows (win32) | 32 | 0 | 0 |
| Linux | 32 | num_proc 13, online 26 | num_proc 10, online 20 |

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_PROC` wins 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):

| dataset_num_proc | packing | rows | sha256 of tokenized rows | losses
(first 3, last) | grad norms (first 2) |
|---|---|---|---|---|---|
| 1 (veto) | off | 4000 | `bb48fd178fb0f72c` | 10.3799, 10.3837,
10.3826, 10.3557 | 0.380899, 0.341375 |
| 4 (pool) | off | 4000 | `bb48fd178fb0f72c` | 10.3799, 10.3837,
10.3826, 10.3557 | 0.380899, 0.341375 |
| 1 (veto) | on | 3019 | `c540da4422293d57` | 10.3801, 10.3783, 10.3664,
10.3604 | 0.349844, 0.373813 |
| 4 (pool) | on | 3019 | `c540da4422293d57` | 10.3801, 10.3783, 10.3664,
10.3604 | 0.349844, 0.373813 |

Byte-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`):

| arm | result |
|---|---|
| main code + branch tests (`num_proc` + wiring files) | 2 failed, 66
passed (the two new veto tests) |
| first submitted head | 68 passed; with the online file 139 passed |
| head with follow-up | 148 passed |
| head with follow-up merged with current main (+
`test_multi_lora_trainer.py`) | 188 passed, 8 skipped |
| negative control: Auto counted as engaged | 2 failed (`[auto-None-0]`,
`..._offloaded_nothing_still_goes_online`) |
| negative control: online gate rereads memory | 1 failed
(`test_the_gate_reuses_the_reading...`) |
| negative control: packing ignores the veto | 1 failed
(`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_proc` returns 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.

---------

Co-authored-by: danielhanchen <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants