Skip to content

vllm.models.inkling2

Inkling2: platform-specific implementations live under nvidia/; configs, processing, quantization metadata and the DSpark speculator are shared.

Modules:

  • configs –

    Inkling2 model configs.

  • nvidia –
  • processing –

    Inkling2 image preprocessing and vLLM multimodal processing.

  • quant_config –

    Per-tensor precision metadata of Inkling2 checkpoints (hf_quant_config.json).

  • speculator –

    DSpark speculator for the Inkling2 draft: stores the raw target features

Classes:

Inkling2DSparkModel

Bases: Module

DSpark draft for Inkling2; plugged in by Inkling2DSparkSpeculator.

Methods:

  • attach_target –

    Finish sharing the target's normalized embeddings and LM head (its

  • compute_base_logits –

    TP-local bf16 base logits (bf16 GEMM, as the reference).

  • compute_f_rnn –

    Recurrent-head context from the last committed token's features.

  • markov_argmax –

    markov_logits(...).argmax(-1), NaN as -inf.

  • markov_logits –

    Full-vocab softcapped logits.

  • markov_step –

    Advance the recurrent head; return the state and TP-local bias.

  • refresh_derived_weights –

    Re-derive, in place, the weights computed from the target's LM head

Source code in vllm/models/inkling2/nvidia/dspark.py
class Inkling2DSparkModel(nn.Module):
    """DSpark draft for Inkling2; plugged in by `Inkling2DSparkSpeculator`."""

    # The speculator this is a draft model of (see SpeculativeDraftModel).
    speculator_config_class = Inkling2DSparkSpeculatorConfig
    allow_patterns_overrides = ["mtp.safetensors"]
    has_own_embed_tokens = False
    has_own_lm_head = False
    draft_id_to_target_id = None

    _stacked = (
        (".q_proj.", ".qkv_proj.", "q"),
        (".k_proj.", ".qkv_proj.", "k"),
        (".v_proj.", ".qkv_proj.", "v"),
        (".k_proj_ctx.", ".kv_proj_ctx.", 0),
        (".v_proj_ctx.", ".kv_proj_ctx.", 1),
        (".gate_proj.", ".gate_up_proj.", 0),
        (".up_proj.", ".gate_up_proj.", 1),
    )

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = "") -> None:
        super().__init__()
        assert vllm_config.speculative_config is not None
        config = vllm_config.speculative_config.draft_model_config.hf_config
        assert isinstance(config, Inkling2DSparkConfig)
        num_spec = vllm_config.speculative_config.num_speculative_tokens
        if num_spec != config.draft_block_size - 1:
            raise ValueError(
                "Inkling2 DSpark requires num_speculative_tokens = "
                f"{config.draft_block_size - 1} (the checkpoint's block size - 1)"
            )
        if vllm_config.model_config.max_model_len > config.max_position_embeddings:
            raise ValueError(
                "Inkling2 DSpark drafts up to max_position_embeddings="
                f"{config.max_position_embeddings} positions; set --max-model-len "
                "to at most that"
            )
        self.config = config
        self.model = Inkling2DSparkDecoder(
            config, vllm_config.model_config.max_model_len, f"{prefix}model"
        )
        self.lm_head: nn.Module | None = None

    @torch.no_grad()
    def attach_target(self, target_model: nn.Module) -> None:
        """Finish sharing the target's normalized embeddings and LM head (its
        `embed_tokens` and `lm_head` are aliased by `load_dspark_model`)
        and derive the weights that depend on them."""
        assert self.lm_head is not None and self.lm_head.weight.dtype == torch.bfloat16
        self.model.embed_norm = target_model.model.embed_norm
        head = self.model.markov_head
        head.rnn_bias = torch.empty_like(head.rnn_proj.bias, dtype=torch.float32)
        self.refresh_derived_weights()

    @torch.no_grad()
    def refresh_derived_weights(self) -> None:
        """Re-derive, in place, the weights computed from the target's LM head
        and the draft's own weights; called again after the target's weights
        are replaced (reload, RL weight transfer)."""
        assert self.lm_head is not None
        head = self.model.markov_head
        assert head.rnn_bias is not None
        head.fold(self.lm_head.weight)
        head.rnn_bias.copy_(head.rnn_proj.bias)
        self.model.fuse_alpha.copy_(
            torch.softmax(self.model.fuse_weight.float(), dim=-1)
        )

    def get_draft_kv_cache_layer_names(self) -> list[str]:
        return [layer.self_attn.attn.layer_name for layer in self.model.layers]

    def combine_hidden_states(self, hidden_states: torch.Tensor) -> torch.Tensor:
        # Each draft layer mixes the raw target features itself.
        return hidden_states

    def precompute_and_store_context_kv(
        self,
        context_states: torch.Tensor,
        context_positions: torch.Tensor,
        context_slot_mappings: list[torch.Tensor | None] | None = None,
    ) -> None:
        for i, layer in enumerate(self.model.layers):
            context = self.model.mix(context_states, i, layer.dflare_norm)
            layer.self_attn.store_context_kv(
                context,
                context_positions,
                self.model.cos_sin_cache,
                None if context_slot_mappings is None else context_slot_mappings[i],
            )

    def compute_f_rnn(self, features: torch.Tensor) -> torch.Tensor:
        """Recurrent-head context from the last committed token's features."""
        return self.model.mix(features, -1, self.model.markov_head.dflare_norm)

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        inputs_embeds: torch.Tensor | None = None,
    ) -> torch.Tensor:
        return self.model(input_ids, positions)

    def compute_base_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
        """TP-local bf16 base logits (bf16 GEMM, as the reference)."""
        assert self.lm_head is not None
        return linear(hidden_states, self.lm_head.weight)

    def markov_step(
        self, state: torch.Tensor, prev_tokens: torch.Tensor, context: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor]:
        """Advance the recurrent head; return the state and TP-local bias."""
        return self.model.markov_head.step(state, prev_tokens, context)

    def markov_logits(
        self, base_logits: torch.Tensor, bias: torch.Tensor
    ) -> torch.Tensor:
        """Full-vocab softcapped logits."""
        logits = add_softcap(base_logits, bias, self.config.final_logit_softcapping)
        logits = tensor_model_parallel_all_gather(logits)
        return logits[:, : self.config.vocab_size]

    def markov_argmax(
        self, base_logits: torch.Tensor, bias: torch.Tensor
    ) -> torch.Tensor:
        """`markov_logits(...).argmax(-1)`, NaN as -inf."""
        return greedy_argmax(self.markov_logits(base_logits, bias))

    def map_draft_to_target(self, draft_ids: torch.Tensor) -> torch.Tensor:
        return draft_ids

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        params = dict(self.named_parameters())
        loaded: set[str] = set()
        for name, weight in weights:
            name, shard = f"model.{name}", None
            for old, new, shard_id in self._stacked:
                if old in name:
                    name, shard = name.replace(old, new), shard_id
                    break
            param = params[name]
            if weight.dtype != param.dtype:
                raise ValueError(f"{name}: expected {param.dtype}, got {weight.dtype}")
            if shard is None:
                getattr(param, "weight_loader", default_weight_loader)(param, weight)
            else:
                param.weight_loader(param, weight, shard)
            loaded.add(name)
        return loaded

