Skip to content

Inkling 2: FlexAttention for the language attention (relative bias and sinks fused; L4 -15% per step) - #18943

Merged
danielhanchen merged 19 commits into
mainfrom
inkling2-flex
Nov 23, 2026
Merged

danielhanchen merged 19 commits into
mainfrom
inkling2-flex

Conversation

@danielhanchen

@danielhanchen danielhanchen commented Nov 22, 2026 •

Copy link
Copy Markdown
Member

Stacked on #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.

…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.
…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]
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.
… 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.
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]
…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.
…d sinks fused)

transformers 5.24 runs Inkling 2 eager only, so every layer builds the L x L scores, the gathered relative bias and the
additive mask. The flex path builds a BlockMask from the same transformers mask function (causal, the 1024 token sliding
window, packed documents, padding), adds the hidden-state conditioned relative bias in score_mod from the per-token
[B, L, H, rel_extent] table, and merges the per-token sink exactly from flex's log-sum-exp
(softmax([s, sink])[:-1] = softmax(s) * sigmoid(lse - sink)).

Default per GPU from Inkling-2-Mini QLoRA measurements: flex on sm80+ (L4: 15% faster step at 1024 tokens, same peak
memory), eager on T4 (flex 1.7x slower there). UNSLOTH_INKLING2_FLEX=0 / 1 forces eager / flex,
UNSLOTH_INKLING2_FLEX_MIN_LENGTH sets a length threshold. Decode steps keep eager. Models split over GPUs get per-card
mask closures, non-reentrant checkpointing recomputes flex in backward, and changed modeling code keeps eager.
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 22, 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-23T03:06:10.331915Z a757191 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: Didn't find any major issues. You're on a roll.

Reviewed commit: 1232670b02

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

Base automatically changed from inkling2-support to main November 22, 2026 21:24
@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@danielhanchen

Copy link
Copy Markdown
Member Author

@codex review

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@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: 4ebd3254b5

ℹ️ 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. Hooray!

Reviewed commit: b769cf83b4

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

…ile, eager on mixed cards

- A forward that collects attention maps (output_attentions from the call or the config) now builds eager masks,
  so every language layer returns its map again. Flex never forms the probabilities and returned an empty
  attentions tuple.
- torch.compile over the whole model (fullgraph or not) traces the stock eager attention: the text forward wrapper
  no longer sets its ContextVar inside the trace and the mask builder returns eager's mask inline there. The
  eager-only BlockMask builder is unchanged for Unsloth's compiled mask builders.
- auto takes flex only when every card holding the model qualifies. The mask picks flex from the embedding
  device, so an L4 + T4 split ran flex on the T4.
- A forced ROCm run compiles flex with dynamic = False, the configuration unsloth-zoo#2663 found clean on gfx1151.
- test_auto_policy sets torch.version.hip = None for its NVIDIA capability cases. On a ROCm build the real hip
  version made auto keep eager, so the sm80+ cases failed there.
- The fixture registers the by-path module in sys.modules while a test runs (monkeypatch, removed on teardown).
  Code dynamo compiles from it re-imports the module by name for its guards and raised
  ModuleNotFoundError: _unsloth_inkling2_flex on a gfx1151 host.

[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. Breezy!

Reviewed commit: a757191076

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

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