Repository navigation
Tiled MLP: one flag or one line for any model, on the new sequence tiling engine - #16125
Merged
Merged
Conversation
…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.
… skips on an older zoo
danielhanchen
marked this pull request as ready for review
October 30, 2026 16:05
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
Member
Author
|
@codex review |
|
Codex Review: Didn't find any major issues. More of your lovely PRs please. Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
This was referenced Oct 30, 2026
Merged
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>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 theunsloth-zoo change that adds
unsloth_zoo.tiling_registryandunsloth_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_mlpargument; theUNSLOTH_TILED_MLPspelling 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, withevery decoder block still compiled.
What changed
unsloth/tiling.py:unsloth.tile_mlp(model, rows=None, target_gb=None, modules=None)andunsloth.untile_mlp(model). Both are idempotent.UNSLOTH_TILED_MLPenv var (1,arctic,target:GB[:modules]) and theunsloth_tiled_mlp=Trueloader kwarg.True/1now meanauto(one tile when tiling would not lower thestep peak);
arctickeeps forcing tiles.autoandrows:N.tile_mlp: None, False, 0,"",0,false,off,no,none(any case). An off environment never overridesunsloth_tiled_mlp=True. Before, that held for0only, and
UNSLOTH_TILED_MLP=falsewith the kwarg turned tiling off.tile_mlp/untile_mlpare exported at module scope, so every backend (MLX included) has them.unsloth.tilingimports only
os; the zoo registry loads when a helper is called. Called on an MLX model they raise "notsupported on MLX" (tiling runs PyTorch modules under torch checkpointing).
FastLanguageModelandFastModelcall one helper. sentence-transformers already passes the kwargthrough, and a test now pins that.
Trainer.__init__re-runs the model's tiling plan, so modules that PEFT or the fused LoRA MLP addedafter load are tiled too.
Trainer.call_model_initdoes the same for the fresh model it returns.unsloth/models/_tiled_mlp_ddp.pyand its loader call.backward with the summed gradient.
TiledMLP.applyswap is therefore no longer needed._install_fused_lora_mlp. For a tiled MLP it goes into the inner-forwardslot, so it runs per tile.
_decline_fused_lora_for_fsdpnow restores the forward that ran before the kernel. Before, it reset a tiledMLP'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.
forward,_unsloth_forward,_old_forwardand_orig_moe_forward. After revalidation adopts an accelerate hook, thekernel sits in the hook's
_old_forward, anduntile_mlpon a hooked module hands it there too; before, theFSDP gate saw no fused MLP there and skipped its fallback.
_old_forward, so the hook keeps running. Before, theinstall overwrote the hook wrapper and the hook silently stopped running.
selftwice when itgoes back into a tiled MLP's inner slot.
modules stay untiled unless
UNSLOTH_TILED_MLP_TP=1.unsloth_zoo.memory_budget,unsloth_zoo.sequence_tiling,unsloth_zoo.tiling_registryandunsloth.tilingare added to the spoofed import checks intests/vllm_compat/test_extended_module_imports.py.Compatibility
unsloth_zoofloor moves to2026.10.11, the release with the registry.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:"0"),tile_mlp/untile_mlpround trips;_tiled_mlp_ddpimport left, and the file is gone;tests/test_tiling_ddp.py(2-rank gloo). For thedefault,find_unused_parameters,static_graphandgradient_as_bucket_viewmodes: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 beforeor 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:
torch.compiler.disable) survives fuse, tile, decline.Loader spellings and fail-fast (
tests/test_tiling_integration.py), failing on the previous head: every offspelling 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_initrevalidates the returned model.GPU, tiny models, correctness only, 1 GB cap. Unsloth loader plus tiling vs untiled: same loss, and every LoRA
grad present.
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:
Also fixed:
module.forward. Before, the nextcall 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:
True)autoon this 96 GB card plans one tile (the MLP fits in half of free memory), so it runs at untiled speed andmemory. With one tile the fixed overhead over untiled is +0.1 to +0.5%.
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=unrollkeeps the unrolled loop: about 11% faster per step at 0.6B 16k, for a cold compilethat 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:
tiled MLP (per-tile host time).
unsloth_tiled_mlp=TrueandUNSLOTH_TILED_MLP=1now meanauto, which keeps onetile when tiling would not lower the step peak, so short sequences run at untiled speed.
arctic,rows:Nandtarget[:GB]still force tiles.Not covered here
attention fails with
BFloat16 != floatino_proj: the dense xformers attention path downcasts fp32 Q/K/V tobf16 and does not cast the output back.