Skip to content

Block compile: keep gradient checkpointing on layers behind accelerate device-map hooks - #18811

Merged
danielhanchen merged 1 commit into
mainfrom
block-compile-device-map-hooks
Nov 22, 2026
Merged

danielhanchen merged 1 commit into
mainfrom
block-compile-device-map-hooks

Conversation

@danielhanchen

Copy link
Copy Markdown
Member

With a model split over several GPUs (device_map across cards, for example Kaggle 2x T4), accelerate's device-map hook calls the forward bound at load time, module._old_forward, not the class attribute. On transformers 5.23 and later that bound forward is GradientCheckpointingLayer's wrapper, which only checkpoints while it is still the class forward. Once the block compile replaced the class forward, every hooked layer ran the stock layer forward: no gradient checkpointing and no compiled block, with no error or warning.

Inkling-2-Mini 4-bit on 2x T4 kept about 0.45 GB of activations per layer this way and ran out of memory in the first forward. Any model split across GPUs on transformers >= 5.23 is affected the same way; a single GPU is not, since there is no device-map hook.

Fix

patch_block_compile now points each hooked instance's _old_forward at the installed forward (_rebind_hooked_instances). Only instances of the wrapped class whose _old_forward is still the original bound forward are touched; unhooked layers and other classes are left alone.

Tests

test_block_keeps_checkpointing_under_accelerate_device_map_hooks: a toy checkpointed layer with a real accelerate hook and a transformers 5.23 style wrapper. Before the rebind it runs with no checkpoint (the bug), after it checkpoints and matches the reference output, and unhooked instances are unchanged. The block compile tests pass.

On Kaggle 2x T4 the Inkling-2-Mini QLoRA notebook trains with this change (peak 12.35 GB / 13.62 GB per card) and runs out of memory in the first forward without it.

…e device-map hooks

With a model split over GPUs, accelerate's hook calls the forward bound at load (_old_forward). On transformers
>= 5.23 that is GradientCheckpointingLayer's forward wrapper, which only checkpoints while it is the class forward;
once the block compile replaced the class forward the hooked layers ran the stock forward with no checkpointing and
no compiled block. Inkling-2-Mini 4-bit on 2x T4 kept ~0.45 GB per layer and ran out of memory in the first
forward. Point the hooked instances' _old_forward at the installed forward.
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-21T21:46:56.561298Z 397d154 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. What shall we delve into next?

Reviewed commit: 397d154085

ℹ️ 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 9840f8f into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the block-compile-device-map-hooks branch November 22, 2026 04:24
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 22, 2026
…18812)

Adds training support for Inkling 2 (`thinkingmachines/Inkling-2-Mini`,
`inkling2_loop`, and `Inkling-2-Small`, `inkling2`), native in
transformers 5.24.0. Companion unslothai/unsloth-zoo#2657 (MoE experts
and an eager attention residual) is needed for training. Inference falls
back from vLLM, which has no Inkling 2 support yet, and merged / GGUF
exports are refused (see below); this PR also carries the general fix
from unslothai#18811, which Inkling needs on 2x T4.

## What was broken

