Skip to content

vllm.models.hy_v4

HY V4 (hy_v4) model — hardware-isolated entry point.

HY V4 combines three architectural pieces:

  • iHC (independent Hyper-Connections): the single residual stream is replaced by hc_mult parallel residual channels, gated per sub-block.
  • MLA + lightning indexer: multi-head latent attention with an optional DSA-style sparse top-k selection, plus an output gate and a learnable sink.
  • MoE: sigmoid-routed experts with a clamped SwiGLU and shared experts.

The package is organized like vllm.models.deepseek_v32: this module is the only public entry point and dispatches on the current platform, so registry entries never reach into a platform subpackage.

NVIDIA and ROCm are supported through nvidia/ and amd/, with vendor-neutral code in common/. The port also drops the reference implementation's HPC/TPCP fusion paths, which depend on infrastructure that does not exist in this tree.

Modules:

Classes:

HYV4MTP

Bases: Module

HY V4 MTP draft head.

Not a pipeline-parallel stage: the draft head always runs on a single rank, matching DeepseekV32MTP / KimiK3MTP / HYV3MTP.

Methods:

Source code in vllm/models/hy_v4/nvidia/mtp.py
class HYV4MTP(nn.Module):
    """HY V4 MTP draft head.

    Not a pipeline-parallel stage: the draft head always runs on a single rank,
    matching `DeepseekV32MTP` / `KimiK3MTP` / `HYV3MTP`.
    """

    packed_modules_mapping = {
        "gate_up_proj": ["gate_proj", "up_proj"],
        # MLA runs both latent down-projections as one GEMM.
        "fused_qkv_a_proj": ["q_a_proj", "kv_a_proj_with_mqa"],
    }

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        self.config = vllm_config.model_config.hf_config
        self.model = HYV4MultiTokenPredictor(
            vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model")
        )
        self.quant_config = self.model.quant_config

    def set_topk_indices_buffer(self, topk_indices_buffer: torch.Tensor) -> None:
        """Share the target sparse-index buffer with every draft consumer.

        Proposers that walk `named_modules()` instead of calling this reach
        the same consumers via `HYV4MLAAttention.topk_indices_buffer`.
        """
        self.model.topk_indices_buffer = topk_indices_buffer
        for layer in self.model.layers.values():
            self_attn = layer.mtp_block.self_attn
            if not self_attn.is_sparse:
                continue

            indexer = self_attn.indexer
            assert indexer is not None, "Sparse HYV4 MTP attention requires an indexer"
            indexer.topk_indices_buffer = topk_indices_buffer
            indexer.indexer_op.topk_indices_buffer = topk_indices_buffer

            attn_impl = self_attn.mla_attn.impl
            assert hasattr(attn_impl, "topk_indices_buffer"), (
                "Sparse HYV4 MTP attention backend requires a top-k indices buffer"
            )
            attn_impl.topk_indices_buffer = topk_indices_buffer

    def forward(
        self,
        input_ids: torch.Tensor,
        positions: torch.Tensor,
        hidden_states: torch.Tensor,
        intermediate_tensors: IntermediateTensors | None = None,
        inputs_embeds: torch.Tensor | None = None,
        spec_step_idx: int = 0,
    ) -> torch.Tensor:
        del intermediate_tensors  # the MTP head is single-stage
        if (
            self.model.requires_topk_indices_buffer
            and self.model.topk_indices_buffer is None
        ):
            raise RuntimeError(
                "HYV4 sparse MTP requires the target model's top-k indices buffer. "
                "The proposer must call HYV4MTP.set_topk_indices_buffer() before "
                "the first draft forward."
            )
        self.model.spec_step_idx = spec_step_idx
        return self.model(input_ids, positions, hidden_states, inputs_embeds)

    def compute_logits(
        self,
        hidden_states: torch.Tensor,
        spec_step_idx: int = 0,
    ) -> torch.Tensor | None:
        self.model.spec_step_idx = spec_step_idx
        return self.model.compute_logits(hidden_states)

    def _rewrite_spec_layer_name(self, spec_layer: int, name: str) -> str:
        if f"model.layers.{spec_layer}.embed_tokens" in name:
            return "__skip__"
        if f"model.layers.{spec_layer}.shared_head" in name:
            return "__skip__"

        spec_layer_weight_names = ["enorm", "hnorm", "eh_proj", "final_layernorm"]
        spec_layer_weight = any(
            weight_name in name for weight_name in spec_layer_weight_names
        )
        if not spec_layer_weight:
            name = name.replace(
                f"model.layers.{spec_layer}.",
                f"model.layers.{spec_layer}.mtp_block.",
            )
        return name

    def _load_fused_expert_weights(
        self,
        name: str,
        params_dict: dict,
        loaded_weight: torch.Tensor,
        shard_id: str,
        num_experts: int,
    ) -> bool:
        if name not in params_dict:
            return False
        param = params_dict[name]
        weight_loader = typing.cast(Callable[..., bool], param.weight_loader)
        loaded_local_expert = False
        for expert_id in range(num_experts):
            curr_expert_weight = loaded_weight[expert_id]
            success = weight_loader(
                param,
                curr_expert_weight,
                name,
                shard_id,
                expert_id,
                return_success=True,
            )
            if success:
                loaded_local_expert = True
        return loaded_local_expert

    def _load_expert_weight(
        self,
        name: str,
        loaded_weight: torch.Tensor,
        params_dict: dict,
        loaded_params: set[str],
        split_expert_params_mapping: list[tuple[str, str, int, str]],
        fused_expert_param_names: dict[tuple[str, str], str],
        num_experts: int,
    ) -> bool:
        """Load one routed-expert weight in either checkpoint layout.

        Args:
            name: Weight name already rewritten to draft-module naming.
            loaded_weight: The checkpoint tensor.
            params_dict: The draft model's named parameters.
            loaded_params: Set updated with the parameters that received a value.
            split_expert_params_mapping: Mapping for the per-expert layout.
            fused_expert_param_names: `(mlp_prefix, tag) -> param name` for the
                all-experts-packed layout.
            num_experts: Total number of routed experts.

        Returns:
            True when the weight was consumed (even if this rank holds none of
            the addressed experts).

        """
        base = name.split(".experts.")[0]
        for ckpt_proj, tag in (
            (".experts.gate_up_proj", "w13_weight"),
            (".experts.down_proj", "w2_weight"),
        ):
            if ckpt_proj not in name:
                continue
            param_base = fused_expert_param_names.get((base, tag))
            if param_base is None:
                return False
            # Keep the checkpoint suffix (e.g. `_scale_inv`) so block-scale
            # tensors land in the scale parameter, not in the weight.
            target = _resolve_fused_expert_param(
                param_base, name.split(ckpt_proj, 1)[1], params_dict
            )
            if target is None:
                return False
            if tag == "w13_weight":
                chunks = loaded_weight.chunk(2, dim=-2)
                loaded_w1 = self._load_fused_expert_weights(
                    target, params_dict, chunks[0], "w1", num_experts
                )
                loaded_w3 = self._load_fused_expert_weights(
                    target, params_dict, chunks[1], "w3", num_experts
                )
                loaded = loaded_w1 and loaded_w3
            else:
                loaded = self._load_fused_expert_weights(
                    target, params_dict, loaded_weight, "w2", num_experts
                )
            if loaded:
                loaded_params.add(target)
            # The weight belongs to the experts either way; never fall through.
            return True

        consumed = False
        for param_name, weight_name, expert_id, shard_id in split_expert_params_mapping:
            if weight_name not in name:
                continue
            consumed = True
            name_mapped = name.replace(weight_name, param_name)
            if name_mapped not in params_dict:
                continue
            param = params_dict[name_mapped]
            weight_loader = typing.cast(Callable[..., bool], param.weight_loader)
            if weight_loader(
                param,
                loaded_weight,
                name_mapped,
                shard_id=shard_id,
                expert_id=expert_id,
                return_success=True,
            ):
                loaded_params.add(name_mapped)
        return consumed

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        params_dict = dict(self.named_parameters())
        loaded_params: set[str] = set()

        mtp_start = self.config.num_hidden_layers
        shared_weights = {
            "model.embed_tokens.weight": "model.embed_tokens.weight",
            "lm_head.weight": f"model.layers.{mtp_start}.shared_head.head.weight",
        }

        num_experts = getattr(self.config, "n_routed_experts", 0)

        # Routed-expert weights come in two checkpoint layouts:
        #   split: mlp.experts.<id>.gate_proj.weight
        #   fused: mlp.experts.gate_up_proj (all experts in one tensor)
        # The split layout is resolved through the shared EPLB helper so the
        # target param names stay in sync with the RoutedExperts module layout;
        # the fused layout is resolved from the live parameter names.
        split_expert_params_mapping = fused_moe_make_expert_params_mapping(
            self,
            ckpt_gate_proj_name="gate_proj",
            ckpt_down_proj_name="down_proj",
            ckpt_up_proj_name="up_proj",
            num_experts=num_experts,
        )
        fused_expert_param_names: dict[tuple[str, str], str] = {}
        for param_name in params_dict:
            for tag in ("w13_weight", "w2_weight"):
                if param_name.endswith(tag) and ".experts." in param_name:
                    base = param_name.split(".experts.")[0]
                    fused_expert_param_names[base, tag] = param_name
        stacked_mapping = [
            (".gate_up_proj", ".gate_proj", 0),
            (".gate_up_proj", ".up_proj", 1),
            # MLA runs both latent down-projections as one GEMM.
            (".fused_qkv_a_proj", ".q_a_proj", 0),
            (".fused_qkv_a_proj", ".kv_a_proj_with_mqa", 1),
        ]

        for name, loaded_weight in weights:
            if name in shared_weights:
                target_name = shared_weights[name]
                if target_name in params_dict:
                    param = params_dict[target_name]
                    weight_loader = getattr(
                        param, "weight_loader", default_weight_loader
                    )
                    weight_loader(param, loaded_weight)
                    loaded_params.add(target_name)
                continue

            spec_layer = None
            if name.startswith("model.mtp_layers."):
                parts = name.split(".")
                if len(parts) > 3 and parts[2].isdigit():
                    spec_layer = mtp_start + int(parts[2])
                    name = name.replace(
                        f"model.mtp_layers.{parts[2]}.",
                        f"model.layers.{spec_layer}.",
                    )
            else:
                spec_layer = _get_spec_layer_idx_from_weight_name(self.config, name)

            if spec_layer is None:
                continue

            name = self._rewrite_spec_layer_name(spec_layer, name)
            if name == "__skip__":
                continue
            name, loaded_weight = _prepare_mtp_fp8_expert_scale(
                self.quant_config, name, loaded_weight
            )

            if "mlp.gate.e_score_correction_bias" in name:
                name = name.replace("gate.e_score_correction_bias", "expert_bias")

            is_loaded = False
            for param_name, weight_name, shard_id in stacked_mapping:
                if weight_name not in name or ".experts." in name:
                    continue
                name_mapped = name.replace(weight_name, param_name)
                if name_mapped not in params_dict:
                    if is_pp_missing_parameter(name_mapped, self):
                        is_loaded = True
                    break
                param = params_dict[name_mapped]
                param.weight_loader(param, loaded_weight, shard_id)
                loaded_params.add(name_mapped)
                is_loaded = True
                break
            if is_loaded:
                continue

            is_loaded = False
            if ".experts." in name:
                is_loaded = self._load_expert_weight(
                    name,
                    loaded_weight,
                    params_dict,
                    loaded_params,
                    split_expert_params_mapping,
                    fused_expert_param_names,
                    num_experts,
                )
            if is_loaded:
                continue

            remapped_name = maybe_remap_kv_scale_name(name, params_dict)
            if remapped_name is None:
                continue
            name = remapped_name
            if name not in params_dict:
                if is_pp_missing_parameter(name, self):
                    continue
                if _should_skip_missing_mtp_scale_param(self.quant_config, name):
                    continue
                logger.warning_once("Skipping unknown MTP weight: %s", name)
                continue

            param = params_dict[name]
            weight_loader = getattr(param, "weight_loader", default_weight_loader)
            weight_loader(param, loaded_weight)
            loaded_params.add(name)

        logger.info_once("HYV4 MTP draft model loaded: %d params", len(loaded_params))
        unassigned_all = sorted(set(params_dict) - loaded_params)
        # KVCacheScaleParameter (``k_scale`` / ``v_scale`` / ``q_scale`` /
        # ``prob_scale``) is created by ``BaseKVCacheMethod.create_weights`` for
        # every Attention layer that runs on an fp8-family quant method, and
        # its -1.0 sentinel is replaced by the runtime default (1.0) in
        # ``process_weights_after_loading`` -- which runs *after* this method.
        # HY V4 checkpoints intentionally omit these (``kv_cache_quant_algo:
        # null``); silence them only when the parameter is actually the
        # sentinel type so a genuine mismatch on a same-named tensor still
        # reaches the warning.
        from vllm.model_executor.layers.quantization.kv_cache import (
            KVCacheScaleParameter,
        )

        unassigned = [
            name
            for name in unassigned_all
            if not isinstance(params_dict.get(name), KVCacheScaleParameter)
        ]
        missing_scales = [name for name in unassigned if "weight_scale" in name]
        if missing_scales:
            raise ValueError(
                "Missing MTP checkpoint weight scales: " + ", ".join(missing_scales)
            )
        if unassigned:
            # A draft parameter with no checkpoint source keeps its sentinel
            # init value (FP8 scales start at finfo(float32).min), which
            # silently destroys draft quality instead of failing the load.
            logger.warning(
                "HYV4 MTP draft model: %d parameters received no checkpoint value: %s",
                len(unassigned),
                ", ".join(unassigned),
            )
        return loaded_params

