Skip to content

feat: register inkling2_loop routed experts for defusion - #76

Merged
Qubitium merged 2 commits into
mainfrom
feat/register-inkling2-loop
Nov 21, 2026
Merged

Qubitium merged 2 commits into
mainfrom
feat/register-inkling2-loop

Conversation

@Qubitium

Copy link
Copy Markdown
Contributor

Summary

Registers inkling2_loop (Thinking Machines Inkling 2 Mini) in MODEL_CONFIG with an EXPERTS_DEFUSE patch for Inkling2LoopExperts / linear_loop.

Without the entry, convert_model() returns False for the released checkpoint and every routed expert keeps its fused 3-D gate_up_proj / down_proj parameters, so downstream quantizers silently skip all experts (GPT-QModel's inkling2_loop definition raises rather than quantize a half-converted model, which is how this gap surfaced).

What the entry does

  • transformers.models.inkling2_loop.modeling_inkling2_loop.Inkling2LoopExperts → per-expert _ExpertContainer with gate_proj / up_proj / down_proj Linear modules.
  • forward_impl: linear_loop — the class already takes (hidden_states, top_k_index, top_k_weights), matching the fused MoE interface.

Tests

  • Added inkling2_loop to test_native_moe_model_types_are_registered.
  • New test_inkling2_loop_experts_defuse_preserves_forward: builds a real tiny Inkling2LoopForConditionalGeneration (4 layers, 3 experts, top-2, loop core), asserts the fused 3-D experts exist before conversion, converts, asserts every layer expanded into per-expert nn.Linear gate/up/down with no gate_up_proj left, and compares logits before/after with atol=1e-6.
  • The model class only exists on the open huggingface/transformers#51050 branch, so the real-model test uses pytest.importorskip with a precise reason; the registration assertion always runs.
# with transformers#51050 on PYTHONPATH
tests/test_convert_model.py -k inkling2_loop    -> 2 passed
# installed transformers 5.23.0 (no inkling2_loop)
tests/test_convert_model.py -k inkling2_loop    -> 1 passed, 1 skipped

tests/test_convert_model.py tests/test_candidate_coverage.py with transformers#51050: 90 passed, 12 failed. The same 12 cases fail identically on pristine main (b722cfd) with the installed Transformers — dbrx, deepseek_v3, dots1, glm4_moe_lite, glm4v_moe, glm_moe_dsa, solar_open, solar_open2, granitemoe, granitemoehybrid, granitemoeshared, test_qwen3_omni — so they are pre-existing and unrelated.

Notes

  • Verified against the real 19.5 GB checkpoint config (24 layers, 128 routed experts): all 24 .mlp.experts containers expand and the converted model produces identical logits to the fused module.
  • ruff check clean.

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).
@Qubitium

Copy link
Copy Markdown
Contributor Author

Companion GPT-QModel PR that consumes this entry: ModelCloud/GPTQModel#5962

@Qubitium
Qubitium merged commit 779e9d3 into main Nov 21, 2026
28 checks passed
@Qubitium
Qubitium deleted the feat/register-inkling2-loop branch November 21, 2026 04:04
Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
…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.
Qubitium added a commit to ModelCloud/GPTQModel that referenced this pull request Nov 21, 2026
…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.
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).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant