Skip to content

Inkling 2 (Mini and Small): LoRA / QLoRA training support - #18812

Merged
danielhanchen merged 13 commits into
mainfrom
inkling2-support
Nov 22, 2026
Merged

danielhanchen merged 13 commits into
mainfrom
inkling2-support

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 21, 2026 •

Copy link
Copy Markdown
Member

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 #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 Block compile: keep gradient checkpointing on layers behind accelerate device-map hooks #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 #18691: will fix.

…FP4 experts out of the ModelOpt rewrite

Inkling-2-Mini (inkling2_loop) and Inkling-2-Small (inkling2) wrap q/k/v/o in modules holding .linear, so the usual
LoRA names hit modules PEFT cannot wrap. Map them to the real Linears (o_proj covers its output gate too) through
unsloth_lora_target_modules, which now also receives the vision flag when the hook accepts it.

The released checkpoints carry quantization_config = modelopt / NVFP4 while their expert layout is Inkling's own,
which transformers' conversion mapping dequantizes. Drop that marker so the generic ModelOpt NVFP4 rewrite (which
needed compressed-tensors and turned off load_in_4bit) stays off and bitsandbytes can quantize the loaded weights.
…nkling 2 Mini

transformers 5.24 decodes the released expert layout (w13_weight + _scale / _amax / _outer_scale_denominator) only
for inkling2_loop. The inkling2 text mapping renames the packed uint8 experts straight into the dense parameters,
so loading Inkling-2-Small without a quantizer fails on mismatched sizes. Register inkling2_text the way upstream
builds inkling2_loop_text: its two dequantizing expert converters plus the remaining inkling2_text transforms.
…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.
MessageGate.forward casts its input to down_proj.weight.dtype, which is uint8
once bitsandbytes packs the weight, so every 4-bit load fed the gates integer
activations and generation degenerated (16-bit and a simulated NF4 round trip
of every weight both stay coherent). The two gate projections are also
fp32-strict upstream. All three are rank 64 (about 7M parameters).
Compiled, Inkling 2 recompiles its layers for every new sequence length:
Mini QLoRA on one A100 took 841, 501, 291, 180, 90 and 85 s for its first six
steps at 1024 tokens; eager it takes 18 s and then 4.4 s per step on an A100
40GB, with finite grad norms and coherent generation. Set
UNSLOTH_COMPILE_DISABLE=partial for inkling2 and inkling2_loop unless the user
chose a value.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@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-22T11:41:17.086091Z a2a6460 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

Copy link
Copy Markdown
Codex Review Summary: ❌ Failed

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

Review Status Commit Review trigger
📝 Code Review ❌ Failed 2026-11-21T21:46:02.530863Z
We couldn’t complete this review. Comment @codex review to try again.
15c976c PR opened
ℹ️ 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: 15c976c1e7

ℹ️ 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/vision.py Resolved
…target remap

target_modules="all-linear" turns every family flag on, but the Inkling 2 /
DeepSeek-V4.1 remap hooks ran first and read the caller's flags: with
finetune_vision_layers=False (or a family off) they returned a narrower list,
and the later all-linear handling never ran because target_modules was no
longer "all-linear". Set the flags before the remap; the explicit-audio
check still reads the caller's own value.

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Another round soon, please!

Reviewed commit: f5ee5431e8

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

No vLLM release registers Inkling 2: 0.34.0 (the latest) has only Inkling v1
and requires transformers < 5.23, while Inkling 2 needs transformers 5.24.
unsloth_zoo also has no vLLM weight layout for the looped layers. Add
inkling2 and inkling2_loop to VLLM_UNSUPPORTED_MODEL_TYPES so
fast_inference = True prints that vLLM does not support the model and loads
it for Unsloth inference, as gpt_oss does.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

… unchanged