_load_expert_weight(name, loaded_weight, params_dict, loaded_params, split_expert_params_mapping, fused_expert_param_names, num_experts)

Load one routed-expert weight in either checkpoint layout.

Parameters:

  • name

    (str) –

    Weight name already rewritten to draft-module naming.

  • loaded_weight

    (Tensor) –

    The checkpoint tensor.

  • params_dict

    (dict) –

    The draft model's named parameters.

  • loaded_params

    (set[str]) –

    Set updated with the parameters that received a value.

  • split_expert_params_mapping

    (list[tuple[str, str, int, str]]) –

    Mapping for the per-expert layout.

  • fused_expert_param_names

    (dict[tuple[str, str], str]) –

    (mlp_prefix, tag) -> param name for the all-experts-packed layout.

  • num_experts

    (int) –

    Total number of routed experts.

Returns:

  • bool –

    True when the weight was consumed (even if this rank holds none of

  • bool –

    the addressed experts).

Source code in vllm/models/hy_v4/nvidia/mtp.py
def _load_expert_weight(
    self,
    name: str,
    loaded_weight: torch.Tensor,
    params_dict: dict,
    loaded_params: set[str],
    split_expert_params_mapping: list[tuple[str, str, int, str]],
    fused_expert_param_names: dict[tuple[str, str], str],
    num_experts: int,
) -> bool:
    """Load one routed-expert weight in either checkpoint layout.

    Args:
        name: Weight name already rewritten to draft-module naming.
        loaded_weight: The checkpoint tensor.
        params_dict: The draft model's named parameters.
        loaded_params: Set updated with the parameters that received a value.
        split_expert_params_mapping: Mapping for the per-expert layout.
        fused_expert_param_names: `(mlp_prefix, tag) -> param name` for the
            all-experts-packed layout.
        num_experts: Total number of routed experts.

    Returns:
        True when the weight was consumed (even if this rank holds none of
        the addressed experts).

    """
    base = name.split(".experts.")[0]
    for ckpt_proj, tag in (
        (".experts.gate_up_proj", "w13_weight"),
        (".experts.down_proj", "w2_weight"),
    ):
        if ckpt_proj not in name:
            continue
        param_base = fused_expert_param_names.get((base, tag))
        if param_base is None:
            return False
        # Keep the checkpoint suffix (e.g. `_scale_inv`) so block-scale
        # tensors land in the scale parameter, not in the weight.
        target = _resolve_fused_expert_param(
            param_base, name.split(ckpt_proj, 1)[1], params_dict
        )
        if target is None:
            return False
        if tag == "w13_weight":
            chunks = loaded_weight.chunk(2, dim=-2)
            loaded_w1 = self._load_fused_expert_weights(
                target, params_dict, chunks[0], "w1", num_experts
            )
            loaded_w3 = self._load_fused_expert_weights(
                target, params_dict, chunks[1], "w3", num_experts
            )
            loaded = loaded_w1 and loaded_w3
        else:
            loaded = self._load_fused_expert_weights(
                target, params_dict, loaded_weight, "w2", num_experts
            )
        if loaded:
            loaded_params.add(target)
        # The weight belongs to the experts either way; never fall through.
        return True

    consumed = False
    for param_name, weight_name, expert_id, shard_id in split_expert_params_mapping:
        if weight_name not in name:
            continue
        consumed = True
        name_mapped = name.replace(weight_name, param_name)
        if name_mapped not in params_dict:
            continue
        param = params_dict[name_mapped]
        weight_loader = typing.cast(Callable[..., bool], param.weight_loader)
        if weight_loader(
            param,
            loaded_weight,
            name_mapped,
            shard_id=shard_id,
            expert_id=expert_id,
            return_success=True,
        ):
            loaded_params.add(name_mapped)
    return consumed