1. LoRA setup failed: Inkling wraps its attention projections, so the
usual target names matched the wrappers, not the Linear layers inside.
Targets now map onto the inner Linears (`unsloth/models/inkling2.py`,
`patch_inkling2_model`), the vision tower included when
`finetune_vision_layers` is on.
2. The released Mini's own `modelopt` quantization config set off
Unsloth's generic NVFP4 / ModelOpt rewrite, which crashed on load and
quietly turned 4-bit off. Inkling's config describes its own expert
layout, decoded by transformers' conversion mapping, so it is dropped
and bitsandbytes quantizes the dequantized weights.
3. Small's released NVFP4 / MXFP8 experts could not load on transformers
5.24: the missing decode step is now registered, the same way as Mini's.
4. Every 4-bit load fed Mini's loop message gates integer activations:
they cast their input to `down_proj.weight.dtype`, which is `uint8` once
packed. Generation degenerated and SFT loss sat around 3.5 instead of
0.5 to 1.0, with no error. Those 12 small rank-64 layers now stay out of
bitsandbytes.
5. Compiled training recompiled the layers for every new sequence length
(A100, Mini QLoRA at 1024 tokens: 85 to 840 s per step) and the compiled
block attention residual had wrong gradients. Inkling 2 now trains
eagerly by default (`UNSLOTH_COMPILE_DISABLE=partial` unless the user
set it): 4.4 s per step on the same A100.
6. On 2x T4 the first forward ran out of memory because gradient
checkpointing silently stopped when the model was split across GPUs (the
unslothai#18811 fix, included here).

Fixes 4 and 5 only show on a GPU and broke results without raising
errors.

## Results

- Parity with plain transformers + PEFT in fp32: losses and every LoRA
gradient agree to about 3e-6 relative, on CPU and GPU, for a tiny Mini,
a tiny Small and a 24-layer Mini fake.
- Kaggle 2x T4, Inkling-2-Mini QLoRA notebook (4 x 1024 tokens, 30
steps): 12.8 min, about 26 s per step, peak 12.35 GB / 13.62 GB per
card, sensible answers after training, adapters saved.
- GRPO (TRL, no vLLM) on real Mini 4-bit on one A100: completions make
sense, rewards vary within each group, non-zero gradient norms. TRL puts
Inkling's thinking text in `reasoning_content`, so reward functions
should read that or the raw tokens.
- A free Colab T4 cannot hold Mini: the 4-bit weights alone are 14.4 GB
on a 15 GB card. Small needs about 290 GB in NF4 (realistically 8x 80
GB) and was only checked on fake models.

## Tests

`tests/test_inkling2_support.py`: LoRA target mapping, the dropped
quantization config, the Small expert decode registration, the message
gates kept out of bitsandbytes, the eager default and its override. Each
test fails without its fix. They skip on transformers older than 5.24.
The neighbouring suites pass (11 FSDP2 tests fail the same way on the
base commit on a CPU-only host).

## Not covered

- vLLM (`fast_inference=True`), the merged 16-bit save and GGUF export,
reloading the saved adapter on GPU.
- Windows, macOS and AMD.
- Generation speed: Unsloth decodes about 1.5 tok/s on an A100 against
about 3 tok/s for plain transformers.
- Unsloth's pins cap transformers at 5.18.0, so Inkling needs
transformers 5.24.0 installed explicitly until the cap moves.

## Inference and export
Two problems found running Inkling-2-Mini end to end on Colab.

#### 1. `fast_inference = True`

No vLLM release registers Inkling 2. vLLM 0.34.0 (the latest) has only
Inkling v1 (`InklingForCausalLM`, `InklingForConditionalGeneration`,
`InklingMTPModel`) and requires `transformers < 5.23`, while Inkling 2
needs transformers 5.24. vLLM main added Inkling 2 on 2026-11-21
(vllm-project/vllm#69028), after every release. unsloth_zoo also has no
vLLM weight layout for the looped layers.

Before, with vLLM 0.34.0 and transformers 5.24.0 forced, `FastModel` and
`FastLanguageModel` raised:

```
RuntimeError: Unsloth: Fast inference is only supported for Language models and these vision model types: ... Found architectures: siglip, inkling2, inkling2_loop!
```

`inkling2` and `inkling2_loop` now join `VLLM_UNSUPPORTED_MODEL_TYPES`
(as `gpt_oss`), so the load prints

```
Unsloth: fast_inference (vLLM) does not support inkling2 yet - will switch to Unsloth inference!
```

and continues with Unsloth inference. Checked on a Colab L4 with vLLM
0.34.0: both loaders on a tiny Mini fake, and the real Mini in 4-bit
through `FastLanguageModel(fast_inference = True)`, which loads and
generates coherent text.

#### 2. Merged 16-bit save writes the base model back

A `save_pretrained_merged(..., save_method = "merged_16bit")` of a 4-bit
Mini with LoRA r 8 (attention and experts, non-zero B) wrote the
released checkpoint back unchanged: 0 of its 1244 tensors differ from
the original, and the reloaded model matches the base with next-token KL
0.0 on four prompts. The checkpoint stores Inkling's own names
(`attn.wq_du`, `controllers.*`, which transformers renames on load) and
packs the experts in NVFP4 / MXFP8, so the merge places none of the LoRA
weights, and its count check passes because both counts are zero.

Merged and GGUF exports of Inkling 2 now raise `NotImplementedError` up
front, pointing at the adapter save. The adapter reloads with
transformers + `PeftModel.from_pretrained` (checked: 168 LoRA tensors,
the adapter changes the logits). On a Colab G4 run with the real Mini,
`merged_16bit` and `save_pretrained_gguf` both refuse and write nothing,
and `merged_4bit` keeps its existing refusal. GGUF is also blocked one
step later: the llama.cpp Unsloth fetches (unslothai/llama.cpp prebuilt
b12588 and its converter) has no Inkling 2 yet; upstream added it in
b12600.

#### Tests

- `tests/test_inkling2_support.py`: Mini and Small map to the vLLM
fallback; every merged and GGUF method refuses while `lora` and
non-Inkling models pass, and each of the four export entry points runs
the check right after the Mistral-format one.
- The save tests that exec `save.py` functions with their own namespace
get the new global.
- CPU, transformers 5.24: the save / GGUF / export suites give the same
result on this branch and on its base (1377 passed, 21 failed, 8 errors,
with the same failing test IDs on both: hub-cache prewarm, FP8 dequant
save policy, MTP head stitch and a few others that fail on this offline
CPU host either way).

## Other models keep their all-linear behaviour

Setting every family flag for `target_modules = "all-linear"` before the
remap now happens only for models whose remap hook takes a `vision`
argument (Inkling 2). Every other model keeps the caller's flags until
the existing all-linear block, as on main. Without this, T5 failed with
"No layers to finetune", BART dropped `fc1` / `fc2` (32 -> 24 LoRA
modules) and DeepSeek-V4.1-style models ignored `finetune_mlp_modules =
False` / `finetune_attention_modules = False` (88 of 1440
target-selection cells differed from main). With the change all 1440
cells match main on transformers 4.57.6 and 5.24.0
(`tests/test_all_linear_family_flags.py`, fails before, passes after).
AMD Linux and Windows (gfx1151): tiny Llama / Qwen3 LoRA training, LoRA
saves and merged 16-bit saves are bit-identical between main and this
branch.




Issue unslothai#18691: will fix.
ouyang-2019 pushed a commit to ouyang-2019/unsloth that referenced this pull request Nov 23, 2026
… replay skip eligibility (unslothai#18986)

### What

Follow-ups to unslothai#18811 and unslothai#18934 in block compile
(`unsloth/models/_block_compile.py`, `unsloth/kernels/fast_lora.py`):

1. The checkpoint shim that block compile puts back outside the block
(`_checkpointing`) now follows the transformers 5.24
`GradientCheckpointingLayer` wrapper. It checkpoints only while grad is
enabled, and it clears the renamed `cache=` keyword as well as
`past_key_values=` / `layer_past=`. `_has_cache` also treats `cache=` as
a cache call, so cached calls keep the stock forward as they did with
`past_key_values=`.
2. `patch_block_compile` rebinds accelerate-hooked layers of a model
whose layer class was already wrapped for an earlier model. The
installed forward keeps the forward it replaced
(`_unsloth_block_before`) for that rebind.
3. `block_skip_down_eligible` refuses MLPs whose gate / up / down
adapters have a dropout module or a `lora_B` bias.
`_mlp_output_unobserved` refuses an MLP class that overrides `__call__`.

### Why

1. transformers 5.24 renamed the layer cache keyword to `cache`. It also
stopped checkpointing a training-mode layer under `no_grad`, so
`generate()` on a model left in `train()` keeps its cache. The shim
still checkpointed under `no_grad`, never cleared `cache=`, and
`_has_cache` missed `cache=`. A cached call therefore ran the compiled
block and could write the cache twice. The repro was a two-layer random
Llama on transformers 5.24.0 behind accelerate dispatch hooks, CPU,
torch 2.14.1. The block was installed with `aot_eager`:
- `no_grad` prefill + decode in train mode: main raised `The size of
tensor a (6) must match the size of tensor b (3)` (6 cached keys against
a 3-position mask), after 17 graphs and 49 breaks. With this change the
cache lengths are 3 then 4 and the logits match stock transformers
exactly (max delta 0), with 0 graphs.
- Grad-enabled forward with an explicit cache: main raised the same
error. Here it runs, matching stock transformers.
2. unslothai#18811 rebinds accelerate's `_old_forward` only when it wraps the
class. A second model of the same layer class, dispatched before the
first was patched, kept the stale bound wrapper. On transformers 5.23+
that means no checkpointing and no compiled block. Same repro,
transformers 5.24: the second model's layer ran its projection once with
no regional graph on main (no checkpoint replay). With this change it
runs twice with one graph, the same as the first model.
3. LoRA dropout and a `lora_B` bias take `LoRA_MLP`'s branch that always
runs the down projection. The compiled block still passed the skip flag
(an extra replay graph) and counted a skip in `MLP_DOWN_SKIP_STATS`. On
Gemma GEGLU with `lora_dropout=0.1`, main counted 3 skips for 3 layers
whose replay outputs were all finite (none skipped). An MLP subclass
that overrides `__call__` can transform `mlp(x)` outside its forward.
With a `__call__` that squares the output, main still skipped that
layer's down projection in eager. The backward through the square then
read the placeholder: 29 of 43 gradient tensors differed from skip-off,
on both GEGLU forms and on Llama SwiGLU.

### Tests

Each new test fails on main (`632c437424`) and passes here (CPU, torch
2.14.1):

-
`tests/test_block_compile.py::test_block_checkpoint_shim_keeps_the_5_24_cache_contract`:
main checkpointed under `no_grad` (`[1] == []`).
-
`tests/test_block_compile.py::test_block_rebinds_hooked_layers_of_a_second_model`:
main ran the second model with no checkpoint (`[] == [1]`).
-
`tests/test_gc_skip_replay_mlp_down_gemma.py::test_mlp_call_override_keeps_down_projection[gemma_approx|gemma_exact|llama]`:
main counted 3 skips where 2 are allowed.
-
`tests/test_gc_skip_replay_mlp_down_gemma.py::test_compiled_replay_with_lora_dropout_counts_no_skip[gemma_approx|gemma_exact]`:
main reported a dropout MLP as skip-eligible.

Suites, run with unsloth-zoo main for
`gradient_checkpoint_replay_module`:

- `tests/test_block_compile.py`,
`tests/test_gc_skip_replay_mlp_down.py`,
`tests/test_gc_skip_replay_mlp_down_gemma.py` and
`tests/test_gc_skip_replay_mlp_down_block_compile.py` on transformers
4.57.6: 134 passed, 25 skipped (CUDA only).
- `tests/test_block_compile.py` on transformers 5.23.0 (torch 2.15.0)
and on 5.24.0: 81 passed, 9 skipped. The 2 failures in each venv also
fail on main: `vllm.sampling_params` is missing there.

### Not covered

- No GPU run. To confirm on a GPU, run training-mode `generate()` from a
QLoRA Llama on transformers 5.24 with block compile on, once on a single
GPU and once with `device_map` split across 2 GPUs. Also run a Gemma
LoRA with `lora_dropout > 0` under block compile and check the graph
count.
- Two findings are not changed here. An enclosing
`torch.compile(fullgraph=True)` around a hooked model still breaks on
the block's inline flags inside the checkpoint. The FP8-LoRA
per-instance `layer.forward` still shadows accelerate's hook (this
predates unslothai#18811).



## GPU check

Colab L4, transformers 5.24.0, QLoRA Llama-3.2-1B through FastModel with
block compile on, left in train(): a no-grad prefill then one cached
step raises `expanded size (12) must match (6)` on the merge base; with
this PR the cache goes 6 then 7. Gemma with lora_dropout=0.1: base marks
the layer skip-eligible and compiles 3 graphs, this PR refuses and
compiles 2. Unit tests: base 7 failed, head 129 passed.
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.

1 participant