Skip to content

Tiled MLP: one flag or one line for any model, on the new sequence tiling engine - #16125

Merged
danielhanchen merged 15 commits into
mainfrom
dh/tiled-integration
Oct 30, 2026
Merged

danielhanchen merged 15 commits into
mainfrom
dh/tiled-integration

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Oct 30, 2026 •

Copy link
Copy Markdown
Member

Summary

Unsloth now tiles MLPs through the new unsloth-zoo sequence tiling registry. Tiling works on any model with one flag
or one call, it works under torch.compile, and DDP no longer needs a process-wide patch. This PR needs the
unsloth-zoo change that adds unsloth_zoo.tiling_registry and unsloth_zoo.sequence_tiling.

Per-block compile

Tiled MLP trains under Unsloth's default per-decoder-block compile (torch 2.11 and newer). Inside a compiled
block a tiled module leaves the graph once (one deliberate exit per tiled block: 6 to 7 graph breaks per step on
Qwen3-0.6B, 0 recompiles) and every tile runs one compiled tile body per module class, so compile
time does not grow with the tile count. Checked on tiny Qwen3 (GPU, torch 2.13) with the unsloth_tiled_mlp argument; the UNSLOTH_TILED_MLP spelling of the same test ran out of memory in Inductor autotuning under a 1 GB local cap, as the previous engine does under that cap.

tests/test_tiling_block_compile.py (GPU) pins this: two training steps under the default block compile, with
every decoder block still compiled.

What changed

  • unsloth/tiling.py: unsloth.tile_mlp(model, rows=None, target_gb=None, modules=None) and
    unsloth.untile_mlp(model).
    Both are idempotent.
    • The old spellings still work: the UNSLOTH_TILED_MLP env var (1, arctic, target:GB[:modules]) and the
      unsloth_tiled_mlp=True loader kwarg. True / 1 now mean auto (one tile when tiling would not lower the
      step peak); arctic keeps forcing tiles.
    • New spellings: auto and rows:N.
    • One parse for "off", shared by the env var, the kwarg and tile_mlp: None, False, 0, "", 0, false, off,
      no, none (any case). An off environment never overrides unsloth_tiled_mlp=True. Before, that held for 0
      only, and UNSLOTH_TILED_MLP=false with the kwarg turned tiling off.
    • tile_mlp / untile_mlp are exported at module scope, so every backend (MLX included) has them. unsloth.tiling
      imports only os; the zoo registry loads when a helper is called. Called on an MLX model they raise "not
      supported on MLX" (tiling runs PyTorch modules under torch checkpointing).
  • Loaders. FastLanguageModel and FastModel call one helper. sentence-transformers already passes the kwarg
    through, and a test now pins that.
  • Trainer. Trainer.__init__ re-runs the model's tiling plan, so modules that PEFT or the fused LoRA MLP added
    after load are tiled too. Trainer.call_model_init does the same for the fresh model it returns.
  • Removed unsloth/models/_tiled_mlp_ddp.py and its loader call.
    • The new engine runs every tile under one autograd graph, so each parameter's DDP grad hook fires once per
      backward with the summed gradient.
    • The process-wide TiledMLP.apply swap is therefore no longer needed.
  • Fused LoRA MLP and tiling.
    • The fused kernel is installed through _install_fused_lora_mlp. For a tiled MLP it goes into the inner-forward
      slot, so it runs per tile.
    • _decline_fused_lora_for_fsdp now restores the forward that ran before the kernel. Before, it reset a tiled
      MLP's inner forward to the class forward, which silently dropped an adopted grouped-MoE / mxfp4 /
      accelerate-hook forward when FSDP turned the fused kernels off.
    • Detection, the decoder-layer check and the decline read every slot the kernel can sit in: forward,
      _unsloth_forward, _old_forward and _orig_moe_forward. After revalidation adopts an accelerate hook, the
      kernel sits in the hook's _old_forward, and untile_mlp on a hooked module hands it there too; before, the
      FSDP gate saw no fused MLP there and skipped its fallback.
    • On a module with an accelerate hook the kernel goes into _old_forward, so the hook keeps running. Before, the
      install overwrote the hook wrapper and the hook silently stopped running.
    • A plain instance-function forward recorded before the kernel is restored without binding self twice when it
      goes back into a tiled MLP's inner slot.
  • Parallelism rule. Tiling is per rank. Under Ulysses context parallel it tiles the local shard. Tensor-parallel
    modules stay untiled unless UNSLOTH_TILED_MLP_TP=1.
  • Zoo modules in the import checks. unsloth_zoo.memory_budget, unsloth_zoo.sequence_tiling,
    unsloth_zoo.tiling_registry and unsloth.tiling are added to the spoofed import checks in
    tests/vllm_compat/test_extended_module_imports.py.

