drizzlezyk commited on
Commit
b98ed9c
·
verified ·
1 Parent(s): fb53146

Upload modeling_openpangu_dense.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_openpangu_dense.py +576 -0
modeling_openpangu_dense.py ADDED
@@ -0,0 +1,576 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from modular_openpangu_dense.py.
3
+ # Do NOT edit this file manually as any edits will be overwritten by the generation of
4
+ # the file from the modular. If any change should be done, please apply the change to the
5
+ # modular_openpangu_dense.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+
8
+ # coding=utf-8
9
+ # Copyright (c) 2025 Huawei Technologies Co., Ltd. All Rights Reserved.
10
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All Rights Reserved.
11
+ #
12
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
13
+ # and OPT implementations in this library. It has been modified from its
14
+ # original forms to accommodate minor architectural differences compared
15
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
16
+ #
17
+ # Licensed under the Apache License, Version 2.0 (the "License");
18
+ # you may not use this file except in compliance with the License.
19
+ # You may obtain a copy of the License at
20
+ #
21
+ # http://www.apache.org/licenses/LICENSE-2.0
22
+ #
23
+ # Unless required by applicable law or agreed to in writing, software
24
+ # distributed under the License is distributed on an "AS IS" BASIS,
25
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
26
+ # See the License for the specific language governing permissions and
27
+ # limitations under the License.
28
+
29
+ from typing import Callable, Optional, Union
30
+
31
+ import torch
32
+ from torch import nn
33
+ try:
34
+ import torch_npu
35
+ from torch_npu.contrib import transfer_to_npu
36
+ if "910" in torch.npu.get_device_name():
37
+ NPU_ATTN_INFR = True
38
+ print("[INFO] torch_npu detected. Using NPU fused infer attention.")
39
+ else:
40
+ NPU_ATTN_INFR = False
41
+ except ImportError as e:
42
+ NPU_ATTN_INFR = False
43
+
44
+
45
+ from transformers.activations import ACT2FN
46
+ from transformers.cache_utils import Cache, DynamicCache
47
+ from transformers.generation import GenerationMixin
48
+ from transformers.masking_utils import create_causal_mask
49
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
50
+ from transformers.modeling_layers import GradientCheckpointingLayer
51
+ from transformers.modeling_outputs import (
52
+ BaseModelOutputWithPast,
53
+ CausalLMOutputWithPast,
54
+ SequenceClassifierOutputWithPast,
55
+ )
56
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
57
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
58
+ from transformers.processing_utils import Unpack
59
+ from transformers.utils import LossKwargs, auto_docstring, can_return_tuple, logging
60
+ from .configuration_openpangu_dense import PanguEmbeddedConfig
61
+
62
+ logger = logging.get_logger(__name__)
63
+
64
+
65
+ class PanguEmbeddedRMSNorm(nn.Module):
66
+ def __init__(self, hidden_size, eps=1e-6):
67
+ """
68
+ PanguEmbeddedRMSNorm is equivalent to T5LayerNorm
69
+ """
70
+ super().__init__()
71
+ self.weight = nn.Parameter(torch.ones(hidden_size))
72
+ self.variance_epsilon = eps
73
+
74
+ def forward(self, hidden_states):
75
+ input_dtype = hidden_states.dtype
76
+ hidden_states = hidden_states.to(torch.float32)
77
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
78
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
79
+ return self.weight * hidden_states.to(input_dtype)
80
+
81
+ def extra_repr(self):
82
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
83
+
84
+
85
+ class PanguEmbeddedRotaryEmbedding(nn.Module):
86
+ def __init__(self, config: PanguEmbeddedConfig, device=None):
87
+ super().__init__()
88
+ # BC: "rope_type" was originally "type"
89
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
90
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
91
+ else:
92
+ self.rope_type = "default"
93
+ self.max_seq_len_cached = config.max_position_embeddings
94
+ self.original_max_seq_len = config.max_position_embeddings
95
+
96
+ self.config = config
97
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
98
+
99
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
100
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
101
+ self.original_inv_freq = self.inv_freq
102
+
103
+ @torch.no_grad()
104
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
105
+ def forward(self, x, position_ids):
106
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
107
+ position_ids_expanded = position_ids[:, None, :].float()
108
+
109
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
110
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
111
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
112
+ emb = torch.cat((freqs, freqs), dim=-1)
113
+ cos = emb.cos() * self.attention_scaling
114
+ sin = emb.sin() * self.attention_scaling
115
+
116
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
117
+
118
+
119
+ def rotate_half(x):
120
+ """Rotates half the hidden dims of the input."""
121
+ x1 = x[..., : x.shape[-1] // 2]
122
+ x2 = x[..., x.shape[-1] // 2 :]
123
+ return torch.cat((-x2, x1), dim=-1)
124
+
125
+
126
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
127
+ """Applies Rotary Position Embedding to the query and key tensors.
128
+
129
+ Args:
130
+ q (`torch.Tensor`): The query tensor.
131
+ k (`torch.Tensor`): The key tensor.
132
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
133
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
134
+ position_ids (`torch.Tensor`, *optional*):
135
+ Deprecated and unused.
136
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
137
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
138
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
139
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
140
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
141
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
142
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
143
+ Returns:
144
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
145
+ """
146
+ cos = cos.unsqueeze(unsqueeze_dim)
147
+ sin = sin.unsqueeze(unsqueeze_dim)
148
+ q_embed = (q * cos) + (rotate_half(q) * sin)
149
+ k_embed = (k * cos) + (rotate_half(k) * sin)
150
+ return q_embed, k_embed
151
+
152
+
153
+ class PanguEmbeddedMLP(nn.Module):
154
+ def __init__(self, config):
155
+ super().__init__()
156
+ self.config = config
157
+ self.hidden_size = config.hidden_size
158
+ self.intermediate_size = config.intermediate_size
159
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
160
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=False)
161
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=False)
162
+ self.act_fn = ACT2FN[config.hidden_act]
163
+
164
+ def forward(self, x):
165
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
166
+ return down_proj
167
+
168
+
169
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
170
+ """
171
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
172
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
173
+ """
174
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
175
+ if n_rep == 1:
176
+ return hidden_states
177
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
178
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
179
+
180
+
181
+ def eager_attention_forward(
182
+ module: nn.Module,
183
+ query: torch.Tensor,
184
+ key: torch.Tensor,
185
+ value: torch.Tensor,
186
+ attention_mask: Optional[torch.Tensor],
187
+ scaling: float,
188
+ dropout: float = 0.0,
189
+ **kwargs,
190
+ ):
191
+ key_states = repeat_kv(key, module.num_key_value_groups)
192
+ value_states = repeat_kv(value, module.num_key_value_groups)
193
+
194
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
195
+ if attention_mask is not None:
196
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
197
+ attn_weights = attn_weights + causal_mask
198
+
199
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
200
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
201
+ attn_output = torch.matmul(attn_weights, value_states)
202
+ attn_output = attn_output.transpose(1, 2).contiguous()
203
+
204
+ return attn_output, attn_weights
205
+
206
+
207
+ class PanguEmbeddedAttention(nn.Module):
208
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
209
+
210
+ def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):
211
+ super().__init__()
212
+ self.config = config
213
+ self.layer_idx = layer_idx
214
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
215
+ self.num_heads = config.num_attention_heads
216
+ self.num_key_value_heads = config.num_key_value_heads
217
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
218
+ self.scaling = self.head_dim**-0.5
219
+ self.attention_dropout = config.attention_dropout
220
+ self.is_causal = True
221
+
222
+ self.q_proj = nn.Linear(config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.bias)
223
+ self.k_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)
224
+ self.v_proj = nn.Linear(config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.bias)
225
+ self.o_proj = nn.Linear(config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.bias)
226
+
227
+ def forward(
228
+ self,
229
+ hidden_states: torch.Tensor,
230
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
231
+ attention_mask: Optional[torch.Tensor],
232
+ past_key_value: Optional[Cache] = None,
233
+ cache_position: Optional[torch.LongTensor] = None,
234
+ **kwargs: Unpack[FlashAttentionKwargs],
235
+ ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
236
+ input_shape = hidden_states.shape[:-1]
237
+ hidden_shape = (*input_shape, -1, self.head_dim)
238
+
239
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
240
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
241
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
242
+
243
+ cos, sin = position_embeddings
244
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
245
+
246
+ if past_key_value is not None:
247
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
248
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
249
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
250
+
251
+ attention_interface: Callable = eager_attention_forward
252
+ if self.config._attn_implementation != "eager":
253
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
254
+
255
+ if not self.training and NPU_ATTN_INFR:
256
+ q_len = input_shape[1]
257
+ if attention_mask is not None:
258
+ attention_mask = ~attention_mask.bool()
259
+
260
+ attn_output, _ = torch_npu.npu_fused_infer_attention_score(
261
+ query_states, key_states, value_states,
262
+ num_heads=self.num_heads, num_key_value_heads=self.num_key_value_heads,
263
+ input_layout="BNSD", atten_mask=attention_mask, scale=self.scaling)
264
+ attn_output = attn_output.transpose(1, 2)
265
+ attn_weights = None
266
+ else:
267
+ attn_output, attn_weights = attention_interface(
268
+ self,
269
+ query_states,
270
+ key_states,
271
+ value_states,
272
+ attention_mask,
273
+ dropout=0.0 if not self.training else self.attention_dropout,
274
+ scaling=self.scaling,
275
+ **kwargs,
276
+ )
277
+
278
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
279
+ attn_output = self.o_proj(attn_output)
280
+ return attn_output, attn_weights
281
+
282
+
283
+ class PanguEmbeddedDecoderLayer(GradientCheckpointingLayer):
284
+ def __init__(self, config: PanguEmbeddedConfig, layer_idx: int):
285
+ super().__init__()
286
+ self.hidden_size = config.hidden_size
287
+ self.self_attn = PanguEmbeddedAttention(config=config, layer_idx=layer_idx)
288
+ self.mlp = PanguEmbeddedMLP(config)
289
+ self.input_layernorm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
290
+ self.post_attention_layernorm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
291
+
292
+ def forward(
293
+ self,
294
+ hidden_states: torch.Tensor,
295
+ attention_mask: Optional[torch.Tensor] = None,
296
+ position_ids: Optional[torch.LongTensor] = None,
297
+ past_key_value: Optional[Cache] = None,
298
+ output_attentions: Optional[bool] = False,
299
+ use_cache: Optional[bool] = False,
300
+ cache_position: Optional[torch.LongTensor] = None,
301
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
302
+ **kwargs: Unpack[FlashAttentionKwargs],
303
+ ) -> tuple[torch.FloatTensor, Optional[tuple[torch.FloatTensor, torch.FloatTensor]]]:
304
+ residual = hidden_states
305
+ hidden_states = self.input_layernorm(hidden_states)
306
+
307
+ # Self Attention
308
+ hidden_states, self_attn_weights = self.self_attn(
309
+ hidden_states=hidden_states,
310
+ attention_mask=attention_mask,
311
+ position_ids=position_ids,
312
+ past_key_value=past_key_value,
313
+ output_attentions=output_attentions,
314
+ use_cache=use_cache,
315
+ cache_position=cache_position,
316
+ position_embeddings=position_embeddings,
317
+ **kwargs,
318
+ )
319
+ hidden_states = residual + hidden_states
320
+
321
+ # Fully Connected
322
+ residual = hidden_states
323
+ hidden_states = self.post_attention_layernorm(hidden_states)
324
+ hidden_states = self.mlp(hidden_states)
325
+ hidden_states = residual + hidden_states
326
+
327
+ outputs = (hidden_states,)
328
+ if output_attentions:
329
+ outputs += (self_attn_weights,)
330
+
331
+ return outputs
332
+
333
+
334
+ @auto_docstring
335
+ class PanguEmbeddedPreTrainedModel(PreTrainedModel):
336
+ config_class = PanguEmbeddedConfig
337
+ base_model_prefix = "model"
338
+ supports_gradient_checkpointing = True
339
+ _no_split_modules = ["PanguEmbeddedDecoderLayer"]
340
+ _skip_keys_device_placement = ["past_key_values"]
341
+ _supports_flash_attn_3 = True
342
+ _supports_flash_attn_2 = True
343
+ _supports_sdpa = True
344
+ _supports_flex_attn = True
345
+ _supports_cache_class = True
346
+ _supports_quantized_cache = True
347
+ _supports_static_cache = True
348
+ _supports_attention_backend = True
349
+
350
+ def _init_weights(self, module):
351
+ std = self.config.initializer_range
352
+ if isinstance(module, nn.Linear):
353
+ module.weight.data.normal_(mean=0.0, std=std)
354
+ if module.bias is not None:
355
+ module.bias.data.zero_()
356
+ elif isinstance(module, nn.Embedding):
357
+ module.weight.data.normal_(mean=0.0, std=std)
358
+ if module.padding_idx is not None:
359
+ module.weight.data[module.padding_idx].zero_()
360
+ elif isinstance(module, PanguEmbeddedRMSNorm):
361
+ module.weight.data.fill_(1.0)
362
+
363
+
364
+ @auto_docstring
365
+ class PanguEmbeddedModel(PanguEmbeddedPreTrainedModel):
366
+ def __init__(self, config: PanguEmbeddedConfig):
367
+ super().__init__(config)
368
+ self.padding_idx = config.pad_token_id
369
+ self.vocab_size = config.vocab_size
370
+
371
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
372
+ self.layers = nn.ModuleList(
373
+ [PanguEmbeddedDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
374
+ )
375
+ self.norm = PanguEmbeddedRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
376
+ self.rotary_emb = PanguEmbeddedRotaryEmbedding(config=config)
377
+ self.gradient_checkpointing = False
378
+
379
+ # Initialize weights and apply final processing
380
+ self.post_init()
381
+
382
+ def get_input_embeddings(self):
383
+ return self.embed_tokens
384
+
385
+ def set_input_embeddings(self, value):
386
+ self.embed_tokens = value
387
+
388
+ @can_return_tuple
389
+ @auto_docstring
390
+ def forward(
391
+ self,
392
+ input_ids: Optional[torch.LongTensor] = None,
393
+ attention_mask: Optional[torch.Tensor] = None,
394
+ position_ids: Optional[torch.LongTensor] = None,
395
+ past_key_values: Optional[Cache] = None,
396
+ inputs_embeds: Optional[torch.FloatTensor] = None,
397
+ use_cache: Optional[bool] = None,
398
+ output_attentions: Optional[bool] = None,
399
+ output_hidden_states: Optional[bool] = None,
400
+ cache_position: Optional[torch.LongTensor] = None,
401
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
402
+ ) -> BaseModelOutputWithPast:
403
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
404
+ output_hidden_states = (
405
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
406
+ )
407
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
408
+
409
+ if (input_ids is None) ^ (inputs_embeds is not None):
410
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
411
+
412
+ if self.gradient_checkpointing and self.training and use_cache:
413
+ logger.warning_once(
414
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
415
+ )
416
+ use_cache = False
417
+
418
+ # TODO (joao): remove this exception in v4.56 -- it exists for users that try to pass a legacy cache
419
+ if not isinstance(past_key_values, (type(None), Cache)):
420
+ raise ValueError("The `past_key_values` should be either a `Cache` object or `None`.")
421
+
422
+ if inputs_embeds is None:
423
+ inputs_embeds = self.embed_tokens(input_ids)
424
+
425
+ if use_cache and past_key_values is None:
426
+ past_key_values = DynamicCache()
427
+
428
+ if cache_position is None:
429
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
430
+ cache_position = torch.arange(
431
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
432
+ )
433
+
434
+ if position_ids is None:
435
+ position_ids = cache_position.unsqueeze(0)
436
+
437
+ hidden_states = inputs_embeds
438
+
439
+ # create position embeddings to be shared across the decoder layers
440
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
441
+
442
+ # decoder layers
443
+ all_hidden_states = () if output_hidden_states else None
444
+ all_self_attns = () if output_attentions else None
445
+
446
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
447
+ if output_hidden_states:
448
+ all_hidden_states += (hidden_states,)
449
+
450
+ layer_outputs = decoder_layer(
451
+ hidden_states,
452
+ attention_mask=attention_mask,
453
+ position_ids=position_ids,
454
+ past_key_value=past_key_values,
455
+ output_attentions=output_attentions,
456
+ use_cache=use_cache,
457
+ cache_position=cache_position,
458
+ position_embeddings=position_embeddings,
459
+ **flash_attn_kwargs,
460
+ )
461
+
462
+ hidden_states = layer_outputs[0]
463
+
464
+ if output_attentions:
465
+ all_self_attns += (layer_outputs[1],)
466
+
467
+ hidden_states = self.norm(hidden_states)
468
+
469
+ # add hidden states from the last decoder layer
470
+ if output_hidden_states:
471
+ all_hidden_states += (hidden_states,)
472
+
473
+ return BaseModelOutputWithPast(
474
+ last_hidden_state=hidden_states,
475
+ past_key_values=past_key_values if use_cache else None,
476
+ hidden_states=all_hidden_states,
477
+ attentions=all_self_attns,
478
+ )
479
+
480
+
481
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
482
+
483
+
484
+ @auto_docstring
485
+ class PanguEmbeddedForCausalLM(PanguEmbeddedPreTrainedModel):
486
+ _tied_weights_keys = ["lm_head.weight"]
487
+ _tp_plan = {"lm_head": "colwise_rep"}
488
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
489
+
490
+ def __init__(self, config):
491
+ super().__init__(config)
492
+ self.model = PanguEmbeddedModel(config)
493
+ self.vocab_size = config.vocab_size
494
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
495
+
496
+ # Initialize weights and apply final processing
497
+ self.post_init()
498
+
499
+ def get_input_embeddings(self):
500
+ return self.model.embed_tokens
501
+
502
+ def set_input_embeddings(self, value):
503
+ self.model.embed_tokens = value
504
+
505
+ def get_output_embeddings(self):
506
+ return self.lm_head
507
+
508
+ def set_output_embeddings(self, new_embeddings):
509
+ self.lm_head = new_embeddings
510
+
511
+ def set_decoder(self, decoder):
512
+ self.model = decoder
513
+
514
+ def get_decoder(self):
515
+ return self.model
516
+
517
+ @can_return_tuple
518
+ @auto_docstring
519
+ def forward(
520
+ self,
521
+ input_ids: Optional[torch.LongTensor] = None,
522
+ attention_mask: Optional[torch.Tensor] = None,
523
+ position_ids: Optional[torch.LongTensor] = None,
524
+ past_key_values: Optional[Cache] = None,
525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
526
+ labels: Optional[torch.LongTensor] = None,
527
+ use_cache: Optional[bool] = None,
528
+ output_attentions: Optional[bool] = None,
529
+ output_hidden_states: Optional[bool] = None,
530
+ cache_position: Optional[torch.LongTensor] = None,
531
+ logits_to_keep: Union[int, torch.Tensor] = 0,
532
+ **kwargs: Unpack[KwargsForCausalLM],
533
+ ) -> CausalLMOutputWithPast:
534
+
535
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
536
+ output_hidden_states = (
537
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
538
+ )
539
+
540
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
541
+ outputs: BaseModelOutputWithPast = self.model(
542
+ input_ids=input_ids,
543
+ attention_mask=attention_mask,
544
+ position_ids=position_ids,
545
+ past_key_values=past_key_values,
546
+ inputs_embeds=inputs_embeds,
547
+ use_cache=use_cache,
548
+ output_attentions=output_attentions,
549
+ output_hidden_states=output_hidden_states,
550
+ cache_position=cache_position,
551
+ **kwargs,
552
+ )
553
+
554
+ hidden_states = outputs.last_hidden_state
555
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
556
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
557
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
558
+
559
+ loss = None
560
+ if labels is not None:
561
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
562
+
563
+ return CausalLMOutputWithPast(
564
+ loss=loss,
565
+ logits=logits,
566
+ past_key_values=outputs.past_key_values,
567
+ hidden_states=outputs.hidden_states,
568
+ attentions=outputs.attentions,
569
+ )
570
+
571
+
572
+ __all__ = [
573
+ "PanguEmbeddedForCausalLM",
574
+ "PanguEmbeddedModel",
575
+ "PanguEmbeddedPreTrainedModel",
576
+ ]