set_topk_indices_buffer(topk_indices_buffer)

Share the target sparse-index buffer with every draft consumer.

Proposers that walk named_modules() instead of calling this reach the same consumers via HYV4MLAAttention.topk_indices_buffer.

Source code in vllm/models/hy_v4/nvidia/mtp.py
def set_topk_indices_buffer(self, topk_indices_buffer: torch.Tensor) -> None:
    """Share the target sparse-index buffer with every draft consumer.

    Proposers that walk `named_modules()` instead of calling this reach
    the same consumers via `HYV4MLAAttention.topk_indices_buffer`.
    """
    self.model.topk_indices_buffer = topk_indices_buffer
    for layer in self.model.layers.values():
        self_attn = layer.mtp_block.self_attn
        if not self_attn.is_sparse:
            continue

        indexer = self_attn.indexer
        assert indexer is not None, "Sparse HYV4 MTP attention requires an indexer"
        indexer.topk_indices_buffer = topk_indices_buffer
        indexer.indexer_op.topk_indices_buffer = topk_indices_buffer

        attn_impl = self_attn.mla_attn.impl
        assert hasattr(attn_impl, "topk_indices_buffer"), (
            "Sparse HYV4 MTP attention backend requires a top-k indices buffer"
        )
        attn_impl.topk_indices_buffer = topk_indices_buffer

