Skip to content

feat(models): add Inkling 2 Mini (inkling2_loop) support - #5962

Merged
Qubitium merged 11 commits into
mainfrom
feat/inkling2-loop-model-support
Nov 21, 2026
Merged

Qubitium merged 11 commits into
mainfrom
feat/inkling2-loop-model-support

Conversation

@Qubitium

@Qubitium Qubitium commented Nov 21, 2026 •

Copy link
Copy Markdown
Collaborator

Summary

Adds GPT-QModel support for Inkling 2 Mini (model_type: inkling2_loop, Inkling2LoopForConditionalGeneration) from the Thinking Machines release.

Model type inkling2_loop
Definition Inkling2LoopQModel
Loader AutoModelForMultimodalLM (text + image-to-text)
Checkpoint 26.4 B params, 24 layers, 128 routed experts
Expert formats NVFP4 (layers 0-19), MXFP8 (layers 20-23)

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/@strict scaffolding and no version-conditional compatibility layer. The earlier gptqmodel/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, plus Inkling2LoopPackedExperts.
  • conversion.py - checkpoint key mapping (pure renames plus the layer+1 shift of attn_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):

Loading weights: 100%|##########| 1244/1244
params: 17.6 B
packed layers: 24
logits (1, 8, 200058) finite: True absmax: 25.79 std: 5.82

0 missing, 0 unexpected, 0 mismatched, no random init. Counted from the loader's own LoadStateDictInfo, not from the absence of a report:

missing: 0 unexpected: 0 mismatched: 0 errors: 0
params: 17597906472
layers: 24 experts: 128 formats: ['mxfp8', 'nvfp4']
packed containers: 24
logits (1, 8, 200058) finite: True absmax: 25.7869

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:

  1. Attention renames. The exporter's projection names (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 for inkling2_loop.
  2. Packed experts. They land directly in 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

Inkling2LoopPackedExperts never dequantizes the checkpoint to bf16 for compute. Both projections go through the fused W*A16 Triton GEMMs in gptqmodel/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):

Layer Format Projection N x K rel. Frobenius
0 NVFP4 gate_up 2304 x 2304 1.665e-3
0 NVFP4 down 2304 x 1152 1.661e-3
20 MXFP8 gate_up 2304 x 2304 1.662e-3
20 MXFP8 down 2304 x 1152 1.662e-3

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_scales selects 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.py still 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:

state_dict=1604 file_keys=1604 mismatched=0 file_only=0

The packed experts needed one loader addition. Inkling2LoopPackedExperts declares CHECKPOINT_EXACT_DTYPE_PARAMETERS for its payload, block scales and FP32 amax/outer_scale factors, 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 real GPTQModel.load() of the released checkpoint was rejected as mixed dtypes even though the model was correct; it now returns params: 17,597,906,472, meta params: 0, packed containers: 24, finite logits (absmax 25.8517).

Quantization path

  • A checkpoint whose experts are already NVFP4/MXFP8 is re-quantized, not passed through. pre_quantize() materializes the layer and calls Inkling2LoopPackedExperts.defuse(), which 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.
  • Calibration therefore runs on the packed kernels: the leaf's forward() calls nvfp4_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 recorded kernel=7410, dense=0, dense_in_forward=0 during capture.
  • The quantization processor receives the fully dequantized bf16 weight: weight is 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() rewrites experts_formats to 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.
  • What Defuser actually touches on the released checkpoint: nothing. defuser.convert_model() returns True (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 88 Conv1d modules that carry 3-D parameters and skips every one (does not support @use_experts_implementation); inkling2_loop has no replace_module entry 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 by test_defuser_leaves_a_packed_checkpoint_payload_untouched.
  • Re-fusion is contract-checked (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 declared experts_formats entry raise RefusionContractError before 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 into refuse().
  • Only one fused projection exists in this architecture, so 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.linear and o_proj.gate_proj are two checkpoint tensors and stay two planned modules (subsets 1 and 2). The 88 3-D Conv1d.weight tensors (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.linear is declared in awq_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 ordinary nn.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):

[ref]      bf16 reference: finite, absmax 25.852
[load]     1.9 s (meta)
[quantize] 1222.7 s -> 9336 CPTCLinear (attention x 24 layers + 24 x 128 x 3 defused experts)
[modules]  cptc: 9336, packed containers: 24, defused: 24
[mem]      finite, absmax 26.102
[bf16 vs cptc] max_abs 29.23 rel_l2 0.6095 top1 0.625
[save]     25.1 s
[reload]   60.3 s, finite, absmax 25.587, rel_l2 0.6067 vs bf16 (in-memory was 0.6095)

The rel_l2 ~0.61 is 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 gives rel_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's experts_formats entry. 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):

[defused] [True, True]
[leaves]  ['TorchLinear', 'TorchLinear']
[saved formats] [None, None]        [manifest copied] False
[reload]  finite=True max_abs_diff=8.869e-04

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)"]
Loading

Two shapes reach the save, and the declaration follows the storage, not the other way round:

Layer outcome Storage at save experts_formats[i] Reload builds
Quantized per-expert QuantLinear/CPTCLinear None fused Inkling2LoopExperts -> Defuser -> per-expert linears
Skipped by the plan packed NVFP4/MXFP8 payload (re-fused) unchanged Inkling2LoopPackedExperts
Partially quantized mixed - rejected at after_quantize()

Tests

tests/kernels/test_nvfp4_w4a16.py                              -> 91 passed   (sm_89 and sm_120)
tests/kernels/test_marlin_mxfp8.py                             -> 62 passed   (unchanged)
tests/module_tree/test_registered_module_plans.py
tests/module_tree/test_fusable_models.py
tests/module_tree/test_inkling2_loop_plan.py                   -> 1008 passed
tests/test_cptc.py                                             -> 41 passed
tests/test_lazy_turtle_conversion_mapping.py                   -> 55 passed
tests/test_checkpoint_exact_dtype_parameters.py                -> 1 passed
tests/test_load_state_assertions.py                            -> 20 passed
tests/test_checkpoint_*dtype*.py                               -> 27 passed
tests/test_inkling2_loop_packed_requant.py                     -> 13 passed

test_inkling2_loop_plan.py builds 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.py covers 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-side experts_formats rewrite, and the reversed checkpoint mapping save_pretrained needs.

test_checkpoint_exact_dtype_parameters.py pins the loader rule (a declared storage parameter keeps the checkpoint dtype while an undeclared one follows the model dtype), and the reverse-map test in test_lazy_turtle_conversion_mapping.py resolves every Inkling runtime name, including the four message-gate down_weight renames, the vision tower and the packed-expert w13_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.
  • Fusion is intentionally unqualified for this module tree, recorded in tests/module_tree/fixtures/fusable_models.json and docs/fusion-model-coverage.md.

@Qubitium

Copy link
Copy Markdown
Collaborator Author

Companion Defuser PR (required for per-expert defusion of the routed experts): ModelCloud/Defuser#76

Comment thread gptqmodel/utils/nvfp4_triton.py Dismissed
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
Qubitium force-pushed the feat/inkling2-loop-model-support branch from 3bfa279 to a917625 Compare November 21, 2026 08:25
- 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
Qubitium force-pushed the feat/inkling2-loop-model-support branch from 62b7646 to 8cffb2a Compare November 21, 2026 08:34
…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).
@Qubitium
Qubitium merged commit 4682e21 into main Nov 21, 2026
8 checks passed
@Qubitium
Qubitium deleted the feat/inkling2-loop-model-support branch November 21, 2026 12:02
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