| 1 | # SPDX-License-Identifier: Apache-2.0 |
| 2 | # SPDX-FileCopyrightText: Copyright contributors to the vLLM project |
| 3 | from collections.abc import Iterable |
| 4 | |
| 5 | import torch |
| 6 | from torch import nn |
| 7 | from transformers import PreTrainedConfig |
| 8 | |
| 9 | from vllm.compilation.decorators import support_torch_compile |
| 10 | from vllm.config import CacheConfig, VllmConfig |
| 11 | from vllm.distributed import ( |
| 12 | divide, |
| 13 | get_tensor_model_parallel_rank, |
| 14 | get_tensor_model_parallel_world_size, |
| 15 | tensor_model_parallel_all_reduce, |
| 16 | ) |
| 17 | from vllm.model_executor.layers.activation import get_act_and_mul_fn, get_act_fn |
| 18 | from vllm.model_executor.layers.attention import ( |
| 19 | EncoderOnlyAttention, |
| 20 | ) |
| 21 | from vllm.model_executor.layers.fused_moe import ( |
| 22 | GateLinear, |
| 23 | activation_without_mul, |
| 24 | fused_topk, |
| 25 | ) |
| 26 | from vllm.model_executor.layers.linear import ( |
| 27 | ColumnParallelLinear, |
| 28 | MergedColumnParallelLinear, |
| 29 | QKVParallelLinear, |
| 30 | ReplicatedLinear, |
| 31 | RowParallelLinear, |
| 32 | ) |
| 33 | from vllm.model_executor.layers.pooler import DispatchPooler |
| 34 | from vllm.model_executor.layers.quantization import QuantizationConfig |
| 35 | from vllm.model_executor.layers.rotary_embedding import get_rope |
| 36 | from vllm.model_executor.layers.vocab_parallel_embedding import VocabParallelEmbedding |
| 37 | from vllm.model_executor.model_loader.weight_utils import default_weight_loader |
| 38 | from vllm.model_executor.models.utils import ( |
| 39 | AutoWeightsLoader, |
| 40 | WeightsMapper, |
| 41 | maybe_prefix, |
| 42 | ) |
| 43 | from vllm.model_executor.utils import set_weight_attrs |
| 44 | from vllm.platforms import current_platform |
| 45 | from vllm.sequence import IntermediateTensors |
| 46 | |
| 47 | from .bert import BertPooler |
| 48 | from .interfaces import SupportsCrossEncoding, SupportsQuant |
| 49 | from .interfaces_base import default_pooling_type |
| 50 | |
| 51 | |
| 52 | class BertWithRopeEmbedding(nn.Module): |
| 53 | def __init__(self, config: PreTrainedConfig): |
| 54 | super().__init__() |
| 55 | if config.position_embedding_type not in ["rope", "rotary"]: |
| 56 | raise ValueError( |
| 57 | "Only 'rotary'('rope') position_embedding_type" + " is supported" |
| 58 | ) |
| 59 | |
| 60 | self.word_embeddings = VocabParallelEmbedding( |
| 61 | config.vocab_size, config.hidden_size |
| 62 | ) |
| 63 | if config.type_vocab_size > 0: |
| 64 | self.token_type_embeddings: VocabParallelEmbedding | None = ( |
| 65 | VocabParallelEmbedding(config.type_vocab_size, config.hidden_size) |
| 66 | ) |
| 67 | else: |
| 68 | self.token_type_embeddings = None |
| 69 | |
| 70 | self.LayerNorm = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 71 | |
| 72 | def forward( |
| 73 | self, |
| 74 | input_ids: torch.Tensor, |
| 75 | token_type_ids: torch.Tensor | None = None, |
| 76 | ) -> torch.Tensor: |
| 77 | input_shape = input_ids.size() |
| 78 | inputs_embeds = self.word_embeddings(input_ids) |
| 79 | |
| 80 | embeddings = inputs_embeds |
| 81 | if self.token_type_embeddings is not None: |
| 82 | if token_type_ids is None: |
| 83 | token_type_ids = torch.zeros( |
| 84 | input_shape, dtype=torch.long, device=inputs_embeds.device |
| 85 | ) |
| 86 | |
| 87 | token_type_embeddings = self.token_type_embeddings(token_type_ids) |
| 88 | embeddings += token_type_embeddings |
| 89 | |
| 90 | embeddings = self.LayerNorm(embeddings) |
| 91 | return embeddings |
| 92 | |
| 93 | |
| 94 | class BertWithRopeAttention(nn.Module): |
| 95 | def __init__( |
| 96 | self, |
| 97 | hidden_size: int, |
| 98 | num_attention_heads: int, |
| 99 | cache_config: CacheConfig | None = None, |
| 100 | quant_config: QuantizationConfig | None = None, |
| 101 | bias: bool = True, |
| 102 | rotary_kwargs: dict | None = None, |
| 103 | prefix: str = "", |
| 104 | ): |
| 105 | super().__init__() |
| 106 | |
| 107 | self.hidden_size = hidden_size |
| 108 | tp_size = get_tensor_model_parallel_world_size() |
| 109 | |
| 110 | self.total_num_heads = num_attention_heads |
| 111 | assert self.total_num_heads % tp_size == 0 |
| 112 | |
| 113 | self.num_heads = self.total_num_heads // tp_size |
| 114 | self.total_num_kv_heads = self.total_num_heads |
| 115 | self.head_dim = self.hidden_size // self.total_num_heads |
| 116 | assert self.head_dim * self.total_num_heads == self.hidden_size |
| 117 | |
| 118 | self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size) |
| 119 | |
| 120 | self.q_size = self.num_heads * self.head_dim |
| 121 | self.kv_size = self.num_kv_heads * self.head_dim |
| 122 | self.scaling = self.head_dim**-0.5 |
| 123 | |
| 124 | self.qkv_proj = QKVParallelLinear( |
| 125 | hidden_size=self.hidden_size, |
| 126 | head_size=self.head_dim, |
| 127 | total_num_heads=self.total_num_heads, |
| 128 | total_num_kv_heads=self.total_num_kv_heads, |
| 129 | bias=bias, |
| 130 | quant_config=quant_config, |
| 131 | prefix=f"{prefix}.qkv_proj", |
| 132 | ) |
| 133 | |
| 134 | assert rotary_kwargs is not None |
| 135 | self.rotary_emb = get_rope(**rotary_kwargs) |
| 136 | |
| 137 | self.attn = EncoderOnlyAttention( |
| 138 | num_heads=self.num_heads, |
| 139 | head_size=self.head_dim, |
| 140 | scale=self.scaling, |
| 141 | num_kv_heads=self.num_kv_heads, |
| 142 | cache_config=cache_config, |
| 143 | quant_config=quant_config, |
| 144 | prefix=f"{prefix}.attn", |
| 145 | ) |
| 146 | |
| 147 | self.out_proj = RowParallelLinear( |
| 148 | input_size=hidden_size, |
| 149 | output_size=hidden_size, |
| 150 | bias=bias, |
| 151 | quant_config=quant_config, |
| 152 | prefix=f"{prefix}.dense", |
| 153 | ) |
| 154 | |
| 155 | def forward( |
| 156 | self, |
| 157 | positions: torch.Tensor, |
| 158 | hidden_states: torch.Tensor, |
| 159 | ) -> torch.Tensor: |
| 160 | qkv, _ = self.qkv_proj(hidden_states) |
| 161 | q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1) |
| 162 | q, k = self.rotary_emb(positions, q, k) |
| 163 | attn_output = self.attn(q, k, v) |
| 164 | output, _ = self.out_proj(attn_output) |
| 165 | return output |
| 166 | |
| 167 | |
| 168 | class BertWithRopeGatedMLP(nn.Module): |
| 169 | def __init__( |
| 170 | self, |
| 171 | hidden_size: int, |
| 172 | intermediate_size: int, |
| 173 | hidden_act: str, |
| 174 | bias: bool = True, |
| 175 | quant_config: QuantizationConfig | None = None, |
| 176 | prefix: str = "", |
| 177 | ): |
| 178 | super().__init__() |
| 179 | self.act_fn = get_act_and_mul_fn(hidden_act) |
| 180 | self.gate_up_proj = MergedColumnParallelLinear( |
| 181 | hidden_size, |
| 182 | [intermediate_size] * 2, |
| 183 | bias=bias, |
| 184 | quant_config=quant_config, |
| 185 | prefix=f"{prefix}.gate_up_proj", |
| 186 | ) |
| 187 | self.down_proj = RowParallelLinear( |
| 188 | input_size=intermediate_size, |
| 189 | output_size=hidden_size, |
| 190 | bias=bias, |
| 191 | quant_config=quant_config, |
| 192 | prefix=f"{prefix}.down_proj", |
| 193 | ) |
| 194 | |
| 195 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 196 | gate_up, _ = self.gate_up_proj(hidden_states) |
| 197 | hidden_states = self.act_fn(gate_up) |
| 198 | hidden_states, _ = self.down_proj(hidden_states) |
| 199 | return hidden_states |
| 200 | |
| 201 | |
| 202 | class BertWithRopeMLP(nn.Module): |
| 203 | def __init__( |
| 204 | self, |
| 205 | hidden_size: int, |
| 206 | intermediate_size: int, |
| 207 | hidden_act: str, |
| 208 | bias: bool = True, |
| 209 | quant_config: QuantizationConfig | None = None, |
| 210 | prefix: str = "", |
| 211 | ): |
| 212 | super().__init__() |
| 213 | self.act_fn = get_act_fn(hidden_act) |
| 214 | self.up_proj = ColumnParallelLinear( |
| 215 | input_size=hidden_size, |
| 216 | output_size=intermediate_size, |
| 217 | bias=bias, |
| 218 | quant_config=quant_config, |
| 219 | prefix=f"{prefix}.up_proj", |
| 220 | ) |
| 221 | self.down_proj = RowParallelLinear( |
| 222 | input_size=intermediate_size, |
| 223 | output_size=hidden_size, |
| 224 | bias=bias, |
| 225 | quant_config=quant_config, |
| 226 | prefix=f"{prefix}.down_proj", |
| 227 | ) |
| 228 | |
| 229 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 230 | hidden_states, _ = self.up_proj(hidden_states) |
| 231 | hidden_states = self.act_fn(hidden_states) |
| 232 | hidden_states, _ = self.down_proj(hidden_states) |
| 233 | return hidden_states |
| 234 | |
| 235 | |
| 236 | class NomicMoE(nn.Module): |
| 237 | def __init__( |
| 238 | self, |
| 239 | num_experts: int, |
| 240 | top_k: int, |
| 241 | hidden_size: int, |
| 242 | intermediate_size: int, |
| 243 | hidden_act: str, |
| 244 | params_dtype: torch.dtype | None = None, |
| 245 | tp_size: int | None = None, |
| 246 | ): |
| 247 | super().__init__() |
| 248 | |
| 249 | self.tp_size = tp_size or get_tensor_model_parallel_world_size() |
| 250 | self.num_total_experts = num_experts |
| 251 | self.top_k = top_k |
| 252 | self.hidden_size = hidden_size |
| 253 | self.total_intermediate_size = intermediate_size |
| 254 | self.intermediate_size = divide(intermediate_size, self.tp_size) |
| 255 | self.hidden_act = activation_without_mul(hidden_act) |
| 256 | |
| 257 | if params_dtype is None: |
| 258 | params_dtype = torch.get_default_dtype() |
| 259 | self.params_dtype = params_dtype |
| 260 | |
| 261 | self.router = GateLinear(self.hidden_size, self.num_total_experts) |
| 262 | self.w1 = nn.Parameter( |
| 263 | torch.empty( |
| 264 | self.num_total_experts, |
| 265 | self.intermediate_size, |
| 266 | self.hidden_size, |
| 267 | device=current_platform.device_type, |
| 268 | dtype=self.params_dtype, |
| 269 | ) |
| 270 | ) |
| 271 | self.w2 = nn.Parameter( |
| 272 | torch.empty( |
| 273 | self.num_total_experts, |
| 274 | self.hidden_size, |
| 275 | self.intermediate_size, |
| 276 | device=current_platform.device_type, |
| 277 | dtype=self.params_dtype, |
| 278 | ) |
| 279 | ) |
| 280 | self.bias = nn.Parameter(torch.zeros(self.hidden_size)) |
| 281 | set_weight_attrs( |
| 282 | self.w1, |
| 283 | { |
| 284 | "weight_loader": self.weight_loader, |
| 285 | }, |
| 286 | ) |
| 287 | set_weight_attrs( |
| 288 | self.w2, |
| 289 | { |
| 290 | "weight_loader": self.weight_loader, |
| 291 | }, |
| 292 | ) |
| 293 | |
| 294 | def weight_loader( |
| 295 | self, |
| 296 | param: nn.Parameter, |
| 297 | loaded_weight: torch.Tensor, |
| 298 | weight_name: str, |
| 299 | ): |
| 300 | # NOTE: Nomic-MoE has fused experts weights with shape |
| 301 | # (num_experts * intermediate_size, hidden_size) |
| 302 | tp_rank = get_tensor_model_parallel_rank() |
| 303 | param_data = param.data |
| 304 | shard_size = self.intermediate_size |
| 305 | shard = slice(tp_rank * shard_size, (tp_rank + 1) * shard_size) |
| 306 | if weight_name.endswith("w1"): |
| 307 | loaded_weight = loaded_weight.reshape( |
| 308 | self.num_total_experts, |
| 309 | self.total_intermediate_size, |
| 310 | self.hidden_size, |
| 311 | )[:, shard] |
| 312 | if weight_name.endswith("w2"): |
| 313 | loaded_weight = loaded_weight.reshape( |
| 314 | self.num_total_experts, |
| 315 | self.total_intermediate_size, |
| 316 | self.hidden_size, |
| 317 | )[:, shard].transpose(1, 2) |
| 318 | param_data.copy_(loaded_weight) |
| 319 | |
| 320 | def forward(self, hidden_states: torch.Tensor) -> torch.Tensor: |
| 321 | num_tokens, hidden_size = hidden_states.shape |
| 322 | hidden_states = hidden_states.view(-1, self.hidden_size) |
| 323 | # router_logits: (num_tokens, n_experts) |
| 324 | router_logits, _ = self.router(hidden_states) |
| 325 | # FIXME(Isotr0py): This implementation is too tricky, |
| 326 | # we should use FusedMoEFactory instead in the future |
| 327 | # after supporting ungated activation for it. |
| 328 | topk_weights, topk_ids, _ = fused_topk( |
| 329 | hidden_states, router_logits, self.top_k, renormalize=False |
| 330 | ) |
| 331 | |
| 332 | final_hidden_states = torch.ops.vllm.fused_experts( |
| 333 | hidden_states=hidden_states, |
| 334 | w1=self.w1, |
| 335 | w2=self.w2, |
| 336 | topk_weights=topk_weights, |
| 337 | topk_ids=topk_ids, |
| 338 | activation=self.hidden_act, |
| 339 | ) |
| 340 | |
| 341 | if self.tp_size > 1: |
| 342 | final_hidden_states = tensor_model_parallel_all_reduce(final_hidden_states) |
| 343 | |
| 344 | return final_hidden_states.view(num_tokens, hidden_size) + self.bias |
| 345 | |
| 346 | |
| 347 | class BertWithRopeBlock(nn.Module): |
| 348 | def __init__( |
| 349 | self, |
| 350 | config: PreTrainedConfig, |
| 351 | cache_config: CacheConfig | None = None, |
| 352 | quant_config: QuantizationConfig | None = None, |
| 353 | moe: bool = False, |
| 354 | bias: bool = True, |
| 355 | rotary_kwargs: dict | None = None, |
| 356 | prefix: str = "", |
| 357 | ): |
| 358 | super().__init__() |
| 359 | self.attn = BertWithRopeAttention( |
| 360 | hidden_size=config.hidden_size, |
| 361 | num_attention_heads=config.num_attention_heads, |
| 362 | cache_config=cache_config, |
| 363 | quant_config=quant_config, |
| 364 | bias=bias, |
| 365 | rotary_kwargs=rotary_kwargs, |
| 366 | prefix=f"{prefix}.attention", |
| 367 | ) |
| 368 | |
| 369 | if moe: |
| 370 | self.mlp = NomicMoE( |
| 371 | num_experts=config.num_experts, |
| 372 | top_k=config.moe_top_k, |
| 373 | hidden_size=config.hidden_size, |
| 374 | intermediate_size=config.intermediate_size, |
| 375 | hidden_act=config.hidden_act, |
| 376 | ) |
| 377 | else: |
| 378 | if config.hidden_act in ["silu", "geglu"]: |
| 379 | self.mlp = BertWithRopeGatedMLP( |
| 380 | hidden_size=config.hidden_size, |
| 381 | intermediate_size=config.intermediate_size, |
| 382 | hidden_act=config.hidden_act, |
| 383 | bias=bias, |
| 384 | quant_config=quant_config, |
| 385 | prefix=f"{prefix}.mlp", |
| 386 | ) |
| 387 | else: |
| 388 | self.mlp = BertWithRopeMLP( |
| 389 | hidden_size=config.hidden_size, |
| 390 | intermediate_size=config.intermediate_size, |
| 391 | hidden_act=config.hidden_act, |
| 392 | bias=bias, |
| 393 | quant_config=quant_config, |
| 394 | prefix=f"{prefix}.mlp", |
| 395 | ) |
| 396 | |
| 397 | self.attn_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 398 | self.mlp_ln = nn.LayerNorm(config.hidden_size, eps=config.layer_norm_eps) |
| 399 | |
| 400 | def forward(self, positions: torch.Tensor, hidden_states: torch.Tensor): |
| 401 | attn_output = self.attn(positions, hidden_states) |
| 402 | hidden_states = self.attn_ln(hidden_states + attn_output) |
| 403 | mlp_out = self.mlp(hidden_states) |
| 404 | hidden_states = self.mlp_ln(hidden_states + mlp_out) |
| 405 | return hidden_states |
| 406 | |
| 407 | |
| 408 | class BertWithRopeEncoder(nn.Module): |
| 409 | def __init__( |
| 410 | self, |
| 411 | vllm_config: VllmConfig, |
| 412 | bias: bool = True, |
| 413 | rotary_kwargs: dict | None = None, |
| 414 | prefix: str = "", |
| 415 | ): |
| 416 | super().__init__() |
| 417 | config = vllm_config.model_config.hf_config |
| 418 | cache_config = vllm_config.cache_config |
| 419 | quant_config = vllm_config.quant_config |
| 420 | every_n = getattr(config, "moe_every_n_layers", 0) |
| 421 | self.layers = nn.ModuleList( |
| 422 | [ |
| 423 | BertWithRopeBlock( |
| 424 | config=config, |
| 425 | cache_config=cache_config, |
| 426 | quant_config=quant_config, |
| 427 | bias=bias, |
| 428 | moe=every_n > 0 and (layer_idx % every_n == 1), |
| 429 | rotary_kwargs=rotary_kwargs, |
| 430 | prefix=f"{prefix}.layer.{layer_idx}", |
| 431 | ) |
| 432 | for layer_idx in range(config.num_hidden_layers) |
| 433 | ] |
| 434 | ) |
| 435 | |
| 436 | def forward( |
| 437 | self, |
| 438 | positions: torch.Tensor, |
| 439 | hidden_states: torch.Tensor, |
| 440 | ) -> torch.Tensor: |
| 441 | for layer in self.layers: |
| 442 | hidden_states = layer(positions, hidden_states) |
| 443 | return hidden_states |
| 444 | |
| 445 | |
| 446 | @support_torch_compile |
| 447 | @default_pooling_type(seq_pooling_type="CLS") |
| 448 | class BertWithRope(nn.Module, SupportsQuant): |
| 449 | hf_to_vllm_mapper = WeightsMapper(orig_to_new_prefix={"model.": ""}) |
| 450 | |
| 451 | def __init__( |
| 452 | self, |
| 453 | *, |
| 454 | vllm_config: VllmConfig, |
| 455 | prefix: str = "", |
| 456 | add_pooling_layer: bool = False, |
| 457 | ): |
| 458 | super().__init__() |
| 459 | |
| 460 | self.vllm_config = vllm_config |
| 461 | self.add_pooling_layer = add_pooling_layer |
| 462 | self.config = vllm_config.model_config.hf_config |
| 463 | self.embeddings = BertWithRopeEmbedding(self.config) |
| 464 | self.encoder = BertWithRopeEncoder( |
| 465 | vllm_config=vllm_config, |
| 466 | bias=getattr(self.config, "bias", True), |
| 467 | rotary_kwargs=self.config.rotary_kwargs, |
| 468 | prefix=f"{prefix}.encoder", |
| 469 | ) |
| 470 | |
| 471 | if add_pooling_layer: |
| 472 | self.pooler: BertPooler | None = BertPooler(vllm_config.model_config) |
| 473 | else: |
| 474 | self.pooler = None |
| 475 | |
| 476 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 477 | return self.embeddings(input_ids) |
| 478 | |
| 479 | def forward( |
| 480 | self, |
| 481 | input_ids: torch.Tensor | None, |
| 482 | positions: torch.Tensor, |
| 483 | intermediate_tensors: IntermediateTensors | None = None, |
| 484 | inputs_embeds: torch.Tensor | None = None, |
| 485 | token_type_ids: torch.Tensor | None = None, |
| 486 | ) -> torch.Tensor: |
| 487 | if inputs_embeds is not None: |
| 488 | hidden_states = inputs_embeds |
| 489 | else: |
| 490 | hidden_states = self.embeddings( |
| 491 | input_ids=input_ids, token_type_ids=token_type_ids |
| 492 | ) |
| 493 | return self.encoder(positions, hidden_states) |
| 494 | |
| 495 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 496 | weights = self.hf_to_vllm_mapper.apply(weights) |
| 497 | |
| 498 | if self.config.hidden_act in ["silu", "geglu"]: |
| 499 | stacked_params_mapping = [ |
| 500 | # (param_name, shard_name, shard_id) |
| 501 | ("gate_up_proj", "gate_proj", 0), |
| 502 | ("gate_up_proj", "up_proj", 1), |
| 503 | ] |
| 504 | else: |
| 505 | stacked_params_mapping = [] |
| 506 | |
| 507 | params_dict = dict(self.named_parameters()) |
| 508 | loaded_params: set[str] = set() |
| 509 | for name, loaded_weight in weights: |
| 510 | if not self.add_pooling_layer and "pooler" in name: |
| 511 | continue |
| 512 | for param_name, weight_name, shard_id in stacked_params_mapping: |
| 513 | if weight_name not in name: |
| 514 | continue |
| 515 | name = name.replace(weight_name, param_name) |
| 516 | # Skip loading extra bias for GPTQ models. |
| 517 | if name.endswith(".bias") and name not in params_dict: |
| 518 | continue |
| 519 | param = params_dict[name] |
| 520 | weight_loader = param.weight_loader |
| 521 | weight_loader(param, loaded_weight, shard_id) |
| 522 | break |
| 523 | else: |
| 524 | # Skip loading extra bias for GPTQ models. |
| 525 | if name.endswith(".bias") and name not in params_dict: |
| 526 | continue |
| 527 | param = params_dict[name] |
| 528 | weight_loader = getattr(param, "weight_loader", default_weight_loader) |
| 529 | if name.endswith((".w1", ".w2")): |
| 530 | # Nomic-MoE has fused experts weights |
| 531 | weight_loader(param, loaded_weight, name) |
| 532 | else: |
| 533 | weight_loader(param, loaded_weight) |
| 534 | loaded_params.add(name) |
| 535 | return loaded_params |
| 536 | |
| 537 | |
| 538 | class NomicBertModel(BertWithRope): |
| 539 | # for https://huggingface.co/nomic-ai/nomic-bert-2048 |
| 540 | |
| 541 | hf_to_vllm_mapper = WeightsMapper( |
| 542 | orig_to_new_substr={ |
| 543 | "emb_ln": "embeddings.LayerNorm", |
| 544 | "attn.Wqkv": "attn.qkv_proj", |
| 545 | "norm1": "attn_ln", |
| 546 | "mlp.fc1.": "mlp.up_proj.", |
| 547 | "mlp.fc11": "mlp.up_proj", |
| 548 | "mlp.fc12": "mlp.gate_proj", |
| 549 | "mlp.fc2": "mlp.down_proj", |
| 550 | "norm2": "mlp_ln", |
| 551 | # MoE mapping |
| 552 | "experts.mlp.": "", |
| 553 | "experts.": "", |
| 554 | "router.layer": "router", |
| 555 | } |
| 556 | ) |
| 557 | |
| 558 | |
| 559 | class GteNewModel(BertWithRope): |
| 560 | # for https://huggingface.co/Alibaba-NLP/new-impl |
| 561 | |
| 562 | hf_to_vllm_mapper = WeightsMapper( |
| 563 | orig_to_new_substr={ |
| 564 | "new.": "", |
| 565 | "layer": "layers", |
| 566 | "attention.qkv_proj": "attn.qkv_proj", |
| 567 | "attention.o_proj": "attn.out_proj", |
| 568 | } |
| 569 | ) |
| 570 | |
| 571 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = "", **kwargs): |
| 572 | super().__init__(vllm_config=vllm_config, prefix=prefix, **kwargs) |
| 573 | |
| 574 | # GteNewModel only gate_up_proj does not have bias. |
| 575 | for layer in self.encoder.layers: |
| 576 | layer.mlp.gate_up_proj.bias = None |
| 577 | layer.mlp.gate_up_proj.skip_bias_add = True |
| 578 | |
| 579 | def split_up_gate_proj(self, weights: Iterable[tuple[str, torch.Tensor]]): |
| 580 | n = "mlp.up_gate_proj" |
| 581 | for name, weight in weights: |
| 582 | if n in name: |
| 583 | up, gate = weight.chunk(2, dim=0) |
| 584 | yield name.replace(n, "mlp.up_proj"), up |
| 585 | yield name.replace(n, "mlp.gate_proj"), gate |
| 586 | else: |
| 587 | yield name, weight |
| 588 | |
| 589 | def ignore_unnecessary_layers(self, weights: Iterable[tuple[str, torch.Tensor]]): |
| 590 | for name, weight in weights: |
| 591 | if name.startswith("classifier"): |
| 592 | continue |
| 593 | yield name, weight |
| 594 | |
| 595 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 596 | weights = self.ignore_unnecessary_layers(weights) |
| 597 | weights = self.split_up_gate_proj(weights) |
| 598 | return super().load_weights(weights) |
| 599 | |
| 600 | |
| 601 | class SnowflakeGteNewModel(GteNewModel): |
| 602 | # for Snowflake/snowflake-arctic-embed-m-v2.0 |
| 603 | |
| 604 | hf_to_vllm_mapper = WeightsMapper( |
| 605 | orig_to_new_substr={ |
| 606 | "layer": "layers", |
| 607 | "attention.qkv_proj": "attn.qkv_proj", |
| 608 | "attention.o_proj": "attn.out_proj", |
| 609 | } |
| 610 | ) |
| 611 | |
| 612 | |
| 613 | class JinaRobertaModel(BertWithRope): |
| 614 | # for https://huggingface.co/jinaai/jina-embeddings-v3 |
| 615 | |
| 616 | hf_to_vllm_mapper = WeightsMapper( |
| 617 | orig_to_new_substr={ |
| 618 | "emb_ln": "embeddings.LayerNorm", |
| 619 | "mixer.Wqkv": "attn.qkv_proj", |
| 620 | "mixer.out_proj": "attn.out_proj", |
| 621 | "norm1": "attn_ln", |
| 622 | "mlp.fc1.": "mlp.up_proj.", |
| 623 | "mlp.fc2": "mlp.down_proj", |
| 624 | "norm2": "mlp_ln", |
| 625 | } |
| 626 | ) |
| 627 | |
| 628 | @torch.inference_mode() |
| 629 | def jina_merge_lora_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): |
| 630 | # use for jina-embeddings-v3 |
| 631 | # Merge Lora weights into a single weight tensor. |
| 632 | # This is a temporary solution until we have a better way to handle |
| 633 | |
| 634 | scaling = self.config.lora_alpha / self.config.lora_rank |
| 635 | device = self.vllm_config.device_config.device |
| 636 | |
| 637 | weights_dict = {name: weight for name, weight in weights} |
| 638 | |
| 639 | o = ".original" |
| 640 | a = ".0.lora_A" |
| 641 | b = ".0.lora_B" |
| 642 | |
| 643 | # text-matching |
| 644 | i = -1 |
| 645 | |
| 646 | for name in list(weights_dict.keys()): |
| 647 | if o in name: |
| 648 | dtype = weights_dict[name].dtype |
| 649 | shape = weights_dict[name].shape |
| 650 | weight_name = name[: -len(o)] |
| 651 | |
| 652 | if "embeddings" in weight_name: |
| 653 | B = weights_dict[weight_name + a][i].to(device).float() |
| 654 | A = weights_dict[weight_name + b][i].to(device).float() |
| 655 | else: |
| 656 | B = weights_dict[weight_name + b][i].to(device).float() |
| 657 | A = weights_dict[weight_name + a][i].to(device).float() |
| 658 | |
| 659 | weight = ( |
| 660 | weights_dict[weight_name + o].to(device) |
| 661 | + torch.matmul(B, A).view(shape) * scaling |
| 662 | ) |
| 663 | weight = weight.cpu().to(dtype) |
| 664 | |
| 665 | weights_dict[weight_name.replace(".parametrizations", "")] = weight |
| 666 | |
| 667 | del ( |
| 668 | weights_dict[weight_name + o], |
| 669 | weights_dict[weight_name + a], |
| 670 | weights_dict[weight_name + b], |
| 671 | ) |
| 672 | |
| 673 | return [(name, weight) for name, weight in weights_dict.items()] |
| 674 | |
| 675 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]) -> set[str]: |
| 676 | weights = self.jina_merge_lora_weights(weights) |
| 677 | return super().load_weights(weights) |
| 678 | |
| 679 | |
| 680 | @default_pooling_type(seq_pooling_type="CLS") |
| 681 | class GteNewForSequenceClassification(nn.Module, SupportsCrossEncoding): |
| 682 | is_pooling_model = True |
| 683 | |
| 684 | def __init__(self, *, vllm_config: VllmConfig, prefix: str = ""): |
| 685 | super().__init__() |
| 686 | config = vllm_config.model_config.hf_config |
| 687 | quant_config = vllm_config.quant_config |
| 688 | |
| 689 | self.new = GteNewModel( |
| 690 | vllm_config=vllm_config, prefix=prefix, add_pooling_layer=True |
| 691 | ) |
| 692 | self.classifier = ReplicatedLinear( |
| 693 | config.hidden_size, |
| 694 | config.num_labels, |
| 695 | bias=True, |
| 696 | quant_config=quant_config, |
| 697 | params_dtype=vllm_config.model_config.head_dtype, |
| 698 | prefix=maybe_prefix(prefix, "classifier"), |
| 699 | return_bias=False, |
| 700 | ) |
| 701 | |
| 702 | pooler_config = vllm_config.model_config.pooler_config |
| 703 | assert pooler_config is not None |
| 704 | |
| 705 | self.pooler = DispatchPooler.for_seq_cls( |
| 706 | pooler_config, |
| 707 | pooling=self.new.pooler, |
| 708 | classifier=self.classifier, |
| 709 | ) |
| 710 | |
| 711 | def load_weights(self, weights: Iterable[tuple[str, torch.Tensor]]): |
| 712 | loader = AutoWeightsLoader(self) |
| 713 | loaded_params = loader.load_weights(weights) |
| 714 | return loaded_params |
| 715 | |
| 716 | def embed_input_ids(self, input_ids: torch.Tensor) -> torch.Tensor: |
| 717 | return self.new.embed_input_ids(input_ids) |
| 718 | |
| 719 | def forward( |
| 720 | self, |
| 721 | input_ids: torch.Tensor | None, |
| 722 | positions: torch.Tensor, |
| 723 | intermediate_tensors: IntermediateTensors | None = None, |
| 724 | inputs_embeds: torch.Tensor | None = None, |
| 725 | ) -> torch.Tensor: |
| 726 | return self.new( |
| 727 | input_ids=input_ids, |
| 728 | positions=positions, |
| 729 | inputs_embeds=inputs_embeds, |
| 730 | intermediate_tensors=intermediate_tensors, |
| 731 | ) |