Prompt48 commited on
Commit
8f7214a
·
verified ·
1 Parent(s): d1e3090

Upload edit\Qwen3-TTS-test\.venv\Lib\site-packages\transformers\models\helium\modeling_helium.py with huggingface_hub

Browse files
edit//Qwen3-TTS-test//.venv//Lib//site-packages//transformers//models//helium//modeling_helium.py ADDED
@@ -0,0 +1,497 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
2
+ # This file was automatically generated from src/transformers/models/helium/modular_helium.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_helium.py file directly. One of our CI enforces this.
6
+ # 🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨🚨
7
+ # coding=utf-8
8
+ # Copyright 2024 The Kyutai and HuggingFace Inc. teams. All rights reserved.
9
+ #
10
+ #
11
+ # Licensed under the Apache License, Version 2.0 (the "License");
12
+ # you may not use this file except in compliance with the License.
13
+ # You may obtain a copy of the License at
14
+ #
15
+ # http://www.apache.org/licenses/LICENSE-2.0
16
+ #
17
+ # Unless required by applicable law or agreed to in writing, software
18
+ # distributed under the License is distributed on an "AS IS" BASIS,
19
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
20
+ # See the License for the specific language governing permissions and
21
+ # limitations under the License.
22
+ import math
23
+ from typing import Callable, Optional, Union
24
+
25
+ import torch
26
+ import torch.nn as nn
27
+
28
+ from ...activations import ACT2FN
29
+ from ...cache_utils import Cache, DynamicCache
30
+ from ...generation import GenerationMixin
31
+ from ...masking_utils import create_causal_mask
32
+ from ...modeling_layers import (
33
+ GenericForSequenceClassification,
34
+ GenericForTokenClassification,
35
+ GradientCheckpointingLayer,
36
+ )
37
+ from ...modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
38
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS, dynamic_rope_update
39
+ from ...modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
40
+ from ...processing_utils import Unpack
41
+ from ...utils import TransformersKwargs, auto_docstring, can_return_tuple
42
+ from ...utils.deprecation import deprecate_kwarg
43
+ from ...utils.generic import check_model_inputs
44
+ from .configuration_helium import HeliumConfig
45
+
46
+
47
+ class HeliumRMSNorm(nn.Module):
48
+ def __init__(self, hidden_size, eps=1e-6):
49
+ super().__init__()
50
+ self.weight = nn.Parameter(torch.ones(hidden_size))
51
+ self.variance_epsilon = eps
52
+
53
+ def forward(self, hidden_states):
54
+ input_dtype = hidden_states.dtype
55
+ hidden_states = hidden_states.to(torch.float32)
56
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
57
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
58
+ return (self.weight.to(torch.float32) * hidden_states).to(input_dtype)
59
+
60
+ def extra_repr(self):
61
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
62
+
63
+
64
+ class HeliumRotaryEmbedding(nn.Module):
65
+ inv_freq: torch.Tensor # fix linting for `register_buffer`
66
+
67
+ def __init__(self, config: HeliumConfig, device=None):
68
+ super().__init__()
69
+ # BC: "rope_type" was originally "type"
70
+ if hasattr(config, "rope_scaling") and isinstance(config.rope_scaling, dict):
71
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
72
+ else:
73
+ self.rope_type = "default"
74
+ self.max_seq_len_cached = config.max_position_embeddings
75
+ self.original_max_seq_len = config.max_position_embeddings
76
+
77
+ self.config = config
78
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
79
+
80
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
81
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
82
+ self.original_inv_freq = self.inv_freq
83
+
84
+ @torch.no_grad()
85
+ @dynamic_rope_update # power user: used with advanced RoPE types (e.g. dynamic rope)
86
+ def forward(self, x, position_ids):
87
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1).to(x.device)
88
+ position_ids_expanded = position_ids[:, None, :].float()
89
+
90
+ device_type = x.device.type if isinstance(x.device.type, str) and x.device.type != "mps" else "cpu"
91
+ with torch.autocast(device_type=device_type, enabled=False): # Force float32
92
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
93
+ emb = torch.cat((freqs, freqs), dim=-1)
94
+ cos = emb.cos() * self.attention_scaling
95
+ sin = emb.sin() * self.attention_scaling
96
+
97
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
98
+
99
+
100
+ class HeliumMLP(nn.Module):
101
+ def __init__(self, config):
102
+ super().__init__()
103
+ self.config = config
104
+ self.hidden_size = config.hidden_size
105
+ self.intermediate_size = config.intermediate_size
106
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
107
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
108
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
109
+ self.act_fn = ACT2FN[config.hidden_act]
110
+
111
+ def forward(self, x):
112
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
113
+ return down_proj
114
+
115
+
116
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
117
+ """
118
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
119
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
120
+ """
121
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
122
+ if n_rep == 1:
123
+ return hidden_states
124
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
125
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
126
+
127
+
128
+ def eager_attention_forward(
129
+ module: nn.Module,
130
+ query: torch.Tensor,
131
+ key: torch.Tensor,
132
+ value: torch.Tensor,
133
+ attention_mask: Optional[torch.Tensor],
134
+ scaling: float,
135
+ dropout: float = 0.0,
136
+ **kwargs: Unpack[TransformersKwargs],
137
+ ):
138
+ key_states = repeat_kv(key, module.num_key_value_groups)
139
+ value_states = repeat_kv(value, module.num_key_value_groups)
140
+
141
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
142
+ if attention_mask is not None:
143
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
144
+ attn_weights = attn_weights + causal_mask
145
+
146
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
147
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
148
+ attn_output = torch.matmul(attn_weights, value_states)
149
+ attn_output = attn_output.transpose(1, 2).contiguous()
150
+
151
+ return attn_output, attn_weights
152
+
153
+
154
+ def rotate_half(x):
155
+ """Rotates half the hidden dims of the input."""
156
+ x1 = x[..., 0::2]
157
+ x2 = x[..., 1::2]
158
+ return torch.stack((-x2, x1), dim=-1).flatten(-2)
159
+
160
+
161
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
162
+ """Applies Rotary Position Embedding to the query and key tensors.
163
+
164
+ Args:
165
+ q (`torch.Tensor`): The query tensor.
166
+ k (`torch.Tensor`): The key tensor.
167
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
168
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
169
+ position_ids (`torch.Tensor`, *optional*):
170
+ Deprecated and unused.
171
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
172
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
173
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
174
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
175
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
176
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
177
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
178
+ Returns:
179
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
180
+ """
181
+ cos = cos.unsqueeze(unsqueeze_dim)
182
+ sin = sin.unsqueeze(unsqueeze_dim)
183
+
184
+ # Interleave them instead of usual shape
185
+ cos = cos[..., : cos.shape[-1] // 2].repeat_interleave(2, dim=-1)
186
+ sin = sin[..., : sin.shape[-1] // 2].repeat_interleave(2, dim=-1)
187
+
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+
191
+ return q_embed, k_embed
192
+
193
+
194
+ class HeliumAttention(nn.Module):
195
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
196
+
197
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
198
+ super().__init__()
199
+ self.config = config
200
+ self.layer_idx = layer_idx
201
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
202
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
203
+ self.scaling = 1 / math.sqrt(self.head_dim)
204
+ self.attention_dropout = config.attention_dropout
205
+ self.is_causal = True
206
+
207
+ self.q_proj = nn.Linear(
208
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
209
+ )
210
+ self.k_proj = nn.Linear(
211
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
212
+ )
213
+ self.v_proj = nn.Linear(
214
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
215
+ )
216
+ self.o_proj = nn.Linear(config.hidden_size, config.hidden_size, bias=False)
217
+
218
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
219
+ def forward(
220
+ self,
221
+ hidden_states: torch.Tensor,
222
+ position_embeddings: tuple[torch.Tensor, torch.Tensor],
223
+ attention_mask: Optional[torch.Tensor],
224
+ past_key_values: Optional[Cache] = None,
225
+ cache_position: Optional[torch.LongTensor] = None,
226
+ **kwargs: Unpack[TransformersKwargs],
227
+ ) -> tuple[torch.Tensor, torch.Tensor]:
228
+ input_shape = hidden_states.shape[:-1]
229
+ hidden_shape = (*input_shape, -1, self.head_dim)
230
+
231
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
232
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
233
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
234
+
235
+ cos, sin = position_embeddings
236
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
237
+
238
+ if past_key_values is not None:
239
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
240
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
241
+ key_states, value_states = past_key_values.update(key_states, value_states, self.layer_idx, cache_kwargs)
242
+
243
+ attention_interface: Callable = eager_attention_forward
244
+ if self.config._attn_implementation != "eager":
245
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
246
+
247
+ attn_output, attn_weights = attention_interface(
248
+ self,
249
+ query_states,
250
+ key_states,
251
+ value_states,
252
+ attention_mask,
253
+ dropout=0.0 if not self.training else self.attention_dropout,
254
+ scaling=self.scaling,
255
+ **kwargs,
256
+ )
257
+
258
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
259
+ attn_output = self.o_proj(attn_output)
260
+ return attn_output, attn_weights
261
+
262
+
263
+ class HeliumDecoderLayer(GradientCheckpointingLayer):
264
+ def __init__(self, config: HeliumConfig, layer_idx: Optional[int] = None):
265
+ super().__init__()
266
+ self.hidden_size = config.hidden_size
267
+
268
+ self.self_attn = HeliumAttention(config=config, layer_idx=layer_idx)
269
+
270
+ self.mlp = HeliumMLP(config)
271
+ self.input_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
272
+ self.post_attention_layernorm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
273
+
274
+ @deprecate_kwarg("past_key_value", new_name="past_key_values", version="4.58")
275
+ def forward(
276
+ self,
277
+ hidden_states: torch.Tensor,
278
+ attention_mask: Optional[torch.Tensor] = None,
279
+ position_ids: Optional[torch.LongTensor] = None,
280
+ past_key_values: Optional[Cache] = None,
281
+ use_cache: Optional[bool] = False,
282
+ cache_position: Optional[torch.LongTensor] = None,
283
+ position_embeddings: Optional[tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
284
+ **kwargs: Unpack[TransformersKwargs],
285
+ ) -> torch.Tensor:
286
+ residual = hidden_states
287
+ hidden_states = self.input_layernorm(hidden_states)
288
+ # Self Attention
289
+ hidden_states, _ = self.self_attn(
290
+ hidden_states=hidden_states,
291
+ attention_mask=attention_mask,
292
+ position_ids=position_ids,
293
+ past_key_values=past_key_values,
294
+ use_cache=use_cache,
295
+ cache_position=cache_position,
296
+ position_embeddings=position_embeddings,
297
+ **kwargs,
298
+ )
299
+ hidden_states = residual + hidden_states
300
+
301
+ # Fully Connected
302
+ residual = hidden_states
303
+ hidden_states = self.post_attention_layernorm(hidden_states)
304
+ hidden_states = self.mlp(hidden_states)
305
+ hidden_states = residual + hidden_states
306
+ return hidden_states
307
+
308
+
309
+ @auto_docstring
310
+ class HeliumPreTrainedModel(PreTrainedModel):
311
+ config: HeliumConfig
312
+ base_model_prefix = "model"
313
+ supports_gradient_checkpointing = True
314
+ _no_split_modules = ["HeliumDecoderLayer"]
315
+ _skip_keys_device_placement = ["past_key_values"]
316
+ _supports_flash_attn = True
317
+ _supports_sdpa = True
318
+ _supports_flex_attn = True
319
+
320
+ _can_compile_fullgraph = True
321
+ _supports_attention_backend = True
322
+ _can_record_outputs = {
323
+ "hidden_states": HeliumDecoderLayer,
324
+ "attentions": HeliumAttention,
325
+ }
326
+
327
+
328
+ @auto_docstring
329
+ class HeliumModel(HeliumPreTrainedModel):
330
+ def __init__(self, config: HeliumConfig):
331
+ super().__init__(config)
332
+ self.padding_idx = config.pad_token_id
333
+ self.vocab_size = config.vocab_size
334
+
335
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
336
+ self.layers = nn.ModuleList(
337
+ [HeliumDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
338
+ )
339
+ self.norm = HeliumRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
340
+ self.rotary_emb = HeliumRotaryEmbedding(config)
341
+ self.gradient_checkpointing = False
342
+
343
+ # Initialize weights and apply final processing
344
+ self.post_init()
345
+
346
+ @check_model_inputs()
347
+ @auto_docstring
348
+ def forward(
349
+ self,
350
+ input_ids: Optional[torch.LongTensor] = None,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ past_key_values: Optional[Cache] = None,
354
+ inputs_embeds: Optional[torch.FloatTensor] = None,
355
+ cache_position: Optional[torch.LongTensor] = None,
356
+ use_cache: Optional[bool] = None,
357
+ **kwargs: Unpack[TransformersKwargs],
358
+ ) -> BaseModelOutputWithPast:
359
+ if (input_ids is None) ^ (inputs_embeds is not None):
360
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
361
+
362
+ if inputs_embeds is None:
363
+ inputs_embeds: torch.Tensor = self.embed_tokens(input_ids)
364
+
365
+ if use_cache and past_key_values is None:
366
+ past_key_values = DynamicCache(config=self.config)
367
+
368
+ if cache_position is None:
369
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
370
+ cache_position: torch.Tensor = torch.arange(
371
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
372
+ )
373
+
374
+ if position_ids is None:
375
+ position_ids = cache_position.unsqueeze(0)
376
+
377
+ causal_mask = create_causal_mask(
378
+ config=self.config,
379
+ input_embeds=inputs_embeds,
380
+ attention_mask=attention_mask,
381
+ cache_position=cache_position,
382
+ past_key_values=past_key_values,
383
+ position_ids=position_ids,
384
+ )
385
+
386
+ hidden_states = inputs_embeds
387
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
388
+
389
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
390
+ hidden_states = decoder_layer(
391
+ hidden_states,
392
+ attention_mask=causal_mask,
393
+ position_ids=position_ids,
394
+ past_key_values=past_key_values,
395
+ cache_position=cache_position,
396
+ position_embeddings=position_embeddings,
397
+ **kwargs,
398
+ )
399
+
400
+ hidden_states = self.norm(hidden_states)
401
+ return BaseModelOutputWithPast(
402
+ last_hidden_state=hidden_states,
403
+ past_key_values=past_key_values,
404
+ )
405
+
406
+
407
+ @auto_docstring
408
+ class HeliumForCausalLM(HeliumPreTrainedModel, GenerationMixin):
409
+ _tied_weights_keys = ["lm_head.weight"]
410
+ _tp_plan = {"lm_head": "colwise_rep"}
411
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
412
+
413
+ def __init__(self, config):
414
+ super().__init__(config)
415
+ self.model = HeliumModel(config)
416
+ self.vocab_size = config.vocab_size
417
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
418
+
419
+ # Initialize weights and apply final processing
420
+ self.post_init()
421
+
422
+ @can_return_tuple
423
+ @auto_docstring
424
+ def forward(
425
+ self,
426
+ input_ids: Optional[torch.LongTensor] = None,
427
+ attention_mask: Optional[torch.Tensor] = None,
428
+ position_ids: Optional[torch.LongTensor] = None,
429
+ past_key_values: Optional[Cache] = None,
430
+ inputs_embeds: Optional[torch.FloatTensor] = None,
431
+ labels: Optional[torch.LongTensor] = None,
432
+ use_cache: Optional[bool] = None,
433
+ cache_position: Optional[torch.LongTensor] = None,
434
+ logits_to_keep: Union[int, torch.Tensor] = 0,
435
+ **kwargs: Unpack[TransformersKwargs],
436
+ ) -> CausalLMOutputWithPast:
437
+ r"""
438
+ Example:
439
+
440
+ ```python
441
+ >>> from transformers import AutoTokenizer, HeliumForCausalLM
442
+
443
+ >>> model = HeliumForCausalLM.from_pretrained("google/helium-7b")
444
+ >>> tokenizer = AutoTokenizer.from_pretrained("google/helium-7b")
445
+
446
+ >>> prompt = "What is your favorite condiment?"
447
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
448
+
449
+ >>> # Generate
450
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
451
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
452
+ "What is your favorite condiment?"
453
+ ```"""
454
+ outputs: BaseModelOutputWithPast = self.model(
455
+ input_ids=input_ids,
456
+ attention_mask=attention_mask,
457
+ position_ids=position_ids,
458
+ past_key_values=past_key_values,
459
+ inputs_embeds=inputs_embeds,
460
+ use_cache=use_cache,
461
+ cache_position=cache_position,
462
+ **kwargs,
463
+ )
464
+
465
+ hidden_states = outputs.last_hidden_state
466
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
467
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
468
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
469
+
470
+ loss = None
471
+ if labels is not None:
472
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
473
+
474
+ return CausalLMOutputWithPast(
475
+ loss=loss,
476
+ logits=logits,
477
+ past_key_values=outputs.past_key_values,
478
+ hidden_states=outputs.hidden_states,
479
+ attentions=outputs.attentions,
480
+ )
481
+
482
+
483
+ class HeliumForSequenceClassification(GenericForSequenceClassification, HeliumPreTrainedModel):
484
+ pass
485
+
486
+
487
+ class HeliumForTokenClassification(GenericForTokenClassification, HeliumPreTrainedModel):
488
+ pass
489
+
490
+
491
+ __all__ = [
492
+ "HeliumPreTrainedModel",
493
+ "HeliumModel",
494
+ "HeliumForCausalLM",
495
+ "HeliumForSequenceClassification",
496
+ "HeliumForTokenClassification",
497
+ ]