Skip to content

vllm.models.inkling2.nvidia.model

Inkling2 model (NVIDIA).

Decoder layers are tied together by block attention residuals: instead of a single residual stream, each sublayer input is a learned softmax mix over the outputs of previous blocks of n_layers_per_attn_res_block layers plus the running partial block. Residual blocks are stored in bf16; mixes are fp32.

Looped checkpoints (loop_config) are Inkling2LoopModel (loop.py).

Inkling2AttnRes

Bases: Module

Pseudo-queries of the block attention residuals (fp32), pre-scaled by hidden_size**-0.5 at load time.

Source code in vllm/models/inkling2/nvidia/model.py
class Inkling2AttnRes(nn.Module):
    """Pseudo-queries of the block attention residuals (fp32), pre-scaled by
    `hidden_size**-0.5` at load time."""

    def __init__(self, config: Inkling2ModelConfig) -> None:
        super().__init__()
        hidden = config.hidden_size
        local_ids = set(config.local_layer_ids)
        self.attn_queries = nn.ParameterList(
            nn.Parameter(
                torch.zeros(
                    (1, hidden) if i in local_ids else (3, hidden),
                    dtype=torch.float32,
                ),
                requires_grad=False,
            )
            for i in range(1, config.num_hidden_layers)
        )
        self.mlp_queries = nn.ParameterList(
            nn.Parameter(torch.zeros(1, hidden, dtype=torch.float32), False)
            for _ in range(config.num_hidden_layers)
        )
        self.output_query = nn.Parameter(
            torch.zeros(1, hidden, dtype=torch.float32), requires_grad=False
        )
        for param in self.parameters():
            param.weight_loader = self._load_query
        self.scale = hidden**-0.5

    def _load_query(self, param: nn.Parameter, weight: torch.Tensor) -> None:
        param.data.copy_(weight.view(param.shape)).mul_(self.scale)

Inkling2DecoderLayer

Bases: Module

Methods:

  • __init__ –

    num_passes > 1 (a loop core layer) gives each pass its own KV and

  • attention –

    This rank's partial attention output on the normalized inputs

Source code in vllm/models/inkling2/nvidia/model.py
class Inkling2DecoderLayer(nn.Module):
    def __init__(
        self,
        config: Inkling2ModelConfig,
        layer_id: int,
        quant_config: Inkling2QuantConfig | None,
        prefix: str,
        num_passes: int = 1,
    ) -> None:
        """`num_passes > 1` (a loop core layer) gives each pass its own KV and
        conv-state caches."""
        super().__init__()
        self.is_local = layer_id in config.local_layer_ids
        num_kv_heads = (
            config.swa_num_key_value_heads
            if self.is_local
            else config.num_key_value_heads
        )
        self.conv_states = tuple(
            InklingConvState(
                num_kv_heads=num_kv_heads,
                head_dim=config.swa_head_dim if self.is_local else config.head_dim,
                hidden_size=config.hidden_size,
                kernel_size=config.sconv_kernel_size,
                prefix=f"{prefix}.conv_state" + (f".pass{p}" if p else ""),
                replicate_hidden=True,
            )
            for p in range(num_passes)
        )
        self.conv_state = self.conv_states[0]
        self.attn = Inkling2Attention(
            config,
            self.is_local,
            self.conv_state,
            prefix=f"{prefix}.attn",
            pass_conv_states=self.conv_states[1:],
        )
        eps = config.rms_norm_eps
        # Local layers: attn_norm; full layers: q/k/v_input_norm, stacked.
        self.num_attn_inputs = 1 if self.is_local else 3
        self.attn_norm = Inkling2RMSNorm(
            config.hidden_size, eps, num_inputs=self.num_attn_inputs
        )
        self.mlp_norm = Inkling2RMSNorm(config.hidden_size, eps)
        expert_format: QuantFormat = (
            "mxfp8"
            if quant_config is not None and quant_config.is_mxfp8_layer(layer_id)
            else "nvfp4"
        )
        self.mlp = Inkling2MoE(config, expert_format, config.layer_visit_ids(layer_id))
        self.attn_sconv, self.mlp_sconv = (
            Inkling2ShortConv(
                config.hidden_size, config.sconv_kernel_size, self.conv_state, stream
            )
            for stream in (ATTN_STREAM, MLP_STREAM)
        )

    def attention(
        self,
        positions: torch.Tensor,
        inputs: Sequence[torch.Tensor],
        tau: torch.Tensor | None,
        out: torch.Tensor | None = None,
        pass_idx: int = 0,
    ) -> torch.Tensor:
        """This rank's partial attention output on the normalized `inputs`
        (one for local layers, or separate q/k/v inputs)."""
        if self.is_local and len(inputs) == 1:
            return self.attn(positions, inputs[0], out=out, pass_idx=pass_idx)
        return self.attn(
            positions,
            inputs[0],
            inputs[1],
            inputs[2],
            None if self.is_local else tau,
            out,
            pass_idx,
        )

