Skip to content

vllm.models.nemotron_shortcut.nvidia.model

Inference-only Nemotron Shortcut language model for HuggingFace weights.

Classes:

Functions:

NemotronShortcutAttention

Bases: Module

Methods:

  • project –

    The input projection, which precedes the attention op.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutAttention(nn.Module):
    def __init__(
        self,
        config: PreTrainedConfig,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        prefix: str = "",
    ) -> None:
        super().__init__()
        tp_size = get_tensor_model_parallel_world_size()
        self.total_num_heads = config.num_attention_heads
        assert self.total_num_heads % tp_size == 0
        self.num_heads = self.total_num_heads // tp_size
        self.total_num_kv_heads = config.num_key_value_heads
        if self.total_num_kv_heads >= tp_size:
            assert self.total_num_kv_heads % tp_size == 0
        else:
            assert tp_size % self.total_num_kv_heads == 0
        self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
        self.head_dim = config.head_dim
        self.q_size = self.num_heads * self.head_dim
        self.kv_size = self.num_kv_heads * self.head_dim
        self.scaling = self.head_dim**-0.5

        self.qkv_proj = QKVParallelLinear(
            config.hidden_size,
            self.head_dim,
            self.total_num_heads,
            self.total_num_kv_heads,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
        )
        self.o_proj = RowParallelLinear(
            self.total_num_heads * self.head_dim,
            config.hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.o_proj",
        )
        # NoPE: position information only enters the model through the GDP mixers.
        self.attn = Attention(
            self.num_heads,
            self.head_dim,
            self.scaling,
            num_kv_heads=self.num_kv_heads,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=f"{prefix}.attn",
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        return self.forward_projected(*self.project(hidden_states))

    def project(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
        """The input projection, which precedes the attention op."""
        qkv, _ = self.qkv_proj(hidden_states)
        return (qkv,)

    def forward_projected(self, qkv: torch.Tensor) -> torch.Tensor:
        q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
        output, _ = self.o_proj(self.attn(q, k, v))
        return output

project(hidden_states)

The input projection, which precedes the attention op.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def project(self, hidden_states: torch.Tensor) -> tuple[torch.Tensor]:
    """The input projection, which precedes the attention op."""
    qkv, _ = self.qkv_proj(hidden_states)
    return (qkv,)

NemotronShortcutAttentionLayer

Bases: Module

Methods:

  • attention –

    SDSA if the model has SDSA's buffers, which it allocates when its

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutAttentionLayer(nn.Module):
    @staticmethod
    def attention(
        config: PreTrainedConfig,
        cache_config: CacheConfig | None,
        quant_config: QuantizationConfig | None,
        prefix: str,
        sdsa_buffers: SdsaBuffers | None,
    ) -> nn.Module:
        """SDSA if the model has SDSA's buffers, which it allocates when its
        config has index_topk; full attention if not."""
        if sdsa_buffers is None:
            return NemotronShortcutAttention(config, cache_config, quant_config, prefix)
        return NemotronShortcutSparseAttention(
            config, cache_config, quant_config, prefix, sdsa_buffers
        )

    def __init__(
        self,
        config,
        layer_idx,
        model_config,
        cache_config,
        quant_config,
        *_,
        prefix="",
        sdsa_buffers=None,
    ):
        super().__init__()
        self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.self_attn = self.attention(
            config, cache_config, quant_config, f"{prefix}.self_attn", sdsa_buffers
        )
        self.residual_connection = NemotronShortcutWideResidualConnection(config)

    def forward(self, streams: torch.Tensor) -> torch.Tensor:
        x = self.residual_connection.read(streams, self.input_layernorm)
        return self.residual_connection.write(streams, self.self_attn(x))

attention(config, cache_config, quant_config, prefix, sdsa_buffers) staticmethod

SDSA if the model has SDSA's buffers, which it allocates when its config has index_topk; full attention if not.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
@staticmethod
def attention(
    config: PreTrainedConfig,
    cache_config: CacheConfig | None,
    quant_config: QuantizationConfig | None,
    prefix: str,
    sdsa_buffers: SdsaBuffers | None,
) -> nn.Module:
    """SDSA if the model has SDSA's buffers, which it allocates when its
    config has index_topk; full attention if not."""
    if sdsa_buffers is None:
        return NemotronShortcutAttention(config, cache_config, quant_config, prefix)
    return NemotronShortcutSparseAttention(
        config, cache_config, quant_config, prefix, sdsa_buffers
    )

NemotronShortcutMoEAttentionLayer

Bases: Module

Attention then MoE on a plain residual.

The MTP block under moe_shortcut_disable_mtp: the routed and shared experts both read the post-attention state.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutMoEAttentionLayer(nn.Module):
    """Attention then MoE on a plain residual.

    The MTP block under `moe_shortcut_disable_mtp`: the routed and shared
    experts both read the post-attention state.
    """

    def __init__(
        self,
        config: PreTrainedConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
        sdsa_buffers: SdsaBuffers | None = None,
    ) -> None:
        super().__init__()
        self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.self_attn = NemotronShortcutAttentionLayer.attention(
            config, cache_config, quant_config, f"{prefix}.self_attn", sdsa_buffers
        )
        self.pre_moe_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.moe = NemotronShortcutMoE(
            config,
            quant_config=quant_config,
            parallel_config=parallel_config,
            prefix=f"{prefix}.moe",
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        hidden_states = hidden_states + self.self_attn(
            self.input_layernorm(hidden_states)
        )
        moe_input = self.pre_moe_layernorm(hidden_states)
        return hidden_states + self.moe(moe_input, moe_input)

NemotronShortcutPlainResidualConnection

Bases: Module

Ordinary pre-norm residual behind the wide-residual port interface.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutPlainResidualConnection(nn.Module):
    """Ordinary pre-norm residual behind the wide-residual port interface."""

    def __init__(self, config: PreTrainedConfig | None = None) -> None:
        super().__init__()

    def read(self, hidden_states: torch.Tensor, norm: RMSNorm) -> torch.Tensor:
        return norm(hidden_states.to(norm.weight.dtype))

    def write(self, hidden_states: torch.Tensor, update: torch.Tensor) -> torch.Tensor:
        return hidden_states + update.to(hidden_states.dtype)

NemotronShortcutPlainResidualRead

Bases: Module

Wide-residual read for a block that carries one hidden state.

The MTP head runs a shortcut-MoE block outside the residual streams, so the checkpoint has no read logits and the read is the identity.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutPlainResidualRead(nn.Module):
    """Wide-residual read for a block that carries one hidden state.

    The MTP head runs a shortcut-MoE block outside the residual streams, so the
    checkpoint has no read logits and the read is the identity.
    """

    def __init__(self, config: PreTrainedConfig | None = None) -> None:
        super().__init__()

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        return hidden_states

NemotronShortcutSparseAttention

Bases: Module

Methods:

  • project –

    The input projections, which precede the indexer and attention ops.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutSparseAttention(nn.Module):
    def __init__(
        self,
        config: PreTrainedConfig,
        cache_config: CacheConfig | None,
        quant_config: QuantizationConfig | None,
        prefix: str,
        sdsa_buffers: SdsaBuffers,
    ) -> None:
        super().__init__()
        assert config.num_key_value_heads == 1, "SDSA attends over one KV head"
        assert cache_config is not None
        self.num_heads = divide(
            config.num_attention_heads, get_tensor_model_parallel_world_size()
        )
        self.head_dim = config.head_dim
        self.qkv_proj = QKVParallelLinear(
            config.hidden_size,
            self.head_dim,
            config.num_attention_heads,
            total_num_kv_heads=1,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.qkv_proj",
        )
        self.o_proj = RowParallelLinear(
            config.num_attention_heads * self.head_dim,
            config.hidden_size,
            bias=False,
            quant_config=quant_config,
            prefix=f"{prefix}.o_proj",
        )
        # A 128-dim query and key head: the indexer's key formats hold 128 values.
        if config.index_head_dim != 128:
            raise ValueError(
                f"SDSA serves index_head_dim 128, got {config.index_head_dim}"
            )
        self.indexer = nn.ModuleDict(
            {
                name: ReplicatedLinear(
                    config.hidden_size,
                    config.index_head_dim,
                    bias=False,
                    quant_config=quant_config,
                    prefix=f"{prefix}.indexer.{name}",
                )
                for name in ("q_proj", "k_proj")
            }
        )
        self.attn = SdsaAttention(
            num_heads=self.num_heads,
            sdsa_config=get_sdsa_config(config, self.indexer["k_proj"]),
            buffers=sdsa_buffers,
            cache_config=cache_config,
            quant_config=quant_config,
            prefix=f"{prefix}.attn",
        )

    def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
        return self.forward_projected(*self.project(hidden_states))

    def project(
        self, hidden_states: torch.Tensor
    ) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
        """The input projections, which precede the indexer and attention ops."""
        qkv, _ = self.qkv_proj(hidden_states)
        indexer_q, _ = self.indexer["q_proj"](hidden_states)
        indexer_k, _ = self.indexer["k_proj"](hidden_states)
        return qkv, indexer_q, indexer_k

    def forward_projected(
        self, qkv: torch.Tensor, indexer_q: torch.Tensor, indexer_k: torch.Tensor
    ) -> torch.Tensor:
        q, k, v = qkv.split(
            [self.num_heads * self.head_dim, self.head_dim, self.head_dim], dim=-1
        )
        output, _ = self.o_proj(self.attn(indexer_q, indexer_k, q, k, v))
        return output

project(hidden_states)

The input projections, which precede the indexer and attention ops.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def project(
    self, hidden_states: torch.Tensor
) -> tuple[torch.Tensor, torch.Tensor, torch.Tensor]:
    """The input projections, which precede the indexer and attention ops."""
    qkv, _ = self.qkv_proj(hidden_states)
    indexer_q, _ = self.indexer["q_proj"](hidden_states)
    indexer_k, _ = self.indexer["k_proj"](hidden_states)
    return qkv, indexer_q, indexer_k

NemotronShortcutWideResidualConnection

Bases: Module

Per-branch read and write ports into the residual streams.

Methods:

  • write –

    Y_k = gamma_k X_k + 2 sigmoid(w_k) U for every stream k.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutWideResidualConnection(nn.Module):
    """Per-branch read and write ports into the residual streams."""

    def __init__(self, config: PreTrainedConfig) -> None:
        super().__init__()
        self.num_streams = config.wide_residual_num_streams
        self.retention_max_forget = config.wide_residual_retention_max_forget
        self.read_logit = nn.Parameter(torch.empty(self.num_streams))
        self.write_logit = nn.Parameter(torch.empty(self.num_streams))
        if config.wide_residual_learned_retention:
            self.retention_logit = nn.Parameter(torch.empty(self.num_streams))
        else:
            self.register_parameter("retention_logit", None)

    def read(self, streams: torch.Tensor, norm: RMSNorm) -> torch.Tensor:
        streams = streams.unflatten(-1, (self.num_streams, -1))
        factors = torch.sigmoid(self.read_logit.float()).to(streams.dtype)
        return norm(torch.matmul(factors, streams).to(norm.weight.dtype))

    def write(self, streams: torch.Tensor, update: torch.Tensor) -> torch.Tensor:
        """`Y_k = gamma_k X_k + 2 sigmoid(w_k) U` for every stream `k`."""
        streams = streams.unflatten(-1, (self.num_streams, -1))
        update = update.to(streams.dtype).unsqueeze(-2)
        write = 2.0 * torch.sigmoid(self.write_logit.float())
        write = write.to(streams.dtype).unsqueeze(-1)
        if self.retention_logit is not None:
            retention = 1.0 - self.retention_max_forget * torch.sigmoid(
                -self.retention_logit.float()
            )
            streams = streams * retention.to(streams.dtype).unsqueeze(-1)
        return torch.addcmul(streams, update, write).flatten(-2)

write(streams, update)

Y_k = gamma_k X_k + 2 sigmoid(w_k) U for every stream k.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def write(self, streams: torch.Tensor, update: torch.Tensor) -> torch.Tensor:
    """`Y_k = gamma_k X_k + 2 sigmoid(w_k) U` for every stream `k`."""
    streams = streams.unflatten(-1, (self.num_streams, -1))
    update = update.to(streams.dtype).unsqueeze(-2)
    write = 2.0 * torch.sigmoid(self.write_logit.float())
    write = write.to(streams.dtype).unsqueeze(-1)
    if self.retention_logit is not None:
        retention = 1.0 - self.retention_max_forget * torch.sigmoid(
            -self.retention_logit.float()
        )
        streams = streams * retention.to(streams.dtype).unsqueeze(-1)
    return torch.addcmul(streams, update, write).flatten(-2)

NemotronShortcutWideResidualRead

Bases: Module

Mixes the residual streams down to one backbone-width activation.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class NemotronShortcutWideResidualRead(nn.Module):
    """Mixes the residual streams down to one backbone-width activation."""

    def __init__(self, config: PreTrainedConfig) -> None:
        super().__init__()
        self.num_streams = config.wide_residual_num_streams
        self.logit = nn.Parameter(torch.empty(self.num_streams))

    def forward(self, streams: torch.Tensor) -> torch.Tensor:
        streams = streams.unflatten(-1, (self.num_streams, -1))
        factors = torch.sigmoid(self.logit.float()).to(streams.dtype)
        return torch.matmul(factors, streams)

ShortcutMoELayer

Bases: Module

Mixer and MoE branches sharing one block.

The routed branch reads the block input before the mixer writes back, so routing never observes the mixer output; the shared branch reads after. Subclasses own the mixer and split it at its attention or GDP op: mixer_projections runs the input projections and mix the rest.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
class ShortcutMoELayer(nn.Module):
    """Mixer and MoE branches sharing one block.

    The routed branch reads the block input before the mixer writes back, so
    routing never observes the mixer output; the shared branch reads after.
    Subclasses own the mixer and split it at its attention or GDP op:
    `mixer_projections` runs the input projections and `mix` the rest.
    """

    def __init__(
        self,
        config: PreTrainedConfig,
        layer_idx: int,
        model_config: ModelConfig | None = None,
        cache_config: CacheConfig | None = None,
        quant_config: QuantizationConfig | None = None,
        parallel_config: ParallelConfig | None = None,
        prefix: str = "",
        wide_residual: bool = True,
    ) -> None:
        super().__init__()
        # The MTP head reuses this block outside the residual streams, where the
        # ports degenerate to identity reads and ordinary residual adds.
        read_cls = (
            NemotronShortcutWideResidualRead
            if wide_residual
            else NemotronShortcutPlainResidualRead
        )
        conn_cls = (
            NemotronShortcutWideResidualConnection
            if wide_residual
            else NemotronShortcutPlainResidualConnection
        )
        self.shortcut_read = read_cls(config)
        self.shortcut_input_layernorm = RMSNorm(
            config.hidden_size, eps=config.rms_norm_eps
        )
        self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.mixer_residual_connection = conn_cls(config)
        self.pre_moe_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
        self.moe = NemotronShortcutMoE(
            config,
            quant_config=quant_config,
            parallel_config=parallel_config,
            prefix=f"{prefix}.moe",
        )
        self.shortcut_post_norm = (
            RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
            if config.moe_shortcut_post_norm
            else None
        )
        self.moe_residual_connection = conn_cls(config)

    def mixer_projections(
        self, hidden_states: torch.Tensor
    ) -> tuple[torch.Tensor, ...]:
        raise NotImplementedError

    def mix(self, *projections: torch.Tensor) -> torch.Tensor:
        raise NotImplementedError

    def forward(self, streams: torch.Tensor) -> torch.Tensor:
        norm = self.shortcut_input_layernorm
        routed_input = norm(self.shortcut_read(streams).to(norm.weight.dtype))

        dispatch = self.moe.begin_staged(routed_input)
        mixer_input = self.mixer_residual_connection.read(streams, self.input_layernorm)
        projections = self.mixer_projections(mixer_input)
        # The attention or GDP op ends a piecewise CUDA graph piece, which must
        # not end with the dispatch still in flight.
        dispatch = self.moe.receive_staged(dispatch, projections)
        streams = self.mixer_residual_connection.write(streams, self.mix(*projections))

        shared_input = self.moe_residual_connection.read(
            streams, self.pre_moe_layernorm
        )
        combine = self.moe.run_staged_experts(dispatch, streams)
        moe_output = self.moe.finish_staged(combine, shared_input)
        if self.shortcut_post_norm is not None:
            moe_output = self.shortcut_post_norm(moe_output)
        return self.moe_residual_connection.write(streams, moe_output)

check_sdsa_indexer_loaded(model, loaded)

Refuse to serve SDSA layers whose indexer the checkpoint did not provide.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def check_sdsa_indexer_loaded(model: nn.Module, loaded: set[str]) -> None:
    """Refuse to serve SDSA layers whose indexer the checkpoint did not provide."""
    has_sparse = any(
        isinstance(m, NemotronShortcutSparseAttention) for m in model.modules()
    )
    if has_sparse and not any(".indexer." in name for name in loaded):
        raise ValueError(
            "The checkpoint's config has index_topk, but the checkpoint has no "
            "SDSA indexer weights. Without index_topk the model runs full "
            'attention: --hf-overrides \'{"text_config": {"index_topk": null}}\'.'
        )

check_supported(vllm_config)

Refuse deployments the GDP mixers cannot serve, with every reason.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def check_supported(vllm_config: VllmConfig) -> None:
    """Refuse deployments the GDP mixers cannot serve, with every reason."""
    reasons = []
    if vllm_config.cache_config.use_replayssm:
        reasons.append(
            "ReplaySSM is not supported: the GDP verify kernel writes one state "
            "slot per draft token"
        )
    if reasons:
        raise ValueError(
            "Nemotron Shortcut cannot run this configuration: " + "; ".join(reasons)
        )

load_nemotron_shortcut_weights(model, weights, mapper, check_indexer=True)

Load weights, skipping the SDSA indexer when the model runs dense, and check that SDSA layers got their indexer (unless the caller checks the whole load itself).

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def load_nemotron_shortcut_weights(
    model: nn.Module,
    weights: Iterable[tuple[str, torch.Tensor]],
    mapper: WeightsMapper,
    check_indexer: bool = True,
) -> set[str]:
    """Load weights, skipping the SDSA indexer when the model runs dense, and
    check that SDSA layers got their indexer (unless the caller checks the
    whole load itself)."""
    if not any(isinstance(m, NemotronShortcutSparseAttention) for m in model.modules()):
        weights = skip_indexer_weights(weights)
    loaded = AutoWeightsLoader(model).load_weights(weights, mapper=mapper)
    if check_indexer:
        check_sdsa_indexer_loaded(model, loaded)
    return loaded

skip_indexer_weights(weights)

Skip the SDSA indexer's weights, for a model that runs full attention. If the checkpoint has them, warn that the config has no index_topk.

Source code in vllm/models/nemotron_shortcut/nvidia/model.py
def skip_indexer_weights(
    weights: Iterable[tuple[str, torch.Tensor]],
) -> Iterable[tuple[str, torch.Tensor]]:
    """Skip the SDSA indexer's weights, for a model that runs full attention.
    If the checkpoint has them, warn that the config has no `index_topk`."""
    warned = False
    for name, weight in weights:
        if ".indexer." not in name:
            yield name, weight
        elif not warned:
            warned = True
            logger.warning_once(
                "The checkpoint has SDSA indexer weights, but its config has no "
                "index_topk: running full attention and ignoring the indexer. "
                "To run SDSA, set index_topk: "
                '--hf-overrides \'{"text_config": {"index_topk": 2048}}\'.',
                scope="global",
            )