attach_target(target_model)

Finish sharing the target's normalized embeddings and LM head (its embed_tokens and lm_head are aliased by load_dspark_model) and derive the weights that depend on them.

Source code in vllm/models/inkling2/nvidia/dspark.py
@torch.no_grad()
def attach_target(self, target_model: nn.Module) -> None:
    """Finish sharing the target's normalized embeddings and LM head (its
    `embed_tokens` and `lm_head` are aliased by `load_dspark_model`)
    and derive the weights that depend on them."""
    assert self.lm_head is not None and self.lm_head.weight.dtype == torch.bfloat16
    self.model.embed_norm = target_model.model.embed_norm
    head = self.model.markov_head
    head.rnn_bias = torch.empty_like(head.rnn_proj.bias, dtype=torch.float32)
    self.refresh_derived_weights()

compute_base_logits(hidden_states)

TP-local bf16 base logits (bf16 GEMM, as the reference).

Source code in vllm/models/inkling2/nvidia/dspark.py
def compute_base_logits(self, hidden_states: torch.Tensor) -> torch.Tensor:
    """TP-local bf16 base logits (bf16 GEMM, as the reference)."""
    assert self.lm_head is not None
    return linear(hidden_states, self.lm_head.weight)

compute_f_rnn(features)

Recurrent-head context from the last committed token's features.

Source code in vllm/models/inkling2/nvidia/dspark.py
def compute_f_rnn(self, features: torch.Tensor) -> torch.Tensor:
    """Recurrent-head context from the last committed token's features."""
    return self.model.mix(features, -1, self.model.markov_head.dflare_norm)

markov_argmax(base_logits, bias)

markov_logits(...).argmax(-1), NaN as -inf.

Source code in vllm/models/inkling2/nvidia/dspark.py
def markov_argmax(
    self, base_logits: torch.Tensor, bias: torch.Tensor
) -> torch.Tensor:
    """`markov_logits(...).argmax(-1)`, NaN as -inf."""
    return greedy_argmax(self.markov_logits(base_logits, bias))

markov_logits(base_logits, bias)

Full-vocab softcapped logits.

Source code in vllm/models/inkling2/nvidia/dspark.py
def markov_logits(
    self, base_logits: torch.Tensor, bias: torch.Tensor
) -> torch.Tensor:
    """Full-vocab softcapped logits."""
    logits = add_softcap(base_logits, bias, self.config.final_logit_softcapping)
    logits = tensor_model_parallel_all_gather(logits)
    return logits[:, : self.config.vocab_size]

markov_step(state, prev_tokens, context)

Advance the recurrent head; return the state and TP-local bias.

Source code in vllm/models/inkling2/nvidia/dspark.py
def markov_step(
    self, state: torch.Tensor, prev_tokens: torch.Tensor, context: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor]:
    """Advance the recurrent head; return the state and TP-local bias."""
    return self.model.markov_head.step(state, prev_tokens, context)

refresh_derived_weights()

Re-derive, in place, the weights computed from the target's LM head and the draft's own weights; called again after the target's weights are replaced (reload, RL weight transfer).

Source code in vllm/models/inkling2/nvidia/dspark.py
@torch.no_grad()
def refresh_derived_weights(self) -> None:
    """Re-derive, in place, the weights computed from the target's LM head
    and the draft's own weights; called again after the target's weights
    are replaced (reload, RL weight transfer)."""
    assert self.lm_head is not None
    head = self.model.markov_head
    assert head.rnn_bias is not None
    head.fold(self.lm_head.weight)
    head.rnn_bias.copy_(head.rnn_proj.bias)
    self.model.fuse_alpha.copy_(
        torch.softmax(self.model.fuse_weight.float(), dim=-1)
    )

Inkling2LoopForConditionalGeneration

Bases: Inkling2ForConditionalGeneration

The inkling2_loop checkpoints' architecture name; the model is Inkling2ForConditionalGeneration with an Inkling2LoopModel.

Source code in vllm/models/inkling2/nvidia/loop.py
class Inkling2LoopForConditionalGeneration(Inkling2ForConditionalGeneration):
    """The `inkling2_loop` checkpoints' architecture name; the model is
    `Inkling2ForConditionalGeneration` with an `Inkling2LoopModel`."""