__init__(config, layer_id, quant_config, prefix, num_passes=1)

num_passes > 1 (a loop core layer) gives each pass its own KV and conv-state caches.

Source code in vllm/models/inkling2/nvidia/model.py
def __init__(
    self,
    config: Inkling2ModelConfig,
    layer_id: int,
    quant_config: Inkling2QuantConfig | None,
    prefix: str,
    num_passes: int = 1,
) -> None:
    """`num_passes > 1` (a loop core layer) gives each pass its own KV and
    conv-state caches."""
    super().__init__()
    self.is_local = layer_id in config.local_layer_ids
    num_kv_heads = (
        config.swa_num_key_value_heads
        if self.is_local
        else config.num_key_value_heads
    )
    self.conv_states = tuple(
        InklingConvState(
            num_kv_heads=num_kv_heads,
            head_dim=config.swa_head_dim if self.is_local else config.head_dim,
            hidden_size=config.hidden_size,
            kernel_size=config.sconv_kernel_size,
            prefix=f"{prefix}.conv_state" + (f".pass{p}" if p else ""),
            replicate_hidden=True,
        )
        for p in range(num_passes)
    )
    self.conv_state = self.conv_states[0]
    self.attn = Inkling2Attention(
        config,
        self.is_local,
        self.conv_state,
        prefix=f"{prefix}.attn",
        pass_conv_states=self.conv_states[1:],
    )
    eps = config.rms_norm_eps
    # Local layers: attn_norm; full layers: q/k/v_input_norm, stacked.
    self.num_attn_inputs = 1 if self.is_local else 3
    self.attn_norm = Inkling2RMSNorm(
        config.hidden_size, eps, num_inputs=self.num_attn_inputs
    )
    self.mlp_norm = Inkling2RMSNorm(config.hidden_size, eps)
    expert_format: QuantFormat = (
        "mxfp8"
        if quant_config is not None and quant_config.is_mxfp8_layer(layer_id)
        else "nvfp4"
    )
    self.mlp = Inkling2MoE(config, expert_format, config.layer_visit_ids(layer_id))
    self.attn_sconv, self.mlp_sconv = (
        Inkling2ShortConv(
            config.hidden_size, config.sconv_kernel_size, self.conv_state, stream
        )
        for stream in (ATTN_STREAM, MLP_STREAM)
    )

attention(positions, inputs, tau, out=None, pass_idx=0)

This rank's partial attention output on the normalized inputs (one for local layers, or separate q/k/v inputs).

Source code in vllm/models/inkling2/nvidia/model.py
def attention(
    self,
    positions: torch.Tensor,
    inputs: Sequence[torch.Tensor],
    tau: torch.Tensor | None,
    out: torch.Tensor | None = None,
    pass_idx: int = 0,
) -> torch.Tensor:
    """This rank's partial attention output on the normalized `inputs`
    (one for local layers, or separate q/k/v inputs)."""
    if self.is_local and len(inputs) == 1:
        return self.attn(positions, inputs[0], out=out, pass_idx=pass_idx)
    return self.attn(
        positions,
        inputs[0],
        inputs[1],
        inputs[2],
        None if self.is_local else tau,
        out,
        pass_idx,
    )

Inkling2LogitsProcessor

Bases: LogitsProcessor

Use the low-M projection while preserving vocab gathering and softcaps.

