Skip to content

Block Swap blocker: Qwen3.8-Flash-Next-FP8 can't train with offload_layers, its FP8 n-gram table loads without its weight_scale - #15632

Merged
danielhanchen merged 13 commits into
unslothai:mainfrom
LeoBorcherding:fix/fp8-modules-to-convert-backfill
Nov 4, 2026
Merged

danielhanchen merged 13 commits into
unslothai:mainfrom
LeoBorcherding:fix/fp8-modules-to-convert-backfill

Conversation

@LeoBorcherding

@LeoBorcherding LeoBorcherding commented Oct 28, 2026 •

Copy link
Copy Markdown
Collaborator

Why this PR exists: it's required for Block Swap on Qwen3.8-Flash-Next. Without it, offload_layers can't get past layer 1 on unsloth/Qwen3.8-Flash-Next-FP8. With it, plus #15633 and LeoBorcherding/unsloth-zoo#36, the 180B model trains on one 95 GiB GPU. The bug sits in the FP8 load path, not in Block Swap, so it would also hit anyone loading this checkpoint on transformers 5.21.

Line numbers are at ed067c7.

What's broken

unsloth/Qwen3.8-Flash-Next-FP8 stores its n-gram table as per-tensor FP8 with a weight_scale. The repo's quantization_config doesn't list that table in modules_to_convert; Qwen's own FP8 config lists ple.ple_embedding.ngram_embedding.

transformers 5.21 only builds an FP8Embedding for tables named in modules_to_convert (replace_with_fp8_embedding). So the table stays a plain nn.Embedding, the load report lists ngram_embedding.weight_scale as UNEXPECTED, and the first forward pass dies in layer 1:

RuntimeError: expected mat1 and mat2 to have the same dtype, but got: c10::Float8_e4m3fn != c10::BFloat16

Fix

backfill_fp8_modules_to_convert runs right after the config loads, on both load paths: FastModel (vision.py:3718) and FastLlamaModel in llama.py, which FastLanguageModel uses for llama, mistral, gemma, qwen2 and qwen3 types. It only acts when the config is quant_method: "fp8" and modules_to_convert is empty. In that case it reads the checkpoint's weight map and adds every module that ships a per-tensor .weight_scale. Layer prefixes are stripped, so the entry is the same suffix pattern Qwen's config uses, and anything in modules_to_not_convert is left out.

What it doesn't touch:

  • Block-FP8 checkpoints. They ship weight_scale_inv, so they never match.
  • Configs that already list their tables.
  • Linear layers. transformers only applies modules_to_convert to nn.Embedding, so Linear conversion can't change.

Any failure reading the weight map leaves the config alone.

Before / after

Colab G4 (RTX PRO 6000, 95 GiB VRAM, 177 GiB host RAM), transformers 5.21.0, Block Swap Count 28. Without the backfill, the run hit the dtype error above in layer 1. With it, the table loads with its scale, nothing is UNEXPECTED, and the run gets past layer 1. On Count 32 with 8-bit paged AdamW it trains: 10 steps, loss 1.19 to 0.75.

