Repository navigation
feat(models): add Inkling 2 Mini (inkling2_loop) support - #5962
Merged
Merged
Conversation
Collaborator
Author
|
Companion Defuser PR (required for per-expert defusion of the routed experts): ModelCloud/Defuser#76 |
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.
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.
`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.
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.
…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
force-pushed
the
feat/inkling2-loop-model-support
branch
from
November 21, 2026 08:25
3bfa279 to
a917625
Compare
- 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.
`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.
Qubitium
force-pushed
the
feat/inkling2-loop-model-support
branch
from
November 21, 2026 08:34
62b7646 to
8cffb2a
Compare
…ernels 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.
`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.
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).
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Adds GPT-QModel support for Inkling 2 Mini (
model_type: inkling2_loop,Inkling2LoopForConditionalGeneration) from the Thinking Machines release.inkling2_loopInkling2LoopQModelAutoModelForMultimodalLM(text + image-to-text)Clean-room implementation
gptqmodel/models/inkling2_loop/is written against the released checkpoint's tensor layout and the architecture description. It contains no vendored Transformers file: no generated-file banner, no upstream copyright header, no@auto_docstring/@strictscaffolding and no version-conditional compatibility layer. The earliergptqmodel/hf_inkling2_loop/package is deleted, so nothing here depends on huggingface/transformers#51050.configuration.py- text/vision/wrapper configs, loop-config unpack, layer-type defaults, and the expert-format manifest (experts_formats) read from the checkpoint's quant config.modeling.py- four decoder classes (sliding/full attention x plain/looped), block-state bank, q/k/v/mlp message gates, static and hidden-state-conditioned short convolutions, per-head attention sinks, relative-position bias, sigmoid top-k router, sparse MoE, loop passes with cache offsets.vision.py- ViT tower with axial RoPE, layer scale, position-embedding taps and the merger.experts.py- dense 3-D container for Defuser, plusInkling2LoopPackedExperts.conversion.py- checkpoint key mapping (pure renames plus the layer+1 shift ofattn_res.attn_queries), registered for the wrapper, text, causal-LM and multimodal classes.Loading the released checkpoint
Measured on
/monster/data/model/Inkling-2-Mini(model-00001-of-00001.safetensors, 1244 tensors):0 missing, 0 unexpected, 0 mismatched, no random init. Counted from the loader's own
LoadStateDictInfo, not from the absence of a report:On CUDA (RTX 5090) the same checkpoint loads in 8.2 s at 18.23 GiB bf16 and produces finite logits (
absmax 25.23,std 5.72).The two conversion behaviours the generic loader cannot infer are handled here:
wq_du,wo_ud,wk_dv,wv_dv,gate_attn,rel_logits_proj,q_l2_clip,.attn.->.self_attn., ...) are mapped by rules registered from this package, so the installed Transformers mapping is not consulted forinkling2_loop.Inkling2LoopPackedExperts, which stores the checkpoint bytes, block scales and global scale as parameters - no decode hook, no per-expert materialization during load.Packed experts stay quantized
Inkling2LoopPackedExpertsnever dequantizes the checkpoint to bf16 for compute. Both projections go through the fused W*A16 Triton GEMMs ingptqmodel/utils/nvfp4_triton.py, which decode the weight tile inside the K loop:nvfp4_w4a16_linear-e2m1(code) * e4m3(block_scale) * global_scale, two codes per byte, one E4M3 scale per 16 contiguous columns, one FP32 scale per expert/tensor pair.mxfp8_w8a16_linear-e4m3(byte) * 2 ** (e8m0 - 127), one E8M0 scale per 32 columns.Activations stay in the model dtype, the dot accumulates in FP32. A 4-bit expert therefore keeps its 4-bit footprint for the whole forward.
dequantize()remains for CPU/pre-Ampere fallback and as the numerical oracle; it is not on the CUDA path.Accuracy on the real checkpoint against an FP32 oracle (256 tokens, expert 0):
End to end, the packed container and its own bf16
dequantize()oracle agree at 5.4e-3 (NVFP4) and 2.9e-4 (MXFP8) relative Frobenius, i.e. bf16 GEMM resolution.Why not Marlin
Marlin cannot read this checkpoint's NVFP4 layout:
dequant_fp8_scalesselects the group pair from a per-warp row parity that is constant for these tile shapes, so every odd group reads zero (0.535 agreement with an FP64 oracle, exactly the first 8 of every 16 columns). Marlin is left untouched, so its MXFP4/MXFP8 support is unchanged -tests/kernels/test_marlin_mxfp8.pystill reports 62 passed.Save / reload round trip
Every tensor the model materializes resolves to a checkpoint key (1244/1244), and a
save()->GPTQModel.load()round trip reproduces the file exactly:The packed experts needed one loader addition.
Inkling2LoopPackedExpertsdeclaresCHECKPOINT_EXACT_DTYPE_PARAMETERSfor its payload, block scales and FP32amax/outer_scalefactors, so Accelerate's model-dtype cast no longer narrows them to bf16. Without the declaration, 128 storage tensors came back as bf16 and the reloaded logits drifted (rel_l2 1.12); with it, the reloaded model's logits are identical to the in-memory model (max_abs=0,rel_l2=0, top1 1.000).The post-load dtype guard (
assert_loaded_model_state) now exempts declared storage parameters from its uniform-dtype check (they are still checked for meta materialization). Without that exemption a realGPTQModel.load()of the released checkpoint was rejected asmixed dtypeseven though the model was correct; it now returnsparams: 17,597,906,472,meta params: 0,packed containers: 24, finite logits (absmax 25.8517).Quantization path
pre_quantize()materializes the layer and callsInkling2LoopPackedExperts.defuse(), which splits the fused 3-D payload into one realnn.Linearper expert and projection as views - no copy, no decode - so every expert gets its own calibration/Hessian capture.forward()callsnvfp4_w4a16_linear/mxfp8_w8a16_linear, and only a device without a fused kernel falls back to a full bf16 dequant. On the real checkpoint, layer 0 experts 0-1 recordedkernel=7410, dense=0, dense_in_forward=0during capture.weightis materialized on first access, i.e. when a processor starts packing that module. Planning reads declared geometry and the hook pass leaves packed-source linears on their kernel forward, so nothing decodes early.after_quantize()rewritesexperts_formatsto the storage the save will really hold, so a reload builds per-expert linears instead of the packed container. A layer the plan skipped is re-fused (refuse()) and keeps both its packed declaration and its packed storage; a partially quantized layer is reported instead of being saved mixed.after_defuser_conversion()still validates the load-time layout: packed containers stay packed through Defuser, dense ones must be expanded.defuser.convert_model()returnsTrue(registry/version compatibility) in 0.0 s and leaves all 1220 parameters byte-identical - 0 added/removed, 0 shape/dtype/data_ptr/value changes, 0 module-class changes. It probes the 24 packed containers and the 88Conv1dmodules that carry 3-D parameters and skips every one (does not support @use_experts_implementation);inkling2_loophas noreplace_moduleentry and no runtime patch. Defusion of a packed checkpoint is therefore entirely ours (defuse_packed_experts()per layer). The dense container is decorated and is expanded by Defuser's generic pass - that asymmetry is pinned bytest_defuser_leaves_a_packed_checkpoint_payload_untouched.contracts/model/refusion.md, R1-R3).refuse()only merges modules whose quantization signature is identical - format, bit width, block size, weight/scale dtypes and, for kernel modules,bits/group_size/sym/desc_act/pack dtypes - and only from the container's own packed payload. A quantized leaf, a leaf from another format, or leaves that disagree with the declaredexperts_formatsentry raiseRefusionContractErrorbefore any tensor is created, naming the layer and the first disagreeing pair; the layer stays defused, so a mixed layer can never be saved.declare_expert_storage()passes the layer path intorefuse().refuse()is the only re-fusion the save path needs. Checkpoint inventory:w13_weight/w2_weight(fused gate+up and down, per expert) inside the routed-expert container; everything else is already separate -wq_du/wk_dv/wv_dv/wo_ud/gate_attn,attn_sconv/mlp_sconv,wr_du,attn_sink_proj,q_l2_clip/rel_l2_clip. There is no fused QKV and no fused gated output:o_proj.linearando_proj.gate_projare two checkpoint tensors and stay two planned modules (subsets 1 and 2). The 88 3-DConv1d.weighttensors (48 x(2304, 1, 4), 40 x(1024, 1, 4), fp32) are plain depthwise conv layout, not fusions, and are:!-excluded from the plan.AWQ policy.
self_attn.o_proj.linearis declared inawq_scale_optimize_shape_dependent_modules: it consumes the concatenated attention heads, whose width differs from the key/value projections under GQA. Defused expert leaves are ordinarynn.Linears and use the standard grouping.CPTC end-to-end (calibration-free, real checkpoint)
CPTCConfig(bits=4, trellis_depth=16, table_q=6, block_size=128)on the released checkpoint (RTX 4090):The
rel_l2 ~0.61is 4-bit CPTC applied to an already 4-bit checkpoint with a two-sentence calibration set; the same config on Qwen2.5-0.5B-Instruct givesrel_l2 0.65. The reload figure is the same model read back from disk, which is the check that matters here.Save / reload after re-quantization
A defused layer holds per-expert quantized linears, so
after_quantize()clears that layer'sexperts_formatsentry. Without it the reload builds the packed container again and the quantized tensors have nowhere to land (... does not provide tensors for 176 non-quantized parameter(s): ...experts.gate_up_weight). With it,save()->GPTQModel.load()rebuilds per-expert linears through Defuser and reproduces the in-memory logits.Verified end to end on a tiny Inkling checkpoint (same architecture, tokenizer and config fields, random weights):
Re-quantization flow (defuse -> quantize -> refuse/declare)
flowchart TD A["quantize(): per decoder layer"] --> B["pre_quantize(module, module_path)"] B --> B1["super(): materialize lazy shell (meta -> device)"] B1 --> C["defuse_packed_experts(module)"] C --> C1{"Inkling2LoopPackedExperts?"} C1 -- no --> Z1["leave the layer as it is"] C1 -- yes --> C2["defuse(): per expert i, views of gate_up_weight[i][:I], [I:], down_weight[i]"] C2 --> C3["leaves: Inkling2LoopPackedExpertLinear (real nn.Linear, _packed_source_linear)"] C3 --> C4["stash _fused_factors, drop fused params (views keep storage), _defused = True"] C4 --> D["plan + hooks: find_modules sees leaves; geometry from in/out_features; _replace_module skips them"] D --> E{"layer in the quantization plan?"} E -- yes --> F["capture / Hessian: experts.forward -> leaf.forward"] F --> F1{"fused W*A16 kernel available?"} F1 -- yes --> F2["nvfp4_w4a16_linear / mxfp8_w8a16_linear: decode inside the K loop, no dense weight"] F1 -- no --> F3["dequantize_weight(): transient bf16 (fallback only)"] F2 --> G["processor starts packing"] F3 --> G G --> G1["layer.weight -> __getattr__ -> _materialize_dense_weight() -> dequantize_weight() -> bf16"] G1 --> G2["pack -> QuantLinear / CPTCLinear replaces the leaf"] G2 --> H["after_quantize() -> declare_expert_storage(model)"] E -- no --> H H --> H1{"any Inkling2LoopPackedExpertLinear left under *.mlp.experts?"} H1 -- no --> H2["experts_formats[i] = None"] H1 -- yes --> H3["refuse()"] H3 --> H4{"all 3 projections of every expert still packed?"} H4 -- no --> H5["RuntimeError: quantize every projection of a layer or none"] H4 -- yes --> H6["cat gate/up, stack down, restore amax/outer, drop leaves, _defused = False"] H6 --> H7["experts_formats[i] unchanged (packed declaration kept)"] H2 --> S["save(): config.json + quantize_config.json + shards"] H7 --> S S --> R["reload: build_experts(experts_formats[i])"] R --> R1{"experts_formats[i]"} R1 -- None --> R2["Inkling2LoopExperts (fused 3-D) -> Defuser generic pass -> _ExpertContainer(i).gate/up/down -> QuantLinear + qweight/qzeros/scales"] R1 -- nvfp4/mxfp8 --> R3["Inkling2LoopPackedExperts (payload + block scales + amax/outer, exact dtypes)"]Two shapes reach the save, and the declaration follows the storage, not the other way round:
experts_formats[i]QuantLinear/CPTCLinearNoneInkling2LoopExperts-> Defuser -> per-expert linearsInkling2LoopPackedExpertsafter_quantize()Tests
test_inkling2_loop_plan.pybuilds all four layer variants from a tiny config, runs the normal Defuser conversion, checks declared paths/roles/MoE families and checkpoint weight owners, and compares replay against the native forward.test_inkling2_loop_packed_requant.pycovers defusion without decoding, the kernel forward and its deferred dense weight, the no-kernel fallback, re-fusion, the refusion contract (different format, quantized leaf, declaration mismatch, partially quantized layer), Defuser leaving a packed payload untouched, the save-sideexperts_formatsrewrite, and the reversed checkpoint mappingsave_pretrainedneeds.test_checkpoint_exact_dtype_parameters.pypins the loader rule (a declared storage parameter keeps the checkpoint dtype while an undeclared one follows the model dtype), and the reverse-map test intest_lazy_turtle_conversion_mapping.pyresolves every Inkling runtime name, including the four message-gatedown_weightrenames, the vision tower and the packed-expertw13_weight.Dependency
defuser>=0.0.33(feat: register inkling2_loop routed experts for defusion Defuser#76), the release that knows the Inkling 2 Mini expert container. The merged Defuser PR is already on PyPI.tests/module_tree/fixtures/fusable_models.jsonanddocs/fusion-model-coverage.md.