Compatibility

  • The unsloth_zoo floor moves to 2026.10.11, the release with the registry.
  • An older unsloth-zoo without the registry still imports fine, and tiling off never touches it. Asking for tiling
    raises a clear "update unsloth_zoo" error before any weights load, and Trainer revalidation is skipped. The
    registry-dependent tests skip on such a zoo.

Evidence (CPU unless noted)

  • tests/test_tiling_integration.py:

    • loader spellings (env and kwarg, including "0"), tile_mlp / untile_mlp round trips;
    • Trainer revalidation after PEFT;
    • call-site checks: no _tiled_mlp_ddp import left, and the file is gone;
    • sentence-transformers passthrough.
  • tests/test_tiling_ddp.py (2-rank gloo). For the default, find_unused_parameters, static_graph and
    gradient_as_bucket_view modes:

    • tiled grads equal the untiled all-reduced grads;
    • every grad hook fires once per backward.

    This holds with frozen and trainable MLP input, and with no DDP patch in the tree.

  • tests/test_fsdp_declines_fused_lora.py: decline restores the adopted forward when tiling is installed before
    or after the fused kernel, and a plain module still gets its class forward back. Failing first: before the fix,
    the adopted-forward cases left the class forward in place. Also, each failing on the previous head:

    • tile, fuse, attach an accelerate hook, revalidate: the kernel is detected, declined, and the hook still runs;
    • installing the kernel on a hooked module (tiled or not) keeps the hook running;
    • an instance-function forward (plain or torch.compiler.disable) survives fuse, tile, decline.
  • Loader spellings and fail-fast (tests/test_tiling_integration.py), failing on the previous head: every off
    spelling for env and kwarg; off never imports the registry (0 included); tiling on with no registry raises before
    weights load (both loaders checked); module-scope export; call_model_init revalidates the returned model.

  • GPU, tiny models, correctness only, 1 GB cap. Unsloth loader plus tiling vs untiled: same loss, and every LoRA
    grad present.

    • fp32 FastModel Llama and Qwen3-MoE: worst relative LoRA-grad difference about 1e-6.
    • bf16: 2-5%. A CPU study puts this at bf16 rounding: tiling with 2 tiles is bitwise equal to computing the
      untiled MLP as 2 plain row halves, and fp32 / fp64 match to 6e-7 / 1.5e-15.

Versions run: torch 2.13 + transformers 5.17, and torch 2.6 + transformers 4.57.6. Results:

Suite torch 2.13 + transformers 5.17 torch 2.6 + transformers 4.57.6
tiling integration, fused LoRA decline, spoofed import checks 119 passed 119 passed
gloo DDP (4 DDP modes x frozen / trainable input) 8 passed 8 passed

Also fixed:

  • Tile, fuse, untile, then decline no longer leaves the unbound class forward in module.forward. Before, the next
    call lost self. The test fails on the previous head.

Timing (L4 / G4)

G4 (RTX PRO 6000 Blackwell, torch 2.11), LoRA r 16 on every linear, one VM per run, warmup 2 then 5 timed steps.
Median step time, then peak allocated / peak reserved memory (MiB) and the first (cold) step:

Case untiled previous tiled MLP (arctic) this branch (arctic) this branch (auto, also True)
Qwen3-4B, 4 x 8k 3.951 s, 14141 / 14594, cold 16.6 s 4.645 s, 12162 / 12476, cold 18.5 s 4.851 s, 12162 / 12474, cold 21.9 s 3.966 s, 14141 / 14594, cold 15.1 s
Qwen3-0.6B, 1 x 16k 0.698 s, 2445 / 2654, cold 10.1 s 0.904 s, 2318 / 2394, cold 12.4 s 0.905 s, 2318 / 2394, cold 15.4 s
OLMoE-1B-7B, 1 x 8k, default compile 0.436 s, 17181 / 17466, cold 21.3 s 0.541 s, 16122 / 16226, cold 31.1 s 0.542 s, 16098 / 16226, cold 34.7 s
OLMoE-1B-7B, 1 x 8k, Unsloth compile off 0.623 s, 17594 / 17846 0.727 s, 16732 / 17046 0.731 s, 16732 / 17006
  • Peak memory equals the previous tiled MLP in every case; loss matches untiled to the 4th decimal.
  • Step time equals the previous tiled MLP at 0.6B 16k and on OLMoE; at Qwen3-4B 4 x 8k it is 4.4% slower.
  • auto on this 96 GB card plans one tile (the MLP fits in half of free memory), so it runs at untiled speed and
    memory. With one tile the fixed overhead over untiled is +0.1 to +0.5%.
  • Cold first step is 2 to 3.5 s longer than the previous tiled MLP. The tile body is compiled once for dynamic rows
    and shared by every tile and layer, so this cost does not grow with the tile count: on CPU with 64 tiles the first
    step went from 22.2 s (one unrolled graph per tile) to 1.6 s.
  • UNSLOTH_TILED_COMPILE=unroll keeps the unrolled loop: about 11% faster per step at 0.6B 16k, for a cold compile
    that grows about 1.1 s per tile.

Short sequences (sim job, G4, torch 2.11). Qwen3-0.6B LoRA r16 on all linears, 2048 tokens, Unsloth default block
compile, 20 steps, forced tiles (2 tiles of 1024 rows) against the previous tiled MLP and untiled:

Arm Median step (s) Peak alloc / reserved (MiB) Graph breaks per step Recompiles
untiled, before / this branch 0.075 / 0.076 1618 / 1974 0 0
previous tiled MLP 0.126 1618 / 1974 14 to 15 0
this branch, forced tiles 0.156 1618 / 1974 6 to 7 (one deliberate exit per tiled block) 0
QLoRA: untiled / previous tiled / this branch forced 0.085 / 0.140 / 0.163 1037 / 1400 0 / 22 / 9 0
OLMoE-1B-7B 8k, Unsloth compile off: untiled / previous / this branch 0.623 / 0.725 / 0.728 17595 / 16733 / 16733 alloc 0 0
  • At 2k tokens forced tiles save no memory and cost +24% step time in bf16 and +16% in QLoRA against the previous
    tiled MLP (per-tile host time). unsloth_tiled_mlp=True and UNSLOTH_TILED_MLP=1 now mean auto, which keeps one
    tile when tiling would not lower the step peak, so short sequences run at untiled speed. arctic, rows:N and
    target[:GB] still force tiles.
  • Loss matches untiled within the A/A band in every arm.

Not covered here

  • Hopper-only kernels, more than 2 real GPUs, ROCm and Windows.
  • A pre-existing issue, unrelated to tiling, is reported separately. On sm_100+ GPUs, float32 Qwen3 with LoRA on
    attention fails with BFloat16 != float in o_proj: the dense xformers attention path downcasts fp32 Q/K/V to
    bf16 and does not cast the output back.

…p / untile_mlp

- unsloth/tiling.py: tile_mlp(model, rows, target_gb, modules) / untile_mlp(model), the loader
  helper (UNSLOTH_TILED_MLP and unsloth_tiled_mlp spellings unchanged) and the per-Trainer
  revalidation; tiling is per rank, and under Ulysses CP it tiles the local shard.
- FastLanguageModel / FastModel call sites use it; sentence-transformers passes the kwarg through.
- Trainer.__init__ re-runs the plan per instance so modules PEFT adds after load are covered.
- Remove unsloth/models/_tiled_mlp_ddp.py: per-tile checkpoint sums parameter grads before any
  DDP hook fires, so the process-wide TiledMLP.apply swap is no longer needed.
- Tests: loader spellings, tile_mlp / untile_mlp, revalidation with PEFT, 2-rank gloo DDP parity
  (grad hooks fire once per backward), call-site and passthrough checks.
_decline_fused_lora_for_fsdp reset a tiled MLP's _unsloth_forward to the class forward, dropping an adopted instance
forward (grouped MoE, mxfp4, accelerate hook). The install now goes through _install_fused_lora_mlp, which records
the previous forward, and the decline restores it in whichever slot holds the kernel.

Also lists the new unsloth_zoo modules (memory_budget, sequence_tiling, tiling_registry) and unsloth.tiling in the
spoofed import checks, and runs the integration tests on the shipped checkpoint engine.
…instance slot

Tile, fuse, untile, decline left the class function in module.forward, so the next call lost self. The record
stores the class forward as None, and the decline treats it the same way.
The previous TiledMLP failed there on torch >= 2.11 with "A view was created in no_grad mode and its base ... has
been modified inplace with grad mode enabled" (env UNSLOTH_TILED_MLP=arctic and the loader kwarg). GPU test, tiny
Qwen3; it also asserts the blocks really compiled (no fallback to the stock forward).
…ackend

