Delete modeling_ernie4_5.py
Browse files- modeling_ernie4_5.py +0 -1068
modeling_ernie4_5.py
DELETED
@@ -1,1068 +0,0 @@
|
|
1 |
-
# Copyright (c) 2025 Baidu, Inc. All Rights Reserved.
|
2 |
-
#
|
3 |
-
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
-
# you may not use this file except in compliance with the License.
|
5 |
-
# You may obtain a copy of the License at
|
6 |
-
#
|
7 |
-
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
-
#
|
9 |
-
# Unless required by applicable law or agreed to in writing, software
|
10 |
-
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
-
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
-
# See the License for the specific language governing permissions and
|
13 |
-
# limitations under the License.
|
14 |
-
|
15 |
-
from typing import Optional, Tuple, Union
|
16 |
-
|
17 |
-
import torch
|
18 |
-
import torch.nn as nn
|
19 |
-
import torch.nn.functional as F
|
20 |
-
from torch.nn.attention import SDPBackend, sdpa_kernel
|
21 |
-
|
22 |
-
from transformers.activations import ACT2FN
|
23 |
-
from transformers.modeling_utils import PreTrainedModel
|
24 |
-
from transformers.generation import GenerationMixin
|
25 |
-
from transformers.modeling_outputs import (
|
26 |
-
BaseModelOutputWithPast,
|
27 |
-
CausalLMOutputWithPast,
|
28 |
-
)
|
29 |
-
from transformers.utils import logging
|
30 |
-
|
31 |
-
from .configuration_ernie4_5 import Ernie4_5_Config
|
32 |
-
|
33 |
-
|
34 |
-
logger = logging.get_logger(__name__)
|
35 |
-
|
36 |
-
|
37 |
-
class Ernie4_5_RMSNorm(nn.Module):
|
38 |
-
"""
|
39 |
-
Root Mean Square Layer Normalization (Ernie4_5_RMSNorm) implementation.
|
40 |
-
|
41 |
-
Ernie4_5_RMSNorm is a simplified version of LayerNorm that focuses on the root mean square of inputs,
|
42 |
-
omitting the mean-centering operation. This provides computational efficiency while maintaining
|
43 |
-
good performance.
|
44 |
-
"""
|
45 |
-
|
46 |
-
def __init__(self, config):
|
47 |
-
"""
|
48 |
-
Initialize Ernie4_5_RMSNorm layer.
|
49 |
-
|
50 |
-
Args:
|
51 |
-
config: Model configuration.
|
52 |
-
"""
|
53 |
-
super().__init__()
|
54 |
-
self.hidden_size = config.hidden_size
|
55 |
-
self.weight = nn.Parameter(
|
56 |
-
torch.ones(self.hidden_size, dtype=torch.get_default_dtype())
|
57 |
-
)
|
58 |
-
self.variance_epsilon = config.rms_norm_eps
|
59 |
-
|
60 |
-
def forward(self, hidden_states):
|
61 |
-
"""
|
62 |
-
Apply RMS normalization to input hidden states.
|
63 |
-
|
64 |
-
Args:
|
65 |
-
hidden_states (Tensor): Input tensor of shape [batch_size, seq_len, hidden_size]
|
66 |
-
|
67 |
-
Returns:
|
68 |
-
Tensor: Normalized output tensor of same shape as input
|
69 |
-
|
70 |
-
Note:
|
71 |
-
- computes Ernie4_5_RMSNorm manually:
|
72 |
-
1. Compute variance of features
|
73 |
-
2. Apply reciprocal square root normalization
|
74 |
-
3. Scale by learned weight parameter
|
75 |
-
- Maintains original dtype for numerical stability during computation
|
76 |
-
"""
|
77 |
-
variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
|
78 |
-
hidden_states = torch.rsqrt(variance + self.variance_epsilon) * hidden_states
|
79 |
-
return hidden_states.to(self.weight.dtype) * self.weight
|
80 |
-
|
81 |
-
|
82 |
-
class Ernie4_5_RopeEmbedding(nn.Module):
|
83 |
-
"""
|
84 |
-
Rotary Position Embedding (RoPE) implementation for transformer models.
|
85 |
-
|
86 |
-
RoPE encodes absolute positional information with rotation matrices and
|
87 |
-
naturally incorporates relative position information in self-attention.
|
88 |
-
|
89 |
-
Args:
|
90 |
-
head_dim (int): Dimension size of each attention head
|
91 |
-
compression_ratio (float, optional): Sequence length compression ratio. Defaults to 1.0.
|
92 |
-
base (int, optional): Base value for frequency calculation. Defaults to 10000.
|
93 |
-
|
94 |
-
Attributes:
|
95 |
-
head_dim (int): Dimension size of each attention head
|
96 |
-
compression_ratio (float): Sequence length compression factor
|
97 |
-
base (int): Base value for frequency calculation
|
98 |
-
"""
|
99 |
-
|
100 |
-
def __init__(self, head_dim, compression_ratio=1.0, base=10000):
|
101 |
-
"""
|
102 |
-
Initialize RoPE embedding layer.
|
103 |
-
|
104 |
-
Args:
|
105 |
-
head_dim: Dimension of each attention head
|
106 |
-
compression_ratio: Scaling factor for position indices
|
107 |
-
base: Base value for frequency calculation
|
108 |
-
"""
|
109 |
-
super().__init__()
|
110 |
-
self.head_dim = head_dim
|
111 |
-
self.compression_ratio = compression_ratio
|
112 |
-
self.base = base
|
113 |
-
|
114 |
-
def forward(self, seq_length, position_ids=None):
|
115 |
-
"""
|
116 |
-
Compute rotary position embeddings for given sequence length.
|
117 |
-
|
118 |
-
Args:
|
119 |
-
seq_length (int): Maximum sequence length
|
120 |
-
position_ids (Tensor, optional): Custom position indices. Defaults to None.
|
121 |
-
|
122 |
-
Returns:
|
123 |
-
Tensor: Rotary position embeddings of shape [1, 1, seq_length, head_dim]
|
124 |
-
"""
|
125 |
-
indices = torch.arange(0, self.head_dim, 2, dtype=torch.float32)
|
126 |
-
indices = 1 / self.base ** (indices / self.head_dim)
|
127 |
-
if position_ids is None:
|
128 |
-
position_ids = torch.arange(
|
129 |
-
0, seq_length, 1, dtype=torch.float32
|
130 |
-
).unsqueeze(1)
|
131 |
-
position_ids = position_ids / self.compression_ratio
|
132 |
-
sinusoid_inp = position_ids * indices.unsqueeze(0)
|
133 |
-
else:
|
134 |
-
position_ids = position_ids / self.compression_ratio
|
135 |
-
seq_length = position_ids.shape[-1]
|
136 |
-
sinusoid_inp = position_ids.unsqueeze(-1).to(
|
137 |
-
torch.float32
|
138 |
-
) * indices.unsqueeze(0)
|
139 |
-
pos_emb = torch.cat([torch.sin(sinusoid_inp), torch.cos(sinusoid_inp)], dim=-1)
|
140 |
-
pos_emb = pos_emb.view(-1, 1, seq_length, self.head_dim)
|
141 |
-
pos_emb = pos_emb.detach()
|
142 |
-
return pos_emb
|
143 |
-
|
144 |
-
def apply_rotary(self, rp, q, k):
|
145 |
-
"""
|
146 |
-
Apply rotary position embeddings to queries and keys.
|
147 |
-
|
148 |
-
Args:
|
149 |
-
rp (Tensor): Rotary position embeddings
|
150 |
-
q (Tensor): Query tensor [batch, heads, seq_len, dim]
|
151 |
-
k (Tensor): Key tensor [batch, heads, seq_len, dim]
|
152 |
-
|
153 |
-
Returns:
|
154 |
-
Tuple[Tensor, Tensor]: Rotated queries and keys
|
155 |
-
"""
|
156 |
-
sin, cos = torch.chunk(rp.to(q.device), 2, dim=-1)
|
157 |
-
# sin [θ0,θ1,θ2......θd/2-1] -> sin_pos [θ0,θ0,θ1,θ1,θ2,θ2......θd/2-1,θd/2-1]
|
158 |
-
sin_pos = torch.stack([sin, sin], dim=-1).reshape(rp.shape)
|
159 |
-
# cos [θ0,θ1,θ2......θd/2-1] -> cos_pos [θ0,θ0,θ1,θ1,θ2,θ2......θd/2-1,θd/2-1]
|
160 |
-
cos_pos = torch.stack([cos, cos], dim=-1).reshape(rp.shape)
|
161 |
-
# rotate_half_query_layer [-q1,q0,-q3,q2......,-qd-1,qd-2]
|
162 |
-
rotate_half_q = torch.stack(
|
163 |
-
[-q[:, :, :, 1::2], q[:, :, :, 0::2]], dim=-1
|
164 |
-
).reshape(q.shape)
|
165 |
-
query = (q.to(torch.float32) * cos_pos) + (
|
166 |
-
rotate_half_q.to(torch.float32) * sin_pos
|
167 |
-
)
|
168 |
-
# rotate_half_key_layer [-k1,k0,-k3,k2......,-kd-1,kd-2]
|
169 |
-
rotate_half_k = torch.stack(
|
170 |
-
[-k[:, :, :, 1::2], k[:, :, :, 0::2]], dim=-1
|
171 |
-
).reshape(k.shape)
|
172 |
-
key = (k.to(torch.float32) * cos_pos) + (
|
173 |
-
rotate_half_k.to(torch.float32) * sin_pos
|
174 |
-
)
|
175 |
-
return query, key
|
176 |
-
|
177 |
-
|
178 |
-
class Ernie4_5_FusedDropoutImpl(nn.Module):
|
179 |
-
"""
|
180 |
-
Fused dropout implementation with residual connection support.
|
181 |
-
|
182 |
-
This layer combines dropout and residual addition in a single operation for better performance,
|
183 |
-
particularly on GPU devices. The dropout is conditionally applied based on the probability.
|
184 |
-
|
185 |
-
Args:
|
186 |
-
prob (float): Dropout probability (between 0 and 1)
|
187 |
-
|
188 |
-
Attributes:
|
189 |
-
prob (float): Stores the dropout probability
|
190 |
-
dropout (nn.Dropout): The actual dropout layer instance
|
191 |
-
"""
|
192 |
-
|
193 |
-
def __init__(self, prob):
|
194 |
-
"""
|
195 |
-
Initialize the fused dropout layer.
|
196 |
-
|
197 |
-
Args:
|
198 |
-
prob (float): Dropout probability (0 means no dropout)
|
199 |
-
"""
|
200 |
-
super().__init__()
|
201 |
-
self.prob = prob
|
202 |
-
self.dropout = nn.Dropout(p=prob)
|
203 |
-
|
204 |
-
def forward(self, x, y):
|
205 |
-
"""
|
206 |
-
Forward pass of the fused dropout layer.
|
207 |
-
|
208 |
-
Args:
|
209 |
-
x (Tensor): Input tensor to potentially apply dropout
|
210 |
-
y (Tensor): Residual tensor to add to the (possibly dropped out) x
|
211 |
-
|
212 |
-
Returns:
|
213 |
-
Tensor: Result of x (with optional dropout) + y
|
214 |
-
"""
|
215 |
-
if self.prob > 0:
|
216 |
-
x = self.dropout(x)
|
217 |
-
output = x + y
|
218 |
-
|
219 |
-
return output
|
220 |
-
|
221 |
-
|
222 |
-
class Ernie4_5_MLP(nn.Module):
|
223 |
-
"""
|
224 |
-
Ernie4_5_MLP - Gated Multi-Layer Perceptron module used in Ernie model.
|
225 |
-
"""
|
226 |
-
|
227 |
-
def __init__(self, config, layer_idx=0):
|
228 |
-
"""
|
229 |
-
Initialize the MLP module with configuration options.
|
230 |
-
|
231 |
-
Args:
|
232 |
-
config: Model configurations.
|
233 |
-
layer_idx (int): Index of current layer (default: 0)
|
234 |
-
"""
|
235 |
-
super().__init__()
|
236 |
-
self.config = config
|
237 |
-
self.layer_idx = layer_idx
|
238 |
-
self.hidden_size = config.hidden_size
|
239 |
-
self.intermediate_size = config.intermediate_size
|
240 |
-
|
241 |
-
self.gate_proj = nn.Linear(
|
242 |
-
self.hidden_size, self.intermediate_size, bias=config.use_bias
|
243 |
-
)
|
244 |
-
self.up_proj = nn.Linear(
|
245 |
-
self.hidden_size, self.intermediate_size, bias=config.use_bias
|
246 |
-
)
|
247 |
-
self.down_proj = nn.Linear(
|
248 |
-
self.intermediate_size, self.hidden_size, bias=config.use_bias
|
249 |
-
)
|
250 |
-
self.act_fn = ACT2FN[config.hidden_act]
|
251 |
-
|
252 |
-
def forward(self, x):
|
253 |
-
"""
|
254 |
-
Args:
|
255 |
-
x (Tensor): shape [batch_size, seq_len, hidden_size]
|
256 |
-
|
257 |
-
Returns:
|
258 |
-
Tensor: shape [batch_size, seq_len, hidden_size]
|
259 |
-
"""
|
260 |
-
down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
|
261 |
-
return down_proj
|
262 |
-
|
263 |
-
|
264 |
-
class Ernie4_5_Attention(nn.Module):
|
265 |
-
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
266 |
-
|
267 |
-
def __init__(self, config, layer_idx=0):
|
268 |
-
"""Initialize the attention layer.
|
269 |
-
|
270 |
-
Args:
|
271 |
-
config: Model configuration.
|
272 |
-
layer_idx (int, optional): Index in transformer stack. Defaults to 0.
|
273 |
-
"""
|
274 |
-
super().__init__()
|
275 |
-
self.layer_idx = layer_idx
|
276 |
-
self.hidden_size = config.hidden_size
|
277 |
-
self.num_heads = config.num_attention_heads
|
278 |
-
self.num_key_value_heads = config.num_key_value_heads
|
279 |
-
|
280 |
-
if config.head_dim is None:
|
281 |
-
self.head_dim = self.hidden_size // self.num_heads
|
282 |
-
else:
|
283 |
-
self.head_dim = config.head_dim
|
284 |
-
|
285 |
-
self.is_gqa = (
|
286 |
-
self.num_key_value_heads is not None
|
287 |
-
and self.num_key_value_heads != self.num_heads
|
288 |
-
)
|
289 |
-
|
290 |
-
if self.is_gqa:
|
291 |
-
logger.info(
|
292 |
-
f"use GQA - num_heads: {self.num_heads}- num_key_value_heads: {self.num_key_value_heads}"
|
293 |
-
)
|
294 |
-
assert (
|
295 |
-
self.num_heads % self.num_key_value_heads == 0
|
296 |
-
), f"num_heads: {self.num_heads}, num_key_value_heads: {self.num_key_value_heads}"
|
297 |
-
kv_hidden_size = self.head_dim * self.num_key_value_heads
|
298 |
-
q_hidden_size = self.head_dim * self.num_heads
|
299 |
-
else:
|
300 |
-
q_hidden_size = kv_hidden_size = self.head_dim * self.num_heads
|
301 |
-
|
302 |
-
self.q_proj = nn.Linear(self.hidden_size, q_hidden_size, bias=config.use_bias)
|
303 |
-
self.k_proj = nn.Linear(self.hidden_size, kv_hidden_size, bias=config.use_bias)
|
304 |
-
self.v_proj = nn.Linear(self.hidden_size, kv_hidden_size, bias=config.use_bias)
|
305 |
-
self.o_proj = nn.Linear(q_hidden_size, self.hidden_size, bias=config.use_bias)
|
306 |
-
|
307 |
-
self.rotary_emb = Ernie4_5_RopeEmbedding(
|
308 |
-
self.head_dim,
|
309 |
-
compression_ratio=config.compression_ratio,
|
310 |
-
base=config.rope_theta,
|
311 |
-
)
|
312 |
-
self.config = config
|
313 |
-
|
314 |
-
self.set_attn_func()
|
315 |
-
|
316 |
-
def set_attn_func(self):
|
317 |
-
"""Configure attention function based on settings.
|
318 |
-
|
319 |
-
Selects between flash/core attention.
|
320 |
-
"""
|
321 |
-
config = self.config
|
322 |
-
if config.use_flash_attention:
|
323 |
-
self.attn_func = self._flash_attention_wrapper
|
324 |
-
else:
|
325 |
-
self.attn_func = self.core_attn
|
326 |
-
|
327 |
-
def forward(
|
328 |
-
self,
|
329 |
-
hidden_states,
|
330 |
-
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
331 |
-
attention_mask: Optional[torch.Tensor] = None,
|
332 |
-
attn_mask_start_row_indices: Optional[torch.Tensor] = None,
|
333 |
-
position_ids: Optional[Tuple[torch.Tensor]] = None,
|
334 |
-
output_attentions: bool = False,
|
335 |
-
use_cache: bool = False,
|
336 |
-
token_type_ids: Optional[Tuple[torch.Tensor]] = None,
|
337 |
-
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
338 |
-
"""Compute attention outputs.
|
339 |
-
|
340 |
-
Args:
|
341 |
-
hidden_states (torch.Tensor): Input tensor [bsz, seq_len, hidden_size]
|
342 |
-
past_key_value (Optional[Tuple[torch.Tensor, torch.Tensor]]): Cached key/value states
|
343 |
-
attention_mask (Optional[torch.Tensor]): Attention mask tensor
|
344 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Variable length attention indices
|
345 |
-
position_ids (Optional[torch.Tensor]): Position indices for RoPE
|
346 |
-
output_attentions (bool): Return attention weights if True
|
347 |
-
use_cache (bool): Cache key/value states if True
|
348 |
-
|
349 |
-
Returns:
|
350 |
-
Tuple containing:
|
351 |
-
- attention_output: [bsz, seq_len, hidden_size]
|
352 |
-
- attention_weights: Optional attention probabilities
|
353 |
-
- updated_key_value_cache: Optional updated cache
|
354 |
-
"""
|
355 |
-
if token_type_ids is not None:
|
356 |
-
token_type_ids = token_type_ids[:, :-1]
|
357 |
-
|
358 |
-
bsz, q_len, _ = hidden_states.shape
|
359 |
-
|
360 |
-
query_states = self.q_proj(hidden_states).reshape(
|
361 |
-
[bsz, q_len, -1, self.head_dim]
|
362 |
-
)
|
363 |
-
key_states = self.k_proj(hidden_states).reshape([bsz, q_len, -1, self.head_dim])
|
364 |
-
value_states = self.v_proj(hidden_states).reshape(
|
365 |
-
[bsz, q_len, -1, self.head_dim]
|
366 |
-
)
|
367 |
-
|
368 |
-
attn_output, attn_weights, past_key_value = self.rope_attn(
|
369 |
-
query_states=query_states,
|
370 |
-
key_states=key_states,
|
371 |
-
value_states=value_states,
|
372 |
-
attention_mask=attention_mask,
|
373 |
-
position_ids=position_ids,
|
374 |
-
output_attentions=output_attentions,
|
375 |
-
past_key_value=past_key_value,
|
376 |
-
use_cache=use_cache,
|
377 |
-
attn_mask_start_row_indices=attn_mask_start_row_indices,
|
378 |
-
)
|
379 |
-
|
380 |
-
attn_output = self.o_proj(attn_output)
|
381 |
-
|
382 |
-
if not output_attentions:
|
383 |
-
attn_weights = None
|
384 |
-
|
385 |
-
return attn_output, attn_weights, past_key_value
|
386 |
-
|
387 |
-
def repeat_kv(self, hidden_states, n_rep):
|
388 |
-
"""
|
389 |
-
This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
|
390 |
-
num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
|
391 |
-
"""
|
392 |
-
batch, num_key_value_heads, slen, head_dim = hidden_states.shape
|
393 |
-
if n_rep == 1:
|
394 |
-
return hidden_states
|
395 |
-
hidden_states = hidden_states[:, :, None, :, :].expand(
|
396 |
-
batch, num_key_value_heads, n_rep, slen, head_dim
|
397 |
-
)
|
398 |
-
return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
|
399 |
-
|
400 |
-
def _flash_attention_wrapper(
|
401 |
-
self,
|
402 |
-
q,
|
403 |
-
k,
|
404 |
-
v,
|
405 |
-
attention_mask=None,
|
406 |
-
attn_mask_start_row_indices=None,
|
407 |
-
seq_length=None,
|
408 |
-
):
|
409 |
-
"""Wrapper for flash attention implementation.
|
410 |
-
|
411 |
-
Args:
|
412 |
-
q (torch.Tensor): Query tensor
|
413 |
-
k (torch.Tensor): Key tensor
|
414 |
-
v (torch.Tensor): Value tensor
|
415 |
-
attention_mask (Optional[torch.Tensor]): Attention mask
|
416 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Variable length indices
|
417 |
-
seq_length (Optional[int]): Sequence length
|
418 |
-
|
419 |
-
Returns:
|
420 |
-
Tuple[torch.Tensor, torch.Tensor]: Attention output and weights
|
421 |
-
"""
|
422 |
-
q = q.transpose(1, 2)
|
423 |
-
k = k.transpose(1, 2)
|
424 |
-
v = v.transpose(1, 2)
|
425 |
-
|
426 |
-
with sdpa_kernel(SDPBackend.FLASH_ATTENTION):
|
427 |
-
out = F.scaled_dot_product_attention(
|
428 |
-
q,
|
429 |
-
k,
|
430 |
-
v,
|
431 |
-
attn_mask=None,
|
432 |
-
dropout_p=self.config.attention_probs_dropout_prob,
|
433 |
-
is_causal=q.shape[2] != 1,
|
434 |
-
scale=1
|
435 |
-
/ (getattr(self.config, "scale_qk_coeff", 1.0) * self.head_dim**0.5),
|
436 |
-
enable_gqa=self.is_gqa,
|
437 |
-
)
|
438 |
-
out = out.transpose(1, 2)
|
439 |
-
out = out.contiguous().view(out.size(0), out.size(1), -1)
|
440 |
-
|
441 |
-
return out, None
|
442 |
-
|
443 |
-
def core_attn(
|
444 |
-
self,
|
445 |
-
q,
|
446 |
-
k,
|
447 |
-
v,
|
448 |
-
attention_mask=None,
|
449 |
-
attn_mask_start_row_indices=None,
|
450 |
-
seq_length=None,
|
451 |
-
):
|
452 |
-
"""Standard self-attention implementation.
|
453 |
-
|
454 |
-
Args:
|
455 |
-
q (torch.Tensor): Query tensor
|
456 |
-
k (torch.Tensor): Key tensor
|
457 |
-
v (torch.Tensor): Value tensor
|
458 |
-
attention_mask (Optional[torch.Tensor]): Attention mask
|
459 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Variable length indices
|
460 |
-
seq_length (Optional[int]): Sequence length
|
461 |
-
|
462 |
-
Returns:
|
463 |
-
Tuple[torch.Tensor, torch.Tensor]: Attention output and weights
|
464 |
-
"""
|
465 |
-
origin_dtype = q.dtype
|
466 |
-
|
467 |
-
q = q.permute(0, 2, 1, 3)
|
468 |
-
k = k.permute(0, 2, 1, 3)
|
469 |
-
v = v.permute(0, 2, 1, 3)
|
470 |
-
|
471 |
-
scale_qk_coeff = (
|
472 |
-
getattr(self.config, "scale_qk_coeff", 1.0) * self.head_dim**0.5
|
473 |
-
)
|
474 |
-
|
475 |
-
q = q / scale_qk_coeff
|
476 |
-
|
477 |
-
# Handle GQA case - repeat k and v heads to match q heads
|
478 |
-
if self.is_gqa:
|
479 |
-
# [batch, num_key_value_heads, seq_len, head_dim] -> [batch, num_heads, seq_len, head_dim]
|
480 |
-
repeat_factor = self.num_heads // self.num_key_value_heads
|
481 |
-
k = self.repeat_kv(k, repeat_factor)
|
482 |
-
v = self.repeat_kv(v, repeat_factor)
|
483 |
-
|
484 |
-
attn_scores = torch.matmul(q, k.transpose(-2, -1))
|
485 |
-
|
486 |
-
if getattr(self.config, "scale_qk_coeff", 1.0) != 1.0:
|
487 |
-
attn_scores = attn_scores * getattr(self.config, "scale_qk_coeff", 1.0)
|
488 |
-
|
489 |
-
# Causal mask
|
490 |
-
seq_len = attn_scores.size(-1)
|
491 |
-
mask = torch.triu(
|
492 |
-
torch.ones((seq_len, seq_len), dtype=torch.bool, device=attn_scores.device),
|
493 |
-
diagonal=1,
|
494 |
-
)
|
495 |
-
attn_scores = attn_scores.masked_fill(mask, float("-inf"))
|
496 |
-
attn_weights = F.softmax(attn_scores, dim=-1)
|
497 |
-
|
498 |
-
attn_weights = attn_weights.to(origin_dtype)
|
499 |
-
|
500 |
-
# attention_probs_dropout_prob default 0.0
|
501 |
-
if getattr(self.config, "attention_probs_dropout_prob", 0.0) > 0:
|
502 |
-
attn_weights = F.dropout(
|
503 |
-
attn_weights,
|
504 |
-
p=self.config.attention_probs_dropout_prob,
|
505 |
-
training=self.training,
|
506 |
-
)
|
507 |
-
|
508 |
-
# [batch, num_heads, q_len, k_len] @ [batch, num_heads, k_len, head_dim] -> [batch, num_heads, q_len, head_dim]
|
509 |
-
out = torch.matmul(attn_weights, v)
|
510 |
-
|
511 |
-
# [batch, num_heads, seq_len, head_dim] -> [batch, seq_len, num_heads, head_dim]
|
512 |
-
out = out.permute(0, 2, 1, 3)
|
513 |
-
# [batch, seq_len, hidden_size]
|
514 |
-
out = out.contiguous().view(out.size(0), out.size(1), -1)
|
515 |
-
|
516 |
-
return out, attn_weights
|
517 |
-
|
518 |
-
def rope_attn(
|
519 |
-
self,
|
520 |
-
query_states,
|
521 |
-
key_states,
|
522 |
-
value_states,
|
523 |
-
attention_mask,
|
524 |
-
position_ids,
|
525 |
-
output_attentions=False,
|
526 |
-
past_key_value=None,
|
527 |
-
use_cache=False,
|
528 |
-
attn_mask_start_row_indices=None,
|
529 |
-
):
|
530 |
-
"""Attention computation with rotary embeddings.
|
531 |
-
|
532 |
-
Args:
|
533 |
-
query_states (torch.Tensor): Query states
|
534 |
-
key_states (torch.Tensor): Key states
|
535 |
-
value_states (torch.Tensor): Value states
|
536 |
-
attention_mask (Optional[torch.Tensor]): Attention mask
|
537 |
-
position_ids (Optional[torch.Tensor]): Position indices
|
538 |
-
output_attentions (bool): Return attention weights
|
539 |
-
past_key_value (Optional[Tuple[torch.Tensor, torch.Tensor]]): Cached states
|
540 |
-
use_cache (bool): Cache new states
|
541 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Variable length indices
|
542 |
-
|
543 |
-
Returns:
|
544 |
-
Tuple containing:
|
545 |
-
- attention_output: Result tensor
|
546 |
-
- attention_weights: Optional weights
|
547 |
-
- updated_key_value_cache: Optional cache
|
548 |
-
"""
|
549 |
-
|
550 |
-
query_states_dtype = query_states.dtype
|
551 |
-
|
552 |
-
kv_seq_len = key_states.shape[-3]
|
553 |
-
offset = 0
|
554 |
-
if past_key_value is not None:
|
555 |
-
offset = past_key_value[0].shape[-3]
|
556 |
-
kv_seq_len += offset
|
557 |
-
|
558 |
-
cos_sin = self.rotary_emb(kv_seq_len).permute(
|
559 |
-
[0, 2, 1, 3]
|
560 |
-
) # [b,h,s,d]->[b,s,h,d]
|
561 |
-
if offset > 0:
|
562 |
-
cos_sin = cos_sin[:, offset:]
|
563 |
-
query_states, key_states = self.rotary_emb.apply_rotary(
|
564 |
-
cos_sin, query_states, key_states
|
565 |
-
)
|
566 |
-
|
567 |
-
query_states = query_states.to(query_states_dtype)
|
568 |
-
key_states = key_states.to(query_states_dtype)
|
569 |
-
if past_key_value is not None:
|
570 |
-
# reuse k, v, self_attention
|
571 |
-
key_states = torch.cat([past_key_value[0], key_states], dim=1)
|
572 |
-
value_states = torch.cat([past_key_value[1], value_states], dim=1)
|
573 |
-
|
574 |
-
# shape: [2, b, s, kvh, d]
|
575 |
-
past_key_value = [key_states, value_states] if use_cache else None
|
576 |
-
seq_length = query_states.shape[1]
|
577 |
-
attn_output, attn_weights = self.attn_func(
|
578 |
-
query_states,
|
579 |
-
key_states,
|
580 |
-
value_states,
|
581 |
-
attention_mask,
|
582 |
-
attn_mask_start_row_indices,
|
583 |
-
seq_length,
|
584 |
-
)
|
585 |
-
return attn_output, attn_weights, past_key_value
|
586 |
-
|
587 |
-
|
588 |
-
class Ernie4_5_DecoderLayer(nn.Module):
|
589 |
-
"""
|
590 |
-
A single transformer decoder layer in ERNIE model.
|
591 |
-
"""
|
592 |
-
|
593 |
-
def __init__(self, config, layer_idx):
|
594 |
-
"""Initialize the decoder layer.
|
595 |
-
|
596 |
-
Args:
|
597 |
-
config: Model configuration.
|
598 |
-
layer_idx (int): Index of this layer in the transformer stack
|
599 |
-
"""
|
600 |
-
super().__init__()
|
601 |
-
self.hidden_size = config.hidden_size
|
602 |
-
self.layer_idx = layer_idx
|
603 |
-
self.config = config
|
604 |
-
|
605 |
-
self.self_attn = Ernie4_5_Attention(config, layer_idx)
|
606 |
-
self.mlp = Ernie4_5_MLP(config)
|
607 |
-
|
608 |
-
self.input_layernorm = Ernie4_5_RMSNorm(config)
|
609 |
-
self.post_attention_layernorm = Ernie4_5_RMSNorm(config)
|
610 |
-
|
611 |
-
self.residual_add1 = Ernie4_5_FusedDropoutImpl(config.hidden_dropout_prob)
|
612 |
-
self.residual_add2 = Ernie4_5_FusedDropoutImpl(config.hidden_dropout_prob)
|
613 |
-
|
614 |
-
def forward(
|
615 |
-
self,
|
616 |
-
hidden_states: torch.Tensor,
|
617 |
-
attention_mask: Optional[torch.Tensor] = None,
|
618 |
-
attn_mask_start_row_indices: Optional[torch.Tensor] = None,
|
619 |
-
position_ids: Optional[torch.Tensor] = None,
|
620 |
-
token_type_ids: Optional[torch.Tensor] = None,
|
621 |
-
output_attentions: Optional[bool] = False,
|
622 |
-
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
623 |
-
use_cache: Optional[bool] = False,
|
624 |
-
) -> Tuple[torch.Tensor, Optional[Tuple[torch.Tensor, torch.Tensor]]]:
|
625 |
-
"""Forward pass through the decoder layer.
|
626 |
-
|
627 |
-
Args:
|
628 |
-
hidden_states (torch.Tensor): Input tensor [batch_size, seq_len, hidden_size]
|
629 |
-
attention_mask (Optional[torch.Tensor]): Attention mask tensor
|
630 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Indices for variable length attention
|
631 |
-
position_ids (Optional[torch.Tensor]): Position indices for rotary embeddings
|
632 |
-
output_attentions (Optional[bool]): Whether to return attention weights
|
633 |
-
past_key_value (Optional[Tuple[torch.Tensor]]): Cached key/value states
|
634 |
-
use_cache (Optional[bool]): Whether to cache key/value states
|
635 |
-
|
636 |
-
Returns:
|
637 |
-
Union: Various output combinations depending on arguments:
|
638 |
-
- Base case: Hidden states tensor
|
639 |
-
- With attention: Tuple of (hidden_states, attention_weights)
|
640 |
-
- With cache: Tuple of (hidden_states, cached_key_value)
|
641 |
-
"""
|
642 |
-
residual = hidden_states
|
643 |
-
|
644 |
-
hidden_states = self.input_layernorm(hidden_states)
|
645 |
-
|
646 |
-
# Self Attention
|
647 |
-
(hidden_states, self_attn_weights, present_key_value) = self.self_attn(
|
648 |
-
hidden_states=hidden_states,
|
649 |
-
past_key_value=past_key_value,
|
650 |
-
attention_mask=attention_mask,
|
651 |
-
attn_mask_start_row_indices=attn_mask_start_row_indices,
|
652 |
-
position_ids=position_ids,
|
653 |
-
output_attentions=output_attentions,
|
654 |
-
use_cache=use_cache,
|
655 |
-
token_type_ids=token_type_ids,
|
656 |
-
)
|
657 |
-
hidden_states = self.residual_add1(hidden_states, residual)
|
658 |
-
|
659 |
-
# Fully Connected
|
660 |
-
residual = hidden_states
|
661 |
-
hidden_states = self.post_attention_layernorm(hidden_states)
|
662 |
-
hidden_states = self.mlp(hidden_states)
|
663 |
-
|
664 |
-
hidden_states = self.residual_add2(hidden_states, residual)
|
665 |
-
outputs = (hidden_states,)
|
666 |
-
|
667 |
-
if output_attentions:
|
668 |
-
outputs += (self_attn_weights,)
|
669 |
-
|
670 |
-
if use_cache:
|
671 |
-
outputs += (present_key_value,)
|
672 |
-
|
673 |
-
if type(outputs) is tuple and len(outputs) == 1:
|
674 |
-
outputs = outputs[0]
|
675 |
-
|
676 |
-
return outputs
|
677 |
-
|
678 |
-
|
679 |
-
class Ernie4_5_PretrainedModel(PreTrainedModel):
|
680 |
-
"""Base class for ERNIE pretrained models."""
|
681 |
-
|
682 |
-
config_class = Ernie4_5_Config
|
683 |
-
base_model_prefix = "ernie"
|
684 |
-
|
685 |
-
|
686 |
-
class Ernie4_5_Model(Ernie4_5_PretrainedModel):
|
687 |
-
|
688 |
-
def __init__(self, config):
|
689 |
-
"""Initialize the ERNIE model architecture.
|
690 |
-
|
691 |
-
Args:
|
692 |
-
config: Model configuration.
|
693 |
-
"""
|
694 |
-
super().__init__(config)
|
695 |
-
self.padding_idx = config.pad_token_id
|
696 |
-
self.vocab_size = config.vocab_size
|
697 |
-
self.hidden_size = config.hidden_size
|
698 |
-
self.config = config
|
699 |
-
|
700 |
-
self.embed_tokens = nn.Embedding(
|
701 |
-
self.vocab_size,
|
702 |
-
self.hidden_size,
|
703 |
-
)
|
704 |
-
|
705 |
-
self.layers = nn.ModuleList(
|
706 |
-
[Ernie4_5_DecoderLayer(config, i) for i in range(config.num_hidden_layers)]
|
707 |
-
)
|
708 |
-
|
709 |
-
self.norm = Ernie4_5_RMSNorm(config)
|
710 |
-
|
711 |
-
self.gradient_checkpointing = False
|
712 |
-
|
713 |
-
def get_input_embeddings(self):
|
714 |
-
"""Get the input embedding layer.
|
715 |
-
|
716 |
-
Returns:
|
717 |
-
nn.Embedding: The embedding layer for input tokens
|
718 |
-
"""
|
719 |
-
return self.embed_tokens
|
720 |
-
|
721 |
-
def set_input_embeddings(self, value):
|
722 |
-
"""Set new input embeddings.
|
723 |
-
|
724 |
-
Args:
|
725 |
-
value (nn.Embedding): New embedding layer to use
|
726 |
-
"""
|
727 |
-
self.embed_tokens = value
|
728 |
-
|
729 |
-
def forward(
|
730 |
-
self,
|
731 |
-
input_ids=None,
|
732 |
-
position_ids=None,
|
733 |
-
token_type_ids=None,
|
734 |
-
attention_mask=None,
|
735 |
-
attn_mask_start_row_indices=None,
|
736 |
-
inputs_embeds=None,
|
737 |
-
use_cache=None,
|
738 |
-
past_key_values=None,
|
739 |
-
output_attentions=False,
|
740 |
-
output_hidden_states=None,
|
741 |
-
return_dict=False,
|
742 |
-
):
|
743 |
-
"""Forward pass through the ERNIE model.
|
744 |
-
|
745 |
-
Args:
|
746 |
-
input_ids (Optional[torch.Tensor]): Input token IDs
|
747 |
-
position_ids (Optional[torch.Tensor]): Position indices
|
748 |
-
attention_mask (Optional[torch.Tensor]): Attention mask
|
749 |
-
attn_mask_start_row_indices (Optional[torch.Tensor]): Variable length attention indices
|
750 |
-
inputs_embeds (Optional[torch.Tensor]): Precomputed embeddings
|
751 |
-
use_cache (Optional[bool]): Whether to cache key/value states
|
752 |
-
past_key_values (Optional[Tuple[Tuple[torch.Tensor]]]): Cached key/value states
|
753 |
-
output_attentions (Optional[bool]): Whether to output attention weights
|
754 |
-
output_hidden_states (Optional[bool]): Whether to output all hidden states
|
755 |
-
return_dict (Optional[bool]): Whether to return dict or tuple
|
756 |
-
|
757 |
-
Returns:
|
758 |
-
Union[Tuple, BaseModelOutputWithPast]:
|
759 |
-
Various outputs depending on configuration, including:
|
760 |
-
- last_hidden_state: Final layer hidden states
|
761 |
-
- past_key_values: Cached key/value states if use_cache=True
|
762 |
-
- hidden_states: All hidden states if output_hidden_states=True
|
763 |
-
- attentions: Attention weights if output_attentions=True
|
764 |
-
"""
|
765 |
-
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
766 |
-
|
767 |
-
# retrieve input_ids and inputs_embeds
|
768 |
-
if input_ids is not None and inputs_embeds is not None:
|
769 |
-
raise ValueError(
|
770 |
-
"You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
|
771 |
-
)
|
772 |
-
elif input_ids is not None:
|
773 |
-
_, seq_length = input_ids.shape
|
774 |
-
elif inputs_embeds is not None:
|
775 |
-
_, seq_length, _ = inputs_embeds.shape
|
776 |
-
else:
|
777 |
-
raise ValueError(
|
778 |
-
"You have to specify either decoder_input_ids or decoder_inputs_embeds"
|
779 |
-
)
|
780 |
-
|
781 |
-
if past_key_values is None:
|
782 |
-
past_key_values = tuple([None] * len(self.layers))
|
783 |
-
|
784 |
-
if inputs_embeds is None:
|
785 |
-
inputs_embeds = self.embed_tokens(input_ids)
|
786 |
-
inputs_embeds = inputs_embeds.to(self.embed_tokens.weight.dtype)
|
787 |
-
|
788 |
-
hidden_states = inputs_embeds
|
789 |
-
|
790 |
-
# decoder layers
|
791 |
-
all_hidden_states = () if output_hidden_states else None
|
792 |
-
all_self_attns = () if output_attentions else None
|
793 |
-
next_decoder_cache = () if use_cache else None
|
794 |
-
|
795 |
-
for idx, (decoder_layer) in enumerate(self.layers):
|
796 |
-
|
797 |
-
if output_hidden_states:
|
798 |
-
all_hidden_states += (hidden_states,)
|
799 |
-
|
800 |
-
past_key_value = (
|
801 |
-
past_key_values[idx] if past_key_values is not None else None
|
802 |
-
)
|
803 |
-
|
804 |
-
layer_outputs = decoder_layer(
|
805 |
-
hidden_states,
|
806 |
-
attention_mask,
|
807 |
-
attn_mask_start_row_indices,
|
808 |
-
position_ids,
|
809 |
-
token_type_ids,
|
810 |
-
output_attentions,
|
811 |
-
past_key_value,
|
812 |
-
use_cache,
|
813 |
-
)
|
814 |
-
|
815 |
-
if isinstance(layer_outputs, (tuple, list)):
|
816 |
-
hidden_states = layer_outputs[0]
|
817 |
-
else:
|
818 |
-
hidden_states = layer_outputs
|
819 |
-
|
820 |
-
if use_cache:
|
821 |
-
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
822 |
-
|
823 |
-
if output_attentions:
|
824 |
-
all_self_attns += (layer_outputs[1],)
|
825 |
-
|
826 |
-
# apply kv cache
|
827 |
-
if past_key_value is not None:
|
828 |
-
hidden_states = hidden_states[:, -1:, :]
|
829 |
-
|
830 |
-
hidden_states = self.norm(hidden_states)
|
831 |
-
|
832 |
-
# add hidden states from the last decoder layer
|
833 |
-
if output_hidden_states:
|
834 |
-
all_hidden_states += (hidden_states,)
|
835 |
-
|
836 |
-
next_cache = next_decoder_cache if use_cache else None
|
837 |
-
|
838 |
-
if not return_dict:
|
839 |
-
return tuple(
|
840 |
-
v
|
841 |
-
for v in [
|
842 |
-
hidden_states,
|
843 |
-
next_cache,
|
844 |
-
all_hidden_states,
|
845 |
-
all_self_attns,
|
846 |
-
]
|
847 |
-
if v is not None
|
848 |
-
)
|
849 |
-
|
850 |
-
return BaseModelOutputWithPast(
|
851 |
-
last_hidden_state=hidden_states,
|
852 |
-
past_key_values=next_cache,
|
853 |
-
hidden_states=all_hidden_states,
|
854 |
-
attentions=all_self_attns,
|
855 |
-
)
|
856 |
-
|
857 |
-
|
858 |
-
class Ernie4_5_LMHead(nn.Module):
|
859 |
-
"""Language model head for ERNIE"""
|
860 |
-
|
861 |
-
def __init__(self, config):
|
862 |
-
"""Initialize the language model head.
|
863 |
-
|
864 |
-
Args:
|
865 |
-
config: Model configuration containing:
|
866 |
-
- vocab_size: Size of vocabulary
|
867 |
-
- hidden_size: Dimension of hidden states
|
868 |
-
- tie_word_embeddings: Whether to tie input/output embeddings
|
869 |
-
- weight_share_add_bias: Whether to add bias when weight sharing
|
870 |
-
- use_bias: Whether to use bias term
|
871 |
-
"""
|
872 |
-
|
873 |
-
super(Ernie4_5_LMHead, self).__init__()
|
874 |
-
self.config = config
|
875 |
-
vocab_size = config.vocab_size
|
876 |
-
|
877 |
-
if config.tie_word_embeddings:
|
878 |
-
# Weight of shape [vocab_size, hidden_size]
|
879 |
-
self.weight = nn.Parameter(
|
880 |
-
torch.empty(
|
881 |
-
vocab_size, config.hidden_size, dtype=torch.get_default_dtype()
|
882 |
-
)
|
883 |
-
)
|
884 |
-
else:
|
885 |
-
# Weight of shape [hidden_size, vocab_size]
|
886 |
-
self.weight = nn.Parameter(
|
887 |
-
torch.empty(
|
888 |
-
config.hidden_size, vocab_size, dtype=torch.get_default_dtype()
|
889 |
-
)
|
890 |
-
)
|
891 |
-
nn.init.xavier_uniform_(self.weight)
|
892 |
-
|
893 |
-
logger.info(
|
894 |
-
f"output-weight: {self.weight.shape}, tie_word_embeddings: {config.tie_word_embeddings}"
|
895 |
-
)
|
896 |
-
|
897 |
-
if config.weight_share_add_bias and config.use_bias:
|
898 |
-
self.bias = nn.Parameter(
|
899 |
-
torch.zeros(vocab_size, dtype=torch.get_default_dtype())
|
900 |
-
)
|
901 |
-
else:
|
902 |
-
self.bias = None
|
903 |
-
|
904 |
-
def forward(self, hidden_states):
|
905 |
-
"""Project hidden states to vocabulary logits.
|
906 |
-
|
907 |
-
Args:
|
908 |
-
hidden_states (torch.Tensor): Input tensor of shape [batch_size, seq_len, hidden_size]
|
909 |
-
|
910 |
-
Returns:
|
911 |
-
Logits tensor of shape [batch_size, seq_len, vocab_size]
|
912 |
-
"""
|
913 |
-
return self.calc_lm_head_logits(
|
914 |
-
self.config, hidden_states, self.weight, self.bias
|
915 |
-
)
|
916 |
-
|
917 |
-
def calc_lm_head_logits(self, config, hidden_states, weight, bias):
|
918 |
-
"""
|
919 |
-
Calculate language model head logits.
|
920 |
-
|
921 |
-
This is the core function that computes the final output logits for a language model.
|
922 |
-
|
923 |
-
Args:
|
924 |
-
config: Model configuration.
|
925 |
-
hidden_states (Tensor): Hidden states from the transformer layers
|
926 |
-
weight (Tensor): Weight matrix for the language model head
|
927 |
-
bias (Tensor): Bias vector for the language model head
|
928 |
-
|
929 |
-
Returns:
|
930 |
-
Tensor: The computed logits for language modeling.
|
931 |
-
"""
|
932 |
-
|
933 |
-
if config.tie_word_embeddings:
|
934 |
-
logits = torch.matmul(hidden_states, weight.T)
|
935 |
-
else:
|
936 |
-
logits = torch.matmul(hidden_states, weight)
|
937 |
-
|
938 |
-
if bias is not None:
|
939 |
-
logits = logits + bias
|
940 |
-
|
941 |
-
return logits
|
942 |
-
|
943 |
-
|
944 |
-
class Ernie4_5_ForCausalLM(Ernie4_5_PretrainedModel, GenerationMixin):
|
945 |
-
"""ERNIE model for causal language modeling."""
|
946 |
-
|
947 |
-
_tied_weights_keys = ["lm_head.weight"]
|
948 |
-
_tp_plan = {"lm_head": "colwise_rep"}
|
949 |
-
_pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
|
950 |
-
|
951 |
-
def __init__(self, config):
|
952 |
-
"""
|
953 |
-
Initializes the ERNIE model for causal language modeling.
|
954 |
-
|
955 |
-
Args:
|
956 |
-
config: Model configuration.
|
957 |
-
"""
|
958 |
-
super().__init__(config)
|
959 |
-
|
960 |
-
self.config = config
|
961 |
-
self.model = Ernie4_5_Model(config)
|
962 |
-
self.lm_head = Ernie4_5_LMHead(config)
|
963 |
-
|
964 |
-
# Initialize weights and apply final processing
|
965 |
-
self.post_init()
|
966 |
-
|
967 |
-
@torch.no_grad()
|
968 |
-
def set_state_dict(self, state_dict, *args, **kwargs):
|
969 |
-
"""
|
970 |
-
Loads the model state dictionary.
|
971 |
-
"""
|
972 |
-
ret = super().set_state_dict(state_dict)
|
973 |
-
return ret
|
974 |
-
|
975 |
-
def get_input_embeddings(self):
|
976 |
-
"""Returns the input embeddings layer."""
|
977 |
-
return self.model.embed_tokens
|
978 |
-
|
979 |
-
def set_input_embeddings(self, value):
|
980 |
-
"""Sets the input embeddings layer."""
|
981 |
-
self.model.embed_tokens = value
|
982 |
-
|
983 |
-
def get_output_embeddings(self):
|
984 |
-
"""Returns the output embeddings (LM head)."""
|
985 |
-
return self.lm_head
|
986 |
-
|
987 |
-
def set_output_embeddings(self, new_embeddings):
|
988 |
-
"""Sets the output embeddings layer."""
|
989 |
-
self.lm_head = new_embeddings
|
990 |
-
|
991 |
-
def set_decoder(self, decoder):
|
992 |
-
"""Sets the ERNIE decoder model."""
|
993 |
-
self.model = decoder
|
994 |
-
|
995 |
-
def get_decoder(self):
|
996 |
-
"""Gets the ERNIE decoder model."""
|
997 |
-
return self.model
|
998 |
-
|
999 |
-
def forward(
|
1000 |
-
self,
|
1001 |
-
input_ids,
|
1002 |
-
position_ids=None,
|
1003 |
-
attention_mask=None,
|
1004 |
-
attn_mask_start_row_indices=None,
|
1005 |
-
token_type_ids=None,
|
1006 |
-
inputs_embeds=None,
|
1007 |
-
labels=None,
|
1008 |
-
use_cache=False,
|
1009 |
-
past_key_values=None,
|
1010 |
-
output_attentions=None,
|
1011 |
-
output_hidden_states=None,
|
1012 |
-
**kwargs,
|
1013 |
-
):
|
1014 |
-
"""
|
1015 |
-
Forward pass for causal language modeling.
|
1016 |
-
|
1017 |
-
Args:
|
1018 |
-
input_ids (torch.Tensor): Input token IDs.
|
1019 |
-
position_ids (torch.Tensor): Position IDs.
|
1020 |
-
attention_mask (torch.Tensor): Attention mask.
|
1021 |
-
attn_mask_start_row_indices (torch.Tensor): Attention mask start indices.
|
1022 |
-
inputs_embeds (torch.Tensor): Optional embedded inputs.
|
1023 |
-
labels (torch.Tensor): Target labels.
|
1024 |
-
use_cache (bool): Whether to use cached hidden states.
|
1025 |
-
past_key_values (dict): Pre-computed hidden states.
|
1026 |
-
output_attentions (bool): Whether to output attentions.
|
1027 |
-
output_hidden_states (bool): Whether to output hidden states.
|
1028 |
-
|
1029 |
-
Returns:
|
1030 |
-
CausalLMOutputWithPast: Model outputs.
|
1031 |
-
"""
|
1032 |
-
|
1033 |
-
if past_key_values is not None:
|
1034 |
-
input_ids = input_ids[:, -1:]
|
1035 |
-
|
1036 |
-
outputs = self.model(
|
1037 |
-
input_ids,
|
1038 |
-
position_ids=position_ids,
|
1039 |
-
attention_mask=attention_mask,
|
1040 |
-
token_type_ids=token_type_ids,
|
1041 |
-
attn_mask_start_row_indices=attn_mask_start_row_indices,
|
1042 |
-
inputs_embeds=inputs_embeds,
|
1043 |
-
use_cache=use_cache,
|
1044 |
-
past_key_values=past_key_values,
|
1045 |
-
output_attentions=output_attentions,
|
1046 |
-
output_hidden_states=output_hidden_states,
|
1047 |
-
return_dict=True,
|
1048 |
-
)
|
1049 |
-
|
1050 |
-
hidden_states = outputs.last_hidden_state
|
1051 |
-
logits = self.lm_head(hidden_states)
|
1052 |
-
|
1053 |
-
loss = None
|
1054 |
-
if labels is not None:
|
1055 |
-
loss = self.loss_function(
|
1056 |
-
logits=logits,
|
1057 |
-
labels=labels,
|
1058 |
-
vocab_size=self.config.vocab_size,
|
1059 |
-
**kwargs,
|
1060 |
-
)
|
1061 |
-
|
1062 |
-
return CausalLMOutputWithPast(
|
1063 |
-
loss=loss,
|
1064 |
-
logits=logits,
|
1065 |
-
past_key_values=outputs.past_key_values,
|
1066 |
-
hidden_states=outputs.hidden_states,
|
1067 |
-
attentions=outputs.attentions,
|
1068 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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