Skip to content

Add Inkling2 Mini - #51050

Merged
Cyrilvallez merged 70 commits into
mainfrom
add-inkling2-mini
Nov 21, 2026
Merged

Cyrilvallez merged 70 commits into
mainfrom
add-inkling2-mini

Conversation

@guarin

@guarin guarin commented Nov 20, 2026 •

Copy link
Copy Markdown
Member

🤗 Transformers CI

What does this PR do?

Adds Inkling2 Mini loop model: https://thinkingmachines.ai/news/inkling-2-mini/

Who can review?

cc @ArthurZucker @Cyrilvallez

@benthecarman

Copy link
Copy Markdown
Contributor

transformers PR #51050 (tested at 6173a2f)

Misleading quantization warning. Loading thinkingmachines/Inkling-2-Mini with
AutoModelForImageTextToText.from_pretrained(..., dtype=torch.bfloat16) prints:

Unknown quantization type, got modelopt - supported types are: [...]. Hence, we will
skip the quantization. To remove the warning, you can delete the quantization_config
attribute in config.json

The NVFP4/MXFP8 experts are in fact dequantized and the model generates correctly. Loaded
mlp.experts.down_proj against an independent decode of the stored w2_weight: relative
error 0.0025 at layer 0 (NVFP4) and 0 at layer 23 (MXFP8). The warning's advice to delete
quantization_config is therefore wrong for this checkpoint.

causal_conv1d not listed as an optional dependency. Without it, the first forward pass
prints:

`causal_conv1d_fn` is falling back to its reference PyTorch implementation because
`causal_conv1d` is not installed. This is correct but much slower; install
`causal_conv1d` for the optimized kernel.

The model doc (docs/source/en/model_doc/inkling2_loop.md) does not mention the package.

Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
`inkling2_loop` now registers its own config and conditional-generation class
with `AutoConfig` / `AutoModelForMultimodalLM`, so a released Inkling 2 Mini
checkpoint resolves without `huggingface/transformers#51050` on the installed
release. A native implementation still wins when Transformers ships one: the
config is only registered when `CONFIG_MAPPING` has no `inkling2_loop` entry.

The vendored copy needed four compatibility fixes to run on 5.23 as well as on
the 5.24 API it was written against:

* the mask builders' cache argument (`past_key_values` before 5.24, `cache`
  after) is resolved from the live signature instead of hardcoded;
* the shared `MoeModelOutputWithPast` cache field is read and written through
  the name the installed release defines;
* `MultimodalBaseModelOutputWithPast` / `MultimodalCausalLMOutputWithPast` were
  missing their `@dataclass` decorator, so their annotated fields were not
  dataclass fields and every constructor call raised;
* the two output dataclasses drop `@auto_docstring`, which only exists to check
  public docstrings and logged an error per field.

tests/module_tree/test_inkling2_loop_plan.py now imports the vendored modules
and builds the real model class from a tiny config for all four decoder layer
variants: 10 passed, 0 skipped. The real config also builds through
`AutoModelForMultimodalLM.from_config` (26.39 B parameters) on the meta device.
Qubitium added a commit to ModelCloud/Defuser that referenced this pull request Nov 21, 2026
* feat: register inkling2_loop routed experts for defusion

Inkling 2 Mini keeps its routed experts as 3-D gate_up_proj/down_proj
parameters, so convert_model() returned False and downstream quantizers
silently left every expert in the source dtype. Register the native
Inkling2LoopExperts class with the linear_loop forward and cover it with
a real tiny-model defusion test that compares logits before and after.

