Align with transformers merging

#10
Files changed (1) hide show
  1. modeling_youtu.py +0 -586
modeling_youtu.py DELETED
@@ -1,586 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2025 Tencent Youtu lab, DeepSeek-AI and The HuggingFace Inc. team. All rights reserved.
3
- #
4
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
- # and OPT implementations in this library. It has been modified from its
6
- # original forms to accommodate minor architectural differences compared
7
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
- #
9
- # Licensed under the Apache License, Version 2.0 (the "License");
10
- # you may not use this file except in compliance with the License.
11
- # You may obtain a copy of the License at
12
- #
13
- # http://www.apache.org/licenses/LICENSE-2.0
14
- #
15
- # Unless required by applicable law or agreed to in writing, software
16
- # distributed under the License is distributed on an "AS IS" BASIS,
17
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
- # See the License for the specific language governing permissions and
19
- # limitations under the License.
20
- import math
21
- from typing import Callable, Optional, Union
22
-
23
- import torch
24
- import torch.nn.functional as F
25
- from torch import nn
26
-
27
- from transformers.activations import ACT2FN
28
- from transformers.cache_utils import Cache, DynamicCache
29
- from transformers.generation import GenerationMixin
30
- from transformers.integrations import use_kernel_forward_from_hub
31
- from transformers.masking_utils import create_causal_mask
32
- from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
33
- from transformers.modeling_layers import GradientCheckpointingLayer
34
- from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
35
- from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
36
- from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
37
- from transformers.processing_utils import Unpack
38
- from transformers.utils import TransformersKwargs, auto_docstring, can_return_tuple
39
- from transformers.utils.deprecation import deprecate_kwarg
40
- from transformers.utils.generic import check_model_inputs
41
- from .configuration_youtu import YoutuConfig
42
-
43
-
44
- @use_kernel_forward_from_hub("RMSNorm")
45
- class YoutuRMSNorm(nn.Module):
46
- def __init__(self, hidden_size, eps=1e-6):
47
- """
48
- YoutuRMSNorm is equivalent to T5LayerNorm
49
- """
50
- super().__init__()
51
- self.weight = nn.Parameter(torch.ones(hidden_size))
52
- self.variance_epsilon = eps
53
-
54
- def forward(self, hidden_states):
55
- input_dtype = hidden_states.dtype
56
- hidden_states = hidden_states.to(torch.float32)
57
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
58
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
59
- return self.weight * hidden_states.to(input_dtype)
60
-
61
- def extra_repr(self):
62
- return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
63
-
64
-
65
- class YoutuRotaryEmbedding(nn.Module):
66
- inv_freq: torch.Tensor # fix linting for `register_buffer`
67
-
68
- def __init__(self, config: YoutuConfig, device=None):
69
- super().__init__()
70
- # BC: "rope_type" was originally "type"
71
- if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
72
- self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
73
- else:
74
- self.rope_type = "default"
75
- self.max_seq_len_cached = config.max_position_embeddings
76
- self.original_max_seq_len = config.max_position_embeddings
77
-
78
- self.config = config
79
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
80
-
81
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
82
- self.register_buffer("inv_freq", inv_freq, persistent=False)
83
- self.original_inv_freq = self.inv_freq
84
-
85
- @torch.no_grad()
86
- @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
87
- def forward(self, x, position_ids):
88
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
89
- position_ids_expanded = position_ids[:, None, :].float()
90
-
91
- device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
92
- with torch.autocast(device_type=device_type, enabled=False): # Force float32
93
- freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
94
- emb = torch.cat((freqs, freqs), dim=-1)
95
- cos = emb.cos() * self.attention_scaling
96
- sin = emb.sin() * self.attention_scaling
97
-
98
- return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
99
-
100
-
101
- class YoutuMLP(nn.Module):
102
- def __init__(self, config, hidden_size=None, intermediate_size=None):
103
- super().__init__()
104
- self.config = config
105
- self.hidden_size = config.hidden_size if hidden_size is None else hidden_size
106
- self.intermediate_size = config.intermediate_size if intermediate_size is None else intermediate_size
107
- self.mlp_bias = config.mlp_bias
108
-
109
- self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=self.mlp_bias)
110
- self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=self.mlp_bias)
111
- self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=self.mlp_bias)
112
- self.act_fn = ACT2FN[config.hidden_act]
113
-
114
- def forward(self, x):
115
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
116
- return down_proj
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
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
154
- """
155
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
156
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
157
- """
158
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
159
- if n_rep == 1:
160
- return hidden_states
161
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
162
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
163
-
164
-
165
- def eager_attention_forward(
166
- module: nn.Module,
167
- query: torch.Tensor,
168
- key: torch.Tensor,
169
- value: torch.Tensor,
170
- attention_mask: Optional[torch.Tensor],
171
- scaling: float,
172
- dropout: float = 0.0,
173
- **kwargs: Unpack[TransformersKwargs],
174
- ):
175
- key_states = repeat_kv(key, module.num_key_value_groups)
176
- value_states = repeat_kv(value, module.num_key_value_groups)
177
-
178
- attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
179
- if attention_mask is not None:
180
- causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
181
- attn_weights = attn_weights + causal_mask
182
-
183
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
184
- attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
185
- attn_output = torch.matmul(attn_weights, value_states)
186
- attn_output = attn_output.transpose(1, 2).contiguous()
187
-
188
- return attn_output, attn_weights
189
-
190
-
191
- def apply_rotary_pos_emb_interleave(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
192
- r"""
193
- TODO let's just use the original freqcis computation to not have the view
194
- transpose + reshape! This is not optimized!
195
- Applies Rotary Position Embedding to the query and key tensors.
196
-
197
- Args:
198
- q (`torch.Tensor`): The query tensor.
199
- k (`torch.Tensor`): The key tensor.
200
- cos (`torch.Tensor`): The cosine part of the rotary embedding.
201
- sin (`torch.Tensor`): The sine part of the rotary embedding.
202
- position_ids (`torch.Tensor`):
203
- The position indices of the tokens corresponding to the query and key tensors. For example, this can be
204
- used to pass offsetted position ids when working with a KV-cache.
205
- unsqueeze_dim (`int`, *optional*, defaults to 1):
206
- The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
207
- sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
208
- that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
209
- k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
210
- cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
211
- the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
212
- Returns:
213
- `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
214
- """
215
- cos = cos.unsqueeze(unsqueeze_dim)
216
- sin = sin.unsqueeze(unsqueeze_dim)
217
-
218
- b, h, s, d = q.shape
219
- q = q.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
220
-
221
- b, h, s, d = k.shape
222
- k = k.view(b, h, s, d // 2, 2).transpose(4, 3).reshape(b, h, s, d)
223
-
224
- q_embed = (q * cos) + (rotate_half(q) * sin)
225
- k_embed = (k * cos) + (rotate_half(k) * sin)
226
- return q_embed, k_embed
227
-
228
-
229
- def yarn_get_mscale(scale=1, mscale=1):
230
- if scale <= 1:
231
- return 1.0
232
- return 0.1 * mscale * math.log(scale) + 1.0
233
-
234
-
235
- class YoutuMLAttention(nn.Module):
236
- """Multi-latent attention from 'DeepSeek-V2: A Strong, Economical, and Efficient Mixture-of-Experts Language Model' paper"""
237
-
238
- def __init__(self, config: YoutuConfig, layer_idx: int):
239
- super().__init__()
240
- self.config = config
241
- self.layer_idx = layer_idx
242
- self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
243
- self.attention_dropout = config.attention_dropout
244
- self.num_heads = config.num_attention_heads
245
- self.rope_theta = config.rope_theta
246
- self.q_lora_rank = config.q_lora_rank
247
- self.qk_rope_head_dim = config.qk_rope_head_dim
248
- self.kv_lora_rank = config.kv_lora_rank
249
- self.v_head_dim = config.v_head_dim
250
- self.qk_nope_head_dim = config.qk_nope_head_dim
251
- self.qk_head_dim = config.qk_head_dim
252
-
253
- self.is_causal = True
254
- if self.q_lora_rank is None:
255
- self.q_proj = nn.Linear(config.hidden_size, self.num_heads * self.qk_head_dim, bias=False)
256
- else:
257
- self.q_a_proj = nn.Linear(config.hidden_size, config.q_lora_rank, bias=config.attention_bias)
258
- self.q_a_layernorm = YoutuRMSNorm(config.q_lora_rank)
259
- self.q_b_proj = nn.Linear(config.q_lora_rank, self.num_heads * self.qk_head_dim, bias=False)
260
-
261
- self.kv_a_proj_with_mqa = nn.Linear(
262
- config.hidden_size,
263
- self.kv_lora_rank + self.qk_rope_head_dim,
264
- bias=config.attention_bias,
265
- )
266
- self.kv_a_layernorm = YoutuRMSNorm(self.kv_lora_rank)
267
- self.kv_b_proj = nn.Linear(
268
- self.kv_lora_rank,
269
- self.num_heads * (self.qk_nope_head_dim + self.v_head_dim),
270
- bias=False,
271
- )
272
-
273
- self.o_proj = nn.Linear(
274
- self.num_heads * self.v_head_dim,
275
- config.hidden_size,
276
- bias=config.attention_bias,
277
- )
278
-
279
- self.scaling = self.qk_head_dim ** (-0.5)
280
- if self.config.rope_scaling is not None:
281
- mscale_all_dim = self.config.rope_scaling.get("mscale_all_dim", 0)
282
- scaling_factor = self.config.rope_scaling["factor"]
283
- if mscale_all_dim:
284
- mscale = yarn_get_mscale(scaling_factor, mscale_all_dim)
285
- self.scaling = self.scaling * mscale * mscale
286
-
287
- @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
288
- def forward(
289
- self,
290
- hidden_states: torch.Tensor,
291
- position_embeddings: tuple[torch.Tensor, torch.Tensor],
292
- attention_mask: Optional[torch.Tensor],
293
- past_key_values: Optional[Cache] = None,
294
- cache_position: Optional[torch.LongTensor] = None,
295
- **kwargs: Unpack[FlashAttentionKwargs],
296
- ) -> tuple[torch.Tensor, Optional[torch.Tensor], Optional[tuple[torch.Tensor]]]:
297
- batch_size, seq_length = hidden_states.shape[:-1]
298
- query_shape = (batch_size, seq_length, -1, self.qk_head_dim)
299
- key_shape = (batch_size, seq_length, -1, self.qk_nope_head_dim + self.v_head_dim)
300
-
301
- if self.q_lora_rank is None:
302
- q_states = self.q_proj(hidden_states)
303
- else:
304
- q_states = self.q_b_proj(self.q_a_layernorm(self.q_a_proj(hidden_states)))
305
- q_states = q_states.view(query_shape).transpose(1, 2)
306
- q_pass, q_rot = torch.split(q_states, [self.qk_nope_head_dim, self.qk_rope_head_dim], dim=-1)
307
-
308
- compressed_kv = self.kv_a_proj_with_mqa(hidden_states)
309
- k_pass, k_rot = torch.split(compressed_kv, [self.kv_lora_rank, self.qk_rope_head_dim], dim=-1)
310
-
311
- k_pass = self.kv_b_proj(self.kv_a_layernorm(k_pass)).view(key_shape).transpose(1, 2)
312
- k_pass, value_states = torch.split(k_pass, [self.qk_nope_head_dim, self.v_head_dim], dim=-1)
313
-
314
- k_rot = k_rot.view(batch_size, 1, seq_length, self.qk_rope_head_dim)
315
-
316
- cos, sin = position_embeddings
317
- if self.config.rope_interleave: # support using interleaved weights for efficiency
318
- q_rot, k_rot = apply_rotary_pos_emb_interleave(q_rot, k_rot, cos, sin)
319
- else:
320
- q_rot, k_rot = apply_rotary_pos_emb(q_rot, k_rot, cos, sin)
321
- k_rot = k_rot.expand(*k_pass.shape[:-1], -1)
322
-
323
- query_states = torch.cat((q_pass, q_rot), dim=-1)
324
- key_states = torch.cat((k_pass, k_rot), dim=-1)
325
-
326
- if past_key_values is not None:
327
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
328
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
329
- key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
330
-
331
- if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
332
- value_states = F.pad(value_states, [0, self.qk_head_dim - self.v_head_dim])
333
-
334
- attention_interface: Callable = eager_attention_forward
335
- if self.config._attn_implementation != "eager":
336
- attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
337
-
338
- attn_output, attn_weights = attention_interface(
339
- self,
340
- query_states,
341
- key_states,
342
- value_states,
343
- attention_mask,
344
- dropout=0.0 if not self.training else self.attention_dropout,
345
- scaling=self.scaling,
346
- **kwargs,
347
- )
348
-
349
- if self.config._attn_implementation == "flash_attention_2" and self.qk_head_dim != self.v_head_dim:
350
- attn_output = attn_output[:, :, :, : self.v_head_dim]
351
-
352
- attn_output = attn_output.reshape(batch_size, seq_length, -1).contiguous()
353
- attn_output = self.o_proj(attn_output)
354
- return attn_output, attn_weights
355
-
356
-
357
- class YoutuDecoderLayer(GradientCheckpointingLayer):
358
- def __init__(self, config: YoutuConfig, layer_idx: int):
359
- super().__init__()
360
- self.hidden_size = config.hidden_size
361
- self.self_attn = YoutuMLAttention(config=config, layer_idx=layer_idx)
362
- self.mlp = YoutuMLP(config)
363
- self.input_layernorm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
364
- self.post_attention_layernorm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
365
-
366
- @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
367
- def forward(
368
- self,
369
- hidden_states: torch.Tensor,
370
- attention_mask: Optional[torch.Tensor] = None,
371
- position_ids: Optional[torch.LongTensor] = None,
372
- past_key_values: Optional[Cache] = None,
373
- use_cache: Optional[bool] = False,
374
- cache_position: Optional[torch.LongTensor] = None,
375
- position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
376
- **kwargs: Unpack[TransformersKwargs],
377
- ) -> torch.Tensor:
378
- residual = hidden_states
379
- hidden_states = self.input_layernorm(hidden_states)
380
- # Self Attention
381
- hidden_states, _ = self.self_attn(
382
- hidden_states=hidden_states,
383
- attention_mask=attention_mask,
384
- position_ids=position_ids,
385
- past_key_values=past_key_values,
386
- use_cache=use_cache,
387
- cache_position=cache_position,
388
- position_embeddings=position_embeddings,
389
- **kwargs,
390
- )
391
- hidden_states = residual + hidden_states
392
-
393
- # Fully Connected
394
- residual = hidden_states
395
- hidden_states = self.post_attention_layernorm(hidden_states)
396
- hidden_states = self.mlp(hidden_states)
397
- hidden_states = residual + hidden_states
398
- return hidden_states
399
-
400
- @auto_docstring
401
- class YoutuPreTrainedModel(PreTrainedModel):
402
- config: YoutuConfig
403
- base_model_prefix = "model"
404
- supports_gradient_checkpointing = True
405
- _no_split_modules = ["YoutuDecoderLayer"]
406
- _skip_keys_device_placement = ["past_key_values"]
407
- _supports_flash_attn = True
408
- _supports_sdpa = True
409
- _supports_flex_attn = True
410
- _can_compile_fullgraph = False
411
- _supports_attention_backend = True
412
- _can_record_outputs = {
413
- "hidden_states": YoutuDecoderLayer,
414
- "attentions": YoutuMLAttention,
415
- }
416
-
417
- def _init_weights(self, module):
418
- super()._init_weights(module)
419
- std = self.config.initializer_range
420
- embedding_std = self.config.embedding_initializer_range
421
- if isinstance(module, nn.Linear):
422
- module.weight.data.normal_(mean=0.0, std=std)
423
- if module.bias is not None:
424
- module.bias.data.zero_()
425
- elif isinstance(module, nn.Embedding):
426
- module.weight.data.normal_(mean=0.0, std=embedding_std)
427
- if module.padding_idx is not None:
428
- module.weight.data[module.padding_idx].zero_()
429
-
430
- @auto_docstring
431
- class YoutuModel(YoutuPreTrainedModel):
432
- _keys_to_ignore_on_load_unexpected = [""]
433
-
434
- def __init__(self, config: YoutuConfig):
435
- super().__init__(config)
436
- self.padding_idx = config.pad_token_id
437
- self.vocab_size = config.vocab_size
438
-
439
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
440
- self.layers = nn.ModuleList(
441
- [YoutuDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
442
- )
443
- self.norm = YoutuRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
444
- self.rotary_emb = YoutuRotaryEmbedding(config=config)
445
- self.gradient_checkpointing = False
446
-
447
- # Initialize weights and apply final processing
448
- self.post_init()
449
-
450
- @check_model_inputs
451
- @auto_docstring
452
- def forward(
453
- self,
454
- input_ids: Optional[torch.LongTensor] = None,
455
- attention_mask: Optional[torch.Tensor] = None,
456
- position_ids: Optional[torch.LongTensor] = None,
457
- past_key_values: Optional[Cache] = None,
458
- inputs_embeds: Optional[torch.FloatTensor] = None,
459
- cache_position: Optional[torch.LongTensor] = None,
460
- use_cache: Optional[bool] = None,
461
- **kwargs: Unpack[TransformersKwargs],
462
- ) -> BaseModelOutputWithPast:
463
- if (input_ids is None) ^ (inputs_embeds is not None):
464
- raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
465
-
466
- if inputs_embeds is None:
467
- inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
468
-
469
- if use_cache and past_key_values is None:
470
- past_key_values = DynamicCache(config=self.config)
471
-
472
- if cache_position is None:
473
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
474
- cache_position: torch.Tensor = torch.arange(
475
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
476
- )
477
-
478
- if position_ids is None:
479
- position_ids = cache_position.unsqueeze(0)
480
-
481
- causal_mask = create_causal_mask(
482
- config=self.config,
483
- input_embeds=inputs_embeds,
484
- attention_mask=attention_mask,
485
- cache_position=cache_position,
486
- past_key_values=past_key_values,
487
- position_ids=position_ids,
488
- )
489
-
490
- hidden_states = inputs_embeds
491
- position_embeddings = self.rotary_emb(hidden_states, position_ids)
492
-
493
- for decoder_layer in self.layers[: self.config.num_hidden_layers]:
494
- hidden_states = decoder_layer(
495
- hidden_states,
496
- attention_mask=causal_mask,
497
- position_ids=position_ids,
498
- past_key_values=past_key_values,
499
- cache_position=cache_position,
500
- position_embeddings=position_embeddings,
501
- **kwargs,
502
- )
503
-
504
- hidden_states = self.norm(hidden_states)
505
- return BaseModelOutputWithPast(
506
- last_hidden_state=hidden_states,
507
- past_key_values=past_key_values,
508
- )
509
-
510
-
511
- @auto_docstring
512
- class YoutuForCausalLM(YoutuPreTrainedModel, GenerationMixin):
513
- _tied_weights_keys = ["lm_head.weight"]
514
- _tp_plan = {"lm_head": "colwise_rep"}
515
- _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
516
-
517
- def __init__(self, config):
518
- super().__init__(config)
519
- self.model = YoutuModel(config)
520
- self.vocab_size = config.vocab_size
521
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
522
-
523
- # Initialize weights and apply final processing
524
- self.post_init()
525
-
526
- @can_return_tuple
527
- @auto_docstring
528
- def forward(
529
- self,
530
- input_ids: Optional[torch.LongTensor] = None,
531
- attention_mask: Optional[torch.Tensor] = None,
532
- position_ids: Optional[torch.LongTensor] = None,
533
- past_key_values: Optional[Cache] = None,
534
- inputs_embeds: Optional[torch.FloatTensor] = None,
535
- labels: Optional[torch.LongTensor] = None,
536
- use_cache: Optional[bool] = None,
537
- cache_position: Optional[torch.LongTensor] = None,
538
- logits_to_keep: Union[int, torch.Tensor] = 0,
539
- **kwargs: Unpack[TransformersKwargs],
540
- ) -> CausalLMOutputWithPast:
541
- r"""
542
- Example:
543
-
544
- ```python
545
- >>> from transformers import YoutuTokenizer, YoutuForCausalLM
546
-
547
- >>> model = YoutuForCausalLM.from_pretrained("tencent/Youtu-LLM-2B")
548
- >>> tokenizer = YoutuTokenizer.from_pretrained("tencent/Youtu-LLM-2B")
549
-
550
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
551
- >>> inputs = tokenizer(prompt, return_tensors="pt")
552
-
553
- >>> # Generate
554
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
555
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
556
- ```"""
557
- outputs: BaseModelOutputWithPast = self.model(
558
- input_ids=input_ids,
559
- attention_mask=attention_mask,
560
- position_ids=position_ids,
561
- past_key_values=past_key_values,
562
- inputs_embeds=inputs_embeds,
563
- use_cache=use_cache,
564
- cache_position=cache_position,
565
- **kwargs,
566
- )
567
-
568
- hidden_states = outputs.last_hidden_state
569
- # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
570
- slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
571
- logits = self.lm_head(hidden_states[:, slice_indices, :])
572
-
573
- loss = None
574
- if labels is not None:
575
- loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
576
-
577
- return CausalLMOutputWithPast(
578
- loss=loss,
579
- logits=logits,
580
- past_key_values=outputs.past_key_values,
581
- hidden_states=outputs.hidden_states,
582
- attentions=outputs.attentions,
583
- )
584
-
585
-
586
- __all__ = ["YoutuPreTrainedModel", "YoutuModel", "YoutuForCausalLM"]