A merged_16bit save of a QLoRA-trained Inkling-2-Mini wrote the released
checkpoint back bit for bit: 0 of its 1244 tensors changed, and the reload
matched the base model with KL 0.0. The checkpoint names its tensors in
Inkling's own layout (attn.wq_du, controllers.*, which transformers renames on
load) and packs the MoE experts in NVFP4 / MXFP8, so the merge places none of
the LoRA weights, and the count check passes because both sides are zero.

Refuse merged and GGUF exports for inkling2 / inkling2_loop with a message that
points at the adapter save and at a transformers + PEFT merge_and_unload. The
save tests that exec save.py functions get the new global.
@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: f5ee5431e8

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

The refusal suggested a transformers + PEFT merge_and_unload as the way to get
merged weights. On an A100 check that merge did not reproduce the unmerged
adapter (next-token KL to it up to 0.24; a small adapter added to bf16 weights
loses part of its delta to rounding, and this was not separated from other
causes), so it is not offered as an equivalent. The adapter itself reloads
with Unsloth and with transformers through PeftModel.from_pretrained.
# Conflicts:
#	tests/test_inkling2_support.py

[skip ci]
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. You're on a roll.

Reviewed commit: cd1c594601

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review: Didn't find any major issues. Chef's kiss.

Reviewed commit: e2c6675456

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