* One off parse for UNSLOTH_TILED_MLP, the loader kwarg and tile_mlp: None, False, 0, "", "0", "false", "off",
  "no", "none". An off environment never overrides unsloth_tiled_mlp=True, for every spelling (it did for "0" only).
* Requested tiling checks unsloth_zoo.tiling_registry before any weights load; tiling off never imports it.
* unsloth_zoo floor 2026.10.11 (the release with the registry).
* tile_mlp / untile_mlp exported at module scope, so MLX has them too.
* Trainer.call_model_init revalidates the fresh model's tiling plan.
…e it to

* Detection, the decoder-layer check and the FSDP decline read forward, _unsloth_forward, _old_forward and
  _orig_moe_forward. After revalidation adopts an accelerate hook, the kernel sits in the hook's _old_forward and was
  invisible to the FSDP gate.
* A module with an accelerate hook gets the kernel in _old_forward, so the hook keeps running instead of being
  overwritten.
* A plain instance-function forward recorded before the kernel is wrapped in functools.partial, so restoring it
  into a tiled MLP's inner slot does not bind self twice.
@danielhanchen
danielhanchen marked this pull request as ready for review October 30, 2026 16:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 30, 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-10-30T16:24:46.394444Z 2a6b6fe 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.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. More of your lovely PRs please.

Reviewed commit: 2a6b6fe056

ℹ️ 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 673a44b into main Oct 30, 2026
@danielhanchen
danielhanchen deleted the dh/tiled-integration branch October 30, 2026 19:31
danielhanchen added a commit that referenced this pull request Oct 30, 2026
…, trainer logger) (#16196)

## Problem

Main went red in three Backend CI shards after #16125 (tiled MLP) landed
(seen on the staging run for #16071, reproduced on main):

- `Repo tests (CPU, rest)`: all of
`tests/test_optimized_precision_conflicts.py` fails with `NameError:
name 'check_tiling_available' is not defined`. The fixture runs
`FastLanguageModel.from_pretrained` from `loader.py` in a hand-built
namespace of stubs, and #16125 added a
`check_tiling_available(unsloth_tiled_mlp)` call there that the
namespace does not provide.
- `Repo tests (CPU, rest-2)`: `tests/test_source_read_encoding.py` flags
`tests/test_tiling_integration.py:148: read_text()`. The new test file
reads checked-in sources with the platform default encoding (7 calls).
- `Repo tests (CPU, fsdp2)`: four tests in
`tests/test_fsdp2_native_accelerator_loop_gloo.py` crash every rank with
`NameError: name 'logger' is not defined` from `_unsloth_trainer_init`.
The harness in `tests/test_fsdp2_native_trainer_args_gloo.py` execs that
wrapper in a stub namespace and auto-stubs the bare helper calls it
makes. #16125 added a `try: revalidate_for_trainer(self) except
Exception as e: logger.warning_once(...)`, and in the harness the
revalidation raises, so the warning reaches `logger`, which only exists
as the real module's import.

In all three cases the product is right (`loader.py` imports
`check_tiling_available`, `_utils.py` imports `logger`); the tests'
namespaces had not followed.

## Fix

- `tests/test_optimized_precision_conflicts.py`: stub every name
`loader.py` imports from `..tiling`, the way the fixture already stubs
the Mistral-format helpers. So a future tiling helper called from
`from_pretrained` does not break the precision checks, which never reach
tiling.
- `tests/test_tiling_integration.py`: every `read_text()` names
`encoding = "utf-8"`.
- `tests/test_fsdp2_native_trainer_args_gloo.py`: the harness namespace
carries a no-op `logger` standing in for `_utils.py`'s module logger.

## Verification

Before (main) and after (this branch), same local environment:

| file | main | this branch |
|---|---|---|
| `tests/test_optimized_precision_conflicts.py` | 20 failed | 19 passed
|
| `tests/test_fsdp2_native_accelerator_loop_gloo.py` | 4 failed | 5
passed |
| `tests/test_source_read_encoding.py` | 1 failed | passed |
| `tests/test_tiling_integration.py` (with unsloth-zoo main for
`tiling_registry`) | n/a | 50 passed |
| `tests/test_fsdp2_native_trainer_args_gloo.py` | passed | passed |

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant