Skip to content

Unsloth Studio / Desktop: Block Swap settings, a VRAM budget, and a live layer panel on the training page - #12996

Merged
danielhanchen merged 29 commits into
unslothai:mainfrom
LeoBorcherding:feat/offload-studio
Oct 8, 2026
Merged

danielhanchen merged 29 commits into
unslothai:mainfrom
LeoBorcherding:feat/offload-studio

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 7, 2026 •

Copy link
Copy Markdown
Collaborator

Makes Block Swap (#11832, renamed to offload_layers in #12705) usable from Unsloth Studio and Unsloth Desktop. Until now it could only be turned on from Python.

What changes

Settings (Train → Training Hyperparameters → Memory, hidden on Mac and for full finetuning):

  • Offload layers: Off / Auto / Count.
  • VRAM budget (GiB), Auto only: the worker calls torch.cuda.set_per_process_memory_fraction before loading, and offload_layers="auto" sizes the swap to fit inside it. Two runs can share one card by giving each a budget.
  • Prefetch depth: Auto / 1-4. get_peft_model now takes prefetch_depth (int ≥ 1 or "auto") and passes it to install_block_swap instead of the hard-coded 2.

All three go through the config store, YAML, model defaults, the start-training request, the route and the worker, into every load path in trainer.py. Strings are added in all 14 locales.

Live panel (Current Run): a grid of layers showing on GPU / copying / in system RAM, a VRAM bar against the budget, copy vs compute ms per layer, and % waiting on copies. The trainer sends BlockSwap.stats() over the existing event queue, throttled, and the UI polls GET /api/train/offload. Without unslothai/unsloth-zoo#1619 (no stats()), the panel hides and training is unaffected.

Before / after

AMD Radeon AI PRO R9700 32 GB, Windows 11, torch 2.11.0+rocm7.14.0. Unsloth Desktop shell built from this branch at f4674a1d49, backend overlaid on latest main.

run settings result
Qwen3-0.6B, 30 steps Count 14, depth 2 model.layers.{14...27} on host, trained, loss 1.26 -> 0.98
Qwen3.5-27B 4-bit, 2048 ctx, 10 steps Auto, budget 14 GiB, depth Auto fraction 0.4394 (= 14.0 GiB); auto put 59 of 64 layers (10.46 GiB) in host RAM; 10/10, loss 0.758 -> 0.557, per-step losses equal to the same run with Block Swap off
Qwen3-0.6B, 80 steps (Unsloth Studio web, with unslothai/unsloth-zoo#1619) Count 14, depth Auto panel live: 14 / 28 offloaded, depth settled 1, copy 5-6.5 ms vs compute 3.8 ms, waiting 6-7%; 80/80

Without this PR none of these settings exist in either app, so there's no UI "before" to compare against.

Tests (at f4674a1d49)

  • tests/test_block_swap_install.py: 62 passed
  • studio/backend/tests/test_training_offload_layers.py: 21 passed
  • frontend npm test: 10772 passed. The merge with main turned up one real failure: the budget marker's fixed-alpha wash failed main's new contrast-slider test, and the merge commit fixes it.
  • npm run typecheck: clean

Review fixes

  • A budget the model cannot fit under now fails with "This run is capped at a N GiB VRAM budget. Raise or clear the VRAM budget under Training Hyperparameters > Memory." instead of a bare OOM.
  • Clearing the Count box no longer flips to Off; the budget placeholder is no longer cut off.
  • Offload needs gradient checkpointing: turning it off (any alias) is refused at the request, not after loading.
  • Offload controls are hidden (and nothing is sent) for embedding, decision and audio models and on XPU / CPU / unified-memory APU hosts; the budget only caps LoRA runs on Auto.
  • Auto plans for the run's batch size and LoRA rank; offload_layers=False means off again.
  • Multi-GPU: a fixed count is applied at LoRA setup (core refuses it at a multi-GPU load), and image / audio runs on several GPUs skip the budget (they can only swap after LoRA allocates).
  • Full regression switchboard (Core jobs on Colab / Kaggle, Studio journeys): no functional regression; the only reproduced visual change is the new Offload layers row.

Known gaps

Before / after (Unsloth Studio, this branch at 4a3006edb vs merge base 6a25e672f)

Training Hyperparameters > Memory: before has only Grad Checkpoint; after adds Offload layers (Auto), VRAM budget (GiB) and Prefetch depth

Memory tab, Offload layers set to Auto. GET /api/train/offload goes from 404 to {"active": false} while idle.

…and the load, and refuse offload_layers values it cannot use
…d and read it through the trainer's progress
# Conflicts:
#	studio/backend/core/training/worker.py
#	studio/frontend/src/features/training/api/mappers.ts
#	unsloth/models/_utils.py
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Oct 8, 2026
@shimmyshimmer

Copy link
Copy Markdown
Member

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

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 81021a1b6 (no equivalent commit found on this PR)

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

Codex Review: Didn't find any major issues. Bravo.

Reviewed commit: 81021a1b6d

No triage reaction was recorded on the mirror

Verdict

The round converged at mirror 81021a1b6 (no equivalent commit found on this PR).

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

@danielhanchen
danielhanchen marked this pull request as ready for review October 8, 2026 19:05
@danielhanchen
danielhanchen self-requested a review as a code owner October 8, 2026 19:05
@danielhanchen
danielhanchen merged commit d953dca into unslothai:main Oct 8, 2026
Penguinjanator pushed a commit to Penguinjanator/unsloth-zoo that referenced this pull request Nov 13, 2026
…refetch depth with prefetch_depth="auto", and refuse a swap that won't fit in host RAM (unslothai#1619)

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

Follow-up to unslothai#1378 (and the `offload_layers` rename in unslothai#1559). Three
additions to `unsloth_zoo/block_swap.py`, all opt-in or read-only.

## What changes

- **`BlockSwap.stats()`** returns where every swapped layer is (`gpu`,
`host`, `copying`, `held` for backward), the current layer, prefetch
depth, host / pinned / pool bytes, and copy, stall and compute ms plus
copy bytes since the last call. Timing uses CUDA events read lazily
(only completed events, no sync), so calling it every step adds no
stall.
- **`prefetch_depth="auto"`** starts at 1 and deepens one slot at a time
while copies stall a step that could hide them. It backs off if a deeper
pool didn't cut the stall, and settles after a few steps. It prints the
depth it settled on.
- **Host RAM guard.** `_check_host_fit` compares the bytes the swapped
layers will take with the host RAM `memory_budget.host_memory_bytes`
reports (psutil, capped by an enforcing cgroup limit, since psutil sees
the whole host inside a container) minus the same reserve the pin budget
keeps: max(4 GiB, 15% of RAM), but at most a quarter of a small host or
container. It runs in `BlockSwap.__init__` before anything moves, in
`load_layers_to_host` before each layer is evicted, and in
`build_host_layers` (the `attach_offload_layers` path, sized on meta)
before anything is copied. An offload that can't fit is refused with a
readable `ValueError` (layers asked for, GiB needed, GiB available, most
that would fit) instead of the OS swapping or the process dying. Without
psutil it does nothing.
- Weights already in host RAM are credited as their block is packed, on
both the registered arena and the chunked fallback (which frees each
original right after packing it).
- Host-kept tables (`_no_placement_params`, e.g. Qwen3.8-Flash-Next's
n-gram table) are not charged again, and a large table inside a selected
layer is charged once, with its layer.

## Tests

`pytest tests/test_block_swap.py`: 88 passed on a Colab T4 (torch 2.11
cu130), measured at `16674f75`. Earlier, on the R9700: 62 passed, 1
failed, at `4fb587bc`. The failure is
`test_compiled_layers_match_eager_with_swap`, which fails the same way
at upstream main `189e6fe3` on the same box, so it isn't from this
branch. New tests (psutil mocked): fits, doesn't fit, already-on-host
bytes count as free, psutil missing, the loader refusing at the first
layer with nothing moved, refusing later when RAM drops, and a GPU test
that `BlockSwap` raises with the weights still on the card and no hooks
installed.

## GPU run

AMD Radeon AI PRO R9700 32 GB, Windows 11, torch 2.11.0+rocm7.14.0, at
zoo `4fb587bc` + unsloth `f4674a1d49`. Qwen3-0.6B 4-bit, LoRA r16, seq
2048, 40 steps, `stats()` read after every step.

| run | swapped | depth | train peak | losses vs off |
|---|---|---|---|---|
| off | 0 | n/a | 3.22 GiB | baseline |
| 14 layers, depth 2 | 14 of 28 | 2 | 2.12 GiB | bitwise equal |
| 14 layers, depth auto | 14 of 28 | settled on 1 (stall 1.2%) | 2.11
GiB | bitwise equal |
| auto layers, depth auto | 0 (fits) | n/a | 3.22 GiB | bitwise equal |

## NVIDIA runs (Colab)

Qwen3.5-4B, Count 16, `prefetch_depth="auto"` through Unsloth (reentrant
checkpointing, fused cross entropy) on a T4 at `16674f75`: settles on
depth 1, 3.72 GiB, loss 1.43 to 0.61, the same as depth 2.

Across 21 paired runs on T4, L4 and A100 40/80 GB, auto depth pays off
under `offload_layers="auto"` (up to 46% faster per step, using some of
the VRAM auto left free) and is a wash under a fixed Count:

![prefetch_depth auto vs depth
2](https://raw.githubusercontent.com/LeoBorcherding/unsloth/4ec6bb59c9deb3c139886a164352bfff28f6947f/block-swap-1619/prefetch-auto.png)

The host-RAM guard on Qwen3.8-Flash-Next (RTX PRO 6000, 177 GiB host
RAM): before it, Auto planned 42 of 48 layers to host and the VM was
killed at about 170 GiB. With it, Auto is refused up front (41 layers
need 194.8 GiB) and Count 32 fits and trains:

![Flash-Next host RAM per
run](https://raw.githubusercontent.com/LeoBorcherding/unsloth/62007dc8f4a7f5db167b5711a83b406ad063e5c4/block-swap-flash-next/flash-next-host-ram.png)

Rerun at this PR's current head `16674f75`, stacked with the other open
Block Swap PRs (Colab G4, transformers 5.22.1): Auto is refused at load
("43 layers in host RAM, which needs 199.8 GiB, but only 142.5 GiB is
available"), Count 32 with 8-bit paged AdamW trains 10 steps (loss 1.19
to 0.76, 6.8 s/step, 82.8 GiB VRAM), and Count 34 trains with
unslothai#2268 (157 GiB host peak) and is refused without it
(132.2 GiB asked, 42.1 GiB free) instead of running the host out of
memory.

## Not tested

- A low-RAM host under a cgroup limit. Colab exposes no cgroup memory
limit, so the clamp is covered by a unit test only.
- The extra embedding tables `load_layers_to_host(embeddings=True)`
streams to host aren't counted by the guard.

The Unsloth Studio / Desktop panel that shows these stats is
unslothai/unsloth#12996.

---------

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.

3 participants