drizzlezyk commited on
Commit
2b9837f
·
verified ·
1 Parent(s): 3a87bae

Upload inference/modeling_openpangu.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. inference/modeling_openpangu.py +840 -0
inference/modeling_openpangu.py ADDED
@@ -0,0 +1,840 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+
22
+ from collections.abc import Iterable
23
+ from typing import Any, Optional, Union, Callable
24
+
25
+ import torch
26
+ from torch import nn
27
+ import torch_npu
28
+
29
+ from vllm.attention import Attention, AttentionType, AttentionMetadata
30
+ from vllm.compilation.decorators import support_torch_compile
31
+ from vllm.config import CacheConfig, VllmConfig, get_current_vllm_config
32
+ from vllm.distributed import get_pp_group, get_tensor_model_parallel_world_size
33
+ from vllm.model_executor.layers.activation import SiluAndMul
34
+ from vllm.model_executor.layers.layernorm import RMSNorm
35
+ from vllm.model_executor.layers.linear import (MergedColumnParallelLinear,
36
+ QKVParallelLinear,
37
+ RowParallelLinear)
38
+ from vllm.model_executor.layers.logits_processor import LogitsProcessor
39
+ from vllm.model_executor.layers.quantization import QuantizationConfig
40
+ from vllm.model_executor.layers.rotary_embedding import get_rope
41
+ from vllm.model_executor.layers.vocab_parallel_embedding import (
42
+ DEFAULT_VOCAB_PADDING_SIZE, ParallelLMHead, VocabParallelEmbedding)
43
+ from vllm.model_executor.model_loader.weight_utils import (
44
+ default_weight_loader, sharded_weight_loader, row_parallel_weight_loader, maybe_remap_kv_scale_name)
45
+ from vllm.sequence import IntermediateTensors
46
+
47
+ from vllm.model_executor.models.interfaces import SupportsLoRA, SupportsPP
48
+ from vllm.model_executor.models.utils import (AutoWeightsLoader, PPMissingLayer, extract_layer_index,
49
+ is_pp_missing_parameter,
50
+ make_empty_intermediate_tensors_factory, make_layers,
51
+ maybe_prefix)
52
+ from vllm.forward_context import ForwardContext, get_forward_context
53
+ from vllm.utils import direct_register_custom_op
54
+
55
+ from configuration_openpangu_dense import PanguEmbeddedConfig
56
+
57
+
58
+ def aggregate_hiddden(
59
+ hidden_states: torch.Tensor,
60
+ cache_states: torch.Tensor,
61
+ cache_length: torch.Tensor,
62
+ fn_name: str,
63
+ aggre_output: torch.Tensor
64
+ ) -> torch.Tensor:
65
+ """
66
+ input_hidden.shape = (S, H) or (B, H)
67
+
68
+ conv(H, S) or (B, H, 1)
69
+ ^ ^
70
+ return.shape = (S, H) or (B, H)
71
+ """
72
+ forward_context: ForwardContext = get_forward_context()
73
+ attn_metadata = forward_context.attn_metadata
74
+ if attn_metadata is None: #dummy run
75
+ return hidden_states
76
+
77
+ aggregate_fn = forward_context.no_compile_layers[fn_name]
78
+ num_tokens, hidden_dim = hidden_states.shape
79
+
80
+ cache_slot_id = forward_context.cache_slot_id
81
+ query_start_loc = forward_context.query_start_loc
82
+
83
+ if forward_context.with_prefill:
84
+ is_first_chunk = forward_context.is_first_chunk
85
+ for i, q_start in enumerate(query_start_loc[:-1]):
86
+ slot_id = cache_slot_id[i]
87
+ q_end = query_start_loc[i+1]
88
+ aggre_input = torch.empty(
89
+ (cache_length + q_end - q_start, hidden_dim),
90
+ device=hidden_states.device, dtype=hidden_states.dtype
91
+ )
92
+
93
+ if is_first_chunk[i]:
94
+ aggre_input[:cache_length].fill_(0)
95
+ else:
96
+ aggre_input[:cache_length].copy_(cache_states[slot_id, :cache_length])
97
+ aggre_input[cache_length:].copy_(hidden_states[q_start:q_end])
98
+
99
+ aggre_input[cache_length:].copy_(hidden_states[q_start:q_end])
100
+ output = aggregate_fn(aggre_input.permute(1, 0))
101
+ aggre_output[q_start:q_end].copy_(output.permute(1, 0))
102
+ cache_states[slot_id, :cache_length].copy_(aggre_input[-cache_length:])
103
+ return aggre_output
104
+ else:
105
+ # decode stage
106
+ num_tokens = query_start_loc[-1]
107
+ cache_slot_id_t = cache_slot_id.unsqueeze(0).permute(1, 0)
108
+ torch_npu.npu_scatter_nd_update_(cache_states[:, -1, :], cache_slot_id_t, hidden_states[:num_tokens])
109
+ aggre_input = cache_states[cache_slot_id].permute(0, 2, 1)
110
+ aggre_output[:num_tokens] = aggregate_fn(aggre_input).squeeze(2)
111
+ torch_npu.npu_scatter_nd_update_(cache_states[:, :cache_length, :], cache_slot_id_t,
112
+ cache_states[cache_slot_id, -cache_length:, :])
113
+ return aggre_output
114
+
115
+ def aggregate_hiddden_fake(
116
+ hidden_states: torch.Tensor,
117
+ cache_states: torch.Tensor,
118
+ cache_length: torch.Tensor,
119
+ fn_name: str,
120
+ aggre_output: torch.Tensor
121
+ ) -> torch.Tensor:
122
+ return hidden_states
123
+
124
+ direct_register_custom_op(
125
+ op_name="aggregate_hiddden",
126
+ op_func=aggregate_hiddden,
127
+ mutates_args=["cache_states", "aggre_output"],
128
+ fake_impl=aggregate_hiddden_fake,
129
+ )
130
+
131
+
132
+ class PanguEmbeddedMLP(nn.Module):
133
+
134
+ def __init__(
135
+ self,
136
+ hidden_size: int,
137
+ intermediate_size: int,
138
+ hidden_act: str,
139
+ quant_config: Optional[QuantizationConfig] = None,
140
+ bias: bool = False,
141
+ prefix: str = "",
142
+ reduce_results: bool = True,
143
+ ) -> None:
144
+ super().__init__()
145
+ self.gate_up_proj = MergedColumnParallelLinear(
146
+ input_size=hidden_size,
147
+ output_sizes=[intermediate_size] * 2,
148
+ bias=bias,
149
+ quant_config=quant_config,
150
+ prefix=f"{prefix}.gate_up_proj",
151
+ )
152
+ self.down_proj = RowParallelLinear(
153
+ input_size=intermediate_size,
154
+ output_size=hidden_size,
155
+ bias=bias,
156
+ quant_config=quant_config,
157
+ reduce_results=reduce_results,
158
+ prefix=f"{prefix}.down_proj",
159
+ )
160
+ if hidden_act != "silu":
161
+ raise ValueError(f"Unsupported activation: {hidden_act}. "
162
+ "Only silu is supported for now.")
163
+ self.act_fn = SiluAndMul()
164
+
165
+ def forward(self, x):
166
+ x, _ = self.gate_up_proj(x)
167
+ x = self.act_fn(x)
168
+ x, _ = self.down_proj(x)
169
+ return x
170
+
171
+
172
+ class PanguEmbeddedAttention(nn.Module):
173
+
174
+ def __init__(
175
+ self,
176
+ config: PanguEmbeddedConfig,
177
+ hidden_size: int,
178
+ num_heads: int,
179
+ num_kv_heads: int,
180
+ rope_theta: float = 10000,
181
+ rope_scaling: Optional[dict[str, Any]] = None,
182
+ max_position_embeddings: int = 8192,
183
+ quant_config: Optional[QuantizationConfig] = None,
184
+ bias: bool = False,
185
+ bias_o_proj: bool = False,
186
+ cache_config: Optional[CacheConfig] = None,
187
+ prefix: str = "",
188
+ attn_type: str = AttentionType.DECODER,
189
+ ) -> None:
190
+ super().__init__()
191
+ layer_idx = extract_layer_index(prefix)
192
+ self.hidden_size = hidden_size
193
+ tp_size = get_tensor_model_parallel_world_size()
194
+ self.total_num_heads = num_heads
195
+ self.num_heads = self.total_num_heads // tp_size
196
+ self.total_num_kv_heads = num_kv_heads
197
+ self.num_kv_heads = max(1, self.total_num_kv_heads // tp_size)
198
+ # MistralConfig has an optional head_dim introduced by Mistral-Nemo
199
+ head_dim = getattr(config, "head_dim", None)
200
+ if head_dim is None:
201
+ head_dim = self.hidden_size // self.total_num_heads
202
+ self.head_dim = head_dim
203
+ # Phi models introduced a partial_rotary_factor parameter in the config
204
+ self.partial_rotary_factor = getattr(config, "partial_rotary_factor", 1)
205
+ self.q_size = self.num_heads * self.head_dim
206
+ self.kv_size = self.num_kv_heads * self.head_dim
207
+ self.scaling = self.head_dim**-0.5
208
+ self.rope_theta = rope_theta
209
+ self.rotary_dim = getattr(config, "qk_rope_dim", head_dim)
210
+ self.max_position_embeddings = max_position_embeddings
211
+ self.v_channels = getattr(config, "v_channels", None)
212
+
213
+ self.qkv_proj = QKVParallelLinear(
214
+ hidden_size=hidden_size,
215
+ head_size=self.head_dim,
216
+ total_num_heads=self.total_num_heads,
217
+ total_num_kv_heads=self.total_num_kv_heads,
218
+ bias=bias,
219
+ quant_config=quant_config,
220
+ prefix=f"{prefix}.qkv_proj",
221
+ )
222
+
223
+ self.o_proj = RowParallelLinear(
224
+ input_size=self.total_num_heads * self.head_dim,
225
+ output_size=hidden_size,
226
+ bias=bias_o_proj,
227
+ quant_config=quant_config,
228
+ prefix=f"{prefix}.o_proj",
229
+ )
230
+
231
+ self._init_rotary_emb(config,
232
+ rope_scaling=rope_scaling,
233
+ quant_config=quant_config)
234
+
235
+ if hasattr(config, "interleaved_sliding_window"):
236
+ interleaved_sliding_window = config.interleaved_sliding_window
237
+ if isinstance(interleaved_sliding_window, int):
238
+ sliding_window = interleaved_sliding_window
239
+ elif isinstance(interleaved_sliding_window, list):
240
+ sw_idx = layer_idx % len(interleaved_sliding_window)
241
+ sliding_window = interleaved_sliding_window[sw_idx]
242
+ else:
243
+ raise ValueError(
244
+ f"{type(interleaved_sliding_window)} is not supported.")
245
+ else:
246
+ sliding_window = None
247
+
248
+ self.attn = Attention(
249
+ self.num_heads,
250
+ self.head_dim,
251
+ self.scaling,
252
+ num_kv_heads=self.num_kv_heads,
253
+ cache_config=cache_config,
254
+ quant_config=quant_config,
255
+ per_layer_sliding_window=sliding_window,
256
+ attn_type=attn_type,
257
+ prefix=f"{prefix}.attn",
258
+ sinks={}
259
+ )
260
+ # Patch for Sink
261
+ param_sink_number = getattr(config, 'param_sink_number', 0)
262
+ param_sink_with_value = getattr(config, 'param_sink_with_value', False)
263
+ if param_sink_number > 0:
264
+ self.enable_sink = True
265
+ self.param_sink_query = torch.zeros((
266
+ param_sink_number,
267
+ self.num_heads,
268
+ self.head_dim),
269
+ dtype=config.torch_dtype
270
+ )
271
+ self.param_sink_key = torch.nn.Parameter(
272
+ torch.empty((
273
+ param_sink_number,
274
+ self.num_kv_heads,
275
+ self.head_dim),
276
+ dtype=config.torch_dtype
277
+ )
278
+ )
279
+ if param_sink_with_value:
280
+ self.param_sink_value = torch.nn.Parameter(
281
+ torch.empty((
282
+ param_sink_number,
283
+ self.num_kv_heads,
284
+ self.v_channels),
285
+ dtype=config.torch_dtype
286
+ )
287
+ )
288
+ else:
289
+ self.param_sink_value = torch.zeros((
290
+ param_sink_number,
291
+ self.num_kv_heads,
292
+ self.v_channels),
293
+ dtype=config.torch_dtype
294
+ )
295
+ else:
296
+ self.enable_sink = False
297
+
298
+ attn_groupnorm = getattr(config, 'attn_groupnorm', False)
299
+ if attn_groupnorm:
300
+ self.groupnorm = RMSNorm(hidden_size=self.head_dim, eps=config.rms_norm_eps)
301
+ else:
302
+ self.groupnorm = None
303
+
304
+ attn_elementwise_gate = getattr(config, 'attn_elementwise_gate', False)
305
+ if attn_elementwise_gate:
306
+ self.attention_gate = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
307
+ else:
308
+ self.attention_gate = None
309
+
310
+ def forward(
311
+ self,
312
+ positions: torch.Tensor,
313
+ hidden_states: torch.Tensor,
314
+ ) -> torch.Tensor:
315
+ qkv, _ = self.qkv_proj(hidden_states)
316
+ q, k, v = qkv.split([self.q_size, self.kv_size, self.kv_size], dim=-1)
317
+ q, k = self.rotary_emb(positions, q, k)
318
+ attn_output = self.attn(
319
+ q, k, v,
320
+ ** (dict(
321
+ sink_query=self.param_sink_query,
322
+ sink_key=self.param_sink_key,
323
+ sink_value=self.param_sink_value,
324
+ v_head_size=self.v_channels
325
+ ) if self.enable_sink else {})
326
+ )
327
+ # groupnorm (s, h, d)
328
+ if self.groupnorm is not None:
329
+ num_tokens, hidden_dim = attn_output.shape
330
+ attn_norm = attn_output.view(num_tokens, self.num_heads, self.head_dim)
331
+ attn_norm = self.groupnorm(attn_norm)
332
+ attn_output = attn_norm.view(num_tokens, hidden_dim)
333
+ # gate (s, h*d)
334
+ if self.attention_gate is not None:
335
+ gate_score = self.attention_gate(hidden_states)
336
+ attn_output = attn_output * torch.sigmoid(gate_score)
337
+ output, _ = self.o_proj(attn_output)
338
+ return output
339
+
340
+ def _init_rotary_emb(self, config: PanguEmbeddedConfig,
341
+ rope_scaling: Optional[dict[str, Any]],
342
+ quant_config: Optional[QuantizationConfig]) -> None:
343
+ is_neox_style = True
344
+ is_gguf = quant_config and quant_config.get_name() == "gguf"
345
+ if is_gguf and config.model_type == "Pangu":
346
+ is_neox_style = False
347
+
348
+ self.rotary_emb = get_rope(
349
+ self.head_dim,
350
+ rotary_dim=self.rotary_dim,
351
+ max_position=self.max_position_embeddings,
352
+ base=self.rope_theta,
353
+ rope_scaling=rope_scaling,
354
+ is_neox_style=is_neox_style,
355
+ )
356
+
357
+
358
+ class PanguEmbeddedDecoderLayer(nn.Module):
359
+
360
+ def __init__(
361
+ self,
362
+ config: PanguEmbeddedConfig,
363
+ cache_config: Optional[CacheConfig] = None,
364
+ quant_config: Optional[QuantizationConfig] = None,
365
+ prefix: str = "",
366
+ ) -> None:
367
+ super().__init__()
368
+ torch_npu.npu.config.allow_internal_format = False
369
+ self.hidden_size = config.hidden_size
370
+ rope_theta = getattr(config, "rope_theta", 10000)
371
+ rope_scaling = getattr(config, "rope_scaling", None)
372
+ if rope_scaling is not None and getattr(
373
+ config, "original_max_position_embeddings", None):
374
+ rope_scaling["original_max_position_embeddings"] = (
375
+ config.original_max_position_embeddings)
376
+ max_position_embeddings = getattr(config, "max_position_embeddings",
377
+ 8192)
378
+ # Support abacusai/Smaug-72B-v0.1 with attention_bias
379
+ # Support internlm/internlm-7b with bias
380
+ attention_bias = getattr(config, "attention_bias", False) or getattr(
381
+ config, "bias", False)
382
+ bias_o_proj = attention_bias
383
+ # support internlm/internlm3-8b with qkv_bias
384
+ if hasattr(config, 'qkv_bias'):
385
+ attention_bias = config.qkv_bias
386
+
387
+ # By default, PanguEmbedded uses causal attention as it is a decoder-only model.
388
+ # You can override the HF config with `is_causal=False` to enable
389
+ # bidirectional attention, which is used in some embedding models
390
+ # (e.g. parasail-ai/GritLM-7B-vllm)
391
+ if getattr(config, "is_causal", True):
392
+ attn_type = AttentionType.DECODER
393
+ else:
394
+ attn_type = AttentionType.ENCODER_ONLY
395
+
396
+ self.self_attn = PanguEmbeddedAttention(
397
+ config=config,
398
+ hidden_size=self.hidden_size,
399
+ num_heads=config.num_attention_heads,
400
+ num_kv_heads=getattr(config, "num_key_value_heads",
401
+ config.num_attention_heads),
402
+ rope_theta=rope_theta,
403
+ rope_scaling=rope_scaling,
404
+ max_position_embeddings=max_position_embeddings,
405
+ quant_config=quant_config,
406
+ bias=attention_bias,
407
+ bias_o_proj=bias_o_proj,
408
+ cache_config=cache_config,
409
+ prefix=f"{prefix}.self_attn",
410
+ attn_type=attn_type,
411
+ )
412
+ self.mlp = PanguEmbeddedMLP(
413
+ hidden_size=self.hidden_size,
414
+ intermediate_size=config.intermediate_size,
415
+ hidden_act=config.hidden_act,
416
+ quant_config=quant_config,
417
+ bias=getattr(config, "mlp_bias", False),
418
+ prefix=f"{prefix}.mlp",
419
+ )
420
+ self.input_layernorm = RMSNorm(config.hidden_size,
421
+ eps=config.rms_norm_eps)
422
+ self.post_attention_layernorm = RMSNorm(config.hidden_size,
423
+ eps=config.rms_norm_eps)
424
+
425
+ # merge_conv
426
+ layer_idx = extract_layer_index(prefix)
427
+ self.router_sliding_window = getattr(config, 'router_sliding_window', 0)
428
+ if self.router_sliding_window > 1 and layer_idx in [0, config.num_hidden_layers - 1]:
429
+ self.merge_conv = torch.nn.Conv1d(
430
+ in_channels=config.hidden_size,
431
+ out_channels=config.hidden_size,
432
+ kernel_size=self.router_sliding_window,
433
+ groups=config.hidden_size,
434
+ bias=False,
435
+ )
436
+ vllm_config = get_current_vllm_config()
437
+ self.max_num_seqs = vllm_config.scheduler_config.max_num_seqs
438
+ self.cache_states = \
439
+ torch.zeros((self.max_num_seqs, self.router_sliding_window, config.hidden_size), device='npu')
440
+ self.cache_length = torch.tensor(self.router_sliding_window - 1).npu()
441
+ # add conv to static_forward_context
442
+ self.conv_name = f"{prefix}.conv"
443
+ vllm_config.compilation_config.static_forward_context[self.conv_name] = self.merge_conv
444
+
445
+ else:
446
+ self.merge_conv = None
447
+ self.cache_states = None
448
+
449
+ def aggregate(self, hidden_states: torch.Tensor) -> torch.Tensor:
450
+ aggre_output = torch.zeros((hidden_states.shape), dtype=hidden_states.dtype, device=hidden_states.device)
451
+ torch.ops.vllm.aggregate_hiddden(
452
+ hidden_states=hidden_states,
453
+ cache_states=self.cache_states,
454
+ cache_length=self.cache_length,
455
+ fn_name=self.conv_name,
456
+ aggre_output=aggre_output
457
+ )
458
+ return aggre_output
459
+
460
+ def forward(
461
+ self,
462
+ positions: torch.Tensor,
463
+ hidden_states: torch.Tensor,
464
+ residual: Optional[torch.Tensor] = None,
465
+ ) -> tuple[torch.Tensor, torch.Tensor]:
466
+ # Self Attention
467
+ if residual is None:
468
+ residual = hidden_states
469
+ hidden_states = self.input_layernorm(hidden_states)
470
+ else:
471
+ hidden_states, residual = self.input_layernorm(
472
+ hidden_states, residual)
473
+ hidden_states = self.self_attn(positions=positions,
474
+ hidden_states=hidden_states)
475
+
476
+ # Add
477
+ hidden_states = residual + hidden_states
478
+ residual = hidden_states
479
+ # Conv
480
+ if self.merge_conv is not None:
481
+ hidden_states = self.aggregate(hidden_states=hidden_states)
482
+
483
+ # Fully Connected
484
+ hidden_states = self.post_attention_layernorm(hidden_states)
485
+ hidden_states = self.mlp(hidden_states)
486
+
487
+ return hidden_states, residual
488
+
489
+
490
+ @support_torch_compile
491
+ class PanguEmbeddedModel(nn.Module):
492
+
493
+ def __init__(self,
494
+ *,
495
+ vllm_config: VllmConfig,
496
+ prefix: str = "",
497
+ layer_type: type[nn.Module] = PanguEmbeddedDecoderLayer):
498
+ super().__init__()
499
+
500
+ config = vllm_config.model_config.hf_config
501
+ cache_config = vllm_config.cache_config
502
+ quant_config = vllm_config.quant_config
503
+ lora_config = vllm_config.lora_config
504
+
505
+ self.config = config
506
+ self.quant_config = quant_config
507
+ lora_vocab = (lora_config.lora_extra_vocab_size *
508
+ (lora_config.max_loras or 1)) if lora_config else 0
509
+ self.vocab_size = config.vocab_size + lora_vocab
510
+ self.org_vocab_size = config.vocab_size
511
+ if get_pp_group().is_first_rank or (config.tie_word_embeddings
512
+ and get_pp_group().is_last_rank):
513
+ self.embed_tokens = VocabParallelEmbedding(
514
+ self.vocab_size,
515
+ config.hidden_size,
516
+ org_num_embeddings=config.vocab_size,
517
+ quant_config=quant_config,
518
+ prefix=f"{prefix}.embed_tokens",
519
+ )
520
+ else:
521
+ self.embed_tokens = PPMissingLayer()
522
+ self.start_layer, self.end_layer, self.layers = make_layers(
523
+ config.num_hidden_layers,
524
+ lambda prefix: layer_type(config=config,
525
+ cache_config=cache_config,
526
+ quant_config=quant_config,
527
+ prefix=prefix),
528
+ prefix=f"{prefix}.layers",
529
+ )
530
+ if get_pp_group().is_last_rank:
531
+ self.norm = RMSNorm(config.hidden_size, eps=config.rms_norm_eps)
532
+ else:
533
+ self.norm = PPMissingLayer()
534
+
535
+ self.aux_hidden_state_layers: tuple[int] = tuple()
536
+
537
+ self.make_empty_intermediate_tensors = (
538
+ make_empty_intermediate_tensors_factory(
539
+ ["hidden_states", "residual"], config.hidden_size))
540
+
541
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
542
+ return self.embed_tokens(input_ids)
543
+
544
+ def forward(
545
+ self,
546
+ input_ids: Optional[torch.Tensor],
547
+ positions: torch.Tensor,
548
+ intermediate_tensors: Optional[IntermediateTensors],
549
+ inputs_embeds: Optional[torch.Tensor] = None,
550
+ ) -> Union[torch.Tensor, IntermediateTensors, tuple[torch.Tensor,
551
+ list[torch.Tensor]]]:
552
+ if get_pp_group().is_first_rank:
553
+ if inputs_embeds is not None:
554
+ hidden_states = inputs_embeds
555
+ else:
556
+ hidden_states = self.get_input_embeddings(input_ids)
557
+ residual = None
558
+ else:
559
+ hidden_states = intermediate_tensors["hidden_states"]
560
+ residual = intermediate_tensors["residual"]
561
+
562
+ aux_hidden_states = []
563
+ for idx, layer in enumerate(
564
+ self.layers[self.start_layer:self.end_layer]):
565
+ if idx in self.aux_hidden_state_layers:
566
+ aux_hidden_states.append(hidden_states + residual)
567
+ hidden_states, residual = layer(positions, hidden_states, residual)
568
+
569
+ if not get_pp_group().is_last_rank:
570
+ return IntermediateTensors({
571
+ "hidden_states": hidden_states,
572
+ "residual": residual
573
+ })
574
+
575
+ hidden_states, _ = self.norm(hidden_states, residual)
576
+
577
+ if len(aux_hidden_states) > 0:
578
+ return hidden_states, aux_hidden_states
579
+ return hidden_states
580
+
581
+ def load_weights(self, weights: Iterable[tuple[str,
582
+ torch.Tensor]]) -> set[str]:
583
+ stacked_params_mapping = [
584
+ # (param_name, shard_name, shard_id)
585
+ (".qkv_proj", ".q_proj", "q"),
586
+ (".qkv_proj", ".k_proj", "k"),
587
+ (".qkv_proj", ".v_proj", "v"),
588
+ (".gate_up_proj", ".gate_proj", 0),
589
+ (".gate_up_proj", ".up_proj", 1),
590
+ ]
591
+ # skip second norms.1.weights
592
+ skip_unneeded_norm = (not isinstance(self.norm, nn.ModuleList))
593
+
594
+ params_dict = dict(self.named_parameters())
595
+ loaded_params: set[str] = set()
596
+ for name, loaded_weight in weights:
597
+ if valid_name_layer(name, self.end_layer):
598
+ continue
599
+ if skip_unneeded_norm and name.startswith('norms.'):
600
+ norm_idx = int(name.split('norms.')[-1].split('.')[0])
601
+ if norm_idx > 0:
602
+ continue
603
+ name = name.replace(f"norms.{norm_idx}",
604
+ f"norm")
605
+
606
+ if "rotary_emb.inv_freq" in name:
607
+ continue
608
+ if ("rotary_emb.cos_cached" in name
609
+ or "rotary_emb.sin_cached" in name):
610
+ # Models trained using ColossalAI may include these tensors in
611
+ # the checkpoint. Skip them.
612
+ continue
613
+ if (self.quant_config is not None and
614
+ (scale_name := self.quant_config.get_cache_scale(name))):
615
+ # Loading kv cache quantization scales
616
+ param = params_dict[scale_name]
617
+ weight_loader = getattr(param, "weight_loader",
618
+ default_weight_loader)
619
+ loaded_weight = (loaded_weight if loaded_weight.dim() == 0 else
620
+ loaded_weight[0])
621
+ weight_loader(param, loaded_weight)
622
+ loaded_params.add(scale_name)
623
+ continue
624
+ if "scale" in name:
625
+ # Remapping the name of FP8 kv-scale.
626
+ name = maybe_remap_kv_scale_name(name, params_dict)
627
+ if name is None:
628
+ continue
629
+ for param_name, weight_name, shard_id in stacked_params_mapping:
630
+ if weight_name not in name:
631
+ continue
632
+ name = name.replace(weight_name, param_name)
633
+ # Skip loading extra bias for GPTQ models.
634
+ if name.endswith(".bias") and name not in params_dict:
635
+ continue
636
+
637
+ if is_pp_missing_parameter(name, self):
638
+ continue
639
+
640
+ param = params_dict[name]
641
+ weight_loader = param.weight_loader
642
+ weight_loader(param, loaded_weight, shard_id)
643
+ break
644
+ else:
645
+ # Skip loading extra bias for GPTQ models.
646
+ if name.endswith(".bias") and name not in params_dict:
647
+ continue
648
+
649
+ if is_pp_missing_parameter(name, self):
650
+ continue
651
+
652
+ param = params_dict[name]
653
+ if name.endswith("param_sink_key") or name.endswith("param_sink_value"):
654
+ weight_loader = getattr(param, "weight_loader", sharded_weight_loader(-2)) # [S,N,D]
655
+ elif name.endswith("attention_gate.weight"):
656
+ weight_loader = getattr(param, "weight_loader", row_parallel_weight_loader)
657
+ else:
658
+ weight_loader = getattr(param, "weight_loader", default_weight_loader)
659
+ weight_loader(param, loaded_weight)
660
+ loaded_params.add(name)
661
+ return loaded_params
662
+
663
+
664
+ class PanguEmbeddedForCausalLM(nn.Module, SupportsLoRA, SupportsPP):
665
+ packed_modules_mapping = {
666
+ "qkv_proj": ["q_proj", "k_proj", "v_proj"],
667
+ "gate_up_proj": ["gate_proj", "up_proj"]
668
+ }
669
+
670
+ # LoRA specific attributes
671
+ embedding_modules = {
672
+ "embed_tokens": "input_embeddings",
673
+ "lm_head": "output_embeddings"
674
+ }
675
+ embedding_padding_modules = ["lm_head"]
676
+
677
+ # Mistral/PanguEmbedded models can also be loaded with --load-format mistral
678
+ # from consolidated.safetensors checkpoints
679
+ mistral_mapping = {
680
+ "layers": "model.layers",
681
+ "attention": "self_attn",
682
+ "qscale_act": "input_scale",
683
+ "qscale_weight": "weight_scale",
684
+ "kv_fake_quantizer.qscale_act": "kv_scale",
685
+ "wq": "q_proj",
686
+ "wk": "k_proj",
687
+ "wv": "v_proj",
688
+ "wo": "o_proj",
689
+ "attention_norm": "input_layernorm",
690
+ "feed_forward": "mlp",
691
+ "w1": "gate_proj",
692
+ "w2": "down_proj",
693
+ "w3": "up_proj",
694
+ "ffn_norm": "post_attention_layernorm",
695
+ "tok_embeddings": "model.embed_tokens",
696
+ "output": "lm_head",
697
+ "norm": "model.norm",
698
+ }
699
+
700
+ def __init__(self,
701
+ *,
702
+ vllm_config: VllmConfig,
703
+ prefix: str = "",
704
+ layer_type: type[nn.Module] = PanguEmbeddedDecoderLayer):
705
+ super().__init__()
706
+ config = vllm_config.model_config.hf_config
707
+ quant_config = vllm_config.quant_config
708
+ lora_config = vllm_config.lora_config
709
+ self.config = config
710
+ self.lora_config = lora_config
711
+
712
+ self.model = self._init_model(vllm_config=vllm_config,
713
+ prefix=maybe_prefix(prefix, "model"),
714
+ layer_type=layer_type)
715
+
716
+ if get_pp_group().is_last_rank:
717
+ self.unpadded_vocab_size = config.vocab_size
718
+ if lora_config:
719
+ self.unpadded_vocab_size += lora_config.lora_extra_vocab_size
720
+ self.lm_head = ParallelLMHead(
721
+ self.unpadded_vocab_size,
722
+ config.hidden_size,
723
+ org_num_embeddings=config.vocab_size,
724
+ padding_size=(
725
+ DEFAULT_VOCAB_PADDING_SIZE
726
+ # We need bigger padding if using lora for kernel
727
+ # compatibility
728
+ if not lora_config else
729
+ lora_config.lora_vocab_padding_size),
730
+ quant_config=quant_config,
731
+ prefix=maybe_prefix(prefix, "lm_head"),
732
+ )
733
+ if config.tie_word_embeddings:
734
+ self.lm_head = self.lm_head.tie_weights(
735
+ self.model.embed_tokens)
736
+
737
+ logit_scale = getattr(config, "logit_scale", 1.0)
738
+ self.logits_processor = LogitsProcessor(self.unpadded_vocab_size,
739
+ config.vocab_size,
740
+ logit_scale)
741
+ else:
742
+ self.lm_head = PPMissingLayer()
743
+
744
+ self.make_empty_intermediate_tensors = (
745
+ self.model.make_empty_intermediate_tensors)
746
+
747
+ def set_aux_hidden_state_layers(self, layers: tuple[int]) -> None:
748
+ self.model.aux_hidden_state_layers = layers
749
+
750
+ def get_eagle3_aux_hidden_state_layers(self) -> tuple[int]:
751
+ num_layers = len(self.model.layers)
752
+ return (2, num_layers // 2, num_layers - 3)
753
+
754
+ def _init_model(self,
755
+ vllm_config: VllmConfig,
756
+ prefix: str = "",
757
+ layer_type: type[nn.Module] = PanguEmbeddedDecoderLayer):
758
+ return PanguEmbeddedModel(vllm_config=vllm_config,
759
+ prefix=prefix,
760
+ layer_type=layer_type)
761
+
762
+ def get_input_embeddings(self, input_ids: torch.Tensor) -> torch.Tensor:
763
+ return self.model.get_input_embeddings(input_ids)
764
+
765
+ def forward(
766
+ self,
767
+ input_ids: torch.Tensor,
768
+ positions: torch.Tensor,
769
+ intermediate_tensors: Optional[IntermediateTensors] = None,
770
+ inputs_embeds: Optional[torch.Tensor] = None,
771
+ ) -> Union[torch.Tensor, IntermediateTensors]:
772
+ model_output = self.model(input_ids, positions, intermediate_tensors,
773
+ inputs_embeds)
774
+ return model_output
775
+
776
+ def compute_logits(
777
+ self,
778
+ hidden_states: torch.Tensor,
779
+ ) -> Optional[torch.Tensor]:
780
+ logits = self.logits_processor(self.lm_head, hidden_states)
781
+ return logits
782
+
783
+ def load_weights(self, weights: Iterable[tuple[str,
784
+ torch.Tensor]]) -> set[str]:
785
+ loader = AutoWeightsLoader(
786
+ self,
787
+ skip_prefixes=(["lm_head."]
788
+ if self.config.tie_word_embeddings else None),
789
+ )
790
+ return loader.load_weights(
791
+ self.maybe_remap_mistral(name, loaded_weight)
792
+ for name, loaded_weight in weights)
793
+
794
+ # This function is used to remap the mistral format as
795
+ # used by Mistral and PanguEmbedded <=2
796
+ def maybe_remap_mistral(
797
+ self,
798
+ name: str,
799
+ loaded_weight: torch.Tensor,
800
+ ) -> tuple[str, torch.Tensor]:
801
+
802
+ def permute(w: torch.Tensor, n_heads: int):
803
+ attn_in = self.config.head_dim * n_heads
804
+ attn_out = self.config.hidden_size
805
+
806
+ return w.view(n_heads, attn_in // n_heads // 2, 2,
807
+ attn_out).transpose(1, 2).reshape(attn_in, attn_out)
808
+
809
+ mapping = self.mistral_mapping
810
+ modules = name.split(".")
811
+
812
+ # rotary embeds should be sliced
813
+ if "wk" in modules and modules[-1] == "weight":
814
+ loaded_weight = permute(loaded_weight,
815
+ self.config.num_key_value_heads)
816
+ elif "wq" in modules and modules[-1] == "weight":
817
+ loaded_weight = permute(loaded_weight,
818
+ self.config.num_attention_heads)
819
+
820
+ num_modules = len(modules)
821
+ for i in range(num_modules):
822
+ item = modules[i]
823
+ next_item = modules[i + 1] if i < num_modules - 1 else None
824
+
825
+ combined_item = (f"{item}.{next_item}"
826
+ if next_item is not None else None)
827
+
828
+ if combined_item in mapping:
829
+ name = name.replace(combined_item, mapping[combined_item])
830
+ elif item in mapping and mapping[item] not in name:
831
+ name = name.replace(item, mapping[item])
832
+
833
+ return name, loaded_weight
834
+
835
+ def valid_name_layer(name: str, end_layer: int) -> bool:
836
+ if "layers" in name:
837
+ layer_idx = extract_layer_index(name)
838
+ if layer_idx >= end_layer:
839
+ return True
840
+ return False