The test skips with a precise reason unless transformers.models.inkling2_loop
is importable (open huggingface/transformers#51050).

* chore: bump version to 0.0.33
Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
Register `inkling2_loop` -> `Inkling2LoopQModel` for Thinking Machines'
Inkling 2 Mini. The checkpoint keeps four decoder layer classes
(sliding/full attention, each looped or not), gated attention outputs,
short-convolution and L2-clip children that stay in full precision, and
routed experts stored as 3-D parameters that Defuser expands per expert.

Cached decoder replay needs two model-specific hooks: the attention
residual bank (`block_states`, the second positional layer argument the
generic capture drops) is rebuilt per batch from the block-boundary layers
already replayed, and the sliding/full mask is rebuilt per layer with the
mask builder's cache keyword resolved from the live Transformers
signature (`past_key_values` before 5.24, `cache` after).

Covered by tests/module_tree/test_inkling2_loop_plan.py, which builds the
real model class from a tiny config for all four layer variants, checks
checkpoint weight owners against the compiled plan, and compares replay
against the native forward. The real-model cases skip with a precise
reason unless transformers.models.inkling2_loop exists (open
huggingface/transformers#51050); the registry contract always runs.
Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
`inkling2_loop` now registers its own config and conditional-generation class
with `AutoConfig` / `AutoModelForMultimodalLM`, so a released Inkling 2 Mini
checkpoint resolves without `huggingface/transformers#51050` on the installed
release. A native implementation still wins when Transformers ships one: the
config is only registered when `CONFIG_MAPPING` has no `inkling2_loop` entry.

The vendored copy needed four compatibility fixes to run on 5.23 as well as on
the 5.24 API it was written against:

* the mask builders' cache argument (`past_key_values` before 5.24, `cache`
  after) is resolved from the live signature instead of hardcoded;
* the shared `MoeModelOutputWithPast` cache field is read and written through
  the name the installed release defines;
* `MultimodalBaseModelOutputWithPast` / `MultimodalCausalLMOutputWithPast` were
  missing their `@dataclass` decorator, so their annotated fields were not
  dataclass fields and every constructor call raised;
* the two output dataclasses drop `@auto_docstring`, which only exists to check
  public docstrings and logged an error per field.

tests/module_tree/test_inkling2_loop_plan.py now imports the vendored modules
and builds the real model class from a tiny config for all four decoder layer
variants: 10 passed, 0 skipped. The real config also builds through
`AutoModelForMultimodalLM.from_config` (26.39 B parameters) on the meta device.
@github-actions

Copy link
Copy Markdown
Contributor

[For maintainers] Suggested jobs to run (before merge)

run-slow: auto, inkling2, inkling2_loop, finegrained_fp8

@guarin

guarin commented Nov 21, 2026

Copy link
Copy Markdown
Member Author

Misleading quantization warning. Loading thinkingmachines/Inkling-2-Mini with AutoModelForImageTextToText.from_pretrained(..., dtype=torch.bfloat16) prints:

Unknown quantization type, got modelopt - supported types are: [...]. Hence, we will
skip the quantization. To remove the warning, you can delete the quantization_config
attribute in config.json

This is expected for now, we'll soon release support for loading the quantized model. The warning can be ignored for now as the model is dequantized on load.

Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
* feat(models): add Inkling 2 Mini (inkling2_loop) support

Register `inkling2_loop` -> `Inkling2LoopQModel` for Thinking Machines'
Inkling 2 Mini. The checkpoint keeps four decoder layer classes
(sliding/full attention, each looped or not), gated attention outputs,
short-convolution and L2-clip children that stay in full precision, and
routed experts stored as 3-D parameters that Defuser expands per expert.

Cached decoder replay needs two model-specific hooks: the attention
residual bank (`block_states`, the second positional layer argument the
generic capture drops) is rebuilt per batch from the block-boundary layers
already replayed, and the sliding/full mask is rebuilt per layer with the
mask builder's cache keyword resolved from the live Transformers
signature (`past_key_values` before 5.24, `cache` after).

Covered by tests/module_tree/test_inkling2_loop_plan.py, which builds the
real model class from a tiny config for all four layer variants, checks
checkpoint weight owners against the compiled plan, and compares replay
against the native forward. The real-model cases skip with a precise
reason unless transformers.models.inkling2_loop exists (open
huggingface/transformers#51050); the registry contract always runs.

* feat(kernels): fused-decode W4A16/W8A16 Triton GEMMs for NVFP4 and MXFP8

Inkling 2 Mini ships its routed experts as NVFP4 (layers 0-19) and MXFP8
(20-23) 3-D parameters. Decoding them to BF16 costs ~49 GB for the expert
stack alone, and the Marlin path cannot read the checkpoint's NVFP4 layout:
`dequant_fp8_scales` pairs two adjacent groups into one 16-bit slot and
selects the pair from a per-warp row parity that is constant for these tile
shapes, so every odd group reads zero (measured: 0.535 agreement against an
FP64 oracle on a real expert, exactly 8 of every 16 columns).

Both formats instead get a Triton GEMM that decodes the weight tile inside
the K loop and never materializes a dense matrix:

* `nvfp4_w4a16_linear`: value = e2m1(code) * e4m3(block_scale) * global_scale,
  two codes per byte with the even column in the low nibble, one E4M3 scale
  per 16 contiguous columns, one FP32 scale per tensor.
* `mxfp8_w8a16_linear`: value = e4m3(byte) * 2 ** (e8m0 - 127), one E8M0
  scale per 32 columns.

Activations stay in the model dtype and the dot accumulates in FP32, so the
kernels need only a plain BF16/FP16 `tl.dot` -- no `tl.dot_scaled`, no SM100
or SM120 gate, no CUTLASS, no Marlin permutation, no HF Transformers. The
E4M3 block scale is applied to the decoded tile and the FP32 global scale to
the accumulator, so each weight is rounded once and each output once.

tests/kernels/test_nvfp4_w4a16.py pins the decode against an FP64 oracle on
the real expert shapes with a distinct E4M3 scale per 16-wide group: an
identity probe recovers the decoded BF16 weight bit-exactly, so the nibble
order, the group width and the scale grid are all checked rather than
inferred. Uniform scales are kept only as the degenerate case; they hide a
wrong-group read, which is how the Marlin defect stayed invisible.

Measured on the released checkpoint (expert 0, both projections, both
formats): 1.66e-3 Frobenius against an FP64 oracle, the same resolution as
torch's own BF16 GEMM (2.9e-3) and strictly closer.

* feat(models): load inkling2_loop from the vendored architecture

`inkling2_loop` now registers its own config and conditional-generation class
with `AutoConfig` / `AutoModelForMultimodalLM`, so a released Inkling 2 Mini
checkpoint resolves without `huggingface/transformers#51050` on the installed
release. A native implementation still wins when Transformers ships one: the
config is only registered when `CONFIG_MAPPING` has no `inkling2_loop` entry.

The vendored copy needed four compatibility fixes to run on 5.23 as well as on
the 5.24 API it was written against:

* the mask builders' cache argument (`past_key_values` before 5.24, `cache`
  after) is resolved from the live signature instead of hardcoded;
* the shared `MoeModelOutputWithPast` cache field is read and written through
  the name the installed release defines;
* `MultimodalBaseModelOutputWithPast` / `MultimodalCausalLMOutputWithPast` were
  missing their `@dataclass` decorator, so their annotated fields were not
  dataclass fields and every constructor call raised;
* the two output dataclasses drop `@auto_docstring`, which only exists to check
  public docstrings and logged an error per field.

tests/module_tree/test_inkling2_loop_plan.py now imports the vendored modules
and builds the real model class from a tiny config for all four decoder layer
variants: 10 passed, 0 skipped. The real config also builds through
`AutoModelForMultimodalLM.from_config` (26.39 B parameters) on the meta device.

* chore(inkling2_loop): sort imports and record the load-path gap

The definition docstring claimed Transformers converts the packed experts
while loading. It does not on the installed release: the installed
`inkling2_text` conversion mapping has 28 entries and lacks the attention
renames the released checkpoint needs (`.attn.` -> `.self_attn.`,
`wq_du` -> `q_proj.linear`, `wo_ud`, `wk_dv`, `wv_dv`, `gate_attn`,
`rel_logits_proj`, `q_l2_clip`, ...), so every checkpoint key is unmatched.

Measured on the released checkpoint with this branch: 26.39 B parameters
loaded, 74 parameter groups MISSING and every checkpoint key UNEXPECTED.
The architecture and the NVFP4/MXFP8 decode kernels are ready; the
conversion mapping and the packed-expert decode hook are not, and the
docstring now says so instead of implying the load already works.

* feat(models): clean-room Inkling 2 Mini port with packed NVFP4/MXFP8 experts

Replace the vendored Transformers copy with an implementation derived from the
released checkpoint layout and the architecture description. The HF banner,
Apache header, generated-file warning and the 5.23 compatibility shims are gone;
`gptqmodel/hf_inkling2_loop/` is deleted.

* configuration: text/vision/wrapper configs, loop config unpack, expert format
  manifest (`nvfp4` on layers 0-19, `mxfp8` on 20-23).
* modeling: four decoder layer classes (sliding/full x plain/looped), block-state
  bank, message gates, short/dynamic convs, attention sinks and relative-position
  bias, sparse MoE router, loop passes with cache offsets.
* experts: dense 3-D container for Defuser, plus `Inkling2LoopPackedExperts` that
  keeps the checkpoint payload in NVFP4/MXFP8 and decodes inside the fused
  W*A16 Triton GEMM; `dequantize()` remains as the CPU path and oracle.
* conversion: pure-rename mapping (incl. the layer+1 attention-residual query
  shift) registered for the wrapper, text, causal-LM and multimodal classes.

Real checkpoint: 1244/1244 tensors loaded, 0 missing, 0 unexpected, 17.6 B
params, 24 packed layers. Forward is finite on CPU and CUDA (18.2 GiB bf16).
Fused kernels match an FP32 oracle at 1.66e-3 rel. Frobenius on layers 0 and 20.

Defuser requirement is 0.0.33 (ModelCloud/Defuser#76), the release that knows
the Inkling 2 Mini expert container.

* fix(inkling2_loop): keep packed-expert storage dtypes on reload

- Loader: a module can declare `CHECKPOINT_EXACT_DTYPE_PARAMETERS`. Those
  parameters keep the checkpoint dtype on a normal load instead of following
  Accelerate's model-dtype cast. `Inkling2LoopPackedExperts` declares its
  packed payload, block scales and FP32 global scales, so save/reload no
  longer narrows 128 storage tensors to bf16 (state_dict now matches the
  safetensors file: 1604 keys, 0 mismatched).
- Conversion: spell out the four `*_message_gate.down_weight` renames. The
  runtime->checkpoint walker strips non-capturing groups from a source
  pattern, so the previous alternation never produced a reverse target and
  the message-gate `down_proj` weights stayed on the meta device
  (1244/1244 runtime tensors now resolve).
- Vision: keep the rotary config so the loader can rebuild the
  non-persistent `inv_freq` buffer instead of leaving the tower on meta.
- NF12: clone a weight out of inference mode when its version counter is
  disabled and views are illegal.
- Tests: declared storage parameters keep the checkpoint dtype; the Inkling
  reverse map covers message gates, packed experts, vision and the
  `attn_queries` layer shift.

* fix(load): exempt declared storage parameters from the dtype guard

`assert_loaded_model_state` holds every floating parameter to the requested
model dtype. The packed-expert payload and scale parameters now keep their
checkpoint dtype (float8/uint8/float32), so a real Inkling 2 Mini load was
rejected as "mixed dtypes" even though the model was correct.

Exclude parameters a module declares in `CHECKPOINT_EXACT_DTYPE_PARAMETERS`
from the dtype checks (they are still checked for meta materialization), and
cover the rule plus its two failure modes with tests.

* feat(inkling2_loop): defuse packed experts and re-quantize on W4A16 kernels

A checkpoint whose routed experts are already NVFP4/MXFP8 is re-quantized,
never passed through:

- `Inkling2LoopPackedExperts.defuse()` splits the fused 3-D payload into one
  real `nn.Linear` per expert and projection as views (no copy, no decode), so
  every expert gets its own calibration/Hessian capture. `refuse()` re-fuses a
  layer the plan skipped, keeping its packed declaration and storage.
- `Inkling2LoopPackedExpertLinear` keeps the packed payload for the forward:
  calibration runs `nvfp4_w4a16_linear`/`mxfp8_w8a16_linear` (bf16
  activations, decode inside the K loop) and falls back to a full dequant only
  where no fused kernel exists. The fully dequantized bf16 weight is
  materialized on first `weight` access, i.e. when a quantization processor
  starts packing that module.
- Planning reads declared geometry instead of `weight`, and the hook pass
  leaves packed-source linears on their kernel forward.
- `after_quantize()` rewrites `experts_formats` to the storage the save will
  really hold, so a reload builds per-expert linears instead of the packed
  container.

* fix(inkling2_loop): reverse the checkpoint mapping into clean save keys

`save_pretrained` reverts the registered conversions. Swapping the two
pattern strings verbatim wrote keys such as `...embed.weight$` (the source
pattern's anchor) and crashed on `IndexShiftRename` (no `offset` in the
reversed copy). Every rename now reverses through its key template, mirroring
the anchor, and `IndexShiftRename` spells out its reverse patterns because the
reverse of a `\\1` template is not a regex.

* test(inkling2_loop): pin Defuser's no-op on packed expert payloads

* feat(refusion): enforce one quantization per fused container

Re-fusing defused modules rebuilds a single checkpoint tensor, so every
module that would be merged must carry the identical quantization
signature: format, bit width, block size, weight/scale dtypes and, for
kernel modules, bits/group_size/sym/desc_act/pack dtypes. A container is
also only rebuildable from its own packed payload, never from quantized
kernel modules, and its leaves must agree with the format it declares.

quantization_signature() derives that identity from what a module holds
(packed payload, kernel payload or dense weight) and assert_refusable()
enforces it before any tensor is created. Inkling2LoopPackedExperts.refuse()
now runs it first and declare_expert_storage() passes the layer path, so a
rejected layer names the container and the first disagreeing pair and stays
defused. Documented as contracts/model/refusion.md (R1-R3).
@Cyrilvallez
Cyrilvallez merged commit 046bdb8 into main Nov 21, 2026
9 of 11 checks passed
@Cyrilvallez
Cyrilvallez deleted the add-inkling2-mini branch November 21, 2026 12:07
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.

5 participants