Rerun at the current heads (core main + #15159 + #15633 + this PR at 6b71c822, zoo with every open Block Swap PR, transformers 5.22.1, same G4), Count 32 + paged AdamW: with this PR, 10 steps, loss 1.19 to 0.76, 6.8 s/step, 82.8 GiB VRAM. The same stack without it: expected mat1 and mat2 to have the same dtype, but got: c10::Float8_e4m3fn != c10::BFloat16 in layer 1's first forward.

Tests

tests/test_fp8_modules_to_convert_backfill.py uses the real index keys from the checkpoint, trimmed. It covers: the left-out table gets added; configs that already list it, or aren't FP8, stay untouched; block-only and skipped tables add nothing; subfolder, cache_dir and variant reach the index lookup; a single-file repo is never downloaded just to list its keys; both loaders call the backfill before the weights load. 6 pass at 6b71c822, and on a Colab T4 the Block Swap core tests (this file plus the #15159 and #15633 ones) go from 18 failed against main to 19 passed on the stack. The proper fix is also adding the entry to the Hugging Face repo's config. This PR covers that repo and any other FP8 upload that leaves it out.

…ules_to_convert (unsloth/Qwen3.8-Flash-Next-FP8 n-gram table)
danielhanchen added a commit that referenced this pull request Oct 28, 2026
…helper (#15679)

## Summary

`Repo tests (CPU, gloo)` has failed twice with every rank dying before
the test starts:

```
torch.distributed.DistNetworkError: The server socket has failed to listen on any local network address. port: 45095, useIpv6: false, code: -98, name: EADDRINUSE
AssertionError: rank exit codes [1, 1]
```

- #15616:
`tests/test_tp_native_gloo.py::test_sharded_loading_matches_full_load[phi3-2-None]`
- #15632: `test_tp_x_fsdp2_refuses_trainable_head_norms`, port 42541,
also in `tests/test_tp_native_gloo.py`

#14334 fixed this race by adding `tests/_rendezvous_port.free_port()`:
- It draws MASTER_PORT from below the kernel's ephemeral range
(32768-60999 on Linux), in a slice per xdist worker.
- So neither another worker nor an outgoing gloo connection can take the
port between the test releasing it and rank 0 listening on it.

That PR moved 21 tests onto the helper, but 15 distributed tests still
pick their port with `bind(("127.0.0.1", 0))`,
`tests/test_tp_native_gloo.py` among them. Both failing ports above are
inside the ephemeral range.

## Change

- **14 test files:** their local `_free_port()` now delegates to
`tests._rendezvous_port.free_port()`, the same three lines the other 21
files use, and their now-unused `socket` imports are dropped:
- `test_tp_native_gloo.py`, `test_pp_native_gloo.py`,
`test_pp_fsdp2_gloo.py`, `test_parallel_general_gloo.py`
- `test_moe_dw_accumulate.py`, `test_ddp_find_unused_default.py`,
`test_ddp_comm_defaults.py`
- `test_fast_inference_torchrun_agreement.py`,
`test_cudnn_sdpa_grad_layout_dtensor.py`
- five under `tests/python/`: block compile DDP, GRPO DDP sync, plain
trainer DDP, sentence transformer DDP and FSDP2 save
- **`tests/test_token_budget_batches.py`:** the inline `bind(0)` before
`MASTER_PORT` now uses the helper.
- **`tests/test_rendezvous_port_everywhere.py`** (new): any test outside
`tests/studio` that sets up a torch rendezvous (`MASTER_PORT`,
`master_port`, `init_process_group` or `TCPStore`) must either define
`_free_port` through the helper or not bind port 0 at all.
- Studio tests are out of scope: their ports are for HTTP servers they
start themselves.
- It includes self-tests for both shapes of the mistake, and a check
that the helper stays below the ephemeral range for several worker ids.

## Testing

- **`tests/test_rendezvous_port_everywhere.py`:** 6 passed.
- **Sabotage:** with `tests/test_tp_native_gloo.py` and
`tests/test_token_budget_batches.py` restored from main, the guard fails
and names both files.
- The 14 converted files plus `tests/test_token_budget_batches.py` and
the new guard, under `-n 4`: 243 passed, 2 skipped. On main the same 14
files plus `test_token_budget_batches.py` (without the guard): 237
passed, 2 skipped.
@LeoBorcherding LeoBorcherding changed the title FP8 loads: Qwen3.8-Flash-Next-FP8's n-gram table loads without its weight_scale, so key_proj gets fp8 input Block Swap blocker: Qwen3.8-Flash-Next-FP8 can't train with offload_layers, its FP8 n-gram table loads without its weight_scale Oct 28, 2026
@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 24c9c862. The backfill probed the default root and cache, so a load with subfolder, variant or cache_dir could miss the scale map. It now forwards all three to _load_fp8_weight_map, as the block-FP8 caller does. Test added, fails on the previous head.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

CI is clean at 60c223f7 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.

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

Pushed 6b71c822. FastLanguageModel sends llama, mistral, gemma, qwen2 and qwen3 model types through FastLlamaModel.from_pretrained in llama.py, which read the config and never ran the backfill, so an FP8 checkpoint of one of those types with an unlisted per-tensor embedding scale would still load it raw. The backfill now runs there too, right after the config loads. test_both_loaders_backfill_before_loading checks both loaders call it before the weights load; it fails without the llama.py change. tests/test_fp8_modules_to_convert_backfill.py: 6 passed.

Codex is clean at this commit (review on the fork mirror, same diff as this PR).

@LeoBorcherding

Copy link
Copy Markdown
Collaborator Author

CI is clean at 6b71c822 apart from Repo tests (CPU, studio-install): 3 tests fail with Could not resolve a compatible unsloth / unsloth-zoo pair for no-torch mode, the install resolver picking package versions. This diff doesn't touch the installer, and #15159 fails the same 3 tests in the same job.

@LeoBorcherding

LeoBorcherding commented Nov 4, 2026 •

Copy link
Copy Markdown
Collaborator Author

ci failures unrelated
image

@LeoBorcherding
LeoBorcherding marked this pull request as ready for review November 4, 2026 07:11
@danielhanchen danielhanchen self-assigned this Nov 4, 2026
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 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 ✅ Completed 2026-11-04T14:02:13.488244Z 655737e Manual request
ℹ️ 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.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 14cefada97

ℹ️ 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".

Comment thread unsloth/models/loader_utils.py Outdated
skip = set(quant.get("modules_to_not_convert") or [])
modules = {k[: -len(".weight_scale")] for k in weight_map or {} if k.endswith(".weight_scale")}
# Linear blocks carry weight_scale_inv; only embeddings match, and the quantizer converts nn.Embedding only.
found = sorted({re.sub(r"^.*\.layers\.\d+\.", "", m) for m in modules - skip})

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge Preserve layer scope when inferring FP8 table conversions

For a mixed-precision checkpoint with model.layers.0.table.weight_scale but only a BF16 model.layers.1.table.weight, stripping the layer prefix produces the conversion pattern table. The embedding replacement matches that suffix across layers, including through _keep_fp8_embeddings on the NF4 path, so the dense layer-1 table is also replaced with FP8Embedding despite having no checkpoint scale. Even an exact layer-1 exclusion cannot prevent this because exclusions are applied before the name is broadened. This can change previously dense table values or cause missing-scale loading problems. Retain layer-qualified matches, or verify that every matching table has a scale before generalizing the pattern.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 655737e: patterns keep the layer index (layers.1.ple.ple_embedding.ngram_embedding), so another layer's dense table no longer matches; test added.

@danielhanchen

Copy link
Copy Markdown
Member

@codex review

1 similar comment
@danielhanchen

Copy link
Copy Markdown
Member

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: 655737ea8a

ℹ️ 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".

@danielhanchen
danielhanchen merged commit 2ed0e98 into unslothai:main Nov 4, 2026
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