← Back to Pull requests

feat(inkling2): add Inkling-2-Small training support #4751

Open
unknown opened this pull request with 650 lines diff across 8 files
View on GitHub
unknown unknown commented on Nov 13, 2026 02:41 UTC
Author

What does this PR do ?

Adds training support for thinkingmachines/Inkling-2-Small (594B total, 17B active, text and image MoE) in a new components/models/inkling2/ package: the model, loading the released NVFP4/MXFP8 checkpoint, expert parallelism with HybridEP, MedPix SFT and LoRA recipes, and DSpark training of a drafter in the released mtp.safetensors layout.

  • Config, registry and text model: relative-position attention with L2-clipped q/k/rel heads, value norm, output gate and sinks, short convolutions (dynamic ones on the global layers), FP32 block attention residuals, biased sigmoid router with softcapped SwiGLU experts, final logit softcap

  • Vision tower, projector and processor

  • Released checkpoint: NVFP4 (layers 0-39) and MXFP8 (layers 40-47) experts dequantized to BF16 on load through the base-checkpoint path, BF16 export

  • Drafter in the released mtp.safetensors layout, trained through the DSpark recipe from a fresh draft (starting from the released weights uses draft_weights_path from #4725)

  • EP over the 384 experts (torch, DeepEP/HybridEP dispatch; torch_mm or TE grouped experts) with FSDP2

  • MedPix SFT and LoRA recipes for H100, added to the model page
  • Changelog

  • inkling2/configuration.py: Inkling2TextConfig, Inkling2VisionConfig, Inkling2Config, same field names and aliases as the transformers inkling2 config, so the released config.json loads with transformers 5.18. layer_types comes from local_layer_ids when absent. get_config_dict reads the hf_quant_config.json beside the selected config.json (same revision and subfolder) and sets quantization_config, so the base-checkpoint load dequantizes the experts; a BF16 export has no such file and loads as is.

  • inkling2/text.py: sliding and global attention, short convolutions, block attention residuals, decoder layers, text model. eager and sdpa attention (default sdpa); the sink is an extra key slot whose mask value is the sink logit. The FP32 parts stay FP32 under autocast. Rows whose position_ids restart (packed documents) raise.

  • inkling2/layers.py: Inkling2MoE on the existing MoE layer and Gate (sigmoid_with_bias, FP32 routing, weight applied after the down projection), with the softcapped SwiGLU as the expert activation hook on GroupedExperts, GroupedExpertsDeepEP and GroupedExpertsTE.

  • inkling2/vision.py, processing.py, image_processing.py: ViT, merger and processor. The processor loads with Inkling2Processor.from_pretrained, since 5.18's auto classes don't know it.

  • inkling2/quantization.py: dequantize_nvfp4_experts (E2M1 codes x E4M3 block scales x amax / denominator, one rounding) and dequantize_mxfp8_experts (E4M3 x UE8M0 per row and 32 columns), chunked over experts; parsing of hf_quant_config.json.

  • inkling2/state_dict_adapter.py: released model.llm. / model.visual. layout to native names and back, quantized placeholders for the DCP load path (sharded experts included), BF16 export under the released key names. Experts keep the released gate/up interleaved order. LoRA adapter tensors (base_model.model.*) keep their native names and layouts on save and resume.

  • inkling2/model.py, inkling2/multimodal.py: Inkling2ForConditionalGeneration; lm_head with FP32 output, softcap 30, logits cut to the 200058 real tokens. Declares EP support; TP, CP and PP are declared unsupported.

  • inkling2/parallelization.py: puts the final residual query in its own FP32 FSDP unit (FSDP2 needs one dtype per unit).

  • inkling2/dspark.py, inkling2/dspark_target.py: the released drafter (8-slot blocks with the normalized anchor embedding and mask_embed, 7 proposals per block, per-layer softmax mix of 8 target features, separate context k/v projections, window anchored at the block start, rnn_hidden Markov head) with parameter names equal to the released mtp.safetensors tensors, so the adapter loads and exports all 84 of them, and the frozen target on the EP mesh. The recipe starts the draft from a fresh initialization.

  • speculative/dspark/registry.py, recipes/speculative_decoding/train_dspark.py, _dspark_target_build.py: a target config can provide its own build_dspark_target; composite configs take their text fields from get_text_config(); the full-weight gather also covers child modules, so a sharded target keeps its embedding norm. The target check follows the existing ModelOwnedDSparkProvider check in the same recipe. No model names in shared code.

  • _transformers/registry.py: Inkling2ForConditionalGeneration in MODEL_ARCH_MAPPING, inkling2 in _CUSTOM_CONFIG_REGISTRATIONS. _transformers/model_init.py: the registered-config lookup reads through a config class's own get_config_dict when it defines one.

  • datasets/vlm/collate_fns.py: Inkling2Processor takes the Inkling label path, so answers are labeled through <|content_model_end_sampling|>. The generic path stops at <|end_message|>.

  • Recipes examples/vlm_finetune/inkling2/inkling2_small_medpix_sft_ep128.yaml (16x8 H100, EP128) and inkling2_small_medpix_lora_ep32.yaml (4x8 H100, EP32, rank 8 on q/k/v/o and every routed expert), both FSDP2 with HybridEP and torch_mm experts; examples/speculative/dspark/inkling2_small_dspark.yaml.

  • Docs: the H100 MedPix recipes and the DSpark recipe go on the Inkling-2-Small page (inkling2.mdx), whose note now says which recipes run with this implementation; an Inkling 2 section in docs/guides/speculative/dspark.mdx.

  • Tests in tests/unit_tests/models/inkling2/, tests/unit_tests/recipes/test_inkling2_recipes.py, a 2-GPU test tests/functional_tests/models/inkling2/test_inkling2_expert_dispatch.py, and parity scripts parity_check_inkling2{,_vision,_processing}.py against the HF reference.
  • Code provenance

  • Source URL, immutable revision, and original file(s): https://github.com/huggingface/transformers/pull/50682 at 109a7d19bf667168837f32929e00b791e195d14d: src/transformers/models/inkling2/{configuration,modeling,image_processing,processing}_inkling2.py, src/transformers/conversion_mapping.py, src/transformers/core_model_loading.py

  • Files in this PR containing copied or adapted code: nemo_automodel/components/models/inkling2/{configuration,text,layers,model,multimodal,vision,processing,image_processing,state_dict_adapter}.py

  • Applicable license(s): Apache-2.0

  • Required copyright notices and attribution, and where they are retained or added: each file above keeps the upstream file's copyright line with source, revision and original file, in a comment block under the NVIDIA header. That is "Copyright 2026 the HuggingFace Team. All rights reserved." for the model files, and "Copyright (C) 2025 the HuggingFace Inc. team. All rights reserved." in state_dict_adapter.py (from conversion_mapping.py and core_model_loading.py)
  • inkling2/dspark.py copies no code. Its arithmetic is written from the serving code of lightseekorg/tokenspeed#3371 (c485a46a, inkling2_mtp.py, execution/drafter/inkling2.py) and vllm-project/vllm#67325, which its docstring names.

    Before your PR is "Ready for review"

    Pre checks:

  • Make sure you read and followed Contributor guidelines

  • Did you write any new necessary tests?

  • Did you add or update any necessary documentation?
  • Additional Information

    No issue for this. Inkling v1 code is unchanged.

    #4752 added the Inkling-2-Small page and three GB200 recipes for the implementation in #4755 (draft), which also adds Inkling 2 training support. Both implementations load the released NVFP4/MXFP8 experts and have MedPix recipes. This one also trains a drafter in the released layout through DSpark and checks parity against the transformers reference; #4755 also covers pipeline and context parallelism, packed sequences, flex attention and a fused cross-entropy loss.

    The reference is the HF implementation from huggingface/transformers#50682 (109a7d19bf), not in a release yet. The pin stays at 5.18.0; the reference was installed separately for the parity scripts.

    Parity, CPU. Tiny 7-layer config (sliding and global layers, block boundaries at 0 and 6), one row left-padded, small clip and softcap thresholds so every nonlinearity is active. HF loads the raw checkpoint our adapter writes, so its own key conversion runs too. Router top-k picks are compared per layer.

    | | logits max abs (ref max 0.5) | worst grad rel | router top-k mismatches |
    |---|---|---|---|
    | text, FP32, eager and sdpa | 3.2e-06 | 4.2e-06 | 0 |
    | image + text, FP32, eager and sdpa | 2.8e-06 | 4.7e-06 | 0 |
    | text and image + text, BF16, eager | 0 (bitwise) | | 0 |
    | text and image + text, BF16, sdpa vs HF eager | 0.98 | | 28 / 21 |

    Grad rel is the max abs gradient difference over the reference's max gradient in that parameter group. HF has no sdpa path for this model, so BF16 sdpa is compared with HF eager. The fused kernel sums in a different order, and in this tiny random model the small differences flip router picks, which then move logits a lot.

    Real weights, CPU, read by shard.

    | Check | Result |
    |---|---|
    | Vision tower, 2 images (960x686 and 333x217) in one batch, FP32, vs HF | pooler_output [486, 4608] bitwise equal |
    | Processor vs HF processor, released tokenizer and chat template | 22 of 22 tensors equal |
    | NVFP4 experts, layer 0, 64 of 384 experts, vs TokenSpeed's block decode x amax / denominator (the outer term the SkyRL and miles loaders use) | bitwise equal |
    | MXFP8 experts, layer 47, 64 of 384 experts, vs transformers Fp8Dequantize | bitwise equal |
    | Checkpointer.load_base_model on a one-layer release cut (layer 0, NVFP4), 1 process and 2 ranks with EP | 448 of 448 params bitwise equal to the checkpoint, experts equal to a direct decode |
    | Same with layer 47 (global, MXFP8) as layer 0 | 452 of 452 params bitwise equal |
    | BF16 export, then reload | identical |
    | Drafter: mtp.safetensors into the draft | 84 of 84 tensors, same shapes and values |

    EP and FSDP2, 2x H100, tiny model.

    | Check | Result |
    |---|---|
    | EP2 + FSDP2 (torch dispatcher) vs 1 GPU, FP32 | grad rel-L2 max 1.1e-6, loss diff 4.8e-7 |
    | Experts with exactly representable inputs: torch, HybridEP + torch_mm, HybridEP + TE vs an FP64 reference | outputs and all four grads bitwise equal |
    | BF16, distance to the FP32 run (median per-tensor rel-L2) | torch dispatcher 0.122, HybridEP 0.117 |
    | TE vs torch_mm experts, activation checkpointing on vs off | bitwise equal |

    HybridEP combine takes 16-bit tokens only, so it has no FP32 run.

    Real weights through the SFT recipe, 2x H100. Layers 0 (sliding, NVFP4 experts) and 5 (global) of the release as a 2-layer model, the real vision tower, MedPix, EP2 with HybridEP and torch_mm, SGD, 6 steps. Load reports no missing or unexpected keys, and the checked tensors equal the checkpoint. Loss 17.7, 19.4, 21.3, 19.2, 19.5, 18.4 (2 of 48 layers, so high). 0.31 s per step after the first, 57.4 GiB peak. 99-221 image tokens per step reach the model. With TE grouped experts the same cut runs out of memory at load on EP2, since TE's state_dict stacks a copy of the 192 local experts; the recipes use torch_mm.

    One layer at release dims, EP2, 4096 tokens (measured on e9b7bf9ed, before the autocast guards; this path runs without autocast, so they don't change it): 0.45-0.64 s per step with the 200k-vocab head and the optimizer, 65-68 GiB peak. Per forward, attention takes about 26 ms (the relative bias is a dense mask), experts 11 ms, block residuals 6.7 ms, dispatch and combine 2-4 ms.

    Drafter, CPU. FP32 forward and backward vs an FP64 per-block reference written from the serving math, random weights: logits 6.4e-7, grads up to 4.9e-6 abs (1.3e-6 rel). One recipe step runs against a tiny native target. The taps match the target's layer inputs and the lm_head input exactly.

    Labels, released tokenizer and chat template. One MedPix sample (512x655 image, 221 image tokens) through the recipe's processor and default_collate_fn labels A mass in the left lower lobe.<|end_message|><|content_model_end_sampling|>.

    Recipe sizing. From arithmetic, not from a run: 593.7B parameters, per GPU with experts EP only.

    | Recipe | GPUs | Params per GPU | Optimizer | State per GPU |
    |---|---|---|---|---|
    | Full SFT | 128 H100 | 4.64B | TE FusedAdam, FP32 master, BF16 moments | 46 GB |
    | LoRA | 32 H100 | 18.6B frozen BF16, 75M trainable | Adam on the adapters | 37 GB frozen + 0.6 GB adapters |

    Tests, CPU (x86 test container, transformers 5.18.0): on the final head, tests/unit_tests/models/{inkling2,inkling}, functional_tests/models/inkling2, _transformers, checkpoint, _peft, recipes, speculative and datasets/vlm/test_collate_fns.py give 5675 passed, 127 skipped. This includes a LoRA checkpoint test (the LoRA recipe's targets saved with Checkpointer.save_model and loaded into a second model, bitwise equal) and config tests for a subfolder checkpoint and a pinned revision. Before merging main, a wider set (also minimax_m3_vl, datasets/vlm and moe) gave 5705 passed, 121 skipped. The 2-GPU functional test passes on 2x H100. ruff, tools/lint_no_globals.py, tools/recipes/check_recipes.py and tools/docs/check_docs.py (0 errors, the 2 warnings main already has) pass. tools/check_types.py: the annotation policy passes; ty (latest) reports the same 4 diagnostics as on main, none in the changed files.

    Not tested:

  • Full-model training. Neither recipe has run at its 128-GPU or 32-GPU size, so their memory fit is unverified.

  • EP8 or larger (no 8-GPU run), and TE grouped experts at release dims, which need EP 8 or more to fit at load.

  • NVFP4 or MXFP8 training. The experts are trained in BF16 after dequant.

  • Context and pipeline parallelism and packed sequences are out of scope: CP, PP and TP are declared unsupported, and packed rows raise.

  • Contexts near the 1M-token limit, video inputs.

  • Loading a saved LoRA adapter with HF PEFT. Adapters are saved under AutoModel's native names, with the expert adapters in the grouped layout.

  • Loading the BF16 export in a serving engine. vLLM and TokenSpeed take NVFP4/MXFP8 experts only, so serving a fine-tune needs a separate re-quantization step.

  • Drafter training against the full 48-layer target, and its acceptance rate. Starting from the released draft weights needs draft_weights_path from #4725; that loader reads this draft's exported files unchanged (checked on CPU).
  • Implementation and validation were AI-assisted.

    Diff: 650 lines (+487 / -163) across 8 files Reviewer: ischencheng Review duration: 6525m
    All Vouch review confidence checks passed
    Residual risk 0.30 = Change Risk (0.52) × (1 − Review Confidence (0.43)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.02 · 1 substantive comment(s)
    0.02
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    42%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.344
    Real PR Conversation Timeline
    1 comments
    "Review active on #4751"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 43.0% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 43.0% · Lower = rushed or shallow review
    43.0%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 29.7% · Safe to merge
    29.7%