Repository navigation
Inkling 2: FlexAttention for the language attention (relative bias and sinks fused; L4 -15% per step) - #18943
Conversation
…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.
…e attention or experts [skip ci]
…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.
|
@codex review |
Codex Review Summary: ✅ CompletedThis 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. |
|
Codex Review: Didn't find any major issues. You're on a roll. 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". |
# Conflicts: # unsloth/models/vision.py
…at32 gradient is not NaN [skip ci]
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
@codex review |
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
|
@codex review |
|
Codex Review: Didn't find any major issues. 🚀 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". |
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! 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". |
…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]
|
@codex review |
|
Codex Review: Didn't find any major issues. Breezy! 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". |
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 fullL x Lscores, a gatheredL x Lrelative bias and anL x Ladditive 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):
with the sliding layers masked to
q - 1024 < k <= qand the global layers causal.rel_extentis 1024 on both layer types in the released configs.The flex path
score_modaddsrel_logits[b, q, h, q - kv]from the per-token[B, L, H, rel_extent]table (0 beyond the extent, as eager). TheL x Lbias is never built.softmax([s, sink])[:-1] = softmax(s) * sigmoid(lse - sink), with the gradient through flex'slse. Fully masked rows give 0, as eager does.L x Lint64 relative distance matrix is skipped when the masks are BlockMasks.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.UNSLOTH_INKLING2_FLEX=0keeps eager everywhere,=1forces 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=Noverrides 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_modandlseare checked directly. Lengths below, at and above the window and the extent; plain, padded and packed rows.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.
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=1still forces flex; decode stays eager.tests/test_inkling2_flex.pyon the ROCm host: 31 pass / 0 fail at a757191 (the previous head failed 16 there: 2 policy cases that lefttorch.version.hipset 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=Truereturns every map, equal to eager;UNSLOTH_INKLING2_FLEX=0keeps it off.