Source code in vllm/models/inkling2/nvidia/model.py
class Inkling2LogitsProcessor(LogitsProcessor):
    """Use the low-M projection while preserving vocab gathering and softcaps."""

    def _apply_head(self, lm_head, hidden_states, embedding_bias):
        from vllm.model_executor.layers.linear import UnquantizedLinearMethod
        from vllm.model_executor.layers.vocab_parallel_embedding import (
            UnquantizedEmbeddingMethod,
        )

        if (
            self.head_dtype == torch.float32
            and isinstance(
                lm_head.quant_method,
                (UnquantizedEmbeddingMethod, UnquantizedLinearMethod),
            )
            and use_sm12x_bf16_ll_gemm(hidden_states, lm_head.weight, embedding_bias)
        ):
            return sm12x_bf16_ll_gemm(
                hidden_states, lm_head.weight, embedding_bias, out_dtype=torch.float32
            )
        return super()._apply_head(lm_head, hidden_states, embedding_bias)

Inkling2Model

Bases: Module

Source code in vllm/models/inkling2/nvidia/model.py
class Inkling2Model(nn.Module):
    # Whether TP > 1 keeps a token shard of the hidden stream for large
    # batches (sequence parallel).
    seq_parallel_paths = True

    def __init__(
        self,
        config: Inkling2ModelConfig,
        quant_config: Inkling2QuantConfig | None,
        prefix: str,
    ) -> None:
        super().__init__()
        self.config = config
        self.block_size = config.n_layers_per_attn_res_block
        self.normalize_values = config.attn_res_normalize_values
        self.embed_tokens = VocabParallelEmbedding(
            config.padded_vocab_size, config.hidden_size
        )
        self.embed_norm = Inkling2RMSNorm(
            config.hidden_size, config.rms_norm_eps, out_dtype=None
        )
        self.layers = nn.ModuleList(
            self._make_layer(config, i, quant_config, f"{prefix}.layers.{i}")
            for i in range(config.num_hidden_layers)
        )
        self.attn_res = Inkling2AttnRes(config)
        self.norm = Inkling2RMSNorm(config.hidden_size, config.rms_norm_eps)
        # Large batches keep a token shard of the hidden stream on each rank.
        self.allreduce_workspace = None
        self.seq_parallel = None
        if get_tensor_model_parallel_world_size() > 1:
            assert self.normalize_values
            group = get_tp_group().cpu_group
            self.allreduce_workspace = Inkling2AllReduceWorkspace.create(
                group, config.hidden_size
            )
            if self.allreduce_workspace is not None and self.seq_parallel_paths:
                vllm_config = get_current_vllm_config()
                spec = vllm_config.speculative_config
                num_spec = 0 if spec is None else spec.num_speculative_tokens
                self.seq_parallel = SeqParallel(
                    group,
                    config.hidden_size,
                    vllm_config.scheduler_config.max_num_batched_tokens,
                    tail_rows=max(config.sconv_kernel_size - 1, num_spec + 1),
                )
        # Layers whose input (the partial block) the DSpark draft reads; layer
        # id num_hidden_layers stands for the final-norm output.
        self.aux_hidden_state_layers: tuple[int, ...] = ()

    def _make_layer(
        self,
        config: Inkling2ModelConfig,
        layer_id: int,
        quant_config: Inkling2QuantConfig | None,
        prefix: str,
    ) -> Inkling2DecoderLayer:
        return Inkling2DecoderLayer(config, layer_id, quant_config, prefix)

    def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor:
        return self.embed_norm(self.embed_tokens(input_ids))

    def _mix(
        self,
        stack: torch.Tensor,
        last: torch.Tensor,
        query: torch.Tensor,
        norm: Inkling2RMSNorm,
        addend: torch.Tensor | None = None,
    ) -> torch.Tensor:
        return attn_res(
            stack, last, addend, query, norm.weight, norm.eps, self.normalize_values
        )

    def forward(
        self, positions: torch.Tensor, inputs_embeds: torch.Tensor
    ) -> torch.Tensor | tuple[torch.Tensor, list[torch.Tensor]]:
        num_tokens, hidden = inputs_embeds.shape
        aux_hidden_states = []
        num_layers = len(self.layers)
        # With a conv-state cache (TP > 1), the hidden-stream conv runs fused
        # with the next AttnRes mix: small batches also fuse each sublayer's
        # all-reduce, larger ones run it on the all-reduced input. Large
        # batches keep a token shard of the hidden stream on each rank
        # (reduce-scatter, then `conv_mix`), also in profile runs (no
        # conv-state cache) for their memory use.
        workspace = self.allreduce_workspace
        plan = [(False, False)] * 2
        has_cache = conv_metadata(self.layers[0].conv_state) is not None
        sp = self.seq_parallel
        if sp is not None and num_tokens < sp.min_tokens:
            sp = None
        conv_mix = workspace is not None and has_cache
        if conv_mix and sp is None:
            assert workspace is not None
            plan = workspace.plan(num_tokens)
        (attn_fused, attn_two_shot), (moe_fused, moe_two_shot) = plan
        # stack[:num_blocks] holds completed blocks; stack[num_blocks] is the
        # running partial block (of this rank's shard of rows[:capacity]).
        max_blocks = -(-num_layers // self.block_size)
        begin, end, capacity = 0, num_tokens, num_tokens
        prefix_align = 0
        if sp is not None:
            begin, end, capacity = sp.shard(num_tokens)
            prefix_align = self._prefix_align() if has_cache else 0
        stacked = inputs_embeds.new_empty((max_blocks + 1, capacity, hidden))
        stack = stacked[:, : end - begin]
        stack[0].copy_(inputs_embeds[begin:end])
        num_blocks = 0
        tau = self._log_scaling_tau(positions)
        # The fused MoE all-reduce also produces the next layer's inputs.
        inputs = None
        for i, layer in enumerate(self.layers):
            partial = stack[num_blocks]
            if i in self.aux_hidden_state_layers:
                if sp is None:
                    aux_hidden_states.append(partial.clone())
                else:
                    aux_hidden_states.append(
                        tensor_model_parallel_all_gather(stacked[num_blocks], 0)[
                            :num_tokens
                        ]
                    )
            if inputs is None and num_blocks == 0:
                # The shard of the first block holds this rank's rows only.
                first_in = partial if sp is None else inputs_embeds
                inputs = [
                    layer.attn_norm(first_in, j) for j in range(layer.num_attn_inputs)
                ]
            elif inputs is None:
                query = self.attn_res.attn_queries[i - 1]
                inputs = self._mix(stack[:num_blocks], partial, query, layer.attn_norm)
            attn_partial = layer.attention(
                positions,
                inputs,
                tau,
                out=None if sp is None else sp.partial(num_tokens),
            )

            mlp_query = self.attn_res.mlp_queries[i]
            # The MLP input mixes the blocks with (partial +) attn_out.
            first = i % self.block_size == 0
            if sp is not None or conv_mix:
                attn_out = torch.empty_like(partial)
                mix_args = (
                    positions,
                    attn_out,
                    stack[: num_blocks + first],
                    None if first else partial,
                    mlp_query,
                    layer.mlp_norm,
                )
                if sp is not None:
                    shard, halo = sp.reduce_scatter(num_tokens)
                    mlp_in = layer.attn_sconv.conv_mix(
                        shard, *mix_args, sp=sp, halo=halo, prefix_align=prefix_align
                    )
                elif attn_fused:
                    assert workspace is not None
                    mlp_in = layer.attn_sconv.all_reduce_mix(
                        workspace, *mix_args, x=attn_partial, two_shot=attn_two_shot
                    )
                else:
                    attn_reduced = tensor_model_parallel_all_reduce(attn_partial)
                    mlp_in = layer.attn_sconv.conv_mix(attn_reduced, *mix_args)
            else:
                attn_out = layer.attn_sconv(
                    tensor_model_parallel_all_reduce(attn_partial), positions
                )
                if first:
                    mlp_in = self._mix(
                        stack[: num_blocks + 1], attn_out, mlp_query, layer.mlp_norm
                    )
                else:
                    mlp_in = self._mix(
                        stack[:num_blocks], partial, mlp_query, layer.mlp_norm, attn_out
                    )
            # The MLP short conv also applies the residual update.
            residual = None if first else partial
            if residual is None:
                num_blocks += 1
            inputs = None
            if sp is None and not conv_mix:
                layer.mlp_sconv(
                    layer.mlp(mlp_in[0]),
                    positions,
                    addend=attn_out,
                    residual=residual,
                    out=stack[num_blocks],
                )
                continue
            if i + 1 < num_layers:
                query = self.attn_res.attn_queries[i]
                norm = self.layers[i + 1].attn_norm
            else:
                query, norm = self.attn_res.output_query, self.norm
            mix_args = (
                positions,
                stack[num_blocks],
                stack[:num_blocks],
                None,
                query,
                norm,
            )
            if sp is not None:
                layer.mlp(mlp_in[0], reduce=False, push=sp)
                shard, halo = sp.pushed(num_tokens)
                inputs = layer.mlp_sconv.conv_mix(
                    shard,
                    *mix_args,
                    addend=attn_out,
                    residual=residual,
                    sp=sp,
                    halo=halo,
                    prefix_align=prefix_align,
                )
            elif moe_fused:
                assert workspace is not None
                inputs = layer.mlp_sconv.all_reduce_mix(
                    workspace,
                    *mix_args,
                    combine=layer.mlp(mlp_in[0], reduce=False),
                    addend=attn_out,
                    residual=residual,
                    two_shot=moe_two_shot,
                )
            else:
                # The MoE output is all-reduced (in bf16) inside layer.mlp.
                moe_reduced = layer.mlp(mlp_in[0])
                inputs = layer.mlp_sconv.conv_mix(
                    moe_reduced, *mix_args, addend=attn_out, residual=residual
                )

        if inputs is not None:
            # The all-gather buffer is reused by the next forward.
            out = inputs[0] if sp is None else inputs[0].clone()
        else:
            out = self._mix(
                stack[:num_blocks],
                stack[num_blocks],
                self.attn_res.output_query,
                self.norm,
            )[0]
        if self.aux_hidden_state_layers:
            return out, [*aux_hidden_states, out]
        return out

    def _log_scaling_tau(self, positions: torch.Tensor) -> torch.Tensor | None:
        if self.config.log_scaling_n_floor is None:
            return None
        return compute_log_scaling_tau(
            positions, self.config.log_scaling_n_floor, self.config.log_scaling_alpha
        )

    def _prefix_align(self) -> int:
        """A token multiple of every prefix-cache hit (a KV cache block size
        of the full-attention layers)."""
        layer = next(layer for layer in self.layers if not layer.is_local)
        return layer.attn.kv_cache.shape[2]

_prefix_align()

A token multiple of every prefix-cache hit (a KV cache block size of the full-attention layers).

Source code in vllm/models/inkling2/nvidia/model.py
def _prefix_align(self) -> int:
    """A token multiple of every prefix-cache hit (a KV cache block size
    of the full-attention layers)."""
    layer = next(layer for layer in self.layers if not layer.is_local)
    return layer.attn.kv_cache.shape[2]

Inkling2RMSNorm

Bases: Module

RMSNorm; num_inputs > 1 stacks the weights of per-input norms (the block AttnRes mixes apply them in the same kernel).

Source code in vllm/models/inkling2/nvidia/model.py
class Inkling2RMSNorm(nn.Module):
    """RMSNorm; `num_inputs > 1` stacks the weights of per-input norms (the
    block AttnRes mixes apply them in the same kernel)."""

    def __init__(
        self,
        hidden_size: int,
        eps: float,
        out_dtype: torch.dtype | None = torch.bfloat16,
        num_inputs: int = 1,
    ) -> None:
        super().__init__()
        self.weight = nn.Parameter(
            torch.ones(num_inputs, hidden_size), requires_grad=False
        )
        self.weight.weight_loader = self._load
        self.eps = eps
        self.out_dtype = out_dtype

    @staticmethod
    def _load(param: nn.Parameter, loaded: torch.Tensor, shard_id: int = 0) -> None:
        param.data[shard_id].copy_(loaded)

    def forward(self, x: torch.Tensor, index: int = 0) -> torch.Tensor:
        return rms_norm(x, self.weight[index], self.eps, self.out_dtype)