| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | """Inference-only Laguna model compatible with HuggingFace weights.""" |
| 4 | |
| 5 | from collections.abc import Iterable |
| 6 | from itertools import islice |
| 7 | |
| 8 | import torch |
| 9 | import torch.nn.functional as F |
| 10 | from torch import nn |
| 11 | |
| 12 | from vllm.compilation.decorators import support_torch_compile |
| 13 | from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config |
| 14 | from vllm.distributed import ( |
| 15 | get_ep_group, |
| 16 | get_pp_group, |
| 17 | get_tensor_model_parallel_rank, |
| 18 | get_tensor_model_parallel_world_size, |
| 19 | ) |
| 20 | from vllm.logger import init_logger |
| 21 | from vllm.model_executor.layers.attention import Attention |
| 22 | from vllm.model_executor.layers.fused_moe import ( |
| 23 | FusedMoEFactory, |
| 24 | GateLinear, |
| 25 | ) |
| 26 | from vllm.model_executor.layers.layernorm import RMSNorm |
| 27 | from vllm.model_executor.layers.linear import ( |
| 28 | ColumnParallelLinear, |
| 29 | QKVParallelLinear, |
| 30 | RowParallelLinear, |
| 31 | ) |
| 32 | from vllm.model_executor.layers.logits_processor import LogitsProcessor |
| 33 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 34 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 35 | from vllm.model_executor.layers.vocab_parallel_embedding import ( |
| 36 | ParallelLMHead, |
| 37 | VocabParallelEmbedding, |
| 38 | ) |
| 39 | from vllm.model_executor.models.interfaces import ( |
| 40 | EagleModelMixin, |
| 41 | SupportsEagle3, |
| 42 | SupportsLoRA, |
| 43 | SupportsPP, |
| 44 | ) |
| 45 | from vllm.model_executor.models.utils import ( |
| 46 | AutoWeightsLoader, |
| 47 | PPMissingLayer, |
| 48 | WeightsMapper, |
| 49 | extract_layer_index, |
| 50 | make_empty_intermediate_tensors_factory, |
| 51 | make_layers, |
| 52 | maybe_prefix, |
| 53 | ) |
| 54 | from vllm.sequence import IntermediateTensors |
| 55 | |
| 56 | logger = init_logger(__name__) |
| 57 | |
| 58 | |
| 59 | def get_mlp_layer_types(config) -> list[str]: |
| 60 | """Return which layers are MoE, rejecting configs predating Transformers support.""" |
| 61 | mlp_layer_types = getattr(config, "mlp_layer_types", None) |
| 62 | if mlp_layer_types is None: |
| 63 | raise ValueError( |
| 64 | "Laguna requires the `LagunaConfig` from Transformers, which is " |
| 65 | "available from v5.17.0. Please update Transformers to run this model." |
| 66 | ) |
| 67 | return mlp_layer_types |
| 68 | |
| 69 | |
| 70 | class LagunaMLP(nn.Module): |
| 71 | """Dense MLP for Laguna.""" |
| 72 | |
| 73 | def __init__( |
| 74 | self, |
| 75 | hidden_size: int, |
| 76 | intermediate_size: int, |
| 77 | hidden_act: str, |
| 78 | quant_config: QuantizationConfig | None = None, |
| 79 | reduce_results: bool = True, |
| 80 | prefix: str = "", |
| 81 | ) -> None: |
| 82 | super().__init__() |
| 83 | # gate_proj and up_proj are kept as separate ColumnParallelLinear |
| 84 | # rather than merged via MergedColumnParallelLinear. The merged form |
| 85 | # requires per-partition NVFP4 global scales (weight_global_scale, |
| 86 | # input_global_scale) to be packed into a length-2 PerTensorScaleParameter |
| 87 | # and then collapsed via .max() in process_weights_after_loading; this |
| 88 | # doesn't round-trip cleanly through Marlin's NVFP4 stacked-layer code |
| 89 | # path. Splitting yields one global scale per Linear, exactly matching |
| 90 | # the standard compressed-tensors per-Linear schema on disk. |
| 91 | self.gate_proj = ColumnParallelLinear( |
| 92 | hidden_size, |
| 93 | intermediate_size, |
| 94 | bias=False, |
| 95 | quant_config=quant_config, |
| 96 | prefix=f"{prefix}.gate_proj", |
| 97 | ) |
| 98 | self.up_proj = ColumnParallelLinear( |
| 99 | hidden_size, |
| 100 | intermediate_size, |
| 101 | bias=False, |
| 102 | quant_config=quant_config, |
| 103 | prefix=f"{prefix}.up_proj", |
| 104 | ) |
| 105 | self.down_proj = RowParallelLinear( |
| 106 | intermediate_size, |
| 107 | hidden_size, |
| 108 | bias=False, |
| 109 | quant_config=quant_config, |
| 110 | reduce_results=reduce_results, |
| 111 | prefix=f"{prefix}.down_proj", |
| 112 | ) |
| 113 | if hidden_act != "silu": |
| 114 | raise ValueError( |
| 115 | f"Unsupported activation: {hidden_act}. Only silu is supported." |
| 116 | ) |
| 117 | |
| 118 | def forward(self, x: torch.Tensor) -> torch.Tensor: |
| 119 | gate, _ = self.gate_proj(x) |
| 120 | up, _ = self.up_proj(x) |
| 121 | x, _ = self.down_proj(F.silu(gate) * up) |
| 122 | return x |
| 123 | |
| 124 | |
| 125 | class LagunaMoE(nn.Module): |
| 126 | """Sparse MoE block for Laguna with optional shared expert and sigmoid routing. |
| 127 | |
| 128 | Key differences from other MoE implementations: |
| 129 | - Uses SIGMOID routing activation (not softmax) |
| 130 | - Shared expert runs in parallel with routed experts (when enabled) |
| 131 | - Matches HF reference: modular_laguna.py LagunaSparseMoeBlock |
| 132 | """ |
| 133 | |
| 134 | def __init__( |
| 135 | self, |
| 136 | config, |
| 137 | quant_config: QuantizationConfig | None = None, |
| 138 | prefix: str = "", |
| 139 | enable_eplb: bool = False, |
| 140 | ): |
| 141 | super().__init__() |
| 142 | self.config = config |
| 143 | self.num_experts = config.num_experts |
| 144 | self.top_k = config.num_experts_per_tok |
| 145 | |
| 146 | self.tp_size = get_tensor_model_parallel_world_size() |
| 147 | self.ep_group = get_ep_group().device_group |
| 148 | self.ep_size = self.ep_group.size() |
| 149 | |
| 150 | self.n_routed_experts = config.num_experts |
| 151 | self.n_shared_experts = 1 if config.shared_expert_intermediate_size > 0 else 0 |
| 152 | self.routed_scaling_factor = float( |
| 153 | getattr(config, "moe_routed_scaling_factor", 1.0) |
| 154 | ) |
| 155 | |
| 156 | if self.tp_size > config.num_experts: |
| 157 | raise ValueError( |
| 158 | f"Tensor parallel size {self.tp_size} is greater than " |
| 159 | f"the number of experts {config.num_experts}." |
| 160 | ) |
| 161 | |
| 162 | # Load balancing settings. |
| 163 | vllm_config = get_current_vllm_config() |
| 164 | eplb_config = vllm_config.parallel_config.eplb_config |
| 165 | self.enable_eplb = enable_eplb |
| 166 | eplb_config.num_redundant_experts = ( |
| 167 | eplb_config.num_redundant_experts |
| 168 | if eplb_config.num_redundant_experts is not None |
| 169 | else 0 |
| 170 | ) |
| 171 | self.n_redundant_experts = eplb_config.num_redundant_experts |
| 172 | self.n_logical_experts = self.n_routed_experts |
| 173 | self.n_physical_experts = self.n_logical_experts + self.n_redundant_experts |
| 174 | self.n_local_physical_experts = self.n_physical_experts // self.ep_size |
| 175 | # Router gate |
| 176 | self.gate = GateLinear( |
| 177 | config.hidden_size, |
| 178 | config.num_experts, |
| 179 | prefix=f"{prefix}.gate", |
| 180 | ) |
| 181 | |
| 182 | # Shared expert (optional) - passed to FusedMoEFactory for overlap optimization |
| 183 | self.shared_expert: LagunaMLP | None |
| 184 | if config.shared_expert_intermediate_size > 0: |
| 185 | self.shared_expert = LagunaMLP( |
| 186 | hidden_size=config.hidden_size, |
| 187 | intermediate_size=config.shared_expert_intermediate_size, |
| 188 | hidden_act=config.hidden_act, |
| 189 | quant_config=quant_config, |
| 190 | reduce_results=False, # Reduce after shared+routed combine |
| 191 | prefix=f"{prefix}.shared_expert", |
| 192 | ) |
| 193 | else: |
| 194 | self.shared_expert = None |
| 195 | |
| 196 | # Auxiliary-loss-free load-balancing bias (arXiv:2408.15664). The |
| 197 | # checkpoint stores one [num_experts] tensor per MoE layer at |
| 198 | # `mlp.experts.e_score_correction_bias`; registering it as a Parameter |
| 199 | # on the MoERunner lets the weight loader pick it up and the router |
| 200 | # add it during top-k selection. The fused top-k bias router requires |
| 201 | # float32 regardless of model dtype. |
| 202 | e_score_correction_bias = torch.nn.Parameter( |
| 203 | torch.zeros(config.num_experts, dtype=torch.float32), |
| 204 | requires_grad=False, |
| 205 | ) |
| 206 | # MoERunner with SIGMOID routing. Passing `shared_experts=` lets the |
| 207 | # layer overlap the shared-expert compute with the all2all dispatch. |
| 208 | # `apply_routed_scale_to_output=True` makes MoERunner handle the |
| 209 | # FusedMoEFactory with SIGMOID routing. Passing `shared_experts=` lets the |
| 210 | # layer overlap the shared-expert compute with the all2all dispatch. |
| 211 | # `apply_routed_scale_to_output=True` makes FusedMoEFactory handle the |
| 212 | # routed_scaling_factor, shared+routed combine, and TP all-reduce |
| 213 | # internally, so forward() just returns the final hidden states. |
| 214 | self.experts = FusedMoEFactory( |
| 215 | shared_experts=self.shared_expert, |
| 216 | num_experts=config.num_experts, |
| 217 | top_k=config.num_experts_per_tok, |
| 218 | hidden_size=config.hidden_size, |
| 219 | intermediate_size=config.moe_intermediate_size, |
| 220 | renormalize=True, |
| 221 | quant_config=quant_config, |
| 222 | prefix=f"{prefix}.experts", |
| 223 | scoring_func="sigmoid", |
| 224 | use_grouped_topk=False, |
| 225 | apply_router_weight_on_input=bool(config.moe_apply_router_weight_on_input), |
| 226 | e_score_correction_bias=e_score_correction_bias, |
| 227 | enable_eplb=self.enable_eplb, |
| 228 | num_redundant_experts=self.n_redundant_experts, |
| 229 | routed_scaling_factor=self.routed_scaling_factor, |
| 230 | apply_routed_scale_to_output=True, |
| 231 | ) |
| 232 | |
| 233 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 234 | orig_shape = hidden_states.shape |
| 235 | hidden_dim = hidden_states.shape[-1] |
| 236 | hidden_states = hidden_states.view(-1, hidden_dim) |
| 237 | |
| 238 | router_logits, _ = self.gate(hidden_states) |
| 239 | router_logits = router_logits.float() |
| 240 | softcap = getattr(self.config, "moe_router_logit_softcapping", 0.0) or 0.0 |
| 241 | if softcap > 0.0: |
| 242 | router_logits = torch.tanh(router_logits / softcap) * softcap |
| 243 | |
| 244 | final_hidden_states = self.experts(hidden_states, router_logits) |
| 245 | return final_hidden_states.view(orig_shape) |
| 246 | |
| 247 | |
| 248 | class LagunaAttention(nn.Module): |
| 249 | """Laguna attention with optional softplus output gating. |
| 250 | |
| 251 | Supports per-layer sliding window attention when ``config.layer_types`` |
| 252 | is present. Layers whose type is ``"sliding_attention"`` use |
| 253 | ``config.sliding_window``; all other layers (typically labelled |
| 254 | ``"full_attention"``) use full attention. When ``layer_types`` is |
| 255 | absent every layer defaults to full attention for backwards |
| 256 | compatibility. |
| 257 | """ |
| 258 | |
| 259 | def __init__( |
| 260 | self, |
| 261 | config, |
| 262 | hidden_size: int, |
| 263 | num_heads: int, |
| 264 | num_kv_heads: int, |
| 265 | max_position_embeddings: int = 131072, |
| 266 | head_dim: int | None = None, |
| 267 | cache_config: CacheConfig | None = None, |
| 268 | quant_config: QuantizationConfig | None = None, |
| 269 | prefix: str = "", |
| 270 | attention_sink: bool = False, |
| 271 | layer_idx: int | None = None, |
| 272 | attention_prefix: str | None = None, |
| 273 | ) -> None: |
| 274 | super().__init__() |
| 275 | if layer_idx is None: |
| 276 | layer_idx = extract_layer_index(prefix) |
| 277 | if attention_prefix is None: |
| 278 | attention_prefix = prefix |
| 279 | self.hidden_size = hidden_size |
| 280 | tp_size = get_tensor_model_parallel_world_size() |
| 281 | self.total_num_heads = num_heads |
| 282 | assert self.total_num_heads % tp_size == 0 |
| 283 | self.num_heads = self.total_num_heads // tp_size |
| 284 | self.total_num_kv_heads = num_kv_heads |
| 285 | if self.total_num_kv_heads >= tp_size: |
| 286 | assert self.total_num_kv_heads % tp_size == 0 |
| 287 | else: |
| 288 | assert tp_size % self.total_num_kv_heads == 0 |
| 289 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 290 | self.head_dim = head_dim or (hidden_size // self.total_num_heads) |
| 291 | self.q_size = self.num_heads * self.head_dim |
| 292 | self.kv_size = self.num_kv_heads * self.head_dim |
| 293 | self.scaling = self.head_dim**-0.5 |
| 294 | self.max_position_embeddings = max_position_embeddings |
| 295 | |
| 296 | # Gating flag |
| 297 | self.gating = config.gating |
| 298 | |
| 299 | # Per-layer sliding window (follows Gemma2/Cohere2 convention) |
| 300 | layer_types = getattr(config, "layer_types", None) |
| 301 | if layer_types is not None: |
| 302 | is_sliding = layer_types[layer_idx] == "sliding_attention" |
| 303 | self.sliding_window = config.sliding_window if is_sliding else None |
| 304 | else: |
| 305 | self.sliding_window = None |
| 306 | |
| 307 | self.qkv_proj = QKVParallelLinear( |
| 308 | self.hidden_size, |
| 309 | self.head_dim, |
| 310 | self.total_num_heads, |
| 311 | self.total_num_kv_heads, |
| 312 | bias=config.attention_bias, |
| 313 | quant_config=quant_config, |
| 314 | prefix=f"{prefix}.qkv_proj", |
| 315 | ) |
| 316 | |
| 317 | # Output projection |
| 318 | self.o_proj = RowParallelLinear( |
| 319 | self.total_num_heads * self.head_dim, |
| 320 | self.hidden_size, |
| 321 | bias=config.attention_bias, |
| 322 | quant_config=quant_config, |
| 323 | prefix=f"{prefix}.o_proj", |
| 324 | ) |
| 325 | |
| 326 | # Gating projection (Laguna-specific, optional) |
| 327 | # config.gating may be: |
| 328 | # - True / "per-element": one gate per (head, head_dim) channel |
| 329 | # - "per-head": one gate per head, broadcast across head_dim |
| 330 | self.g_proj: ColumnParallelLinear | None |
| 331 | if self.gating: |
| 332 | # v5 LagunaConfig uses ``gating=True`` for per-head; older configs |
| 333 | # used ``"per-head"``. Accept both. ``"per-element"`` (or legacy |
| 334 | # ``True``) means per-element gating with output size num_heads × |
| 335 | # head_dim. |
| 336 | gate_per_head = self.gating is True or self.gating == "per-head" |
| 337 | g_out = ( |
| 338 | self.total_num_heads |
| 339 | if gate_per_head |
| 340 | else self.total_num_heads * self.head_dim |
| 341 | ) |
| 342 | self.g_proj = ColumnParallelLinear( |
| 343 | hidden_size, |
| 344 | g_out, |
| 345 | bias=False, |
| 346 | quant_config=quant_config, |
| 347 | prefix=f"{prefix}.g_proj", |
| 348 | ) |
| 349 | self.gate_per_head = gate_per_head |
| 350 | else: |
| 351 | self.g_proj = None |
| 352 | self.gate_per_head = False |
| 353 | |
| 354 | # Attention sinks (learnable per-head bias for SWA layers) |
| 355 | sinks = None |
| 356 | if attention_sink: |
| 357 | self.sink = torch.nn.Parameter( |
| 358 | torch.empty(self.total_num_heads // tp_size, requires_grad=False) |
| 359 | ) |
| 360 | sinks = self.sink |
| 361 | |
| 362 | # Resolve rope params per-layer-type. ``config.rope_parameters`` is |
| 363 | # either a flat dict (legacy) or a nested ``{layer_type: rope_dict}`` |
| 364 | # (v5 Laguna-XS schema). The v5 form is unhashable as-is and would |
| 365 | # crash `get_rope`'s cache lookup, so always pull out the layer's |
| 366 | # sub-dict before forwarding. |
| 367 | layer_type = ( |
| 368 | layer_types[layer_idx] if layer_types is not None else "full_attention" |
| 369 | ) |
| 370 | is_sliding = layer_type == "sliding_attention" |
| 371 | |
| 372 | top_rope = getattr(config, "rope_parameters", None) or {} |
| 373 | if any(isinstance(v, dict) for v in top_rope.values()): |
| 374 | # Nested per-layer-type form. |
| 375 | base_rope = top_rope.get(layer_type) or top_rope.get("full_attention") or {} |
| 376 | else: |
| 377 | base_rope = top_rope |
| 378 | |
| 379 | # Older flat-rope ckpts can carry a separate `swa_rope_parameters` |
| 380 | # for SWA layers. Prefer it when present; otherwise the nested |
| 381 | # rope dict above already supplies the correct sub-config. |
| 382 | swa_rope = getattr(config, "swa_rope_parameters", None) |
| 383 | if ( |
| 384 | is_sliding |
| 385 | and swa_rope is None |
| 386 | and not any(isinstance(v, dict) for v in top_rope.values()) |
| 387 | ): |
| 388 | logger.warning_once( |
| 389 | "Laguna config has sliding_attention layers but neither " |
| 390 | "`swa_rope_parameters` nor a nested per-layer-type " |
| 391 | "`rope_parameters` — SWA layers will reuse the global rope. " |
| 392 | "If the checkpoint was trained with distinct SWA rope " |
| 393 | "(theta / partial_rotary_factor), regenerate its HF config " |
| 394 | "to include either form." |
| 395 | ) |
| 396 | rope_params = swa_rope if (is_sliding and swa_rope is not None) else base_rope |
| 397 | # `partial_rotary_factor` may live on the top-level config (main attention) |
| 398 | # or on the per-layer rope dict itself (e.g. SWA can differ). Inject the |
| 399 | # top-level value into `rope_params` if the dict doesn't already set it. |
| 400 | top_partial = getattr(config, "partial_rotary_factor", None) |
| 401 | if top_partial is not None and "partial_rotary_factor" not in rope_params: |
| 402 | rope_params = {**rope_params, "partial_rotary_factor": top_partial} |
| 403 | |
| 404 | # Rotary embeddings (YaRN) |
| 405 | self.rotary_emb = get_rope( |
| 406 | head_size=self.head_dim, |
| 407 | max_position=max_position_embeddings, |
| 408 | is_neox_style=True, |
| 409 | rope_parameters=rope_params, |
| 410 | ) |
| 411 | |
| 412 | self.attn = Attention( |
| 413 | self.num_heads, |
| 414 | self.head_dim, |
| 415 | self.scaling, |
| 416 | num_kv_heads=self.num_kv_heads, |
| 417 | cache_config=cache_config, |
| 418 | quant_config=quant_config, |
| 419 | per_layer_sliding_window=self.sliding_window, |
| 420 | prefix=f"{attention_prefix}.attn", |
| 421 | sinks=sinks, |
| 422 | ) |
| 423 | |
| 424 | # QK normalization (like Qwen3) |
| 425 | self.q_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps) |
| 426 | self.k_norm = RMSNorm(self.head_dim, eps=config.rms_norm_eps) |
| 427 | |
| 428 | def forward( |
| 429 | self, |
| 430 | positions: torch.Tensor, |
| 431 | hidden_states: torch.Tensor, |
| 432 | ) -> torch.Tensor: |
| 433 | qkv, _ = self.qkv_proj(hidden_states) |
| 434 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 435 | |
| 436 | q_by_head = q.view(*q.shape[:-1], q.shape[-1] // self.head_dim, self.head_dim) |
| 437 | q_by_head = self.q_norm(q_by_head) |
| 438 | q = q_by_head.view(q.shape) |
| 439 | |
| 440 | k_by_head = k.view(*k.shape[:-1], k.shape[-1] // self.head_dim, self.head_dim) |
| 441 | k_by_head = self.k_norm(k_by_head) |
| 442 | k = k_by_head.view(k.shape) |
| 443 | |
| 444 | q, k = self.rotary_emb(positions, q, k) |
| 445 | attn_output = self.attn(q, k, v) |
| 446 | |
| 447 | # Apply gating if enabled (compute softplus in float32 for precision) |
| 448 | if self.gating and self.g_proj is not None: |
| 449 | gate, _ = self.g_proj(hidden_states) |
| 450 | gate = F.softplus(gate.float()).type_as(attn_output) |
| 451 | if self.gate_per_head: |
| 452 | # gate: [..., num_heads]; broadcast across head_dim |
| 453 | attn_shape = attn_output.shape |
| 454 | attn_output = ( |
| 455 | attn_output.view(*attn_shape[:-1], self.num_heads, self.head_dim) |
| 456 | * gate.unsqueeze(-1) |
| 457 | ).view(attn_shape) |
| 458 | else: |
| 459 | attn_output = attn_output * gate |
| 460 | |
| 461 | output, _ = self.o_proj(attn_output) |
| 462 | return output |
| 463 | |
| 464 | |
| 465 | class LagunaDecoderLayer(nn.Module): |
| 466 | def __init__( |
| 467 | self, |
| 468 | config, |
| 469 | cache_config: CacheConfig | None = None, |
| 470 | quant_config: QuantizationConfig | None = None, |
| 471 | prefix: str = "", |
| 472 | enable_eplb: bool = False, |
| 473 | layer_idx: int | None = None, |
| 474 | attention_prefix: str | None = None, |
| 475 | ) -> None: |
| 476 | super().__init__() |
| 477 | self.hidden_size = config.hidden_size |
| 478 | if layer_idx is None: |
| 479 | layer_idx = extract_layer_index(prefix) |
| 480 | |
| 481 | # Determine if this layer uses sliding window attention |
| 482 | layer_types = getattr(config, "layer_types", None) |
| 483 | is_sliding = ( |
| 484 | layer_types is not None and layer_types[layer_idx] == "sliding_attention" |
| 485 | ) |
| 486 | |
| 487 | # Enable attention sinks on SWA layers when configured |
| 488 | attention_sink = is_sliding and getattr( |
| 489 | config, "swa_attention_sink_enabled", False |
| 490 | ) |
| 491 | |
| 492 | # Optional per-layer override of head count (Laguna-XS). |
| 493 | per_layer_heads = getattr(config, "num_attention_heads_per_layer", None) |
| 494 | layer_num_heads = ( |
| 495 | per_layer_heads[layer_idx] |
| 496 | if per_layer_heads is not None |
| 497 | else config.num_attention_heads |
| 498 | ) |
| 499 | |
| 500 | self.self_attn = LagunaAttention( |
| 501 | config=config, |
| 502 | hidden_size=self.hidden_size, |
| 503 | num_heads=layer_num_heads, |
| 504 | num_kv_heads=config.num_key_value_heads, |
| 505 | max_position_embeddings=config.max_position_embeddings, |
| 506 | head_dim=getattr(config, "head_dim", None), |
| 507 | cache_config=cache_config, |
| 508 | quant_config=quant_config, |
| 509 | prefix=f"{prefix}.self_attn", |
| 510 | attention_sink=attention_sink, |
| 511 | layer_idx=layer_idx, |
| 512 | attention_prefix=( |
| 513 | f"{attention_prefix}.self_attn" |
| 514 | if attention_prefix is not None |
| 515 | else None |
| 516 | ), |
| 517 | ) |
| 518 | |
| 519 | self.is_moe_layer = ( |
| 520 | get_mlp_layer_types(config)[layer_idx] == "sparse" |
| 521 | and config.num_experts > 0 |
| 522 | ) |
| 523 | |
| 524 | if self.is_moe_layer: |
| 525 | self.mlp = LagunaMoE( |
| 526 | config=config, |
| 527 | quant_config=quant_config, |
| 528 | prefix=f"{prefix}.mlp", |
| 529 | enable_eplb=enable_eplb, |
| 530 | ) |
| 531 | else: |
| 532 | self.mlp = LagunaMLP( |
| 533 | hidden_size=config.hidden_size, |
| 534 | intermediate_size=config.intermediate_size, |
| 535 | hidden_act=config.hidden_act, |
| 536 | quant_config=quant_config, |
| 537 | prefix=f"{prefix}.mlp", |
| 538 | ) |
| 539 | |
| 540 | self.input_layernorm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 541 | self.post_attention_layernorm = RMSNorm( |
| 542 | config.hidden_size, eps=config.rms_norm_eps |
| 543 | ) |
| 544 | |
| 545 | def forward( |
| 546 | self, |
| 547 | positions: torch.Tensor, |
| 548 | hidden_states: torch.Tensor, |
| 549 | residual: torch.Tensor | None, |
| 550 | ) -> tuple[torch.Tensor, torch.Tensor]: |
| 551 | # Self Attention |
| 552 | if residual is None: |
| 553 | residual = hidden_states |
| 554 | hidden_states = self.input_layernorm(hidden_states) |
| 555 | else: |
| 556 | hidden_states, residual = self.input_layernorm(hidden_states, residual) |
| 557 | |
| 558 | hidden_states = self.self_attn( |
| 559 | positions=positions, |
| 560 | hidden_states=hidden_states, |
| 561 | ) |
| 562 | |
| 563 | # Fully Connected |
| 564 | hidden_states, residual = self.post_attention_layernorm(hidden_states, residual) |
| 565 | hidden_states = self.mlp(hidden_states) |
| 566 | |
| 567 | return hidden_states, residual |
| 568 | |
| 569 | |
| 570 | @support_torch_compile |
| 571 | class LagunaModel(nn.Module, EagleModelMixin): |
| 572 | hf_to_vllm_mapper = WeightsMapper( |
| 573 | orig_to_new_stacked={ |
| 574 | ".q_proj": (".qkv_proj", "q"), |
| 575 | ".k_proj": (".qkv_proj", "k"), |
| 576 | ".v_proj": (".qkv_proj", "v"), |
| 577 | } |
| 578 | ) |
| 579 | |
| 580 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 581 | super().__init__() |
| 582 | |
| 583 | config = vllm_config.model_config.hf_config |
| 584 | cache_config = vllm_config.cache_config |
| 585 | quant_config = vllm_config.quant_config |
| 586 | enable_eplb = vllm_config.parallel_config.enable_eplb |
| 587 | eplb_config = vllm_config.parallel_config.eplb_config |
| 588 | self.num_redundant_experts = eplb_config.num_redundant_experts |
| 589 | self.config = config |
| 590 | self.quant_config = quant_config |
| 591 | |
| 592 | # Disable the model-level sliding-window fallback in Attention.__init__. |
| 593 | # Laguna drives SWA per-layer via `layer_types`, passing |
| 594 | # `per_layer_sliding_window=self.sliding_window` (None for global |
| 595 | # layers). Without this, global layers whose `per_layer_sliding_window` |
| 596 | # is None would pick up `cache_config.sliding_window` |
| 597 | # (populated from `config.sliding_window`) as a fallback, silently |
| 598 | # applying a 512-token window to full-attention layers. |
| 599 | if cache_config is not None: |
| 600 | cache_config.sliding_window = None |
| 601 | |
| 602 | self.vocab_size = config.vocab_size |
| 603 | |
| 604 | if get_pp_group().is_first_rank or ( |
| 605 | config.tie_word_embeddings and get_pp_group().is_last_rank |
| 606 | ): |
| 607 | self.embed_tokens = VocabParallelEmbedding( |
| 608 | config.vocab_size, |
| 609 | config.hidden_size, |
| 610 | quant_config=quant_config, |
| 611 | prefix=f"{prefix}.embed_tokens", |
| 612 | ) |
| 613 | else: |
| 614 | self.embed_tokens = PPMissingLayer() |
| 615 | |
| 616 | self.start_layer, self.end_layer, self.layers = make_layers( |
| 617 | config.num_hidden_layers, |
| 618 | lambda prefix: LagunaDecoderLayer( |
| 619 | config=config, |
| 620 | cache_config=cache_config, |
| 621 | quant_config=quant_config, |
| 622 | prefix=prefix, |
| 623 | enable_eplb=enable_eplb, |
| 624 | ), |
| 625 | prefix=f"{prefix}.layers", |
| 626 | ) |
| 627 | |
| 628 | if get_pp_group().is_last_rank: |
| 629 | self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps) |
| 630 | else: |
| 631 | self.norm = PPMissingLayer() |
| 632 | |
| 633 | self.make_empty_intermediate_tensors = make_empty_intermediate_tensors_factory( |
| 634 | ["hidden_states", "residual"], config.hidden_size |
| 635 | ) |
| 636 | |
| 637 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 638 | return self.embed_tokens(input_ids) |
| 639 | |
| 640 | def forward( |
| 641 | self, |
| 642 | input_ids: torch.Tensor, |
| 643 | positions: torch.Tensor, |
| 644 | intermediate_tensors: IntermediateTensors | None = None, |
| 645 | inputs_embeds: torch.Tensor | None = None, |
| 646 | ) -> torch.Tensor | IntermediateTensors: |
| 647 | if get_pp_group().is_first_rank: |
| 648 | if inputs_embeds is not None: |
| 649 | hidden_states = inputs_embeds |
| 650 | else: |
| 651 | hidden_states = self.embed_tokens(input_ids) |
| 652 | residual = None |
| 653 | else: |
| 654 | assert intermediate_tensors is not None |
| 655 | hidden_states = intermediate_tensors["hidden_states"] |
| 656 | residual = intermediate_tensors["residual"] |
| 657 | |
| 658 | aux_hidden_states = self._maybe_add_hidden_state( |
| 659 | [], self.start_layer, hidden_states, residual |
| 660 | ) |
| 661 | for layer_idx, layer in enumerate( |
| 662 | islice(self.layers, self.start_layer, self.end_layer), |
| 663 | start=self.start_layer, |
| 664 | ): |
| 665 | hidden_states, residual = layer(positions, hidden_states, residual) |
| 666 | self._maybe_add_hidden_state( |
| 667 | aux_hidden_states, layer_idx + 1, hidden_states, residual |
| 668 | ) |
| 669 | |
| 670 | if not get_pp_group().is_last_rank: |
| 671 | return IntermediateTensors( |
| 672 | {"hidden_states": hidden_states, "residual": residual} |
| 673 | ) |
| 674 | |
| 675 | hidden_states, _ = self.norm(hidden_states, residual) |
| 676 | if len(aux_hidden_states) > 0: |
| 677 | return hidden_states, aux_hidden_states |
| 678 | return hidden_states |
| 679 | |
| 680 | def _slice_sink( |
| 681 | self, weights: Iterable[tuple[str, torch.Tensor]] |
| 682 | ) -> Iterable[tuple[str, torch.Tensor]]: |
| 683 | tp_size = get_tensor_model_parallel_world_size() |
| 684 | tp_rank = get_tensor_model_parallel_rank() |
| 685 | for name, loaded_weight in weights: |
| 686 | # Handle attention sinks (distributed across ranks). Derive the |
| 687 | # per-rank slice from the parameter's own shape so per-layer |
| 688 | # variations in head count are handled correctly. |
| 689 | if "sink" in name: |
| 690 | heads_per_rank = loaded_weight.shape[0] // tp_size |
| 691 | loaded_weight = loaded_weight.narrow( |
| 692 | 0, tp_rank * heads_per_rank, heads_per_rank |
| 693 | ) |
| 694 | yield name, loaded_weight |
| 695 | |
| 696 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 697 | loader = AutoWeightsLoader( |
| 698 | self, |
| 699 | ignore_unexpected_suffixes=[ |
| 700 | ".bias", |
| 701 | "_bias", |
| 702 | ".k_scale", |
| 703 | "_k_scale", |
| 704 | ".v_scale", |
| 705 | "_v_scale", |
| 706 | ".weight_scale", |
| 707 | "_weight_scale", |
| 708 | ".input_scale", |
| 709 | "_input_scale", |
| 710 | ], |
| 711 | ) |
| 712 | return loader.load_weights( |
| 713 | self._slice_sink(weights), mapper=self.hf_to_vllm_mapper |
| 714 | ) |
| 715 | |
| 716 | |
| 717 | class LagunaForCausalLM(nn.Module, SupportsPP, SupportsLoRA, SupportsEagle3): |
| 718 | fall_back_to_pt_during_load = False |
| 719 | |
| 720 | packed_modules_mapping = { |
| 721 | "qkv_proj": ["q_proj", "k_proj", "v_proj"], |
| 722 | } |
| 723 | |
| 724 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 725 | super().__init__() |
| 726 | config = vllm_config.model_config.hf_config |
| 727 | quant_config = vllm_config.quant_config |
| 728 | self.config = config |
| 729 | self.quant_config = quant_config |
| 730 | |
| 731 | self.model = LagunaModel( |
| 732 | vllm_config=vllm_config, prefix=maybe_prefix(prefix, "model") |
| 733 | ) |
| 734 | |
| 735 | if get_pp_group().is_last_rank: |
| 736 | self.lm_head = ParallelLMHead( |
| 737 | config.vocab_size, |
| 738 | config.hidden_size, |
| 739 | quant_config=quant_config, |
| 740 | prefix=maybe_prefix(prefix, "lm_head"), |
| 741 | ) |
| 742 | if self.config.tie_word_embeddings: |
| 743 | self.lm_head = self.lm_head.tie_weights(self.model.embed_tokens) |
| 744 | else: |
| 745 | self.lm_head = PPMissingLayer() |
| 746 | |
| 747 | self.logits_processor = LogitsProcessor(config.vocab_size) |
| 748 | self.make_empty_intermediate_tensors = ( |
| 749 | self.model.make_empty_intermediate_tensors |
| 750 | ) |
| 751 | |
| 752 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 753 | return self.model.embed_input_ids(input_ids) |
| 754 | |
| 755 | def forward( |
| 756 | self, |
| 757 | input_ids: torch.Tensor, |
| 758 | positions: torch.Tensor, |
| 759 | intermediate_tensors: IntermediateTensors | None = None, |
| 760 | inputs_embeds: torch.Tensor | None = None, |
| 761 | ) -> torch.Tensor | IntermediateTensors: |
| 762 | hidden_states = self.model( |
| 763 | input_ids, positions, intermediate_tensors, inputs_embeds |
| 764 | ) |
| 765 | return hidden_states |
| 766 | |
| 767 | def compute_logits(self, hidden_states: torch.Tensor) -> torch.Tensor | None: |
| 768 | logits = self.logits_processor(self.lm_head, hidden_states) |
| 769 | return logits |
| 770 | |
| 771 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 772 | loader = AutoWeightsLoader(self) |
| 773 | return loader.load_weights(weights) |