optimum-rbln 0.1.12__py3-none-any.whl → 0.1.15__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (90) hide show
  1. optimum/rbln/__init__.py +27 -13
  2. optimum/rbln/__version__.py +16 -1
  3. optimum/rbln/diffusers/__init__.py +22 -2
  4. optimum/rbln/diffusers/models/__init__.py +34 -3
  5. optimum/rbln/{transformers/generation → diffusers/models/autoencoders}/__init__.py +1 -2
  6. optimum/rbln/diffusers/models/{autoencoder_kl.py → autoencoders/autoencoder_kl.py} +66 -111
  7. optimum/rbln/diffusers/models/autoencoders/vae.py +84 -0
  8. optimum/rbln/diffusers/models/controlnet.py +85 -65
  9. optimum/rbln/diffusers/models/transformers/__init__.py +24 -0
  10. optimum/rbln/diffusers/models/transformers/transformer_sd3.py +203 -0
  11. optimum/rbln/diffusers/models/unets/__init__.py +24 -0
  12. optimum/rbln/diffusers/models/{unet_2d_condition.py → unets/unet_2d_condition.py} +129 -163
  13. optimum/rbln/diffusers/pipelines/__init__.py +60 -12
  14. optimum/rbln/diffusers/pipelines/controlnet/multicontrolnet.py +11 -25
  15. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet.py +9 -185
  16. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_img2img.py +9 -190
  17. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl.py +9 -191
  18. optimum/rbln/diffusers/pipelines/controlnet/pipeline_controlnet_sd_xl_img2img.py +9 -192
  19. optimum/rbln/diffusers/pipelines/stable_diffusion/__init__.py +1 -0
  20. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion.py +4 -110
  21. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_img2img.py +4 -118
  22. optimum/rbln/diffusers/pipelines/stable_diffusion/pipeline_stable_diffusion_inpaint.py +32 -0
  23. optimum/rbln/diffusers/pipelines/stable_diffusion_3/__init__.py +26 -0
  24. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3.py +32 -0
  25. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_img2img.py +32 -0
  26. optimum/rbln/diffusers/pipelines/stable_diffusion_3/pipeline_stable_diffusion_3_inpaint.py +32 -0
  27. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/__init__.py +1 -0
  28. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl.py +18 -128
  29. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_img2img.py +18 -131
  30. optimum/rbln/diffusers/pipelines/stable_diffusion_xl/pipeline_stable_diffusion_xl_inpaint.py +32 -0
  31. optimum/rbln/modeling.py +572 -0
  32. optimum/rbln/modeling_alias.py +1 -1
  33. optimum/rbln/modeling_base.py +176 -763
  34. optimum/rbln/modeling_diffusers.py +329 -0
  35. optimum/rbln/transformers/__init__.py +2 -2
  36. optimum/rbln/transformers/cache_utils.py +5 -9
  37. optimum/rbln/transformers/modeling_rope_utils.py +283 -0
  38. optimum/rbln/transformers/models/__init__.py +80 -31
  39. optimum/rbln/transformers/models/auto/auto_factory.py +117 -23
  40. optimum/rbln/transformers/models/auto/modeling_auto.py +37 -12
  41. optimum/rbln/transformers/models/bart/modeling_bart.py +3 -6
  42. optimum/rbln/transformers/models/bert/modeling_bert.py +3 -6
  43. optimum/rbln/transformers/models/clip/modeling_clip.py +8 -34
  44. optimum/rbln/transformers/models/decoderonly/__init__.py +0 -5
  45. optimum/rbln/transformers/models/decoderonly/decoderonly_architecture.py +779 -361
  46. optimum/rbln/transformers/models/decoderonly/modeling_decoderonly.py +83 -142
  47. optimum/rbln/transformers/models/dpt/modeling_dpt.py +1 -1
  48. optimum/rbln/transformers/models/exaone/exaone_architecture.py +64 -39
  49. optimum/rbln/transformers/models/exaone/modeling_exaone.py +6 -29
  50. optimum/rbln/transformers/models/gemma/gemma_architecture.py +31 -92
  51. optimum/rbln/transformers/models/gemma/modeling_gemma.py +4 -28
  52. optimum/rbln/transformers/models/gpt2/gpt2_architecture.py +50 -238
  53. optimum/rbln/transformers/models/gpt2/modeling_gpt2.py +6 -31
  54. optimum/rbln/transformers/models/llama/modeling_llama.py +4 -28
  55. optimum/rbln/transformers/models/llava_next/modeling_llava_next.py +29 -83
  56. optimum/rbln/transformers/models/midm/midm_architecture.py +88 -253
  57. optimum/rbln/transformers/models/midm/modeling_midm.py +8 -33
  58. optimum/rbln/transformers/models/mistral/modeling_mistral.py +4 -29
  59. optimum/rbln/transformers/models/phi/modeling_phi.py +5 -31
  60. optimum/rbln/transformers/models/phi/phi_architecture.py +61 -345
  61. optimum/rbln/transformers/models/qwen2/modeling_qwen2.py +5 -29
  62. optimum/rbln/transformers/models/seq2seq/modeling_seq2seq.py +1 -46
  63. optimum/rbln/transformers/models/t5/__init__.py +1 -1
  64. optimum/rbln/transformers/models/t5/modeling_t5.py +157 -6
  65. optimum/rbln/transformers/models/wav2vec2/modeling_wav2vec2.py +1 -1
  66. optimum/rbln/transformers/models/whisper/modeling_whisper.py +2 -2
  67. optimum/rbln/transformers/models/xlm_roberta/modeling_xlm_roberta.py +3 -35
  68. optimum/rbln/transformers/utils/rbln_quantization.py +128 -5
  69. optimum/rbln/utils/decorator_utils.py +59 -0
  70. optimum/rbln/utils/hub.py +131 -0
  71. optimum/rbln/utils/import_utils.py +21 -0
  72. optimum/rbln/utils/model_utils.py +53 -0
  73. optimum/rbln/utils/runtime_utils.py +5 -5
  74. optimum/rbln/utils/submodule.py +114 -0
  75. optimum/rbln/utils/timer_utils.py +2 -2
  76. optimum_rbln-0.1.15.dist-info/METADATA +106 -0
  77. optimum_rbln-0.1.15.dist-info/RECORD +110 -0
  78. {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/WHEEL +1 -1
  79. optimum/rbln/transformers/generation/streamers.py +0 -139
  80. optimum/rbln/transformers/generation/utils.py +0 -397
  81. optimum/rbln/transformers/models/exaone/hf_hub_cached/configuration_exaone.py +0 -181
  82. optimum/rbln/transformers/models/exaone/hf_hub_cached/modeling_exaone.py +0 -1725
  83. optimum/rbln/transformers/models/midm/hf_hub_cached/configuration_midm.py +0 -22
  84. optimum/rbln/transformers/models/midm/hf_hub_cached/midm_bitext_tokenization.py +0 -304
  85. optimum/rbln/transformers/models/midm/hf_hub_cached/modeling_midm.py +0 -1469
  86. optimum/rbln/transformers/models/midm/hf_hub_cached/rotary_position_embedding.py +0 -98
  87. optimum_rbln-0.1.12.dist-info/METADATA +0 -119
  88. optimum_rbln-0.1.12.dist-info/RECORD +0 -103
  89. optimum_rbln-0.1.12.dist-info/entry_points.txt +0 -4
  90. {optimum_rbln-0.1.12.dist-info → optimum_rbln-0.1.15.dist-info}/licenses/LICENSE +0 -0
@@ -1,1725 +0,0 @@
1
- # coding=utf-8
2
- # Copyright 2021 The LG AI Research EXAONE Lab
3
- # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
4
- #
5
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
- # and OPT implementations in this library. It has been modified from its
7
- # original forms to accommodate minor architectural differences compared
8
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
- #
10
- # Licensed under the Apache License, Version 2.0 (the "License");
11
- # you may not use this file except in compliance with the License.
12
- # You may obtain a copy of the License at
13
- #
14
- # http://www.apache.org/licenses/LICENSE-2.0
15
- #
16
- # Unless required by applicable law or agreed to in writing, software
17
- # distributed under the License is distributed on an "AS IS" BASIS,
18
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- # See the License for the specific language governing permissions and
20
- # limitations under the License.
21
- """LG AI Research EXAONE Lab"""
22
-
23
- import math
24
- import os
25
- from typing import Optional, Tuple, Union
26
-
27
- import torch
28
- import torch.nn.functional as F
29
- import torch.utils.checkpoint
30
- from packaging import version
31
- from torch import nn
32
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
33
- from transformers.activations import ACT2FN
34
- from transformers.cache_utils import Cache, DynamicCache, StaticCache
35
- from transformers.configuration_utils import PretrainedConfig
36
- from transformers.modeling_attn_mask_utils import AttentionMaskConverter
37
- from transformers.modeling_outputs import (
38
- BaseModelOutputWithPast,
39
- BaseModelOutputWithPastAndCrossAttentions,
40
- CausalLMOutputWithPast,
41
- QuestionAnsweringModelOutput,
42
- SequenceClassifierOutputWithPast,
43
- )
44
- from transformers.modeling_utils import PreTrainedModel
45
- from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
46
- from transformers.utils import (
47
- add_code_sample_docstrings,
48
- add_start_docstrings,
49
- add_start_docstrings_to_model_forward,
50
- is_flash_attn_2_available,
51
- logging,
52
- )
53
-
54
- from .configuration_exaone import ExaoneConfig
55
-
56
-
57
- if is_flash_attn_2_available():
58
- try:
59
- import inspect
60
-
61
- from flash_attn import flash_attn_func, flash_attn_varlen_func
62
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input
63
-
64
- _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
65
-
66
- import flash_attn
67
-
68
- if version.parse(flash_attn.__version__) > version.parse("2.4.2"):
69
- from flash_attn.ops.triton.layer_norm import rms_norm_fn
70
- else:
71
- from flash_attn.ops.triton.layernorm import rms_norm_fn
72
- except: # noqa: E722
73
- pass
74
-
75
-
76
- logger = logging.get_logger(__name__)
77
-
78
- _CHECKPOINT_FOR_DOC = "exaone"
79
- _CONFIG_FOR_DOC = "ExaoneConfig"
80
-
81
- EXAONE_PRETRAINED_MODEL_ARCHIVE_LIST = [
82
- "exaone",
83
- ]
84
-
85
-
86
- @torch.jit.script
87
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
88
- """
89
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
90
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
91
- """
92
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
93
- if n_rep == 1:
94
- return hidden_states
95
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
96
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
97
-
98
-
99
- def apply_rotary_pos_emb(q, k, cos, sin, unsqueeze_dim=1):
100
- """Applies Rotary Position Embedding to the query and key tensors.
101
- Args:
102
- q (`torch.Tensor`): The query tensor.
103
- k (`torch.Tensor`): The key tensor.
104
- cos (`torch.Tensor`): The cosine part of the rotary embedding.
105
- sin (`torch.Tensor`): The sine part of the rotary embedding.
106
- unsqueeze_dim (`int`, *optional*, defaults to 1):
107
- The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
108
- sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
109
- that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
110
- k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
111
- cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
112
- the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
113
- Returns:
114
- `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
115
- """
116
- cos = cos.unsqueeze(unsqueeze_dim)
117
- sin = sin.unsqueeze(unsqueeze_dim)
118
- q_embed = (q * cos) + (rotate_half(q) * sin)
119
- k_embed = (k * cos) + (rotate_half(k) * sin)
120
- return q_embed, k_embed
121
-
122
-
123
- def rotate_half(x):
124
- """Rotates half the hidden dims of the input."""
125
- x1 = x[..., : x.shape[-1] // 2]
126
- x2 = x[..., x.shape[-1] // 2 :]
127
- return torch.cat((-x2, x1), dim=-1)
128
-
129
-
130
- # copied from llama
131
- def _prepare_4d_causal_attention_mask_with_cache_position(
132
- attention_mask: torch.Tensor,
133
- sequence_length: int,
134
- target_length: int,
135
- dtype: torch.dtype,
136
- device: torch.device,
137
- min_dtype: float,
138
- cache_position: torch.Tensor,
139
- batch_size: int,
140
- ):
141
- """
142
- Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
143
- `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
144
- Args:
145
- attention_mask (`torch.Tensor`):
146
- A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape `(batch_size, 1, query_length, key_value_length)`.
147
- sequence_length (`int`):
148
- The sequence length being processed.
149
- target_length (`int`):
150
- The target length: when generating with static cache, the mask should be as long as the static cache, to account for the 0 padding, the part of the cache that is not filled yet.
151
- dtype (`torch.dtype`):
152
- The dtype to use for the 4D attention mask.
153
- device (`torch.device`):
154
- The device to plcae the 4D attention mask on.
155
- min_dtype (`float`):
156
- The minimum value representable with the dtype `dtype`.
157
- cache_position (`torch.Tensor`):
158
- Indices depicting the position of the input sequence tokens in the sequence.
159
- batch_size (`torch.Tensor`):
160
- Batch size.
161
- """
162
- if attention_mask is not None and attention_mask.dim() == 4:
163
- # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
164
- causal_mask = attention_mask
165
- else:
166
- causal_mask = torch.full((sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device)
167
- if sequence_length != 1:
168
- causal_mask = torch.triu(causal_mask, diagonal=1)
169
- causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
170
- causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
171
- if attention_mask is not None:
172
- causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
173
- mask_length = attention_mask.shape[-1]
174
- padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
175
- padding_mask = padding_mask == 0
176
- causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
177
- padding_mask, min_dtype
178
- )
179
-
180
- return causal_mask
181
-
182
-
183
- class ExaoneRMSNorm(torch.nn.Module):
184
- def __init__(self, hidden_size, eps=1e-6):
185
- super().__init__()
186
- self.eps = eps
187
- self.weight = torch.nn.Parameter(torch.ones(hidden_size))
188
-
189
- def forward(self, hidden_states):
190
- input_dtype = hidden_states.dtype
191
- hidden_states = hidden_states.to(torch.float32)
192
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
193
- hidden_states = hidden_states * torch.rsqrt(variance + self.eps)
194
- return self.weight * hidden_states.to(input_dtype)
195
-
196
-
197
- class ExaoneTritonRMSNorm(torch.nn.Module):
198
- def __init__(
199
- self,
200
- hidden_size: int = 0,
201
- eps: float = 1e-5,
202
- ):
203
- super().__init__()
204
- self.eps = eps
205
- self.drop = None
206
- self.weight = torch.nn.Parameter(torch.empty(hidden_size))
207
- self.register_parameter("bias", None)
208
- self.reset_parameters()
209
-
210
- def reset_parameters(self):
211
- torch.nn.init.ones_(self.weight)
212
-
213
- def forward(self, x, residual=None, prenorm=False, residual_in_fp32=False):
214
- return rms_norm_fn(
215
- x,
216
- self.weight,
217
- self.bias,
218
- residual=residual,
219
- eps=self.eps,
220
- dropout_p=self.drop.p if self.drop is not None and self.training else 0.0,
221
- prenorm=prenorm,
222
- residual_in_fp32=residual_in_fp32,
223
- )
224
-
225
-
226
- ALL_LAYERNORM_LAYERS.append(ExaoneRMSNorm)
227
- ALL_LAYERNORM_LAYERS.append(ExaoneTritonRMSNorm)
228
-
229
-
230
- class ExaoneRotaryEmbedding(nn.Module):
231
- """
232
- Common description for the functions named `_compute_XXX_rope_parameters()`
233
- - Copied from `transformers.modeling_rope_utils` in v4.43, with some modifications.
234
- Computes the inverse frequencies with linear scaling.
235
- The EXAONE model supports 'default', 'linear', 'dynamic', and 'yarn'.
236
-
237
- Args:
238
- config (:obj:`~transformers.PretrainedConfig`):
239
- The model configuration.
240
- device (:obj:`torch.device`):
241
- The device to use for initialization of the inverse frequencies.
242
- seq_len (:obj:`int`, `optional`):
243
- The current sequence length. Unused for this type of RoPE.
244
- Returns:
245
- Tuple of (:obj:`torch.Tensor`, :obj:`float`), containing the inverse frequencies for the RoPE embeddings and the
246
- post-processing scaling factor applied to the computed cos/sin (unused in some types of RoPE).
247
- """
248
-
249
- def _compute_default_rope_parameters(
250
- self,
251
- config: Optional[PretrainedConfig],
252
- device: Optional["torch.device"] = None,
253
- seq_len: Optional[int] = None,
254
- ) -> Tuple["torch.Tensor", float]:
255
- base = config.rope_theta
256
- partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
257
- dim = int((config.hidden_size // config.num_attention_heads) * partial_rotary_factor)
258
-
259
- attention_factor = 1.0 # Unused in this type of RoPE
260
-
261
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))
262
- return inv_freq, attention_factor
263
-
264
- def _compute_linear_scaling_rope_parameters(
265
- self,
266
- config: Optional[PretrainedConfig],
267
- device: Optional["torch.device"] = None,
268
- seq_len: Optional[int] = None,
269
- ) -> Tuple["torch.Tensor", float]:
270
- factor = config.rope_scaling["factor"]
271
- if factor < 1.0:
272
- logger.warning_once(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
273
-
274
- inv_freq, attention_factor = self._compute_default_rope_parameters(config, device, seq_len)
275
- inv_freq /= factor
276
- return inv_freq, attention_factor
277
-
278
- def _compute_dynamic_ntk_parameters(
279
- self,
280
- config: Optional[PretrainedConfig],
281
- device: Optional["torch.device"] = None,
282
- seq_len: Optional[int] = None,
283
- ) -> Tuple["torch.Tensor", float]:
284
- base = config.rope_theta
285
- partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
286
- dim = int((config.hidden_size // config.num_attention_heads) * partial_rotary_factor)
287
- max_position_embeddings = config.max_position_embeddings
288
- factor = config.rope_scaling["factor"]
289
- if factor < 1.0:
290
- logger.warning_once(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
291
-
292
- attention_factor = 1.0 # Unused in this type of RoPE
293
- seq_len = seq_len if seq_len is not None else max_position_embeddings
294
-
295
- base = base * ((factor * seq_len / max_position_embeddings) - (factor - 1)) ** (dim / (dim - 2))
296
- inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2, dtype=torch.int64).float().to(device) / dim))
297
- return inv_freq, attention_factor
298
-
299
- def _compute_yarn_parameters(
300
- self,
301
- config: PretrainedConfig,
302
- device: "torch.device",
303
- seq_len: Optional[int] = None,
304
- ) -> Tuple["torch.Tensor", float]:
305
- base = config.rope_theta
306
- partial_rotary_factor = config.partial_rotary_factor if hasattr(config, "partial_rotary_factor") else 1.0
307
- dim = int((config.hidden_size // config.num_attention_heads) * partial_rotary_factor)
308
- max_position_embeddings = config.max_position_embeddings
309
- factor = config.rope_scaling["factor"]
310
- if factor < 1.0:
311
- logger.warning_once(f"`rope_scaling`'s factor field must be a float >= 1, got {factor}")
312
-
313
- # Sets the attention factor as suggested in the paper
314
- attention_factor = config.rope_scaling.get("attention_factor")
315
- if attention_factor is None:
316
- attention_factor = 0.1 * math.log(factor) + 1.0
317
- if attention_factor < 0:
318
- logger.warning_once(
319
- f"`rope_scaling`'s attention_factor field must be a float greater than 0, got {attention_factor}"
320
- )
321
-
322
- # Optional config options
323
- # beta_fast/beta_slow: as suggested in the paper, default to 32/1 (correspondingly)
324
- beta_fast = config.rope_scaling.get("beta_fast") or 32
325
- beta_slow = config.rope_scaling.get("beta_slow") or 1
326
- if not isinstance(beta_fast, float):
327
- logger.warning_once(f"`rope_scaling`'s beta_fast field must be a float, got {beta_fast}")
328
- if not isinstance(beta_slow, float):
329
- logger.warning_once(f"`rope_scaling`'s beta_slow field must be a float, got {beta_fast}")
330
- if beta_fast < beta_slow:
331
- logger.warning_once(
332
- f"`rope_scaling`'s beta_fast field must be greater than beta_slow, got beta_fast={beta_fast} "
333
- f"(defaults to 32 if None) and beta_slow={beta_slow} (defaults to 1 if None)"
334
- )
335
-
336
- # Compute the inverse frequencies
337
- def find_correction_dim(num_rotations, dim, base, max_position_embeddings):
338
- """Inverse dimension formula to find the dimension based on the number of rotations"""
339
- return (dim * math.log(max_position_embeddings / (num_rotations * 2 * math.pi))) / (2 * math.log(base))
340
-
341
- def find_correction_range(low_rot, high_rot, dim, base, max_position_embeddings):
342
- """Find dimension range bounds based on rotations"""
343
- low = math.floor(find_correction_dim(low_rot, dim, base, max_position_embeddings))
344
- high = math.ceil(find_correction_dim(high_rot, dim, base, max_position_embeddings))
345
- return max(low, 0), min(high, dim - 1)
346
-
347
- def linear_ramp_mask(min, max, dim):
348
- if min == max:
349
- max += 0.001 # Prevent singularity
350
-
351
- linear_func = (torch.arange(dim, dtype=torch.float32) - min) / (max - min)
352
- ramp_func = torch.clamp(linear_func, 0, 1)
353
- return ramp_func
354
-
355
- pos_freqs = base ** (torch.arange(0, dim, 2).float().to(device) / dim)
356
- inv_freq_extrapolation = 1.0 / pos_freqs
357
- inv_freq_interpolation = 1.0 / (factor * pos_freqs)
358
-
359
- low, high = find_correction_range(beta_fast, beta_slow, dim, base, max_position_embeddings)
360
-
361
- # Get n-dimensional rotational scaling corrected for extrapolation
362
- inv_freq_mask = 1 - linear_ramp_mask(low, high, dim // 2).float().to(device)
363
- inv_freq = inv_freq_interpolation * (1 - inv_freq_mask) + inv_freq_extrapolation * inv_freq_mask
364
-
365
- return inv_freq, attention_factor
366
-
367
- def __init__(self, config: ExaoneConfig, device=None):
368
- ROPE_INIT_FUNCTIONS = {
369
- "default": self._compute_default_rope_parameters,
370
- "linear": self._compute_linear_scaling_rope_parameters,
371
- "dynamic": self._compute_dynamic_ntk_parameters,
372
- "yarn": self._compute_yarn_parameters,
373
- }
374
-
375
- super().__init__()
376
- if config.rope_scaling is not None:
377
- self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
378
- else:
379
- self.rope_type = "default"
380
- self.max_seq_len = config.max_position_embeddings
381
- self.original_max_seq_len = config.max_position_embeddings
382
-
383
- self.config = config
384
- if self.rope_type not in ROPE_INIT_FUNCTIONS:
385
- raise KeyError(f"The EXAONE model does not support RoPE type: {self.rope_type}")
386
- self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
387
-
388
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
389
- self.register_buffer("inv_freq", inv_freq, persistent=False)
390
- self.original_inv_freq = self.inv_freq
391
-
392
- def _update_freq(self, position_ids, device):
393
- """
394
- dynamic RoPE layers should recompute `inv_freq` in the following situations:
395
- 1 - growing beyond the cached sequence length (allow scaling)
396
- 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
397
- """
398
- seq_len = torch.max(position_ids) + 1
399
- if seq_len > self.max_seq_len: # expand to seq_len
400
- inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
401
- self.register_buffer("inv_freq", inv_freq, persistent=False)
402
- self.max_seq_len = seq_len
403
-
404
- if seq_len < self.original_max_seq_len and self.max_seq_len > self.original_max_seq_len: # reset to original
405
- self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
406
- self.max_seq_len = self.original_max_seq_len
407
-
408
- @torch.no_grad()
409
- def forward(self, x, position_ids):
410
- if "dynamic" in self.rope_type:
411
- self._update_freq(position_ids, device=x.device)
412
-
413
- inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
414
- position_ids_expanded = position_ids[:, None, :].float()
415
-
416
- device_type = x.device.type
417
- device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
418
- with torch.autocast(device_type=device_type, enabled=False):
419
- freqs = (inv_freq_expanded @ position_ids_expanded).transpose(1, 2)
420
- emb = torch.cat((freqs, freqs), dim=-1)
421
- cos, sin = emb.cos(), emb.sin()
422
-
423
- cos, sin = cos * self.attention_scaling, sin * self.attention_scaling
424
- return cos.to(x.dtype), sin.to(x.dtype)
425
-
426
-
427
- class ExaoneSelfAttention(nn.Module):
428
- def __init__(self, config: ExaoneConfig, layer_idx: Optional[int] = None):
429
- super().__init__()
430
- self.config = config
431
- self.layer_idx = layer_idx
432
- self.embed_dim = config.hidden_size
433
- self.num_heads = config.num_attention_heads
434
- self.head_dim = self.embed_dim // self.num_heads
435
- self.num_key_value_heads = config.num_key_value_heads
436
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
437
- self.attention_dropout_rate = config.attention_dropout
438
-
439
- if self.head_dim * self.num_heads != self.embed_dim:
440
- raise ValueError(
441
- f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
442
- )
443
-
444
- self.rotary = ExaoneRotaryEmbedding(config)
445
-
446
- self.k_proj = nn.Linear(self.embed_dim, self.num_key_value_heads * self.head_dim, bias=False)
447
- self.v_proj = nn.Linear(self.embed_dim, self.num_key_value_heads * self.head_dim, bias=False)
448
- self.q_proj = nn.Linear(self.embed_dim, self.num_heads * self.head_dim, bias=False)
449
- self.out_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
450
-
451
- def forward(
452
- self,
453
- hidden_states: torch.Tensor,
454
- attention_mask: Optional[torch.Tensor] = None,
455
- position_ids: Optional[torch.LongTensor] = None,
456
- past_key_value: Optional[Cache] = None,
457
- output_attentions: Optional[bool] = False,
458
- use_cache: Optional[bool] = False,
459
- cache_position: Optional[torch.LongTensor] = None,
460
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
461
- **kwargs,
462
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
463
- bsz, q_len, _ = hidden_states.size()
464
- query_states = self.q_proj(hidden_states)
465
- key_states = self.k_proj(hidden_states)
466
- value_states = self.v_proj(hidden_states)
467
-
468
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
469
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
470
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
471
-
472
- if position_embeddings is None:
473
- cos, sin = self.rotary(value_states, position_ids=position_ids)
474
- else:
475
- cos, sin = position_embeddings
476
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
477
-
478
- if past_key_value is not None:
479
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
480
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
481
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
482
-
483
- key_states = repeat_kv(key_states, self.num_key_value_groups)
484
- value_states = repeat_kv(value_states, self.num_key_value_groups)
485
-
486
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
487
-
488
- if attention_mask is not None:
489
- causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
490
- attn_weights = attn_weights + causal_mask
491
-
492
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
493
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout_rate, training=self.training)
494
- attn_output = torch.matmul(attn_weights, value_states)
495
-
496
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
497
- raise ValueError(
498
- f"Attention outputs should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
499
- f" {attn_output.size()}"
500
- )
501
-
502
- attn_output = attn_output.transpose(1, 2).contiguous()
503
- attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
504
-
505
- attn_output = self.out_proj(attn_output)
506
-
507
- if not output_attentions:
508
- attn_weights = None
509
-
510
- return attn_output, attn_weights, past_key_value
511
-
512
-
513
- class ExaoneFlashAttention(ExaoneSelfAttention):
514
- def __init__(self, *args, **kwargs):
515
- super().__init__(*args, **kwargs)
516
-
517
- def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
518
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
519
-
520
- def forward(
521
- self,
522
- hidden_states: torch.Tensor,
523
- attention_mask: Optional[torch.Tensor] = None,
524
- position_ids: Optional[torch.LongTensor] = None,
525
- past_key_value: Optional[Cache] = None,
526
- output_attentions: Optional[bool] = False,
527
- use_cache: Optional[bool] = False,
528
- cache_position: Optional[torch.LongTensor] = None,
529
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
530
- **kwargs,
531
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
532
- if isinstance(past_key_value, StaticCache):
533
- raise ValueError(
534
- "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
535
- "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
536
- )
537
-
538
- output_attentions = False
539
-
540
- bsz, q_len, h_size = hidden_states.size()
541
-
542
- query_states = self.q_proj(hidden_states)
543
- key_states = self.k_proj(hidden_states)
544
- value_states = self.v_proj(hidden_states)
545
-
546
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
547
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
548
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
549
-
550
- if position_embeddings is None:
551
- cos, sin = self.rotary(value_states, position_ids=position_ids)
552
- else:
553
- cos, sin = position_embeddings
554
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
555
-
556
- if past_key_value is not None:
557
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
558
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
559
- # Only update cache as shape of [bsz, n_head, q_len, head_dim]
560
- # TODO: need to be fixed when transformers' KV cache layout is changed
561
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
562
-
563
- query_states = query_states.transpose(1, 2)
564
- key_states = key_states.transpose(1, 2)
565
- value_states = value_states.transpose(1, 2)
566
-
567
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
568
- # therefore the input hidden states gets silently casted in float32. Hence, we need
569
- # cast them back in the correct dtype just to be sure everything works as expected.
570
- input_dtype = query_states.dtype
571
- if input_dtype == torch.float32:
572
- if torch.is_autocast_enabled():
573
- target_dtype = torch.get_autocast_gpu_dtype()
574
- # Handle the case where the model is quantized
575
- elif hasattr(self.config, "_pre_quantization_dtype"):
576
- target_dtype = self.config._pre_quantization_dtype
577
- else:
578
- target_dtype = self.q_proj.weight.dtype
579
-
580
- logger.warning_once(
581
- f"The input hidden states seems to be silently casted in float32, this might be related to"
582
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
583
- f" {target_dtype}."
584
- )
585
-
586
- query_states = query_states.to(target_dtype)
587
- key_states = key_states.to(target_dtype)
588
- value_states = value_states.to(target_dtype)
589
-
590
- dropout_rate = self.attention_dropout_rate if self.training else 0.0
591
-
592
- attn_output = self._flash_attention_forward(
593
- query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate, is_causal=True
594
- )
595
-
596
- attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
597
- attn_output = self.out_proj(attn_output)
598
-
599
- if not output_attentions:
600
- attn_weights = None
601
-
602
- return attn_output, attn_weights, past_key_value
603
-
604
- @staticmethod
605
- def _flash_attention_forward(
606
- query_states: torch.Tensor,
607
- key_states: torch.Tensor,
608
- value_states: torch.Tensor,
609
- attention_mask: torch.Tensor,
610
- query_length: int,
611
- is_causal: bool,
612
- dropout: float = 0.0,
613
- softmax_scale: Optional[float] = None,
614
- sliding_window: Optional[int] = None,
615
- use_top_left_mask: bool = False,
616
- softcap: Optional[float] = None,
617
- deterministic: bool = os.environ.get("FLASH_ATTENTION_DETERMINISTIC", "0") == "1",
618
- ):
619
- """
620
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
621
- first unpad the input, then computes the attention scores and pad the final attention scores.
622
- Args:
623
- query_states (`torch.Tensor`):
624
- Input query states to be passed to Flash Attention API
625
- key_states (`torch.Tensor`):
626
- Input key states to be passed to Flash Attention API
627
- value_states (`torch.Tensor`):
628
- Input value states to be passed to Flash Attention API
629
- attention_mask (`torch.Tensor`):
630
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
631
- position of padding tokens and 1 for the position of non-padding tokens.
632
- dropout (`float`):
633
- Attention dropout
634
- softmax_scale (`float`, *optional*):
635
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
636
- use_top_left_mask (`bool`, defaults to `False`):
637
- flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference.
638
- softcap (`float`, *optional*):
639
- Softcap for the attention logits, used e.g. in gemma2.
640
- deterministic (`bool`, *optional*):
641
- Determines if the deterministic option introduced in flash_attn>=2.4.1 is enabled.
642
- """
643
- if not use_top_left_mask:
644
- causal = is_causal
645
- else:
646
- # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__.
647
- causal = is_causal and query_length != 1
648
-
649
- # Assuming 4D tensors, key_states.shape[1] is the key/value sequence length (source length).
650
- use_sliding_windows = (
651
- _flash_supports_window_size and sliding_window is not None and key_states.shape[1] > sliding_window
652
- )
653
- flash_kwargs = {"window_size": (sliding_window, sliding_window)} if use_sliding_windows else {}
654
-
655
- if softcap is not None:
656
- flash_kwargs["softcap"] = softcap
657
-
658
- # Contains at least one padding token in the sequence
659
- if attention_mask is not None:
660
- batch_size = query_states.shape[0]
661
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = (
662
- ExaoneFlashAttention._upad_input(query_states, key_states, value_states, attention_mask, query_length)
663
- )
664
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
665
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
666
-
667
- attn_output_unpad = flash_attn_varlen_func(
668
- query_states,
669
- key_states,
670
- value_states,
671
- cu_seqlens_q=cu_seqlens_q,
672
- cu_seqlens_k=cu_seqlens_k,
673
- max_seqlen_q=max_seqlen_in_batch_q,
674
- max_seqlen_k=max_seqlen_in_batch_k,
675
- dropout_p=dropout,
676
- softmax_scale=softmax_scale,
677
- causal=causal,
678
- **flash_kwargs,
679
- )
680
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
681
- else:
682
- attn_output = flash_attn_func(
683
- query_states,
684
- key_states,
685
- value_states,
686
- dropout,
687
- softmax_scale=softmax_scale,
688
- causal=causal,
689
- **flash_kwargs,
690
- )
691
-
692
- return attn_output
693
-
694
- @staticmethod
695
- def _upad_input(
696
- query_layer: torch.Tensor,
697
- key_layer: torch.Tensor,
698
- value_layer: torch.Tensor,
699
- attention_mask: torch.Tensor,
700
- query_length: int,
701
- ):
702
- """
703
- Unpads query, key, and values tensors, using a single dimension for all tokens even though they belong to different batches.
704
- This function is used instead of `flash_attn.bert_padding.unpad_input` in order to avoid the recomputation of the same intermediary
705
- tensors for query, key, value tensors.
706
- Arguments:
707
- query_layer (`torch.Tensor`):
708
- Query state with padding. Shape: (batch_size, query_length, num_heads, head_dim).
709
- key_layer (`torch.Tensor`):
710
- Key state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
711
- value_layer (`torch.Tensor`):
712
- Value state with padding. Shape: (batch_size, kv_seq_len, num_key_value_heads, head_dim).
713
- attention_mask (`torch.Tensor`):
714
- Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
715
- query_length (`int`):
716
- Target length.
717
- Return:
718
- query_layer (`torch.Tensor):
719
- Query state without padding. Shape: (total_target_length, num_heads, head_dim).
720
- key_layer (`torch.Tensor`):
721
- Key state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
722
- value_layer (`torch.Tensor`):
723
- Value state with padding. Shape: (total_source_length, num_key_value_heads, head_dim).
724
- indices_q (`torch.Tensor`):
725
- The indices of non-masked tokens from the flattened input target sequence.
726
- (cu_seqlens_q, cu_seqlens_k) (`Tuple[int]`):
727
- The cumulative sequence lengths for the target (query) and source (key, value), used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
728
- (max_seqlen_in_batch_q, max_seqlen_in_batch_k) (`Tuple[int]`):
729
- Maximum sequence length in batch (`max_seqlen_in_batch_q` for the target sequence i.e. query, `max_seqlen_in_batch_k` for the source sequence i.e. key/value).
730
- """
731
- indices_k, cu_seqlens_k, max_seqlen_in_batch_k = ExaoneFlashAttention._get_unpad_data(attention_mask)
732
- batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
733
-
734
- key_layer = index_first_axis(
735
- key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
736
- )
737
- value_layer = index_first_axis(
738
- value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
739
- )
740
- if query_length == kv_seq_len:
741
- query_layer = index_first_axis(query_layer.reshape(batch_size * kv_seq_len, -1, head_dim), indices_k)
742
- cu_seqlens_q = cu_seqlens_k
743
- max_seqlen_in_batch_q = max_seqlen_in_batch_k
744
- indices_q = indices_k
745
- elif query_length == 1:
746
- max_seqlen_in_batch_q = 1
747
- cu_seqlens_q = torch.arange(
748
- batch_size + 1, dtype=torch.int32, device=query_layer.device
749
- ) # There is a memcpy here, that is very bad.
750
- indices_q = cu_seqlens_q[:-1]
751
- query_layer = query_layer.squeeze(1)
752
- else:
753
- # The -q_len: slice assumes left padding.
754
- attention_mask = attention_mask[:, -query_length:]
755
- query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
756
-
757
- return (
758
- query_layer,
759
- key_layer,
760
- value_layer,
761
- indices_q,
762
- (cu_seqlens_q, cu_seqlens_k),
763
- (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
764
- )
765
-
766
- @staticmethod
767
- def _get_unpad_data(attention_mask: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor, int]:
768
- """
769
- Retrieves indexing data required to repad unpadded (ragged) tensors.
770
- Arguments:
771
- attention_mask (`torch.Tensor`):
772
- Boolean or int tensor of shape (batch_size, sequence_length), 1 means valid and 0 means not valid.
773
- Return:
774
- indices (`torch.Tensor):
775
- The indices of non-masked tokens from the flattened input sequence.
776
- cu_seqlens (`torch.Tensor`):
777
- The cumulative sequence lengths, used to index into ragged (unpadded) tensors. `cu_seqlens` shape is (batch_size + 1,).
778
- max_seqlen_in_batch (`int`):
779
- Maximum sequence length in batch.
780
- """
781
- seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
782
- indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
783
- max_seqlen_in_batch = seqlens_in_batch.max().item()
784
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
785
- return (
786
- indices,
787
- cu_seqlens,
788
- max_seqlen_in_batch,
789
- )
790
-
791
-
792
- class ExaoneSdpaAttention(ExaoneSelfAttention):
793
- def __init__(self, *args, **kwargs):
794
- super().__init__(*args, **kwargs)
795
-
796
- def forward(
797
- self,
798
- hidden_states: torch.Tensor,
799
- attention_mask: Optional[torch.Tensor] = None,
800
- position_ids: Optional[torch.LongTensor] = None,
801
- past_key_value: Optional[Cache] = None,
802
- output_attentions: Optional[bool] = False,
803
- use_cache: Optional[bool] = False,
804
- cache_position: Optional[torch.LongTensor] = None,
805
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
806
- **kwargs,
807
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
808
- if output_attentions:
809
- logger.warning_once(
810
- "ExaoneModel is using ExaoneSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
811
- 'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
812
- )
813
- return super().forward(
814
- hidden_states=hidden_states,
815
- attention_mask=attention_mask,
816
- position_ids=position_ids,
817
- past_key_value=past_key_value,
818
- output_attentions=output_attentions,
819
- use_cache=use_cache,
820
- cache_position=cache_position,
821
- position_embeddings=position_embeddings,
822
- **kwargs,
823
- )
824
-
825
- bsz, q_len, _ = hidden_states.size()
826
-
827
- query_states = self.q_proj(hidden_states)
828
- key_states = self.k_proj(hidden_states)
829
- value_states = self.v_proj(hidden_states)
830
-
831
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
832
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
833
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
834
-
835
- if position_embeddings is None:
836
- cos, sin = self.rotary(value_states, position_ids=position_ids)
837
- else:
838
- cos, sin = position_embeddings
839
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
840
-
841
- if past_key_value is not None:
842
- # sin and cos are specific to RoPE models; cache_position needed for the static cache
843
- cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
844
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
845
-
846
- key_states = repeat_kv(key_states, self.num_key_value_groups)
847
- value_states = repeat_kv(value_states, self.num_key_value_groups)
848
-
849
- causal_mask = attention_mask
850
- if attention_mask is not None:
851
- causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
852
-
853
- # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
854
- # Reference: https://github.com/pytorch/pytorch/issues/112577.
855
- if query_states.device.type == "cuda" and causal_mask is not None:
856
- query_states = query_states.contiguous()
857
- key_states = key_states.contiguous()
858
- value_states = value_states.contiguous()
859
-
860
- # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
861
- # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
862
- is_causal = True if causal_mask is None and q_len > 1 else False
863
-
864
- attn_output = torch.nn.functional.scaled_dot_product_attention(
865
- query_states,
866
- key_states,
867
- value_states,
868
- attn_mask=causal_mask,
869
- dropout_p=self.attention_dropout_rate if self.training else 0.0,
870
- is_causal=is_causal,
871
- )
872
-
873
- attn_output = attn_output.transpose(1, 2).contiguous()
874
- attn_output = attn_output.reshape(bsz, q_len, self.embed_dim).contiguous()
875
-
876
- attn_output = self.out_proj(attn_output)
877
-
878
- return attn_output, None, past_key_value
879
-
880
-
881
- class ExaoneAttention(nn.Module):
882
- def __init__(self, config, layer_id=0):
883
- super().__init__()
884
- self.layer_id = layer_id
885
- if "flash" in config._attn_implementation:
886
- self.attention = ExaoneFlashAttention(config, self.layer_id)
887
- elif "sdpa" in config._attn_implementation:
888
- self.attention = ExaoneSdpaAttention(config, self.layer_id)
889
- else:
890
- self.attention = ExaoneSelfAttention(config, self.layer_id)
891
-
892
- def forward(
893
- self,
894
- hidden_states: torch.Tensor,
895
- attention_mask: Optional[torch.Tensor] = None,
896
- position_ids: Optional[torch.LongTensor] = None,
897
- past_key_value: Optional[Cache] = None,
898
- output_attentions: Optional[bool] = False,
899
- use_cache: Optional[bool] = False,
900
- cache_position: Optional[torch.LongTensor] = None,
901
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
902
- **kwargs,
903
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
904
- return self.attention(
905
- hidden_states=hidden_states,
906
- attention_mask=attention_mask,
907
- position_ids=position_ids,
908
- past_key_value=past_key_value,
909
- output_attentions=output_attentions,
910
- use_cache=use_cache,
911
- cache_position=cache_position,
912
- position_embeddings=position_embeddings,
913
- **kwargs,
914
- )
915
-
916
-
917
- class ExaoneGatedMLP(nn.Module):
918
- def __init__(self, intermediate_size, config):
919
- super().__init__()
920
- self.config = config
921
- embed_dim = config.hidden_size
922
- self.c_fc_0 = nn.Linear(embed_dim, intermediate_size, bias=False)
923
- self.c_fc_1 = nn.Linear(embed_dim, intermediate_size, bias=False)
924
- self.c_proj = nn.Linear(intermediate_size, embed_dim, bias=False)
925
- self.act = ACT2FN[config.activation_function]
926
-
927
- def forward(self, hidden_states):
928
- output_proj = self.c_proj(self.act(self.c_fc_0(hidden_states)) * self.c_fc_1(hidden_states))
929
- return output_proj
930
-
931
-
932
- class ExaoneBlock(nn.Module):
933
- def __init__(self, config, layer_id):
934
- super().__init__()
935
- self.config = config
936
- hidden_size = config.hidden_size
937
- inner_dim = config.intermediate_size if config.intermediate_size is not None else 4 * hidden_size
938
- self.ln_1 = ExaoneRMSNorm(hidden_size=hidden_size, eps=config.layer_norm_epsilon)
939
- self.attn = ExaoneAttention(config, layer_id)
940
- self.ln_2 = ExaoneRMSNorm(hidden_size=hidden_size, eps=config.layer_norm_epsilon)
941
- self.mlp = ExaoneGatedMLP(inner_dim, config)
942
-
943
- def forward(
944
- self,
945
- hidden_states: torch.Tensor,
946
- attention_mask: Optional[torch.Tensor] = None,
947
- position_ids: Optional[torch.LongTensor] = None,
948
- past_key_value: Optional[Cache] = None,
949
- output_attentions: Optional[bool] = False,
950
- use_cache: Optional[bool] = False,
951
- cache_position: Optional[torch.LongTensor] = None,
952
- position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None,
953
- **kwargs,
954
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
955
- residual = hidden_states
956
- hidden_states = self.ln_1(hidden_states)
957
-
958
- hidden_states, self_attn_weights, present_key_value = self.attn(
959
- hidden_states=hidden_states,
960
- attention_mask=attention_mask,
961
- position_ids=position_ids,
962
- past_key_value=past_key_value,
963
- output_attentions=output_attentions,
964
- use_cache=use_cache,
965
- cache_position=cache_position,
966
- position_embeddings=position_embeddings,
967
- **kwargs,
968
- )
969
- # residual connection
970
- hidden_states = residual + hidden_states
971
-
972
- residual = hidden_states
973
- hidden_states = self.ln_2(hidden_states)
974
- hidden_states = self.mlp(hidden_states)
975
-
976
- hidden_states = residual + hidden_states
977
-
978
- outputs = (hidden_states,)
979
-
980
- if output_attentions:
981
- outputs += (self_attn_weights,)
982
-
983
- if use_cache:
984
- outputs += (present_key_value,)
985
-
986
- return outputs
987
-
988
-
989
- class ExaonePreTrainedModel(PreTrainedModel):
990
- """
991
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
992
- models.
993
- """
994
-
995
- config_class = ExaoneConfig
996
- base_model_prefix = "transformer"
997
- supports_gradient_checkpointing = True
998
- _no_split_modules = ["ExaoneBlock"]
999
- _skip_keys_device_placement = "past_key_values"
1000
- _supports_flash_attn_2 = True
1001
- _supports_sdpa = True
1002
- _supports_cache_class = True
1003
-
1004
- def __init__(self, *inputs, **kwargs):
1005
- super().__init__(*inputs, **kwargs)
1006
-
1007
- def _init_weights(self, module):
1008
- """Initialize the weights."""
1009
- if isinstance(module, (nn.Linear,)):
1010
- # Slightly different from the TF version which uses truncated_normal for initialization
1011
- # cf https://github.com/pytorch/pytorch/pull/5617
1012
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1013
- if module.bias is not None:
1014
- module.bias.data.zero_()
1015
- elif isinstance(module, nn.Embedding):
1016
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
1017
- if module.padding_idx is not None:
1018
- module.weight.data[module.padding_idx].zero_()
1019
- elif isinstance(module, ExaoneRMSNorm):
1020
- module.weight.data.fill_(1.0)
1021
-
1022
-
1023
- EXAONE_START_DOCSTRING = r"""
1024
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
1025
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
1026
- etc.)
1027
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
1028
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
1029
- and behavior.
1030
- Parameters:
1031
- config (:class:`~transformers.ExaoneConfig`): Model configuration class with all the parameters of the model.
1032
- Initializing with a config file does not load the weights associated with the model, only the
1033
- configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model weights.
1034
- """
1035
-
1036
- EXAONE_INPUTS_DOCSTRING = r"""
1037
- Args:
1038
- input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`):
1039
- :obj:`input_ids_length` = ``sequence_length`` if :obj:`past_key_values` is ``None`` else
1040
- ``past_key_values.get_seq_length()`` (``sequence_length`` of input past key value states). Indices of input
1041
- sequence tokens in the vocabulary.
1042
- If :obj:`past_key_values` is used, only ``input_ids`` that do not have their past calculated should be
1043
- passed as ``input_ids``.
1044
- `What are input IDs? <../glossary.html#input-ids>`__
1045
- attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1046
- Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
1047
- - 1 for tokens that are **not masked**,
1048
- - 0 for tokens that are **masked**.
1049
- `What are attention masks? <../glossary.html#attention-mask>`__
1050
- position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
1051
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
1052
- config.max_position_embeddings - 1]``.
1053
- `What are position IDs? <../glossary.html#position-ids>`_
1054
- past_key_values (:obj:`Cache`, `optional`):
1055
- Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
1056
- :obj:`past_key_values` output below). Can be used to speed up sequential decoding. This typically consists
1057
- in the `past_key_values` returned by the model at a previous stage of decoding, when `use_cache=True` or
1058
- `config.use_cache=True`.
1059
- inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
1060
- Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
1061
- This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
1062
- vectors than the model's internal embedding lookup matrix.
1063
- If :obj:`past_key_values` is used, optionally only the last :obj:`inputs_embeds` have to be input (see
1064
- :obj:`past_key_values`).
1065
- use_cache (:obj:`bool`, `optional`):
1066
- If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
1067
- decoding (see :obj:`past_key_values`).
1068
- output_attentions (:obj:`bool`, `optional`):
1069
- Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
1070
- tensors for more detail.
1071
- output_hidden_states (:obj:`bool`, `optional`):
1072
- Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
1073
- more detail.
1074
- return_dict (:obj:`bool`, `optional`):
1075
- Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
1076
- cache_position (:obj:`torch.LongTensor` of shape :obj:`(sequence_length)`, `optional`):
1077
- Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
1078
- this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
1079
- the complete sequence length.
1080
- """
1081
-
1082
-
1083
- @add_start_docstrings(
1084
- "The bare EXAONE Model transformer outputting raw hidden-states without any specific head on top.",
1085
- EXAONE_START_DOCSTRING,
1086
- )
1087
- class ExaoneModel(ExaonePreTrainedModel):
1088
- def __init__(self, config):
1089
- super().__init__(config)
1090
- self.config = config
1091
- self.embed_dim = config.hidden_size
1092
- self.wte = nn.Embedding(config.vocab_size, self.embed_dim, self.config.pad_token_id)
1093
- self.drop = nn.Dropout(float(config.embed_dropout))
1094
- self.h = nn.ModuleList([ExaoneBlock(config, layer_id=i) for i in range(config.num_layers)])
1095
- self.ln_f = ExaoneRMSNorm(hidden_size=self.embed_dim, eps=config.layer_norm_epsilon)
1096
- self.rotary = ExaoneRotaryEmbedding(config)
1097
- self.gradient_checkpointing = False
1098
- # Initialize weights and apply final processing
1099
- self.post_init()
1100
-
1101
- def get_input_embeddings(self):
1102
- return self.wte
1103
-
1104
- def set_input_embeddings(self, new_embeddings):
1105
- self.wte = new_embeddings
1106
-
1107
- @add_start_docstrings_to_model_forward(EXAONE_INPUTS_DOCSTRING)
1108
- @add_code_sample_docstrings(
1109
- checkpoint=_CHECKPOINT_FOR_DOC,
1110
- output_type=BaseModelOutputWithPastAndCrossAttentions,
1111
- config_class=_CONFIG_FOR_DOC,
1112
- )
1113
- def forward(
1114
- self,
1115
- input_ids: Optional[torch.Tensor] = None,
1116
- attention_mask: Optional[torch.Tensor] = None,
1117
- position_ids: Optional[torch.Tensor] = None,
1118
- past_key_values: Optional[Cache] = None,
1119
- inputs_embeds: Optional[torch.Tensor] = None,
1120
- use_cache: Optional[bool] = None,
1121
- output_attentions: Optional[bool] = None,
1122
- output_hidden_states: Optional[bool] = None,
1123
- return_dict: Optional[bool] = None,
1124
- cache_position: Optional[torch.LongTensor] = None,
1125
- ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
1126
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1127
- output_hidden_states = (
1128
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1129
- )
1130
- use_cache = use_cache if use_cache is not None else self.config.use_cache
1131
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1132
-
1133
- if self.gradient_checkpointing and self.training:
1134
- if use_cache:
1135
- logger.warning_once(
1136
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1137
- )
1138
- use_cache = False
1139
-
1140
- if input_ids is not None and inputs_embeds is not None:
1141
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1142
- elif input_ids is not None:
1143
- batch_size, seq_length = input_ids.shape[:2]
1144
- elif inputs_embeds is not None:
1145
- batch_size, seq_length = inputs_embeds.shape[:2]
1146
- else:
1147
- raise ValueError("You have to specify either input_ids or inputs_embeds")
1148
-
1149
- return_legacy_cache = False
1150
- if (
1151
- use_cache and not isinstance(past_key_values, Cache) and not self.training
1152
- ): # kept for BC (non `Cache` `past_key_values` inputs)
1153
- return_legacy_cache = True
1154
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1155
- logger.warning_once(
1156
- "We detected that you are passing `past_key_values` as a tuple and this is deprecated and will be removed in v4.43. "
1157
- "Please use an appropriate `Cache` class (https://huggingface.co/docs/transformers/v4.41.3/en/internal/generation_utils#transformers.Cache)"
1158
- )
1159
-
1160
- if inputs_embeds is None:
1161
- inputs_embeds = self.wte(input_ids)
1162
-
1163
- if cache_position is None:
1164
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1165
- cache_position = torch.arange(
1166
- past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1167
- )
1168
- if position_ids is None:
1169
- position_ids = cache_position.unsqueeze(0)
1170
-
1171
- causal_mask = self._update_causal_mask(
1172
- attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
1173
- )
1174
-
1175
- hidden_states = inputs_embeds
1176
- hidden_states = self.drop(hidden_states)
1177
-
1178
- position_embeddings = self.rotary(hidden_states, position_ids)
1179
-
1180
- all_hidden_states = () if output_hidden_states else None
1181
- all_self_attns = () if output_attentions else None
1182
- next_decoder_cache = None
1183
-
1184
- for block in self.h:
1185
- if output_hidden_states:
1186
- all_hidden_states = all_hidden_states + (hidden_states,)
1187
-
1188
- if self.gradient_checkpointing and self.training:
1189
- outputs = self._gradient_checkpointing_func(
1190
- block.__call__,
1191
- hidden_states,
1192
- causal_mask,
1193
- position_ids,
1194
- past_key_values,
1195
- output_attentions,
1196
- use_cache,
1197
- cache_position,
1198
- position_embeddings,
1199
- )
1200
- else:
1201
- outputs = block(
1202
- hidden_states,
1203
- attention_mask=causal_mask,
1204
- position_ids=position_ids,
1205
- past_key_value=past_key_values,
1206
- output_attentions=output_attentions,
1207
- use_cache=use_cache,
1208
- cache_position=cache_position,
1209
- position_embeddings=position_embeddings,
1210
- )
1211
-
1212
- hidden_states = outputs[0]
1213
- if use_cache:
1214
- next_decoder_cache = outputs[2 if output_attentions else 1]
1215
-
1216
- if output_attentions:
1217
- all_self_attns += (outputs[1],)
1218
-
1219
- hidden_states = self.ln_f(hidden_states)
1220
- # Add last hidden state
1221
- if output_hidden_states:
1222
- all_hidden_states += (hidden_states,)
1223
-
1224
- next_cache = None
1225
- if use_cache:
1226
- next_cache = next_decoder_cache.to_legacy_cache() if return_legacy_cache else next_decoder_cache
1227
- if not return_dict:
1228
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1229
-
1230
- return BaseModelOutputWithPast(
1231
- last_hidden_state=hidden_states,
1232
- past_key_values=next_cache,
1233
- hidden_states=all_hidden_states,
1234
- attentions=all_self_attns,
1235
- )
1236
-
1237
- # copied from llama
1238
- def _update_causal_mask(
1239
- self,
1240
- attention_mask: torch.Tensor,
1241
- input_tensor: torch.Tensor,
1242
- cache_position: torch.Tensor,
1243
- past_key_values: Cache,
1244
- output_attentions: bool,
1245
- ):
1246
- # TODO: As of torch==2.2.0, the `attention_mask` passed to the model in `generate` is 2D and of dynamic length even when the static
1247
- # KV cache is used. This is an issue for torch.compile which then recaptures cudagraphs at each decode steps due to the dynamic shapes.
1248
- # (`recording cudagraph tree for symint key 13`, etc.), which is VERY slow. A workaround is `@torch.compiler.disable`, but this prevents using
1249
- # `fullgraph=True`. See more context in https://github.com/huggingface/transformers/pull/29114
1250
-
1251
- if self.config._attn_implementation == "flash_attention_2":
1252
- if attention_mask is not None and 0.0 in attention_mask:
1253
- return attention_mask
1254
- return None
1255
-
1256
- # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1257
- # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1258
- # to infer the attention mask.
1259
- past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1260
- using_static_cache = isinstance(past_key_values, StaticCache)
1261
-
1262
- # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1263
- if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1264
- if AttentionMaskConverter._ignore_causal_mask_sdpa(
1265
- attention_mask,
1266
- inputs_embeds=input_tensor,
1267
- past_key_values_length=past_seen_tokens,
1268
- is_training=self.training,
1269
- ):
1270
- return None
1271
-
1272
- dtype, device = input_tensor.dtype, input_tensor.device
1273
- min_dtype = torch.finfo(dtype).min
1274
- sequence_length = input_tensor.shape[1]
1275
- if using_static_cache:
1276
- target_length = past_key_values.get_max_length()
1277
- else:
1278
- target_length = (
1279
- attention_mask.shape[-1]
1280
- if isinstance(attention_mask, torch.Tensor)
1281
- else past_seen_tokens + sequence_length + 1
1282
- )
1283
-
1284
- # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1285
- causal_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1286
- attention_mask,
1287
- sequence_length=sequence_length,
1288
- target_length=target_length,
1289
- dtype=dtype,
1290
- device=device,
1291
- min_dtype=min_dtype,
1292
- cache_position=cache_position,
1293
- batch_size=input_tensor.shape[0],
1294
- )
1295
-
1296
- if (
1297
- self.config._attn_implementation == "sdpa"
1298
- and attention_mask is not None
1299
- and attention_mask.device.type == "cuda"
1300
- and not output_attentions
1301
- ):
1302
- # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1303
- # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1304
- # Details: https://github.com/pytorch/pytorch/issues/110213
1305
- causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1306
-
1307
- return causal_mask
1308
-
1309
-
1310
- @add_start_docstrings(
1311
- """
1312
- The EXAONE Model transformer with a language modeling head on top (linear layer with weights tied to the input
1313
- embeddings).
1314
- """,
1315
- EXAONE_START_DOCSTRING,
1316
- )
1317
- class ExaoneForCausalLM(ExaonePreTrainedModel):
1318
- def __init__(self, config):
1319
- super().__init__(config)
1320
- self.transformer = ExaoneModel(config)
1321
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1322
- self.config = config
1323
- # Initialize weights and apply final processing
1324
- self.post_init()
1325
-
1326
- def get_output_embeddings(self):
1327
- return self.lm_head
1328
-
1329
- def set_output_embeddings(self, new_embeddings):
1330
- self.lm_head = new_embeddings
1331
-
1332
- @add_start_docstrings_to_model_forward(EXAONE_INPUTS_DOCSTRING)
1333
- @add_code_sample_docstrings(
1334
- checkpoint=_CHECKPOINT_FOR_DOC,
1335
- output_type=BaseModelOutputWithPast,
1336
- config_class=_CONFIG_FOR_DOC,
1337
- )
1338
- def forward(
1339
- self,
1340
- input_ids: Optional[torch.Tensor] = None,
1341
- attention_mask: Optional[torch.Tensor] = None,
1342
- position_ids: Optional[torch.Tensor] = None,
1343
- past_key_values: Optional[Cache] = None,
1344
- inputs_embeds: Optional[torch.Tensor] = None,
1345
- labels: Optional[torch.Tensor] = None,
1346
- use_cache: Optional[bool] = None,
1347
- output_attentions: Optional[bool] = None,
1348
- output_hidden_states: Optional[bool] = None,
1349
- return_dict: Optional[bool] = None,
1350
- cache_position: Optional[torch.LongTensor] = None,
1351
- ) -> Union[Tuple[torch.Tensor], BaseModelOutputWithPast]:
1352
- r"""
1353
- Args:
1354
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1355
- Labels for language modeling. Note that the labels **are shifted** inside the model, i.e. you can set
1356
- `labels = input_ids` Indices are selected in `[-100, 0, ..., config.vocab_size]` All labels set to `-100`
1357
- are ignored (masked), the loss is only computed for labels in `[0, ..., config.vocab_size]`
1358
- Example:
1359
- ```python
1360
- >>> from transformers import AutoModelForCausalLM, AutoTokenizer
1361
- >>> model = AutoModelForCausalLM.from_pretrained("LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct",
1362
- trust_remote_code=True)
1363
- >>> tokenizer = AutoTokenizer.from_pretrained("LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct")
1364
- >>> prompt = "Explain how wonderful you are"
1365
- >>> messages = [
1366
- {"role": "system", "content": "You are a helpful assistant."},
1367
- {"role": "user", "content": prompt}
1368
- ]
1369
- >>> input_ids = tokenizer.apply_chat_template(
1370
- messages,
1371
- tokenize=True,
1372
- add_generation_prompt=True,
1373
- return_tensors="pt"
1374
- )
1375
- >>> output = model.generate(input_ids, max_new_tokens=128)
1376
- >>> tokenizer.decode(output[0], skip_special_tokens=True)
1377
- "[|system|]You are a helpful assistant.\n[|user|]Explain how wonderful you are\n[|assistant|]Thank you for your kind words! I'm here to assist you with information, answer questions, and help you in any way I can. My goal is to provide accurate, helpful, and timely responses. Whether you need help with a specific task, want to learn something new, or just need someone to talk to, I'm here for you. How can I assist you today?"
1378
- ```
1379
- """
1380
-
1381
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1382
- output_hidden_states = (
1383
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1384
- )
1385
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1386
- transformer_outputs = self.transformer(
1387
- input_ids,
1388
- attention_mask=attention_mask,
1389
- past_key_values=past_key_values,
1390
- position_ids=position_ids,
1391
- inputs_embeds=inputs_embeds,
1392
- use_cache=use_cache,
1393
- output_attentions=output_attentions,
1394
- output_hidden_states=output_hidden_states,
1395
- return_dict=return_dict,
1396
- cache_position=cache_position,
1397
- )
1398
- hidden_states = transformer_outputs[0]
1399
- lm_logits = self.lm_head(hidden_states)
1400
- lm_logits = lm_logits.float()
1401
- loss = None
1402
- if labels is not None:
1403
- lm_logits = lm_logits.to(torch.float32)
1404
-
1405
- # Shift so that tokens < n predict n
1406
- shift_logits = lm_logits[..., :-1, :].contiguous()
1407
- shift_labels = labels[..., 1:].contiguous()
1408
- # Flatten the tokens
1409
- loss_fct = CrossEntropyLoss()
1410
- loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1411
-
1412
- lm_logits = lm_logits.to(hidden_states.dtype)
1413
- loss = loss.to(hidden_states.dtype)
1414
-
1415
- if not return_dict:
1416
- output = (lm_logits,) + transformer_outputs[1:]
1417
- return ((loss,) + output) if loss is not None else output
1418
-
1419
- return CausalLMOutputWithPast(
1420
- loss=loss,
1421
- logits=lm_logits,
1422
- past_key_values=transformer_outputs.past_key_values,
1423
- hidden_states=transformer_outputs.hidden_states,
1424
- attentions=transformer_outputs.attentions,
1425
- )
1426
-
1427
- def prepare_inputs_for_generation(
1428
- self,
1429
- input_ids,
1430
- past_key_values=None,
1431
- attention_mask=None,
1432
- inputs_embeds=None,
1433
- cache_position=None,
1434
- position_ids=None,
1435
- use_cache=True,
1436
- **kwargs,
1437
- ):
1438
- # If we have cache: let's slice `input_ids` through `cache_position`, to keep only the unprocessed tokens
1439
- # Exception 1: when passing input_embeds, input_ids may be missing entries
1440
- # Exception 2: some generation methods do special slicing of input_ids, so we don't need to do it here
1441
- if past_key_values is not None:
1442
- if inputs_embeds is not None: # Exception 1
1443
- input_ids = input_ids[:, -cache_position.shape[0] :]
1444
- elif input_ids.shape[1] != cache_position.shape[0]: # Default case (the "else", a no op, is Exception 2)
1445
- input_ids = input_ids[:, cache_position]
1446
-
1447
- if attention_mask is not None and position_ids is None:
1448
- # create position_ids on the fly for batch generation
1449
- position_ids = attention_mask.long().cumsum(-1) - 1
1450
- position_ids.masked_fill_(attention_mask == 0, 1)
1451
- if past_key_values:
1452
- position_ids = position_ids[:, -input_ids.shape[1] :]
1453
-
1454
- # This `clone` call is needed to avoid recapturing cuda graphs with `torch.compile`'s `mode="reduce-overhead`, as otherwise the input `position_ids` would have various stride during the decoding. Here, simply using `.contiguous()` is not sufficient as in the batch size = 1 case, `position_ids` is already contiguous but with varying stride which retriggers a capture.
1455
- position_ids = position_ids.clone(memory_format=torch.contiguous_format)
1456
-
1457
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1458
- if inputs_embeds is not None and cache_position[0] == 0:
1459
- model_inputs = {"inputs_embeds": inputs_embeds}
1460
- else:
1461
- model_inputs = {"input_ids": input_ids}
1462
-
1463
- if isinstance(past_key_values, StaticCache) and attention_mask.ndim == 2:
1464
- if inputs_embeds is not None:
1465
- batch_size, sequence_length = inputs_embeds.shape
1466
- device = inputs_embeds.device
1467
- else:
1468
- batch_size, sequence_length = input_ids.shape
1469
- device = input_ids.device
1470
-
1471
- dtype = self.lm_head.weight.dtype
1472
- min_dtype = torch.finfo(dtype).min
1473
-
1474
- attention_mask = _prepare_4d_causal_attention_mask_with_cache_position(
1475
- attention_mask,
1476
- sequence_length=sequence_length,
1477
- target_length=past_key_values.get_max_length(),
1478
- dtype=dtype,
1479
- device=device,
1480
- min_dtype=min_dtype,
1481
- cache_position=cache_position,
1482
- batch_size=batch_size,
1483
- )
1484
-
1485
- model_inputs.update(
1486
- {
1487
- "position_ids": position_ids,
1488
- "cache_position": cache_position,
1489
- "past_key_values": past_key_values,
1490
- "use_cache": use_cache,
1491
- "attention_mask": attention_mask,
1492
- }
1493
- )
1494
- return model_inputs
1495
-
1496
- @staticmethod
1497
- def _reorder_cache(past_key_values, beam_idx):
1498
- reordered_past = ()
1499
- for layer_past in past_key_values:
1500
- reordered_past += (
1501
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1502
- )
1503
- return reordered_past
1504
-
1505
-
1506
- @add_start_docstrings(
1507
- """
1508
- The EXAONE Model transformer with a sequence classification head on top (linear layer).
1509
- :class:`~transformers.ExaoneForSequenceClassification` uses the last token in order to do the classification, as
1510
- other causal models (e.g. GPT-1) do.
1511
- Since it does classification on the last token, it requires to know the position of the last token. If a
1512
- :obj:`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each
1513
- row. If no :obj:`pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
1514
- guess the padding tokens when :obj:`inputs_embeds` are passed instead of :obj:`input_ids`, it does the same (take
1515
- the last value in each row of the batch).
1516
- """,
1517
- EXAONE_START_DOCSTRING,
1518
- )
1519
- class ExaoneForSequenceClassification(ExaonePreTrainedModel):
1520
- _keys_to_ignore_on_load_missing = ["lm_head.weight"]
1521
-
1522
- def __init__(self, config):
1523
- super().__init__(config)
1524
- self.num_labels = config.num_labels
1525
- self.transformer = ExaoneModel(config)
1526
- self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1527
-
1528
- # Initialize weights and apply final processing
1529
- self.post_init()
1530
-
1531
- @add_start_docstrings_to_model_forward(EXAONE_INPUTS_DOCSTRING)
1532
- @add_code_sample_docstrings(
1533
- checkpoint=_CHECKPOINT_FOR_DOC,
1534
- output_type=SequenceClassifierOutputWithPast,
1535
- config_class=_CONFIG_FOR_DOC,
1536
- )
1537
- def forward(
1538
- self,
1539
- input_ids: Optional[torch.Tensor] = None,
1540
- attention_mask: Optional[torch.Tensor] = None,
1541
- position_ids: Optional[torch.Tensor] = None,
1542
- past_key_values: Optional[Cache] = None,
1543
- inputs_embeds: Optional[torch.Tensor] = None,
1544
- labels: Optional[torch.Tensor] = None,
1545
- use_cache: Optional[bool] = None,
1546
- output_attentions: Optional[bool] = None,
1547
- output_hidden_states: Optional[bool] = None,
1548
- return_dict: Optional[bool] = None,
1549
- ) -> Union[Tuple[torch.Tensor], SequenceClassifierOutputWithPast]:
1550
- r"""
1551
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1552
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1553
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1554
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1555
- """
1556
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1557
-
1558
- transformer_outputs = self.transformer(
1559
- input_ids,
1560
- attention_mask=attention_mask,
1561
- position_ids=position_ids,
1562
- past_key_values=past_key_values,
1563
- inputs_embeds=inputs_embeds,
1564
- use_cache=use_cache,
1565
- output_attentions=output_attentions,
1566
- output_hidden_states=output_hidden_states,
1567
- return_dict=return_dict,
1568
- )
1569
- hidden_states = transformer_outputs[0]
1570
- logits = self.score(hidden_states)
1571
-
1572
- if input_ids is not None:
1573
- batch_size, sequence_length = input_ids.shape[:2]
1574
- else:
1575
- batch_size, sequence_length = inputs_embeds.shape[:2]
1576
-
1577
- if self.config.pad_token_id is None and batch_size != 1:
1578
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1579
- if self.config.pad_token_id is None:
1580
- sequence_lengths = -1
1581
- else:
1582
- if input_ids is not None:
1583
- # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1584
- sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1585
- sequence_lengths = sequence_lengths % input_ids.shape[-1]
1586
- sequence_lengths = sequence_lengths.to(logits.device)
1587
- else:
1588
- sequence_lengths = -1
1589
- logger.warning(
1590
- f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1591
- "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1592
- )
1593
-
1594
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1595
-
1596
- loss = None
1597
- if labels is not None:
1598
- labels = labels.to(logits.device)
1599
- if self.config.problem_type is None:
1600
- if self.num_labels == 1:
1601
- self.config.problem_type = "regression"
1602
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1603
- self.config.problem_type = "single_label_classification"
1604
- else:
1605
- self.config.problem_type = "multi_label_classification"
1606
-
1607
- if self.config.problem_type == "regression":
1608
- loss_fct = MSELoss()
1609
- if self.num_labels == 1:
1610
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1611
- else:
1612
- loss = loss_fct(pooled_logits, labels)
1613
- elif self.config.problem_type == "single_label_classification":
1614
- loss_fct = CrossEntropyLoss()
1615
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1616
- elif self.config.problem_type == "multi_label_classification":
1617
- loss_fct = BCEWithLogitsLoss()
1618
- loss = loss_fct(pooled_logits, labels)
1619
- if not return_dict:
1620
- output = (pooled_logits,) + transformer_outputs[1:]
1621
- return ((loss,) + output) if loss is not None else output
1622
-
1623
- return SequenceClassifierOutputWithPast(
1624
- loss=loss,
1625
- logits=pooled_logits,
1626
- past_key_values=transformer_outputs.past_key_values,
1627
- hidden_states=transformer_outputs.hidden_states,
1628
- attentions=transformer_outputs.attentions,
1629
- )
1630
-
1631
-
1632
- @add_start_docstrings(
1633
- """
1634
- The EXAONE Model transformer with a span classification head on top for extractive question-answering tasks like
1635
- SQuAD (a linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
1636
- """,
1637
- EXAONE_START_DOCSTRING,
1638
- )
1639
- class ExaoneForQuestionAnswering(ExaonePreTrainedModel):
1640
- _keys_to_ignore_on_load_missing = ["lm_head.weight"]
1641
-
1642
- def __init__(self, config):
1643
- super().__init__(config)
1644
- self.num_labels = config.num_labels
1645
- self.transformer = ExaoneModel(config)
1646
- self.qa_outputs = nn.Linear(config.hidden_size, config.num_labels)
1647
-
1648
- # Model parallel
1649
- self.model_parallel = False
1650
- self.device_map = None
1651
-
1652
- # Initialize weights and apply final processing
1653
- self.post_init()
1654
-
1655
- def forward(
1656
- self,
1657
- input_ids: Optional[torch.LongTensor] = None,
1658
- attention_mask: Optional[torch.FloatTensor] = None,
1659
- position_ids: Optional[torch.LongTensor] = None,
1660
- past_key_values: Optional[Cache] = None,
1661
- inputs_embeds: Optional[torch.FloatTensor] = None,
1662
- start_positions: Optional[torch.LongTensor] = None,
1663
- end_positions: Optional[torch.LongTensor] = None,
1664
- output_attentions: Optional[bool] = None,
1665
- output_hidden_states: Optional[bool] = None,
1666
- return_dict: Optional[bool] = None,
1667
- ) -> Union[Tuple[torch.Tensor], QuestionAnsweringModelOutput]:
1668
- r"""
1669
- start_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
1670
- Labels for position (index) of the start of the labelled span for computing the token classification loss.
1671
- Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
1672
- sequence are not taken into account for computing the loss.
1673
- end_positions (:obj:`torch.LongTensor` of shape :obj:`(batch_size,)`, `optional`):
1674
- Labels for position (index) of the end of the labelled span for computing the token classification loss.
1675
- Positions are clamped to the length of the sequence (:obj:`sequence_length`). Position outside of the
1676
- sequence are not taken into account for computing the loss.
1677
- """
1678
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1679
-
1680
- outputs = self.transformer(
1681
- input_ids,
1682
- attention_mask=attention_mask,
1683
- position_ids=position_ids,
1684
- past_key_values=past_key_values,
1685
- inputs_embeds=inputs_embeds,
1686
- output_attentions=output_attentions,
1687
- output_hidden_states=output_hidden_states,
1688
- return_dict=return_dict,
1689
- )
1690
-
1691
- sequence_output = outputs[0]
1692
-
1693
- logits = self.qa_outputs(sequence_output)
1694
- start_logits, end_logits = logits.split(1, dim=-1)
1695
- start_logits = start_logits.squeeze(-1).contiguous()
1696
- end_logits = end_logits.squeeze(-1).contiguous()
1697
-
1698
- total_loss = None
1699
- if start_positions is not None and end_positions is not None:
1700
- # If we are on multi-GPU, split add a dimension
1701
- if len(start_positions.size()) > 1:
1702
- start_positions = start_positions.squeeze(-1).to(start_logits.device)
1703
- if len(end_positions.size()) > 1:
1704
- end_positions = end_positions.squeeze(-1).to(end_logits.device)
1705
- # sometimes the start/end positions are outside our model inputs, we ignore these terms
1706
- ignored_index = start_logits.size(1)
1707
- start_positions = start_positions.clamp(0, ignored_index)
1708
- end_positions = end_positions.clamp(0, ignored_index)
1709
-
1710
- loss_fct = CrossEntropyLoss(ignore_index=ignored_index)
1711
- start_loss = loss_fct(start_logits, start_positions)
1712
- end_loss = loss_fct(end_logits, end_positions)
1713
- total_loss = (start_loss + end_loss) / 2
1714
-
1715
- if not return_dict:
1716
- output = (start_logits, end_logits) + outputs[2:]
1717
- return ((total_loss,) + output) if total_loss is not None else output
1718
-
1719
- return QuestionAnsweringModelOutput(
1720
- loss=total_loss,
1721
- start_logits=start_logits,
1722
- end_logits=end_logits,
1723
- hidden_states=outputs.hidden_states,
1724
- attentions=outputs.attentions,
1725
- )