Penguinjanator pushed a commit to Penguinjanator/unsloth-zoo that referenced this pull request Nov 22, 2026
…ning (unslothai#2657)

Fixes Inkling 2 (transformers >= 5.24, `inkling2` / `inkling2_loop`)
needs for Unsloth training and 4-bit decode. Companion
unslothai/unsloth#18812 adds the loader side and the notebook support.

## MoE experts

`Inkling2Experts` / `Inkling2LoopExperts` call `act_fn(gate, up)`, a
softcapped SwiGLU, and accumulate the routed outputs in fp32. Every
Unsloth MoE backend called `act_fn(gate) * up` and raised `TypeError`.
`temporary_patches/inkling2.py` declares `_unsloth_own_apply_gate` and
`_unsloth_moe_fp32_reference` on both classes, so `grouped_mm`,
`unsloth_triton` and `native_torch` all go through the model's own
`_apply_gate` and fp32 accumulation.

## Block attention residuals stay eager

Compiled on its own (`dynamic=True`) on CUDA, the one-query block
attention residual over three or more stacked blocks returns correct
values but wrong input gradients: 8-34% relative on T4 and A100 in a
standalone repro. Every Inkling 2 LoRA run drifted from transformers +
PEFT (worst LoRA gradient 8-20% off, NaN gradient norms in bf16). The
compiler now leaves that module out. Eager, the LoRA gradients match
transformers + PEFT to 3.5e-6 relative.

## Tests

- `tests/test_inkling2_moe_experts.py`: both expert classes declare the
flags, and the native loop matches a softcapped SwiGLU reference with
fp32 accumulation (fails on main).
- `tests/test_inkling2_compile_entries.py`: the residual stays out of
the compiled entries.
- Neighbouring MoE and compiler suites pass. The MoE test skips on
transformers without `inkling2_loop` (older than 5.24).
- On GPU (Kaggle 2x T4 and Colab A100, via the companion unsloth PR)
Inkling-2-Mini QLoRA losses and every LoRA gradient match transformers +
PEFT to about 3e-6 relative in fp32.

## Routed NF4 decode for experts that own their gate
#### Problem

The routed MoE decode path (`moe_routed.py`) declines every expert
module that declares `_unsloth_own_apply_gate`, since its kernels fuse a
fixed activation. Inkling 2's experts own their softcapped SwiGLU, so a
4-bit Inkling-2-Mini dequantized all 128 experts in each of its 48 layer
applications for every generated token.

#### Change

For decode-sized no-grad calls on stacked NF4 experts with their own
`_apply_gate` (at most 32 (token, expert) slots,
`UNSLOTH_MOE_ROUTED_OWN_GATE_MAX_SLOTS`):

- dequantize only the routed experts with the existing bit-exact
`nf4_select_dequant` kernel,
- one batched GEMV per projection, with the module's own gate between
them (in fp32 for `_unsloth_moe_fp32_reference` experts, as the grouped
path does),
- the weighted routed outputs summed in fp32.

Training, grad-enabled calls, larger calls and anything the existing NF4
table checks reject keep the current path. `UNSLOTH_MOE_ROUTED_KERNEL=0`
turns it off. Modules flagged as owning their gate but without a
callable `_apply_gate` are still declined.

I also tried the same thing for 16-bit experts (gathering the routed
experts with `index_select`): it was 1.6% slower than the current
grouped path on an A100 (2.81 vs 2.86 tok/s), so it is not included.

#### Results

Real Inkling-2-Mini, Colab A100 80GB, greedy, 128 new tokens, batch 1,
tok/s (two runs per arm; the transformers arm twice in separate
processes as the A/A):

| arm | VM 1 | VM 2 |
|---|---|---|
| transformers bf16 (A/A) | 3.000, 3.024 / 3.105, 3.127 | 2.993, 3.003 /
3.046, 3.071 |
| transformers + bitsandbytes 4-bit | | 2.565, 2.569 |
| Unsloth 4-bit, `UNSLOTH_MOE_ROUTED_KERNEL=0` | 2.365, 2.369 | 2.214,
2.233 |
| Unsloth 4-bit, this PR | 2.703, 2.709 | 2.616, 2.642 |

So 14-18% faster 4-bit decode, now slightly ahead of transformers' own
4-bit load (which leaves the 3D experts in bf16: 48 GB against 15.8 GB).
The 128 greedy tokens are identical with and without the change.

#### Tests

- `tests/test_inkling2_moe_experts.py`: the routed path engages for Mini
and Small experts (1 and 4 tokens, with and without expert LoRA) and its
error against an fp64 softcapped reference on the same dequantized
weights is no worse than the current path's; calls over the slot cap and
training fall back. These fail before the change and pass after, on a T4
(fp16) and an L4 (bf16).
- `tests/test_moe_routed.py` on the same two GPUs: the same 5 GPT-OSS
compiled-decode tests fail with and without this change (they need more
of the test tree than was copied to the worker); everything else passes.
- LoRA parity against transformers + PEFT on Inkling fakes (fp32, A100)
is unchanged: max loss difference at most 1.9e-6 over 3 SGD steps, grad
norms equal to 6 digits.
…odal remap hooks

Forcing every finetune_* flag before the remap made T5 / BART all-linear send their
leaf names through get_peft_regex (T5 raised "No layers to finetune", BART lost
fc1 / fc2) and handed DeepSeek-V4.1 style hooks all families regardless of the
caller's attention / MLP choice. Inkling 2's hook takes vision and keeps the
early normalisation.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: e2c6675456

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

Copy link
Copy Markdown
Member Author

@codex review

@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: 08a2cad08f

ℹ️ 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/vision.py Resolved
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a2a6460fb7

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

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

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

Reviewed commit: a2a6460fb7

ℹ️ 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 5a5ea1f into main Nov 22, 2026
@danielhanchen
danielhanchen deleted the inkling2-support branch November 22, 2026 21:24
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
…d sinks fused; L4 -15% per step) (unslothai#18943)

Stacked on unslothai#18812 (Inkling 2 support). Routes Inkling 2's language
attention through FlexAttention for training and prefill. transformers
5.24 ships Inkling 2 eager only (`_supports_sdpa / flash / flex =
False`, because of the per-token attention sinks), so every layer
application builds the full `L x L` scores, a gathered `L x L` relative
bias and an `L x L` additive mask.

## What eager computes

Per head, after the projections (scaled L2 clip on q and k, log-position
scaling on the global layers, short causal convolutions on k and v):

```
s[q, k] = scale * <q_q, k_k> + bias[q, k] + mask[q, k]
bias[q, k] = (rel_states[q] @ proj)[q - k]  for 0 <= q - k < rel_extent, else 0
p[q, :] = softmax([s[q, :], sink[q]])[:-1]
```

with the sliding layers masked to `q - 1024 < k <= q` and the global
layers causal. `rel_extent` is 1024 on both layer types in the released
configs.

## The flex path

- Mask: a BlockMask built from the same transformers mask function
(causal, sliding window, packed-sequence document ids, padding), so
packed and padded rows mask exactly as eager does and tiles outside the
window are skipped.
- Relative bias: `score_mod` adds `rel_logits[b, q, h, q - kv]` from the
per-token `[B, L, H, rel_extent]` table (0 beyond the extent, as eager).
The `L x L` bias is never built.
- Sinks: exact log-sum-exp merge, `softmax([s, sink])[:-1] = softmax(s)
* sigmoid(lse - sink)`, with the gradient through flex's `lse`. Fully
masked rows give 0, as eager does.
- The `L x L` int64 relative distance matrix is skipped when the masks
are BlockMasks.
- Models split over two GPUs: layers on the second card get a BlockMask
whose mask tensors live on that card.
- Under `torch.utils.checkpoint(use_reentrant=False)` flex's captured
score_mod buffer gets recomputed twice and its gradient accumulated
twice; the flex call then runs inside an autograd Function that
recomputes it in backward. Unsloth's own checkpointing takes the direct
path.
- Decode steps and cached continuations keep the eager path.
- `UNSLOTH_INKLING2_FLEX=0` keeps eager everywhere, `=1` forces flex on
any CUDA card, `auto` (default): flex on compute capability 8.0 and
newer, eager on T4 / sm75, from the numbers below.
`UNSLOTH_INKLING2_FLEX_MIN_LENGTH=N` overrides the length threshold. The
path is not enabled (eager stays) when the modeling code it mirrors
differs from transformers 5.24, when attention dropout is set, or on
torch < 2.7.

## Parity

fp32, flex vs eager in one process with the same weights, transformers +
PEFT LoRA on the attention Linears and the experts, plus the relative
bias and sink projections trained so their gradients through `score_mod`
and `lse` are checked directly. Lengths below, at and above the window
and the extent; plain, padded and packed rows.

| fake | device | lengths | worst LoRA grad rel | logits rel |
|---|---|---|---|---|
| Mini / Small tiny (window 8, extent 16) | CPU, T4, L4 | 5, 8, 16, 40,
200 | 8.1e-6 .. 1.3e-5 | <= 1.7e-6 |
| Mini / Small, window 1024, extent 1024 | CPU, T4, L4 | 1000, 1024,
1100, 2100 | 4.4e-6 .. 9.4e-6 | <= 1.1e-6 |
| Mini, window 1024, head_dim 128 | T4, L4 | 1100, 2100 | 4.5e-6 ..
5.4e-6 | <= 1.0e-6 |
| Mini tiny, layers split over 2x T4 | T4 x2 | 200, 1100 | 1.2e-5 |
8.3e-7 |
| Mini tiny, gradient checkpointing (reentrant and not) | T4, L4 | 40,
200 | 6.6e-6 .. 1.2e-5 | 7.3e-7 |

Against a float64 eager oracle the fp32 flex arm is as close as the fp32
eager arm (T4, 200 tokens: eager 2.4e-5, flex 1.2e-5); in bf16 both arms
are equally far from it. Greedy generation is token for token equal.
Every flex arm ran flex on every layer application, every eager arm
none, and there were no graph breaks.

Inside Unsloth (`FastModel`, Unsloth gradient checkpointing) eager and
flex agree to 4.4e-6 with right padding or no padding. With a
left-padded row they differ, because Unsloth's eager mask unmasks
padding query rows (they see every key, future ones included) while flex
follows transformers' mask; the last padding position of a left-padded
row predicts the first real token, so that difference reaches the loss.

## Memory and step time, Inkling-2-Mini QLoRA

Real weights, 4-bit, LoRA r 8, Unsloth gradient checkpointing, eager and
flex arms interleaved in one process, 2 timed steps per arm after a
warmup.

| GPU | shape | eager s / step | flex s / step | eager peak GB | flex
peak GB |
|---|---|---|---|---|---|
| L4 (bf16) | 1 x 1024 | 5.83 .. 5.92 | 5.00 .. 5.03 | 21.10 | 21.08 |
| 2x T4 (fp16, split) | 1 x 1024 | 9.21 .. 9.54 | 15.79 .. 15.95 | 11.72
/ 11.99 | 11.56 / 11.79 |
| L4 and 2x T4 | 4 x 1024, 1 x 2048 .. 8192 | out of memory | out of
memory | | |

On L4 flex is 15% faster at the same memory. On T4 it is 1.7x slower (no
tensor-core path in Triton on sm75) and saves under 0.2 GB per card. The
longer shapes fail in both arms on the fp32 logits over the 200058-token
vocabulary and the expert scratch, not in attention.

## Tests

`tests/test_inkling2_flex.py` (CPU, flex's reference math, 23 tests):
the kernel formula against an explicit softmax with sink (float64,
window and extent shorter than the row, a fully masked row), full model
forward + backward against eager for Mini and Small shapes on plain,
padded and packed rows, gradient checkpointing reentrant and
non-reentrant, accelerate-hooked layers, greedy generation, the auto
policy, the kill switch and the modeling-code fingerprint.


## gfx1151 check at the current head (Linux)

- `auto` / unset keep gfx1151 on eager (it reports capability (11, 5));
`UNSLOTH_INKLING2_FLEX=1` still forces flex; decode stays eager.
- Forced flex, 3 steps at length 32 then 3 at 24 in one process, loop
and plain fakes: flex engaged every step, LoRA gradients finite on every
step in float32 and bf16, losses match eager to about 1e-6 (fp32) and
2e-4 (bf16).
- `tests/test_inkling2_flex.py` on the ROCm host: 31 pass / 0 fail at
a757191 (the previous head failed 16 there: 2 policy cases that left
`torch.version.hip` set and 14 fixture import errors under dynamo).



## GPU check

Colab L4: forced flex engages in all four variants (loop / no loop,
plain / padded), loss difference vs eager 0.0, LoRA grad relative
difference at most 1.5e-5; `output_attentions=True` returns every map,
equal to eager; `UNSLOTH_INKLING2_FLEX=0` keeps it off.
shimmyshimmer pushed a commit to shimmyshimmer/unsloth-staging-4 that referenced this pull request Nov 23, 2026
…early, parity tests (unslothai#18959)

Follow-up to unslothai#18812 (Inkling 2 training support, merged). Companion
unsloth-zoo PR unslothai/unsloth-zoo#2688: fused LM-head loss with
Inkling's module softcap, and a bounded expert dequant scratch.

## What this changes

1. Inkling-2-Mini: the loop's message residual (24 calls per forward)
ran between the checkpointed layers, so its fp32 norm, expanded queries,
keys and values stayed alive for the whole step: 1.23 GB on the last
card of a 2x T4 split at 1024 tokens. It now runs under
`torch.utils.checkpoint` when gradient checkpointing is on and the model
is training. The recompute runs the residual's math as plain tensor ops
on inputs moved to the module's device instead of calling the module
again: going back through the accelerate device hook and the
compiled-module wrapper during recompute made two identical runs differ
at step 1 on a two-card split (210 of 336 LoRA gradients).
`UNSLOTH_INKLING2_MESSAGE_CHECKPOINT=0` keeps the old behaviour.
2. Tensor and pipeline parallel are refused for `inkling2` and
`inkling2_loop` from the config, before any weight loads. Tensor
parallel has no sharding rule for the wrapped q / k / v / o projections
or the per-head sink and relative position bias projections; a pipeline
stage cut would split the block attention residual stack and the Mini
loop. Before, `UNSLOTH_PARALLEL="tp=2"` loaded the whole model on every
rank and failed after 101 s on Kaggle 2x T4 with transformers' weight
conversion error; now it stops in 27 s with the reason and the
alternatives (`dp=N`, `fsdp=1`, or `device_map="balanced"`). A matching
row is added to the parallel capability table.
3. CPU tests for the released NVFP4 / MXFP8 layout decode, the default
LoRA targets against PEFT, and the adapter save / reload round trip, for
both `inkling2` and `inkling2_loop`.

## Results (Kaggle 2x T4)

- Mini QLoRA notebook, 4 x 1024 tokens, with the zoo companion: peak
allocated 11.29 / 12.53 GB before, 10.04 / 9.87 GB after (card 0 / card
1); reserved 13.62 GB on card 1 before, 9.95 GB after. `max_seq_length =
2048` now passes the whole notebook (30 steps); before, it ran out of
memory. About 4.6% slower per step on the same machine, from the chunked
expert dequant.
- DDP and FSDP2 match a one GPU run with the same micro-batches on a
fake shaped like Inkling-2-Small (48 layers, 384 experts) and on a
looped Mini fake: fp32 LoRA gradients within 1e-6 relative, FSDP2
bit-identical in fp16, including FSDP2 with one unit per layer, where
each looped layer is gathered three times per forward.
- The real Mini does not fit DDP or FSDP2 on 15 GB cards: every rank
loads the whole 4-bit model (14.3 GB) before sharding. It trains with
the notebook's `device_map` split.
- Inkling-2-Small needs about 310 GB of NF4 weights; it does not fit any
free tier.

- Determinism on the real Mini, two-card split (torch 2.11): repeated
runs are bitwise identical (336 of 336 LoRA gradients, steps 1 to 3)
with every change on, as on the base. The checkpointed residual alone
against the base: 335 of 336 bitwise, worst tensor 4e-7. With the zoo
fused loss the difference to the base is the fused CE rounding (1.6e-4
global).

## Tests

- `tests/test_inkling2_parallel.py`: 10 tests, all fail on the base
commit and pass with the refusal.
- `tests/test_parallel_inkling2_gloo.py`: two-process CPU DDP / FSDP2
parity on tiny Mini and Small configs, plus the refusals (8 tests).
- `tests/test_inkling2_lora_parity.py` (6) and two new tests in
`tests/test_inkling2_support.py` for the message residual checkpoint
(fail on the base commit).
- Together with `tests/test_block_compile.py`: 126 passed, 9 skipped on
CPU, transformers 5.24.

## Not covered

- Real Inkling-2-Small weights (393 GB checkpoint).
- FSDP2 from a checkpoint that is already 4-bit with sharded loading
(none is published for Inkling 2).
- Expert parallel: still refused by `UNSLOTH_PARALLEL` for every model.



## GPU check

Kaggle 2x T4, tiny Mini-shaped fake split with `device_map="balanced"`:
the new message checkpoint runs (24 calls per step, 0 with its opt-out)
and step-1 LoRA grads are bitwise equal across 3 runs; the merge base is
also deterministic at this size, so this is no-regression evidence, not
a flip. The balanced load works on both arms.
danielhanchen added a commit to danielhanchen/unsloth-zoo-staging that referenced this pull request Nov 23, 2026
…nded expert dequant scratch (unslothai#2688)

Two memory changes for Inkling 2 QLoRA, measured on the Inkling-2-Mini
notebook on Kaggle 2x T4. Companion to unslothai/unsloth#18959
(follow-up to unslothai/unsloth#18812).

## Fused LM-head loss with a module softcap

Inkling 2 applies its final logit softcap as a module call (`logits =
self.logit_softcap(logits)`, `tanh(x / 30) * 30`), so the forward
rewriter took the softcap module for the LM head and declined. The model
then built full fp32 logits over its 200058 token vocabulary: 2.29 GB
alive on the last card at 1024 tokens.

`inline_softcap_modules` rewrites that call into the expression form the
rewriter already understands, only when `__init__` builds the attribute
from a module whose whole forward is exactly `tanh(x / C) * C`; a
look-alike module is left alone. It runs on both the compiler route and
the import hook. The fused call no longer reads `logits.shape[-1]` for
`vocab_size` before `logits` exists in that branch.

Parity on fake models on a GPU: fp32 LoRA gradients fused vs unfused
within 6e-7 to 1.7e-6 relative, loss within 1e-6, with right padding,
prompt masks, and with and without `num_items_in_batch`. In fp16 the
fused loss equals an fp32 head reference to the printed digits.

## Bounded expert dequant scratch

Training dequantized each whole 4-bit expert stack per projection call:
1.27 GB for Mini's gate / up stack, and 16.3 GB per call for
Inkling-2-Small. An experts class can now declare
`_unsloth_dequant_scratch_fraction`; a stack larger than twice that
share of the card is dequantized in chunks of at most that share.
Inkling 2 declares 2.5% (Mini: 4 chunks of 36 experts on a T4, unchunked
on a 40 GB card; Small: chunked on every card).
`UNSLOTH_MOE_DEQUANT_MAX_MB` caps it for any model; an explicit
`UNSLOTH_MOE_DEQUANT_CHUNK_EXPERTS`, including 0, still wins. Chunks are
bit-exact: all 336 LoRA gradient tensors equal the unchunked run on T4
and A100.

## Results (Kaggle 2x T4, Mini QLoRA notebook shape, 4 x 1024 tokens)

| | card 0 | card 1 |
|---|---|---|
| peak allocated, before | 11.29 GB | 12.53 GB |
| peak allocated, after (with the unsloth companion) | 10.04 GB | 9.87
GB |
| fp32 logits + softcap | | 2.29 GB -> 0 |
| expert dequant scratch | 1.27 GB -> 0.18 GB | 0.18 GB |

`max_seq_length = 2048` now passes the whole notebook; before, it ran
out of memory. The chunked dequant costs about 4.6% per step on the same
machine (it adds a host sync per MoE call and turns off keeping
checkpoint base outputs).

## Tests

- `tests/test_inkling2_fused_softcap_ce.py`: 5 of 6 fail before, 6 pass
after (CPU); 6 of 6 pass on a GPU.
- `tests/test_moe_bnb4bit_selective_dequant.py`,
`tests/test_inkling2_moe_experts.py`: new cases for the scratch cap.
- Fused loss, compiler, MoE selective dequant, keep-base and Inkling
suites: 233 passed, 51 skipped (base 225 / 51; the 8 extra are new).

## Determinism

On the real Mini split over two Kaggle T4s (torch 2.11), repeated runs
with these changes and the unsloth companion are bitwise identical (336
of 336 LoRA gradients, steps 1 to 3), as on the base. Against the base
the only difference is the fused CE rounding (1.6e-4 global relative on
the LoRA gradients).

## Not covered

- Real Inkling-2-Small weights.
danielhanchen added a commit that referenced this pull request Nov 23, 2026
## Summary

`Repo tests (CPU, rest)` fails on `main`:

```
tests/test_loader_compile_disable_preserve.py::test_partial_is_written_only_inside_the_helper
E   assert False
E    +  where False = all(<generator object test_partial_is_written_only_inside_the_helper.<locals>.<genexpr> ...>)
```

## Root cause

The Inkling 2 branch, not the guard. #18773 added
`_set_partial_compile_disable()` to `unsloth/models/loader.py` and
routed every branch that partly disables compile through it, with a
guard that no other code writes `"partial"`. The Inkling 2 branch from
#18812 / #18959 landed alongside it with its own direct write:

```python
if os.environ.get("UNSLOTH_COMPILE_DISABLE", "0") == "0":
    os.environ["UNSLOTH_COMPILE_DISABLE"] = "partial"
```

Besides tripping the guard, that write keeps a value like `true` or
`yes` as it is, and unsloth_zoo only reads `"1"` and `"partial"` as off,
so `UNSLOTH_COMPILE_DISABLE=true` left Inkling 2 compiled. The helper
turns `1` / `true` / `yes` into `"1"` and everything else into
`"partial"`.

## Fix

- `unsloth/models/loader.py`: the Inkling 2 branch calls
`_set_partial_compile_disable()`. Unset or `0` still becomes `partial`,
and `1` still stays fully off.
- `tests/test_loader_compile_disable_preserve.py`: the helper-call count
goes from five branches to six, with Inkling 2 named.

## Testing

- `tests/test_loader_compile_disable_preserve.py` and
`tests/test_inkling2*.py`: 23 passed, 3 skipped.
- With `main`'s `loader.py`, the guard fails (both the direct write and
the helper count).
- Helper mapping checked directly: unset, `0`, `false` -> `partial`;
`1`, `true` -> `1`; `partial` -> `partial`.
danielhanchen added a commit to danielhanchen/unsloth-staging-2 that referenced this pull request Nov 23, 2026
Inkling 2 merged 16-bit save and GGUF export were refused with
`NotImplementedError` (added on purpose in unslothai#18812). This adds a
dedicated merge so both work.

## Why the generic merge cannot work

The released checkpoint uses Inkling's own key names (`attn.wq_du`,
`controllers.*`) and stores the routed experts as NVFP4 / MXFP8. The
generic merge re-reads the original shards, cannot place any LoRA weight
on those keys, and would write the base model back unchanged.

## What this does

`save_inkling2_merged_16bit` (in `unsloth/models/inkling2.py`), used for
`save_method="merged_16bit"` and therefore by `save_pretrained_gguf`:
- walks the original shards and maps each key to its transformers name
with the model's own conversion mapping;
- dequantizes the experts with transformers'
`Inkling2LoopDequantizeExperts`;
- adds the LoRA deltas in float32 (gate_up deltas re-interleaved to the
checkpoint's layout);
- writes the checkpoint back in its original layout with bfloat16
experts and no quantization config, so transformers reloads it and
llama.cpp's Inkling 2 converter reads it.

`merged_4bit` still refuses.

## Tests

- `tests/test_inkling2_support.py`: updated plus a merge round-trip
test; 21 pass on CPU.
- Tiny fake model on CPU: merged weights equal base plus adapter (max
diff 0.016 against an adapter effect of 2.7); llama.cpp and transformers
give the same 12 greedy tokens.
- Tiny fake model, Unsloth 4-bit, Colab T4: merged weights match base
plus the saved adapter (0.049 against 1.60, 100% argmax agreement); a
`q8_0` GGUF export loads in llama.cpp.
- Real `thinkingmachines/Inkling-2-Mini` (20.19 GB, needed because merge
and GGUF output cannot be judged on random weights), Colab A100 40 GB,
10 training steps: merged save 1116 tensors / 52.78 GB with LoRA targets
changed and norms unchanged; `q4_k_m` GGUF 17.48 GB plus a 0.64 GB image
projector, export 1274 s; llama.cpp (CPU build) generates 6.2 tok/s and
answers the fibonacci prompt correctly.

## Not covered

- Kaggle 2x T4 cannot hold the GGUF export: it needs about 150 GB of
scratch disk and Kaggle's disk went read-only during the second 53 GB
write. The notebook points GGUF export to a Colab A100.
- llama.cpp ran on its CPU build only.
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