HYV4VLForConditionalGeneration

Bases: Module, HYV4VLEncoderCudaGraphMixin, SupportsMultiModal, SupportsEncoderCudaGraph, SupportsMRoPE, SupportsPP

HYV4 VL composition using the platform-selected HYV4 text model.

Source code in vllm/models/hy_v4/common/vl_model.py
@MULTIMODAL_REGISTRY.register_processor(
    HYV4VLMultiModalProcessor,
    info=HYV4VLProcessingInfo,
    dummy_inputs=HYV4VLDummyInputsBuilder,
)
class HYV4VLForConditionalGeneration(
    nn.Module,
    HYV4VLEncoderCudaGraphMixin,
    SupportsMultiModal,
    SupportsEncoderCudaGraph,
    SupportsMRoPE,
    SupportsPP,
):
    """HYV4 VL composition using the platform-selected HYV4 text model."""

    supports_mm_device_do_normalize = True
    language_model_architecture = "HYV4ForCausalLM"

    packed_modules_mapping = {
        **HYV4_PACKED_MODULES_MAPPING,
        "qkv": ["q_proj", "k_proj", "v_proj"],
    }
    hf_to_vllm_mapper = WeightsMapper(
        orig_to_new_prefix={
            "vit.vit.": "visual.",
            "vit.": "visual.",
            "model.": "language_model.model.",
            "lm_head.": "language_model.lm_head.",
        },
        orig_to_new_substr={
            "self_attn.query_layernorm": "self_attn.q_norm",
            "self_attn.key_layernorm": "self_attn.k_norm",
            "mlp.gate.wg": "mlp.gate",
        },
    )

    @classmethod
    def get_placeholder_str(cls, modality: str, i: int) -> str:
        modality = modality.removesuffix("_embeds")
        if modality in ("image", "video"):
            return f"<{modality}>"
        raise ValueError(f"Unsupported HYV4 VL modality: {modality}")

    def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""):
        super().__init__()
        self.model_config = vllm_config.model_config
        self.config = vllm_config.model_config.hf_config
        self.multimodal_config = vllm_config.model_config.get_multimodal_config()
        enabled = any(
            self.multimodal_config.get_limit_per_prompt(m) for m in ("image", "video")
        )
        with self._mark_tower_model(vllm_config, {"image", "video"}):
            self.visual = None
            if enabled:
                quant = vllm_config.quant_config
                self.visual = HYV4VisionTransformer(
                    self.config.vision_config,
                    quant_config=quant,
                    prefix=maybe_prefix(prefix, "visual"),
                    input_norm=build_mm_input_norm(vllm_config.model_config),
                )
        with self._mark_language_model(vllm_config):
            self.language_model = init_vllm_registered_model(
                vllm_config=vllm_config,
                hf_config=self.config.text_config,
                architectures=[self.language_model_architecture],
                prefix=maybe_prefix(prefix, "language_model"),
            )
        self.make_empty_intermediate_tensors = (
            self.language_model.make_empty_intermediate_tensors
        )

    def _parse_and_validate_image_input(
        self, **kwargs: object
    ) -> HYV4VLImagePixelInputs | None:
        pixel_values = kwargs.pop("pixel_values", None)
        if pixel_values is None:
            return None
        if isinstance(pixel_values, list):
            pixel_values = torch.cat(
                [item.reshape(-1, item.shape[-1]) for item in pixel_values]
            )
        elif isinstance(pixel_values, torch.Tensor) and pixel_values.ndim > 0:
            pixel_values = pixel_values.reshape(-1, pixel_values.shape[-1])
        grid = kwargs.pop("image_grid_thw", None)
        if isinstance(grid, list):
            grid = torch.stack(grid)
        if isinstance(grid, torch.Tensor) and grid.ndim > 0:
            grid = grid.reshape(-1, grid.shape[-1])
        config = self.config.vision_config
        return HYV4VLImagePixelInputs(
            pixel_values=pixel_values,
            image_grid_thw=grid,
            resolve_bindings={"cps": config.num_channels * config.patch_size**2},
        )

    def _parse_and_validate_video_input(
        self, **kwargs: object
    ) -> HYV4VLVideoPixelInputs | None:
        pixel_values = kwargs.pop("pixel_values_videos", None)
        if pixel_values is None:
            return None
        if isinstance(pixel_values, list):
            pixel_values = torch.cat(
                [item.reshape(-1, item.shape[-1]) for item in pixel_values]
            )
        elif isinstance(pixel_values, torch.Tensor) and pixel_values.ndim > 0:
            pixel_values = pixel_values.reshape(-1, pixel_values.shape[-1])
        grid = kwargs.pop("video_grid_thw", None)
        if isinstance(grid, list):
            grid = torch.stack(grid)
        if isinstance(grid, torch.Tensor) and grid.ndim > 0:
            grid = grid.reshape(-1, grid.shape[-1])
        config = self.config.vision_config
        return HYV4VLVideoPixelInputs(
            pixel_values_videos=pixel_values,
            video_grid_thw=grid,
            resolve_bindings={"cps": config.num_channels * config.patch_size**2},
        )

    def embed_multimodal(self, **kwargs: object) -> MultiModalEmbeddings:
        if (
            kwargs.get("image_embeds") is not None
            or kwargs.get("video_embeds") is not None
        ):
            raise ValueError("HYV4 VL does not support precomputed visual embeddings")
        outputs = []
        parsers = {
            "pixel_values": ("image", self._parse_and_validate_image_input),
            "pixel_values_videos": ("video", self._parse_and_validate_video_input),
        }
        for key, value in kwargs.items():
            if key not in parsers or value is None:
                continue
            modality, parse_input = parsers[key]
            if self.visual is None:
                raise ValueError(
                    "HYV4 visual inputs are disabled by limit_mm_per_prompt"
                )
            mm_input = parse_input(**kwargs)
            assert mm_input is not None
            grids = mm_input[f"{modality}_grid_thw"].tolist()
            counts = [
                vision_token_count(g, self.config.vision_config, modality)
                for g in grids
            ]
            embeds = self.visual(mm_input[key], grids)
            for embedding, count in zip(embeds, counts, strict=True):
                if embedding.shape != (count, self.config.text_config.hidden_size):
                    raise ValueError(
                        f"{modality} visual embeddings do not match token grid"
                    )
            outputs.extend(embeds)
        return tuple(outputs)

    def forward(
        self,
        input_ids,
        positions,
        intermediate_tensors=None,
        inputs_embeds=None,
        **kwargs,
    ):
        if intermediate_tensors is not None:
            inputs_embeds = None
        return self.language_model(
            input_ids, positions, intermediate_tensors, inputs_embeds
        )

    def compute_logits(self, hidden_states):
        return self.language_model.compute_logits(hidden_states)

    def get_expert_mapping(self):
        return self.language_model.get_expert_mapping()

    def get_mm_mapping(self):
        return MultiModelKeys.from_string_field(
            language_model="language_model",
            connector="visual.perceive",
            tower_model=["visual.embeddings", "visual.layers"],
        )

    def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]:
        loader = AutoWeightsLoader(
            self,
            ignore_unexpected_prefixes=["visual."] if self.visual is None else None,
        )
        return loader.load_weights(weights, mapper=self.hf_to_vllm_mapper)

    def get_mrope_input_positions(
        self,
        input_tokens: list[int],
        mm_features: list[MultiModalFeatureSpec],
    ) -> tuple[torch.Tensor, int]:
        tokens = torch.tensor(input_tokens, dtype=torch.long)
        positions = torch.arange(len(input_tokens)).repeat(3, 1)
        if not input_tokens or not mm_features:
            return positions, 0
        data = MultiModalFeatureSpec.gather_kwargs(
            mm_features, {"image_grid_thw", "video_grid_thw"}
        )
        image_grids = [grid.tolist() for grid in data.get("image_grid_thw", [])]
        video_grids = [grid.tolist() for grid in data.get("video_grid_thw", [])]
        config = self.config
        vision = config.vision_config
        starts = torch.where(tokens == config.image_start_token_id)[0].tolist()
        ends = torch.where(tokens == config.image_end_token_id)[0].tolist()
        if len(starts) != len(ends):
            raise ValueError("HYV4 image/frame start and end tokens must be paired")
        start_pos = start_index = mm_index = scan = 0
        image_index = video_index = -1
        inside_video = False
        while mm_index < len(starts):
            marker = starts[mm_index]
            while scan < marker:
                if input_tokens[scan] == config.video_start_token_id:
                    inside_video = True
                elif input_tokens[scan] == config.video_end_token_id:
                    inside_video = False
                scan += 1
            is_video = inside_video or (
                image_index + 1 >= len(image_grids)
                and video_index + 1 < len(video_grids)
            )
            if is_video:
                video_index += 1
                if video_index >= len(video_grids):
                    raise ValueError("Video placeholders do not match video_grid_thw")
                frames, rows, cols = vision_token_grid(
                    video_grids[video_index], vision, "video"
                )
            else:
                image_index += 1
                if image_index >= len(image_grids):
                    raise ValueError("Image placeholders do not match image_grid_thw")
                frames, rows, cols = vision_token_grid(
                    image_grids[image_index], vision, "image"
                )
            if mm_index + frames > len(starts) or mm_index + frames > len(ends):
                raise ValueError("Missing HYV4 image/frame boundary tokens")
            extra = int(bool(vision.cat_extra_token))
            pos = marker + 1 + extra
            if start_pos < pos:
                positions[:, start_pos:pos] = (
                    torch.arange(pos - start_pos) + start_index
                )
                start_index += pos - start_pos
            count = rows * cols
            for frame in range(frames):
                begin = starts[mm_index + frame] + 1 + extra
                end = begin + count
                pad_id = config.video_token_id if is_video else config.image_token_id
                if end + extra != ends[mm_index + frame] or not torch.all(
                    tokens[begin - extra : end + extra] == pad_id
                ):
                    raise ValueError(
                        "HYV4 visual placeholders do not match "
                        "frame boundaries and grid"
                    )
                positions[0, begin:end] = start_index
                positions[1, begin:end] = (
                    torch.arange(rows).repeat_interleave(cols) + start_index
                )
                positions[2, begin:end] = torch.arange(cols).repeat(rows) + start_index
                start_index += max(rows, cols)
                if is_video and frame + 1 < frames:
                    bridge_start = ends[mm_index + frame]
                    bridge_end = starts[mm_index + frame + 1] + 1
                    positions[:, bridge_start:bridge_end] = (
                        torch.arange(bridge_end - bridge_start) + start_index
                    )
                    start_index += bridge_end - bridge_start
            start_pos = ends[mm_index + frames - 1] if is_video else pos + count
            mm_index += frames
        if start_pos < len(input_tokens):
            positions[:, start_pos:] = (
                torch.arange(len(input_tokens) - start_pos) + start_index
            )
        if image_index + 1 != len(image_grids) or video_index + 1 != len(video_grids):
            raise ValueError("Unused HYV4 media grids after position construction")
        return positions, int(positions.max()) + 1 - len(input_tokens)

__getattr__(name)

Load model code only when requested, keeping config-only imports light.

Source code in vllm/models/hy_v4/__init__.py
def __getattr__(name: str) -> Any:
    """Load model code only when requested, keeping config-only imports light."""
    if name not in __all__:
        raise AttributeError(f"module {__name__!r} has no attribute {name!r}")

    from vllm.platforms import current_platform

    if current_platform.is_xpu():
        raise NotImplementedError("hy_v4 does not yet support XPU.")
    platform = "amd" if current_platform.is_rocm() else "nvidia"
    modules = {
        "HYV4ForCausalLM": f".{platform}.model",
        # The MTP head runs on ROCm through the NVIDIA layers it shares.
        "HYV4MTP": ".nvidia.mtp",
        "HYV4DFlyForCausalLM": f".{platform}.dfly",
        "HYV4DFlySpeculator": f".{platform}.dfly_speculator",
        "HYV4VLForConditionalGeneration": (
            ".common.vl_model" if current_platform.is_cuda_alike() else ".vl_stub"
        ),
    }
    model_cls = getattr(import_module(modules[name], __name__), name)
    globals()[name] = model_cls
    return model_cls