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,1469 +0,0 @@
1
- # coding=utf-8
2
- # Copyright (c) 2018, NVIDIA CORPORATION. All rights reserved.
3
- #
4
- # Licensed under the Apache License, Version 2.0 (the "License");
5
- # you may not use this file except in compliance with the License.
6
- # You may obtain a copy of the License at
7
- #
8
- # http://www.apache.org/licenses/LICENSE-2.0
9
- #
10
- # Unless required by applicable law or agreed to in writing, software
11
- # distributed under the License is distributed on an "AS IS" BASIS,
12
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
- # See the License for the specific language governing permissions and
14
- # limitations under the License.
15
- """PyTorch Midm model."""
16
-
17
- import math
18
- from dataclasses import dataclass
19
- from typing import List, Optional, Tuple
20
-
21
- import torch
22
- import torch.utils.checkpoint
23
- from packaging import version
24
- from torch import nn
25
- from torch.nn import CrossEntropyLoss, MSELoss
26
-
27
- from .rotary_position_embedding import RotaryEmbedding, apply_rotary_pos_emb
28
-
29
-
30
- if version.parse(torch.__version__) >= version.parse("1.6"):
31
- is_amp_available = True
32
- from torch.cuda.amp import autocast
33
- else:
34
- is_amp_available = False
35
-
36
- from transformers.activations import ACT2FN
37
- from transformers.file_utils import (
38
- ModelOutput,
39
- add_code_sample_docstrings,
40
- add_start_docstrings,
41
- add_start_docstrings_to_model_forward,
42
- )
43
- from transformers.modeling_outputs import (
44
- BaseModelOutputWithPastAndCrossAttentions,
45
- CausalLMOutputWithCrossAttentions,
46
- SequenceClassifierOutputWithPast,
47
- TokenClassifierOutput,
48
- )
49
- from transformers.modeling_utils import (
50
- Conv1D,
51
- PreTrainedModel,
52
- SequenceSummary,
53
- find_pruneable_heads_and_indices,
54
- prune_conv1d_layer,
55
- )
56
- from transformers.utils import logging
57
- from transformers.utils.model_parallel_utils import assert_device_map, get_device_map
58
-
59
- from .configuration_midm import MidmBitextConfig
60
-
61
-
62
- logger = logging.get_logger(__name__)
63
-
64
- _CHECKPOINT_FOR_DOC = "Midm"
65
- _CONFIG_FOR_DOC = "MidmBitextConfig"
66
- _TOKENIZER_FOR_DOC = "Midm_bitext_Tokenizer"
67
-
68
- MIDM_PRETRAINED_MODEL_ARCHIVE_LIST = [
69
- "Midm-bitext-S",
70
- ]
71
-
72
-
73
- def layernorm1p(module, input):
74
- return torch.nn.functional.layer_norm(input, module.normalized_shape, module.weight + 1, module.bias, module.eps)
75
-
76
-
77
- class MidmAttention(nn.Module):
78
- def __init__(self, config, is_cross_attention=False, layer_idx=None):
79
- super().__init__()
80
-
81
- max_positions = config.max_position_embeddings
82
- self.register_buffer(
83
- "bias",
84
- torch.tril(torch.ones((max_positions, max_positions), dtype=torch.uint8)).view(
85
- 1, 1, max_positions, max_positions
86
- ),
87
- )
88
- self.register_buffer("masked_bias", torch.tensor(-1e4))
89
-
90
- self.embed_dim = config.hidden_size
91
- self.num_heads = config.num_attention_heads
92
- self.head_dim = self.embed_dim // self.num_heads
93
- self.split_size = self.embed_dim
94
- if self.head_dim * self.num_heads != self.embed_dim:
95
- raise ValueError(
96
- f"`embed_dim` must be divisible by num_heads (got `embed_dim`: {self.embed_dim} and `num_heads`: {self.num_heads})."
97
- )
98
-
99
- self.scale_attn_weights = config.scale_attn_weights
100
- self.is_cross_attention = is_cross_attention
101
-
102
- # Layer-wise attention scaling, reordering, and upcasting
103
- self.scale_attn_by_inverse_layer_idx = config.scale_attn_by_inverse_layer_idx
104
- self.layer_idx = layer_idx
105
- self.reorder_and_upcast_attn = config.reorder_and_upcast_attn
106
- self.scale_qk_by_inverse_layer_idx = config.scale_qk_by_inverse_layer_idx
107
- assert self.scale_attn_by_inverse_layer_idx != self.scale_qk_by_inverse_layer_idx
108
-
109
- if self.is_cross_attention:
110
- self.c_attn = nn.Linear(self.embed_dim, 2 * self.embed_dim, bias=False)
111
- nn.init.normal_(self.c_attn.weight, std=0.02)
112
- self.q_attn = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
113
- nn.init.normal_(self.q_attn.weight, std=0.02)
114
- else:
115
- self.c_attn = nn.Linear(self.embed_dim, 3 * self.embed_dim, bias=False)
116
- nn.init.normal_(self.c_attn.weight, std=0.02)
117
- self.c_proj = nn.Linear(self.embed_dim, self.embed_dim, bias=False)
118
- nn.init.normal_(self.c_proj.weight, std=0.02)
119
-
120
- self.attn_dropout = nn.Dropout(config.attn_pdrop)
121
- self.resid_dropout = nn.Dropout(config.resid_pdrop)
122
-
123
- self.pruned_heads = set()
124
-
125
- def prune_heads(self, heads):
126
- if len(heads) == 0:
127
- return
128
- heads, index = find_pruneable_heads_and_indices(heads, self.num_heads, self.head_dim, self.pruned_heads)
129
- index_attn = torch.cat([index, index + self.split_size, index + (2 * self.split_size)])
130
-
131
- # Prune conv1d layers
132
- self.c_attn = prune_conv1d_layer(self.c_attn, index_attn, dim=1)
133
- self.c_proj = prune_conv1d_layer(self.c_proj, index, dim=0)
134
-
135
- # Update hyper params
136
- self.split_size = (self.split_size // self.num_heads) * (self.num_heads - len(heads))
137
- self.num_heads = self.num_heads - len(heads)
138
- self.pruned_heads = self.pruned_heads.union(heads)
139
-
140
- def _attn(self, query, key, value, attention_mask=None, head_mask=None):
141
- attn_weights = torch.matmul(query, key.transpose(-1, -2))
142
-
143
- if self.scale_attn_weights:
144
- attn_weights = attn_weights / (float(value.size(-1)) ** 0.5)
145
-
146
- # Layer-wise attention scaling
147
- if self.scale_attn_by_inverse_layer_idx or self.scale_qk_by_inverse_layer_idx:
148
- attn_weights = attn_weights / float(self.layer_idx + 1)
149
-
150
- if not self.is_cross_attention:
151
- # if only "normal" attention layer implements causal mask
152
- query_length, key_length = query.size(-2), key.size(-2)
153
- causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
154
- attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
155
-
156
- if attention_mask is not None:
157
- # Apply the attention mask
158
- attn_weights = attn_weights + attention_mask
159
-
160
- if self.scale_qk_by_inverse_layer_idx:
161
- attn_weights = attn_weights * float(self.layer_idx + 1)
162
-
163
- attn_weights = nn.Softmax(dim=-1)(attn_weights)
164
-
165
- # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op otherwise
166
- attn_weights = attn_weights.type(value.dtype)
167
- attn_weights = self.attn_dropout(attn_weights)
168
-
169
- # Mask heads if we want to
170
- if head_mask is not None:
171
- attn_weights = attn_weights * head_mask
172
-
173
- attn_output = torch.matmul(attn_weights, value)
174
-
175
- return attn_output, attn_weights
176
-
177
- def _upcast_and_reordered_attn(self, query, key, value, attention_mask=None, head_mask=None):
178
- # Use `torch.baddbmm` (a bit more efficient w/ alpha param for scaling -- from Megatron-LM)
179
- bsz, num_heads, q_seq_len, dk = query.size()
180
- _, _, k_seq_len, _ = key.size()
181
-
182
- # Preallocate attn_weights for `baddbmm`
183
- attn_weights = torch.empty(bsz * num_heads, q_seq_len, k_seq_len, dtype=torch.float32, device=query.device)
184
-
185
- # Compute Scale Factor
186
- scale_factor = 1.0
187
- if self.scale_attn_weights:
188
- scale_factor /= float(value.size(-1)) ** 0.5
189
-
190
- if self.scale_attn_by_inverse_layer_idx:
191
- scale_factor /= float(self.layer_idx + 1)
192
-
193
- # Upcast (turn off autocast) and reorder (Scale K by 1 / root(dk))
194
- if is_amp_available:
195
- with autocast(enabled=False):
196
- q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
197
- attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
198
- attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
199
- else:
200
- q, k = query.reshape(-1, q_seq_len, dk), key.transpose(-1, -2).reshape(-1, dk, k_seq_len)
201
- attn_weights = torch.baddbmm(attn_weights, q.float(), k.float(), beta=0, alpha=scale_factor)
202
- attn_weights = attn_weights.reshape(bsz, num_heads, q_seq_len, k_seq_len)
203
-
204
- if not self.is_cross_attention:
205
- # if only "normal" attention layer implements causal mask
206
- query_length, key_length = query.size(-2), key.size(-2)
207
- causal_mask = self.bias[:, :, key_length - query_length : key_length, :key_length].bool()
208
- attn_weights = torch.where(causal_mask, attn_weights, self.masked_bias.to(attn_weights.dtype))
209
-
210
- if attention_mask is not None:
211
- # Apply the attention mask
212
- attn_weights = attn_weights + attention_mask
213
-
214
- attn_weights = nn.Softmax(dim=-1)(attn_weights)
215
-
216
- # Downcast (if necessary) back to V's dtype (if in mixed-precision) -- No-Op if otherwise
217
- if attn_weights.dtype != torch.float32:
218
- raise RuntimeError("Error with upcasting, attn_weights does not have dtype torch.float32")
219
- attn_weights = attn_weights.type(value.dtype)
220
- attn_weights = self.attn_dropout(attn_weights)
221
-
222
- # Mask heads if we want to
223
- if head_mask is not None:
224
- attn_weights = attn_weights * head_mask
225
-
226
- attn_output = torch.matmul(attn_weights, value)
227
-
228
- return attn_output, attn_weights
229
-
230
- def _split_heads(self, tensor, num_heads, attn_head_size):
231
- """
232
- Splits hidden_size dim into attn_head_size and num_heads
233
- """
234
- new_shape = tensor.size()[:-1] + (num_heads, attn_head_size)
235
- tensor = tensor.view(*new_shape)
236
- return tensor.permute(0, 2, 1, 3) # (batch, head, seq_length, head_features)
237
-
238
- def _merge_heads(self, tensor, num_heads, attn_head_size):
239
- """
240
- Merges attn_head_size dim and num_attn_heads dim into hidden_size
241
- """
242
- tensor = tensor.permute(0, 2, 1, 3).contiguous()
243
- new_shape = tensor.size()[:-2] + (num_heads * attn_head_size,)
244
- return tensor.view(new_shape)
245
-
246
- def forward(
247
- self,
248
- hidden_states,
249
- layer_past=None,
250
- attention_mask=None,
251
- head_mask=None,
252
- encoder_hidden_states=None,
253
- encoder_attention_mask=None,
254
- use_cache=False,
255
- output_attentions=False,
256
- rotary_pos_emb=None,
257
- ):
258
- if encoder_hidden_states is not None:
259
- if not hasattr(self, "q_attn"):
260
- raise ValueError(
261
- "If class is used as cross attention, the weights `q_attn` have to be defined. "
262
- "Please make sure to instantiate class with `MidmAttention(..., is_cross_attention=True)`."
263
- )
264
-
265
- query = self.q_attn(hidden_states)
266
- key, value = self.c_attn(encoder_hidden_states).split(self.split_size, dim=2)
267
- attention_mask = encoder_attention_mask
268
- else:
269
- query, key, value = self.c_attn(hidden_states).split(self.split_size, dim=2)
270
-
271
- query = self._split_heads(query, self.num_heads, self.head_dim)
272
- key = self._split_heads(key, self.num_heads, self.head_dim)
273
- value = self._split_heads(value, self.num_heads, self.head_dim)
274
-
275
- if layer_past is not None:
276
- past_key, past_value = layer_past
277
- key = torch.cat((past_key, key), dim=-2)
278
- value = torch.cat((past_value, value), dim=-2)
279
-
280
- if use_cache is True:
281
- present = (key, value)
282
- else:
283
- present = None
284
-
285
- if rotary_pos_emb is not None:
286
- query = apply_rotary_pos_emb(query, rotary_pos_emb)
287
- key = apply_rotary_pos_emb(key, rotary_pos_emb)
288
-
289
- if self.reorder_and_upcast_attn:
290
- attn_output, attn_weights = self._upcast_and_reordered_attn(query, key, value, attention_mask, head_mask)
291
- else:
292
- attn_output, attn_weights = self._attn(query, key, value, attention_mask, head_mask)
293
-
294
- attn_output = self._merge_heads(attn_output, self.num_heads, self.head_dim)
295
- attn_output = self.c_proj(attn_output)
296
- attn_output = self.resid_dropout(attn_output)
297
-
298
- outputs = (attn_output, present)
299
- if output_attentions:
300
- outputs += (attn_weights,)
301
-
302
- return outputs # a, present, (attentions)
303
-
304
-
305
- class MidmMLP(nn.Module):
306
- def __init__(self, intermediate_size, config):
307
- super().__init__()
308
- embed_dim = config.hidden_size
309
- self.kt_glu = config.activation_function in ["silu"]
310
- if self.kt_glu:
311
- self.c_fc = nn.Linear(embed_dim, intermediate_size * 2, bias=False)
312
- else:
313
- self.c_fc = nn.Linear(embed_dim, intermediate_size, bias=False)
314
- nn.init.normal_(self.c_fc.weight, std=0.02)
315
- self.c_proj = nn.Linear(intermediate_size, embed_dim, bias=False)
316
- nn.init.normal_(self.c_proj.weight, std=0.02)
317
-
318
- if config.activation_function == "silu":
319
- self.act = torch.nn.functional.silu
320
- else:
321
- self.act = ACT2FN[config.activation_function]
322
- self.dropout = nn.Dropout(config.resid_pdrop)
323
-
324
- def forward(self, hidden_states):
325
- hidden_states = self.c_fc(hidden_states)
326
- if self.kt_glu:
327
- hidden_states1, hidden_states2 = torch.chunk(hidden_states, 2, dim=-1)
328
- hidden_states = self.act(hidden_states1) * hidden_states2
329
- else:
330
- hidden_states = self.act(hidden_states)
331
- hidden_states = self.c_proj(hidden_states)
332
- hidden_states = self.dropout(hidden_states)
333
- return hidden_states
334
-
335
-
336
- class MidmBlock(nn.Module):
337
- def __init__(self, config, layer_idx=None):
338
- super().__init__()
339
- hidden_size = config.hidden_size
340
- inner_dim = config.n_inner if config.n_inner is not None else 4 * hidden_size
341
-
342
- self.ln_1 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
343
- self.attn = MidmAttention(config, layer_idx=layer_idx)
344
- self.ln_2 = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
345
- self.use_layernorm1p = config.normalization_type == "layernorm1p"
346
-
347
- if config.add_cross_attention:
348
- self.crossattention = MidmAttention(config, is_cross_attention=True)
349
- self.ln_cross_attn = nn.LayerNorm(hidden_size, eps=config.layer_norm_epsilon)
350
-
351
- self.mlp = MidmMLP(inner_dim, config)
352
-
353
- def forward(
354
- self,
355
- hidden_states,
356
- layer_past=None,
357
- attention_mask=None,
358
- head_mask=None,
359
- encoder_hidden_states=None,
360
- encoder_attention_mask=None,
361
- use_cache=False,
362
- output_attentions=False,
363
- rotary_pos_emb=None,
364
- ):
365
- residual = hidden_states
366
- if self.use_layernorm1p:
367
- hidden_states = layernorm1p(self.ln_1, hidden_states)
368
- else:
369
- hidden_states = self.ln_1(hidden_states)
370
- attn_outputs = self.attn(
371
- hidden_states,
372
- layer_past=layer_past,
373
- attention_mask=attention_mask,
374
- head_mask=head_mask,
375
- use_cache=use_cache,
376
- output_attentions=output_attentions,
377
- rotary_pos_emb=rotary_pos_emb,
378
- )
379
- attn_output = attn_outputs[0] # output_attn: a, present, (attentions)
380
- outputs = attn_outputs[1:]
381
- # residual connection
382
- hidden_states = attn_output + residual
383
-
384
- if encoder_hidden_states is not None:
385
- # add one self-attention block for cross-attention
386
- if not hasattr(self, "crossattention"):
387
- raise ValueError(
388
- f"If `encoder_hidden_states` are passed, {self} has to be instantiated with "
389
- "cross-attention layers by setting `config.add_cross_attention=True`"
390
- )
391
- residual = hidden_states
392
- if self.use_layernorm1p:
393
- hidden_states = layernorm1p(self.ln_cross_attn, hidden_states)
394
- else:
395
- hidden_states = self.ln_cross_attn(hidden_states)
396
- cross_attn_outputs = self.crossattention(
397
- hidden_states,
398
- attention_mask=attention_mask,
399
- head_mask=head_mask,
400
- encoder_hidden_states=encoder_hidden_states,
401
- encoder_attention_mask=encoder_attention_mask,
402
- output_attentions=output_attentions,
403
- )
404
- attn_output = cross_attn_outputs[0]
405
- # residual connection
406
- hidden_states = residual + attn_output
407
- outputs = outputs + cross_attn_outputs[2:] # add cross attentions if we output attention weights
408
-
409
- residual = hidden_states
410
- if self.use_layernorm1p:
411
- hidden_states = layernorm1p(self.ln_2, hidden_states)
412
- else:
413
- hidden_states = self.ln_2(hidden_states)
414
- feed_forward_hidden_states = self.mlp(hidden_states)
415
- # residual connection
416
- hidden_states = residual + feed_forward_hidden_states
417
-
418
- if use_cache:
419
- outputs = (hidden_states,) + outputs
420
- else:
421
- outputs = (hidden_states,) + outputs[1:]
422
-
423
- return outputs # hidden_states, present, (attentions, cross_attentions)
424
-
425
-
426
- class MidmPreTrainedModel(PreTrainedModel):
427
- """
428
- An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
429
- models.
430
- """
431
-
432
- config_class = MidmBitextConfig
433
- base_model_prefix = "transformer"
434
- is_parallelizable = True
435
- supports_gradient_checkpointing = True
436
- _no_split_modules = ["MidmBlock"]
437
-
438
- def __init__(self, *inputs, **kwargs):
439
- super().__init__(*inputs, **kwargs)
440
-
441
- def _init_weights(self, module):
442
- """Initialize the weights."""
443
- if isinstance(module, (nn.Linear, Conv1D)):
444
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
445
- if module.bias is not None:
446
- module.bias.data.zero_()
447
- elif isinstance(module, nn.Embedding):
448
- module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
449
- if module.padding_idx is not None:
450
- module.weight.data[module.padding_idx].zero_()
451
- elif isinstance(module, nn.LayerNorm):
452
- module.bias.data.zero_()
453
- module.weight.data.fill_(1.0)
454
-
455
- for name, p in module.named_parameters():
456
- if "c_proj" in name and "weight" in name:
457
- # Special Scaled Initialization --> There are 2 Layer Norms per Transformer Block
458
- p.data.normal_(mean=0.0, std=(self.config.initializer_range / math.sqrt(2 * self.config.n_layer)))
459
-
460
- def _set_gradient_checkpointing(self, module, value=False):
461
- if isinstance(module, MidmModel):
462
- module.gradient_checkpointing = value
463
-
464
- def make_tensors_contiguous(self):
465
- for name, param in self.named_parameters():
466
- if not param.is_contiguous():
467
- param.data = param.data.contiguous()
468
-
469
- def save_pretrained(self, save_directory, **kwargs):
470
- # Make tensors contiguous
471
- self.make_tensors_contiguous()
472
-
473
- # Call the original save_pretrained method
474
- super().save_pretrained(save_directory, **kwargs)
475
-
476
-
477
- @dataclass
478
- class MidmDoubleHeadsModelOutput(ModelOutput):
479
- loss: Optional[torch.FloatTensor] = None
480
- mc_loss: Optional[torch.FloatTensor] = None
481
- logits: torch.FloatTensor = None
482
- mc_logits: torch.FloatTensor = None
483
- past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None
484
- hidden_states: Optional[Tuple[torch.FloatTensor]] = None
485
- attentions: Optional[Tuple[torch.FloatTensor]] = None
486
-
487
-
488
- MIDM_START_DOCSTRING = r"""
489
-
490
- This model inherits from :class:`~transformers.PreTrainedModel`. Check the superclass documentation for the generic
491
- methods the library implements for all its model (such as downloading or saving, resizing the input embeddings,
492
- pruning heads etc.)
493
-
494
- This model is also a PyTorch `torch.nn.Module <https://pytorch.org/docs/stable/nn.html#torch.nn.Module>`__
495
- subclass. Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to
496
- general usage and behavior.
497
-
498
- Parameters:
499
- config (:class:`~transformers.MidmBitextConfig`): Model configuration class with all the parameters of the model.
500
- Initializing with a config file does not load the weights associated with the model, only the
501
- configuration. Check out the :meth:`~transformers.PreTrainedModel.from_pretrained` method to load the model
502
- weights.
503
- """
504
-
505
- MIDM_INPUTS_DOCSTRING = r"""
506
- Args:
507
- input_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`):
508
- :obj:`input_ids_length` = ``sequence_length`` if :obj:`past_key_values` is ``None`` else
509
- ``past_key_values[0][0].shape[-2]`` (``sequence_length`` of input past key value states). Indices of input
510
- sequence tokens in the vocabulary.
511
-
512
- If :obj:`past_key_values` is used, only ``input_ids`` that do not have their past calculated should be
513
- passed as ``input_ids``.
514
-
515
- Indices can be obtained using :class:`~transformers.Midm_bitext_Tokenizer`. See
516
- :meth:`transformers.PreTrainedTokenizer.encode` and :meth:`transformers.PreTrainedTokenizer.__call__` for
517
- details.
518
-
519
- `What are input IDs? <../glossary.html#input-ids>`__
520
- past_key_values (:obj:`Tuple[Tuple[torch.Tensor]]` of length :obj:`config.n_layers`):
521
- Contains precomputed hidden-states (key and values in the attention blocks) as computed by the model (see
522
- :obj:`past_key_values` output below). Can be used to speed up sequential decoding. The ``input_ids`` which
523
- have their past given to this model should not be passed as ``input_ids`` as they have already been
524
- computed.
525
- attention_mask (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
526
- Mask to avoid performing attention on padding token indices. Mask values selected in ``[0, 1]``:
527
-
528
- - 1 for tokens that are **not masked**,
529
- - 0 for tokens that are **masked**.
530
-
531
- `What are attention masks? <../glossary.html#attention-mask>`__
532
- token_type_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, input_ids_length)`, `optional`):
533
- Segment token indices to indicate first and second portions of the inputs. Indices are selected in ``[0,
534
- 1]``:
535
-
536
- - 0 corresponds to a `sentence A` token,
537
- - 1 corresponds to a `sentence B` token.
538
-
539
- `What are token type IDs? <../glossary.html#token-type-ids>`_
540
- position_ids (:obj:`torch.LongTensor` of shape :obj:`(batch_size, sequence_length)`, `optional`):
541
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range ``[0,
542
- config.max_position_embeddings - 1]``.
543
-
544
- `What are position IDs? <../glossary.html#position-ids>`_
545
- head_mask (:obj:`torch.FloatTensor` of shape :obj:`(num_heads,)` or :obj:`(num_layers, num_heads)`, `optional`):
546
- Mask to nullify selected heads of the self-attention modules. Mask values selected in ``[0, 1]``:
547
-
548
- - 1 indicates the head is **not masked**,
549
- - 0 indicates the head is **masked**.
550
-
551
- inputs_embeds (:obj:`torch.FloatTensor` of shape :obj:`(batch_size, sequence_length, hidden_size)`, `optional`):
552
- Optionally, instead of passing :obj:`input_ids` you can choose to directly pass an embedded representation.
553
- This is useful if you want more control over how to convert :obj:`input_ids` indices into associated
554
- vectors than the model's internal embedding lookup matrix.
555
-
556
- If :obj:`past_key_values` is used, optionally only the last :obj:`inputs_embeds` have to be input (see
557
- :obj:`past_key_values`).
558
- use_cache (:obj:`bool`, `optional`):
559
- If set to :obj:`True`, :obj:`past_key_values` key value states are returned and can be used to speed up
560
- decoding (see :obj:`past_key_values`).
561
- output_attentions (:obj:`bool`, `optional`):
562
- Whether or not to return the attentions tensors of all attention layers. See ``attentions`` under returned
563
- tensors for more detail.
564
- output_hidden_states (:obj:`bool`, `optional`):
565
- Whether or not to return the hidden states of all layers. See ``hidden_states`` under returned tensors for
566
- more detail.
567
- return_dict (:obj:`bool`, `optional`):
568
- Whether or not to return a :class:`~transformers.file_utils.ModelOutput` instead of a plain tuple.
569
- """
570
- PARALLELIZE_DOCSTRING = r"""
571
- This is an experimental feature and is a subject to change at a moment's notice.
572
-
573
- Uses a device map to distribute attention modules of the model across several devices. If no device map is given,
574
- it will evenly distribute blocks across all devices.
575
-
576
- Args:
577
- device_map (:obj:`Dict[int, list]`, optional, defaults to None):
578
- A dictionary that maps attention modules to devices. Note that the embedding module and LMHead are always
579
- automatically mapped to the first device (for esoteric reasons). That means that the first device should
580
- have fewer attention modules mapped to it than other devices. For reference, the Midm models have the
581
- following number of attention modules:
582
-
583
- - midm-bitext-S: 32
584
-
585
- Example::
586
-
587
- # Here is an example of a device map on a machine with 4 GPUs using midm-bitext-S, which has a total of 48 attention modules:
588
- model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
589
- device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
590
- 1: [9, 10, 11, 12, 13, 14, 15, 16],
591
- 2: [17, 18, 19, 20, 21, 22, 23, 24],
592
- 3: [25, 26, 27, 28, 29, 30, 31, 32]}
593
- model.parallelize(device_map)
594
- """
595
- DEPARALLELIZE_DOCSTRING = r"""
596
- Moves the model to cpu from a model parallel state.
597
-
598
- Example::
599
-
600
- # On a 4 GPU machine with midm-bitext-S:
601
- model = MidmLMHeadModel.from_pretrained('midm-bitext-S')
602
- device_map = {0: [0, 1, 2, 3, 4, 5, 6, 7, 8],
603
- 1: [9, 10, 11, 12, 13, 14, 15, 16],
604
- 2: [17, 18, 19, 20, 21, 22, 23, 24],
605
- 3: [25, 26, 27, 28, 29, 30, 31, 32]}
606
- model.parallelize(device_map) # Splits the model across several devices
607
- model.deparallelize() # Put the model back on cpu and cleans memory by calling torch.cuda.empty_cache()
608
- """
609
-
610
-
611
- @add_start_docstrings(
612
- "The bare Midm Model transformer outputting raw hidden-states without any specific head on top.",
613
- MIDM_START_DOCSTRING,
614
- )
615
- class MidmModel(MidmPreTrainedModel):
616
- _keys_to_ignore_on_load_missing = ["attn.masked_bias"]
617
-
618
- def __init__(self, config):
619
- super().__init__(config)
620
-
621
- self.embed_dim = config.hidden_size
622
-
623
- self.wte = nn.Embedding(config.vocab_size, self.embed_dim)
624
- self.use_absolute_position_embedding = config.use_absolute_position_embedding
625
- if self.use_absolute_position_embedding:
626
- self.wpe = nn.Embedding(config.max_position_embeddings, self.embed_dim)
627
-
628
- self.use_rotary_position_embedding = config.use_rotary_position_embedding
629
- if self.use_rotary_position_embedding:
630
- rotary_dim = config.hidden_size // config.num_attention_heads
631
- assert 0 < config.rotary_percentage <= 1
632
- if config.rotary_percentage < 1:
633
- rotary_dim = int(rotary_dim * config.rotary_percentage)
634
- self.rotary_pos_emb = RotaryEmbedding(
635
- rotary_dim,
636
- seq_len_interpolation_factor=None,
637
- pretrained_max_position_embeddings=config.max_position_embeddings,
638
- )
639
-
640
- self.drop = nn.Dropout(config.embd_pdrop)
641
- self.h = nn.ModuleList([MidmBlock(config, layer_idx=i) for i in range(config.num_hidden_layers)])
642
- self.ln_f = nn.LayerNorm(self.embed_dim, eps=config.layer_norm_epsilon)
643
- self.use_layernorm1p = config.normalization_type == "layernorm1p"
644
-
645
- self.init_weights()
646
-
647
- # Model parallel
648
- self.model_parallel = False
649
- self.device_map = None
650
- self.gradient_checkpointing = False
651
-
652
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
653
- def parallelize(self, device_map=None):
654
- # Check validity of device_map
655
- self.device_map = (
656
- get_device_map(len(self.h), range(torch.cuda.device_count())) if device_map is None else device_map
657
- )
658
- assert_device_map(self.device_map, len(self.h))
659
- self.model_parallel = True
660
- self.first_device = "cpu" if "cpu" in self.device_map.keys() else "cuda:" + str(min(self.device_map.keys()))
661
- self.last_device = "cuda:" + str(max(self.device_map.keys()))
662
- self.wte = self.wte.to(self.first_device)
663
- if self.use_absolute_position_embedding:
664
- self.wpe = self.wpe.to(self.first_device)
665
- # Load onto devices
666
- for k, v in self.device_map.items():
667
- for block in v:
668
- cuda_device = "cuda:" + str(k)
669
- self.h[block] = self.h[block].to(cuda_device)
670
- # ln_f to last
671
- self.ln_f = self.ln_f.to(self.last_device)
672
-
673
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
674
- def deparallelize(self):
675
- self.model_parallel = False
676
- self.device_map = None
677
- self.first_device = "cpu"
678
- self.last_device = "cpu"
679
- self.wte = self.wte.to("cpu")
680
- if self.use_absolute_position_embedding:
681
- self.wpe = self.wpe.to("cpu")
682
- for index in range(len(self.h)):
683
- self.h[index] = self.h[index].to("cpu")
684
- self.ln_f = self.ln_f.to("cpu")
685
- torch.cuda.empty_cache()
686
-
687
- def get_input_embeddings(self):
688
- return self.wte
689
-
690
- def set_input_embeddings(self, new_embeddings):
691
- self.wte = new_embeddings
692
-
693
- def _prune_heads(self, heads_to_prune):
694
- """
695
- Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer}
696
- """
697
- for layer, heads in heads_to_prune.items():
698
- self.h[layer].attn.prune_heads(heads)
699
-
700
- @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
701
- @add_code_sample_docstrings(
702
- processor_class=_TOKENIZER_FOR_DOC,
703
- checkpoint=_CHECKPOINT_FOR_DOC,
704
- output_type=BaseModelOutputWithPastAndCrossAttentions,
705
- config_class=_CONFIG_FOR_DOC,
706
- )
707
- def forward(
708
- self,
709
- input_ids=None,
710
- past_key_values=None,
711
- attention_mask=None,
712
- token_type_ids=None,
713
- position_ids=None,
714
- head_mask=None,
715
- inputs_embeds=None,
716
- encoder_hidden_states=None,
717
- encoder_attention_mask=None,
718
- use_cache=None,
719
- output_attentions=None,
720
- output_hidden_states=None,
721
- return_dict=None,
722
- ):
723
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
724
- output_hidden_states = (
725
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
726
- )
727
- use_cache = use_cache if use_cache is not None else self.config.use_cache
728
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
729
-
730
- if input_ids is not None and inputs_embeds is not None:
731
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
732
- elif input_ids is not None:
733
- input_shape = input_ids.size()
734
- input_ids = input_ids.view(-1, input_shape[-1])
735
- batch_size = input_ids.shape[0]
736
- elif inputs_embeds is not None:
737
- input_shape = inputs_embeds.size()[:-1]
738
- batch_size = inputs_embeds.shape[0]
739
- else:
740
- raise ValueError("You have to specify either input_ids or inputs_embeds")
741
-
742
- device = input_ids.device if input_ids is not None else inputs_embeds.device
743
-
744
- if token_type_ids is not None:
745
- token_type_ids = token_type_ids.view(-1, input_shape[-1])
746
- if position_ids is not None:
747
- position_ids = position_ids.view(-1, input_shape[-1])
748
-
749
- if past_key_values is None:
750
- past_length = 0
751
- past_key_values = tuple([None] * len(self.h))
752
- else:
753
- past_length = past_key_values[0][0].size(-2)
754
- if position_ids is None:
755
- position_ids = torch.arange(past_length, input_shape[-1] + past_length, dtype=torch.long, device=device)
756
- position_ids = position_ids.unsqueeze(0).view(-1, input_shape[-1])
757
-
758
- # MidmAttention mask.
759
- if attention_mask is not None:
760
- if batch_size <= 0:
761
- raise ValueError("batch_size has to be defined and > 0")
762
- attention_mask = attention_mask.view(batch_size, -1)
763
- # We create a 3D attention mask from a 2D tensor mask.
764
- # Sizes are [batch_size, 1, 1, to_seq_length]
765
- # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
766
- # this attention mask is more simple than the triangular masking of causal attention
767
- # used in KT Midm, we just need to prepare the broadcast dimension here.
768
- attention_mask = attention_mask[:, None, None, :]
769
-
770
- # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
771
- # masked positions, this operation will create a tensor which is 0.0 for
772
- # positions we want to attend and -10000.0 for masked positions.
773
- # Since we are adding it to the raw scores before the softmax, this is
774
- # effectively the same as removing these entirely.
775
- attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
776
- attention_mask = (1.0 - attention_mask) * -10000.0
777
-
778
- # If a 2D or 3D attention mask is provided for the cross-attention
779
- # we need to make broadcastable to [batch_size, num_heads, seq_length, seq_length]
780
- if self.config.add_cross_attention and encoder_hidden_states is not None:
781
- encoder_batch_size, encoder_sequence_length, _ = encoder_hidden_states.size()
782
- encoder_hidden_shape = (encoder_batch_size, encoder_sequence_length)
783
- if encoder_attention_mask is None:
784
- encoder_attention_mask = torch.ones(encoder_hidden_shape, device=device)
785
- encoder_attention_mask = self.invert_attention_mask(encoder_attention_mask)
786
- else:
787
- encoder_attention_mask = None
788
-
789
- rotary_pos_emb = None
790
- if self.use_rotary_position_embedding:
791
- rotary_pos_emb = self.rotary_pos_emb(past_length + input_shape[-1])
792
-
793
- # Prepare head mask if needed
794
- # 1.0 in head_mask indicate we keep the head
795
- # attention_probs has shape bsz x n_heads x N x N
796
- # head_mask has shape n_layer x batch x n_heads x N x N
797
- head_mask = self.get_head_mask(head_mask, self.config.n_layer)
798
-
799
- if inputs_embeds is None:
800
- inputs_embeds = self.wte(input_ids)
801
- if self.use_absolute_position_embedding:
802
- position_embeds = self.wpe(position_ids)
803
- hidden_states = inputs_embeds + position_embeds
804
- else:
805
- hidden_states = inputs_embeds
806
-
807
- if token_type_ids is not None:
808
- token_type_embeds = self.wte(token_type_ids)
809
- hidden_states = hidden_states + token_type_embeds
810
-
811
- hidden_states = self.drop(hidden_states)
812
-
813
- output_shape = input_shape + (hidden_states.size(-1),)
814
-
815
- presents = () if use_cache else None
816
- all_self_attentions = () if output_attentions else None
817
- all_cross_attentions = () if output_attentions and self.config.add_cross_attention else None
818
- all_hidden_states = () if output_hidden_states else None
819
- for i, (block, layer_past) in enumerate(zip(self.h, past_key_values)):
820
- # Model parallel
821
- if self.model_parallel:
822
- torch.cuda.set_device(hidden_states.device)
823
- # Ensure layer_past is on same device as hidden_states (might not be correct)
824
- if layer_past is not None:
825
- layer_past = tuple(past_state.to(hidden_states.device) for past_state in layer_past)
826
- # Ensure that attention_mask is always on the same device as hidden_states
827
- if attention_mask is not None:
828
- attention_mask = attention_mask.to(hidden_states.device)
829
- if isinstance(head_mask, torch.Tensor):
830
- head_mask = head_mask.to(hidden_states.device)
831
- if output_hidden_states:
832
- all_hidden_states = all_hidden_states + (hidden_states,)
833
-
834
- if self.gradient_checkpointing and self.training:
835
- if use_cache:
836
- logger.warning(
837
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
838
- )
839
- use_cache = False
840
-
841
- def create_custom_forward(module):
842
- def custom_forward(*inputs):
843
- # None for past_key_value
844
- return module(*inputs, use_cache, output_attentions)
845
-
846
- return custom_forward
847
-
848
- outputs = torch.utils.checkpoint.checkpoint(
849
- create_custom_forward(block),
850
- hidden_states,
851
- None,
852
- attention_mask,
853
- head_mask[i],
854
- encoder_hidden_states,
855
- encoder_attention_mask,
856
- rotary_pos_emb=rotary_pos_emb,
857
- )
858
- else:
859
- outputs = block(
860
- hidden_states,
861
- layer_past=layer_past,
862
- attention_mask=attention_mask,
863
- head_mask=head_mask[i],
864
- encoder_hidden_states=encoder_hidden_states,
865
- encoder_attention_mask=encoder_attention_mask,
866
- use_cache=use_cache,
867
- output_attentions=output_attentions,
868
- rotary_pos_emb=rotary_pos_emb,
869
- )
870
-
871
- hidden_states = outputs[0]
872
- if use_cache is True:
873
- presents = presents + (outputs[1],)
874
-
875
- if output_attentions:
876
- all_self_attentions = all_self_attentions + (outputs[2 if use_cache else 1],)
877
- if self.config.add_cross_attention:
878
- all_cross_attentions = all_cross_attentions + (outputs[3 if use_cache else 2],)
879
-
880
- # Model Parallel: If it's the last layer for that device, put things on the next device
881
- if self.model_parallel:
882
- for k, v in self.device_map.items():
883
- if i == v[-1] and "cuda:" + str(k) != self.last_device:
884
- hidden_states = hidden_states.to("cuda:" + str(k + 1))
885
-
886
- if self.use_layernorm1p:
887
- hidden_states = layernorm1p(self.ln_f, hidden_states)
888
- else:
889
- hidden_states = self.ln_f(hidden_states)
890
-
891
- hidden_states = hidden_states.view(*output_shape)
892
- # Add last hidden state
893
- if output_hidden_states:
894
- all_hidden_states = all_hidden_states + (hidden_states,)
895
-
896
- if not return_dict:
897
- return tuple(
898
- v
899
- for v in [hidden_states, presents, all_hidden_states, all_self_attentions, all_cross_attentions]
900
- if v is not None
901
- )
902
-
903
- return BaseModelOutputWithPastAndCrossAttentions(
904
- last_hidden_state=hidden_states,
905
- past_key_values=presents,
906
- hidden_states=all_hidden_states,
907
- attentions=all_self_attentions,
908
- cross_attentions=all_cross_attentions,
909
- )
910
-
911
-
912
- @add_start_docstrings(
913
- """
914
- The Midm Model transformer with a language modeling head on top (linear layer with weights tied to the input
915
- embeddings).
916
- """,
917
- MIDM_START_DOCSTRING,
918
- )
919
- class MidmLMHeadModel(MidmPreTrainedModel):
920
- _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
921
-
922
- def __init__(self, config):
923
- super().__init__(config)
924
- self.transformer = MidmModel(config)
925
- self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
926
-
927
- self.init_weights()
928
-
929
- # Model parallel
930
- self.model_parallel = False
931
- self.device_map = None
932
-
933
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
934
- def parallelize(self, device_map=None):
935
- self.device_map = (
936
- get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
937
- if device_map is None
938
- else device_map
939
- )
940
- assert_device_map(self.device_map, len(self.transformer.h))
941
- self.transformer.parallelize(self.device_map)
942
- self.lm_head = self.lm_head.to(self.transformer.first_device)
943
- self.model_parallel = True
944
-
945
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
946
- def deparallelize(self):
947
- self.transformer.deparallelize()
948
- self.transformer = self.transformer.to("cpu")
949
- self.lm_head = self.lm_head.to("cpu")
950
- self.model_parallel = False
951
- torch.cuda.empty_cache()
952
-
953
- def get_output_embeddings(self):
954
- return self.lm_head
955
-
956
- def set_output_embeddings(self, new_embeddings):
957
- self.lm_head = new_embeddings
958
-
959
- def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
960
- token_type_ids = kwargs.get("token_type_ids", None)
961
- # only last token for inputs_ids if past is defined in kwargs
962
- if past:
963
- input_ids = input_ids[:, -1].unsqueeze(-1)
964
- if token_type_ids is not None:
965
- token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
966
-
967
- attention_mask = kwargs.get("attention_mask", None)
968
- position_ids = kwargs.get("position_ids", None)
969
-
970
- if attention_mask is not None and position_ids is None:
971
- # create position_ids on the fly for batch generation
972
- position_ids = attention_mask.long().cumsum(-1) - 1
973
- position_ids.masked_fill_(attention_mask == 0, 1)
974
- if past:
975
- position_ids = position_ids[:, -1].unsqueeze(-1)
976
- else:
977
- position_ids = None
978
- return {
979
- "input_ids": input_ids,
980
- "past_key_values": past,
981
- "use_cache": kwargs.get("use_cache"),
982
- "position_ids": position_ids,
983
- "attention_mask": attention_mask,
984
- "token_type_ids": token_type_ids,
985
- }
986
-
987
- @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
988
- @add_code_sample_docstrings(
989
- processor_class=_TOKENIZER_FOR_DOC,
990
- checkpoint=_CHECKPOINT_FOR_DOC,
991
- output_type=CausalLMOutputWithCrossAttentions,
992
- config_class=_CONFIG_FOR_DOC,
993
- )
994
- def forward(
995
- self,
996
- input_ids=None,
997
- past_key_values=None,
998
- attention_mask=None,
999
- token_type_ids=None,
1000
- position_ids=None,
1001
- head_mask=None,
1002
- inputs_embeds=None,
1003
- encoder_hidden_states=None,
1004
- encoder_attention_mask=None,
1005
- labels=None,
1006
- use_cache=None,
1007
- output_attentions=None,
1008
- output_hidden_states=None,
1009
- return_dict=None,
1010
- ):
1011
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1012
-
1013
- transformer_outputs = self.transformer(
1014
- input_ids,
1015
- past_key_values=past_key_values,
1016
- attention_mask=attention_mask,
1017
- token_type_ids=token_type_ids,
1018
- position_ids=position_ids,
1019
- head_mask=head_mask,
1020
- inputs_embeds=inputs_embeds,
1021
- encoder_hidden_states=encoder_hidden_states,
1022
- encoder_attention_mask=encoder_attention_mask,
1023
- use_cache=use_cache,
1024
- output_attentions=output_attentions,
1025
- output_hidden_states=output_hidden_states,
1026
- return_dict=return_dict,
1027
- )
1028
- hidden_states = transformer_outputs[0]
1029
-
1030
- # Set device for model parallelism
1031
- if self.model_parallel:
1032
- torch.cuda.set_device(self.transformer.first_device)
1033
- hidden_states = hidden_states.to(self.lm_head.weight.device)
1034
-
1035
- lm_logits = self.lm_head(hidden_states)
1036
-
1037
- loss = None
1038
- if labels is not None:
1039
- # Shift so that tokens < n predict n
1040
- shift_logits = lm_logits[..., :-1, :].contiguous()
1041
- shift_labels = labels[..., 1:].contiguous()
1042
- # Flatten the tokens
1043
- loss_fct = CrossEntropyLoss()
1044
- # Enable model parallelism
1045
- shift_labels = shift_labels.to(shift_logits.device)
1046
- loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1047
-
1048
- if not return_dict:
1049
- output = (lm_logits,) + transformer_outputs[1:]
1050
- return ((loss,) + output) if loss is not None else output
1051
-
1052
- return CausalLMOutputWithCrossAttentions(
1053
- loss=loss,
1054
- logits=lm_logits,
1055
- past_key_values=transformer_outputs.past_key_values,
1056
- hidden_states=transformer_outputs.hidden_states,
1057
- attentions=transformer_outputs.attentions,
1058
- cross_attentions=transformer_outputs.cross_attentions,
1059
- )
1060
-
1061
- @staticmethod
1062
- def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1063
- """
1064
- This function is used to re-order the :obj:`past_key_values` cache if
1065
- :meth:`~transformers.PreTrainedModel.beam_search` or :meth:`~transformers.PreTrainedModel.beam_sample` is
1066
- called. This is required to match :obj:`past_key_values` with the correct beam_idx at every generation step.
1067
- """
1068
- return tuple(
1069
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1070
- for layer_past in past
1071
- )
1072
-
1073
-
1074
- @add_start_docstrings(
1075
- """
1076
- The Midm Model transformer with a language modeling and a multiple-choice classification head on top e.g. for
1077
- RocStories/SWAG tasks. The two heads are two linear layers. The language modeling head has its weights tied to the
1078
- input embeddings, the classification head takes as input the input of a specified classification token index in the
1079
- input sequence).
1080
- """,
1081
- MIDM_START_DOCSTRING,
1082
- )
1083
- class MidmDoubleHeadsModel(MidmPreTrainedModel):
1084
- _keys_to_ignore_on_load_missing = [r"attn.masked_bias", r"attn.bias", r"lm_head.weight"]
1085
-
1086
- def __init__(self, config):
1087
- super().__init__(config)
1088
- config.num_labels = 1
1089
- self.transformer = MidmModel(config)
1090
- self.lm_head = nn.Linear(config.n_embd, config.vocab_size, bias=False)
1091
- self.multiple_choice_head = SequenceSummary(config)
1092
-
1093
- self.init_weights()
1094
-
1095
- # Model parallel
1096
- self.model_parallel = False
1097
- self.device_map = None
1098
-
1099
- @add_start_docstrings(PARALLELIZE_DOCSTRING)
1100
- def parallelize(self, device_map=None):
1101
- self.device_map = (
1102
- get_device_map(len(self.transformer.h), range(torch.cuda.device_count()))
1103
- if device_map is None
1104
- else device_map
1105
- )
1106
- assert_device_map(self.device_map, len(self.transformer.h))
1107
- self.transformer.parallelize(self.device_map)
1108
- self.lm_head = self.lm_head.to(self.transformer.first_device)
1109
- self.multiple_choice_head = self.multiple_choice_head.to(self.transformer.first_device)
1110
- self.model_parallel = True
1111
-
1112
- @add_start_docstrings(DEPARALLELIZE_DOCSTRING)
1113
- def deparallelize(self):
1114
- self.transformer.deparallelize()
1115
- self.transformer = self.transformer.to("cpu")
1116
- self.lm_head = self.lm_head.to("cpu")
1117
- self.multiple_choice_head = self.multiple_choice_head.to("cpu")
1118
- self.model_parallel = False
1119
- torch.cuda.empty_cache()
1120
-
1121
- def get_output_embeddings(self):
1122
- return self.lm_head
1123
-
1124
- def set_output_embeddings(self, new_embeddings):
1125
- self.lm_head = new_embeddings
1126
-
1127
- def prepare_inputs_for_generation(self, input_ids, past=None, **kwargs):
1128
- token_type_ids = kwargs.get("token_type_ids", None)
1129
- # only last token for inputs_ids if past is defined in kwargs
1130
- if past:
1131
- input_ids = input_ids[:, -1].unsqueeze(-1)
1132
- if token_type_ids is not None:
1133
- token_type_ids = token_type_ids[:, -1].unsqueeze(-1)
1134
-
1135
- attention_mask = kwargs.get("attention_mask", None)
1136
- position_ids = kwargs.get("position_ids", None)
1137
-
1138
- if attention_mask is not None and position_ids is None:
1139
- # create position_ids on the fly for batch generation
1140
- position_ids = attention_mask.long().cumsum(-1) - 1
1141
- position_ids.masked_fill_(attention_mask == 0, 1)
1142
- if past:
1143
- position_ids = position_ids[:, -1].unsqueeze(-1)
1144
- else:
1145
- position_ids = None
1146
-
1147
- return {
1148
- "input_ids": input_ids,
1149
- "past_key_values": past,
1150
- "use_cache": kwargs.get("use_cache"),
1151
- "position_ids": position_ids,
1152
- "attention_mask": attention_mask,
1153
- "token_type_ids": token_type_ids,
1154
- }
1155
-
1156
- @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1157
- def forward(
1158
- self,
1159
- input_ids=None,
1160
- past_key_values=None,
1161
- attention_mask=None,
1162
- token_type_ids=None,
1163
- position_ids=None,
1164
- head_mask=None,
1165
- inputs_embeds=None,
1166
- mc_token_ids=None,
1167
- labels=None,
1168
- mc_labels=None,
1169
- use_cache=None,
1170
- output_attentions=None,
1171
- output_hidden_states=None,
1172
- return_dict=None,
1173
- **kwargs,
1174
- ):
1175
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1176
-
1177
- transformer_outputs = self.transformer(
1178
- input_ids,
1179
- past_key_values=past_key_values,
1180
- attention_mask=attention_mask,
1181
- token_type_ids=token_type_ids,
1182
- position_ids=position_ids,
1183
- head_mask=head_mask,
1184
- inputs_embeds=inputs_embeds,
1185
- use_cache=use_cache,
1186
- output_attentions=output_attentions,
1187
- output_hidden_states=output_hidden_states,
1188
- return_dict=return_dict,
1189
- )
1190
-
1191
- hidden_states = transformer_outputs[0]
1192
-
1193
- # Set device for model parallelism
1194
- if self.model_parallel:
1195
- torch.cuda.set_device(self.transformer.first_device)
1196
- hidden_states = hidden_states.to(self.lm_head.weight.device)
1197
-
1198
- lm_logits = self.lm_head(hidden_states)
1199
- mc_logits = self.multiple_choice_head(hidden_states, mc_token_ids).squeeze(-1)
1200
-
1201
- mc_loss = None
1202
- if mc_labels is not None:
1203
- loss_fct = CrossEntropyLoss()
1204
- mc_loss = loss_fct(mc_logits.view(-1, mc_logits.size(-1)), mc_labels.view(-1))
1205
- lm_loss = None
1206
- if labels is not None:
1207
- shift_logits = lm_logits[..., :-1, :].contiguous()
1208
- shift_labels = labels[..., 1:].contiguous()
1209
- loss_fct = CrossEntropyLoss()
1210
- # Enable model parallelism
1211
- shift_labels = shift_labels.to(shift_logits.device)
1212
- lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), shift_labels.view(-1))
1213
-
1214
- if not return_dict:
1215
- output = (lm_logits, mc_logits) + transformer_outputs[1:]
1216
- if mc_loss is not None:
1217
- output = (mc_loss,) + output
1218
- return ((lm_loss,) + output) if lm_loss is not None else output
1219
-
1220
- return MidmDoubleHeadsModelOutput(
1221
- loss=lm_loss,
1222
- mc_loss=mc_loss,
1223
- logits=lm_logits,
1224
- mc_logits=mc_logits,
1225
- past_key_values=transformer_outputs.past_key_values,
1226
- hidden_states=transformer_outputs.hidden_states,
1227
- attentions=transformer_outputs.attentions,
1228
- )
1229
-
1230
- @staticmethod
1231
- def _reorder_cache(past: Tuple[Tuple[torch.Tensor]], beam_idx: torch.Tensor) -> Tuple[Tuple[torch.Tensor]]:
1232
- return tuple(
1233
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past)
1234
- for layer_past in past
1235
- )
1236
-
1237
-
1238
- @add_start_docstrings(
1239
- """
1240
- The Midm Model transformer with a sequence classification head on top (linear layer).
1241
-
1242
- :class:`~transformers.MidmForSequenceClassification` uses the last token in order to do the classification, as
1243
- other causal models do.
1244
-
1245
- Since it does classification on the last token, it requires to know the position of the last token. If a
1246
- :obj:`pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each
1247
- row. If no :obj:`pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot
1248
- guess the padding tokens when :obj:`inputs_embeds` are passed instead of :obj:`input_ids`, it does the same (take
1249
- the last value in each row of the batch).
1250
- """,
1251
- MIDM_START_DOCSTRING,
1252
- )
1253
- class MidmForSequenceClassification(MidmPreTrainedModel):
1254
- _keys_to_ignore_on_load_missing = [r"h\.\d+\.attn\.masked_bias", r"lm_head\.weight"]
1255
-
1256
- def __init__(self, config):
1257
- super().__init__(config)
1258
- self.num_labels = config.num_labels
1259
- self.transformer = MidmModel(config)
1260
- self.score = nn.Linear(config.n_embd, self.num_labels, bias=False)
1261
-
1262
- self.init_weights()
1263
-
1264
- # Model parallel
1265
- self.model_parallel = False
1266
- self.device_map = None
1267
-
1268
- @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1269
- def forward(
1270
- self,
1271
- input_ids=None,
1272
- past_key_values=None,
1273
- attention_mask=None,
1274
- token_type_ids=None,
1275
- position_ids=None,
1276
- head_mask=None,
1277
- inputs_embeds=None,
1278
- labels=None,
1279
- use_cache=None,
1280
- output_attentions=None,
1281
- output_hidden_states=None,
1282
- return_dict=None,
1283
- ):
1284
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1285
-
1286
- transformer_outputs = self.transformer(
1287
- input_ids,
1288
- past_key_values=past_key_values,
1289
- attention_mask=attention_mask,
1290
- token_type_ids=token_type_ids,
1291
- position_ids=position_ids,
1292
- head_mask=head_mask,
1293
- inputs_embeds=inputs_embeds,
1294
- use_cache=use_cache,
1295
- output_attentions=output_attentions,
1296
- output_hidden_states=output_hidden_states,
1297
- return_dict=return_dict,
1298
- )
1299
- hidden_states = transformer_outputs[0]
1300
- logits = self.score(hidden_states)
1301
-
1302
- if input_ids is not None:
1303
- batch_size, sequence_length = input_ids.shape[:2]
1304
- else:
1305
- batch_size, sequence_length = inputs_embeds.shape[:2]
1306
-
1307
- assert (
1308
- self.config.pad_token_id is not None or batch_size == 1
1309
- ), "Cannot handle batch sizes > 1 if no padding token is defined."
1310
- if self.config.pad_token_id is None:
1311
- sequence_lengths = -1
1312
- else:
1313
- if input_ids is not None:
1314
- sequence_lengths = torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1315
- else:
1316
- sequence_lengths = -1
1317
- logger.warning(
1318
- f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
1319
- f"unexpected if using padding tokens in conjunction with `inputs_embeds.`"
1320
- )
1321
-
1322
- pooled_logits = logits[range(batch_size), sequence_lengths]
1323
-
1324
- loss = None
1325
- if labels is not None:
1326
- if self.num_labels == 1:
1327
- # We are doing regression
1328
- loss_fct = MSELoss()
1329
- loss = loss_fct(pooled_logits.view(-1), labels.to(self.dtype).view(-1))
1330
- else:
1331
- loss_fct = CrossEntropyLoss()
1332
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1333
-
1334
- if not return_dict:
1335
- output = (pooled_logits,) + transformer_outputs[1:]
1336
- return ((loss,) + output) if loss is not None else output
1337
-
1338
- return SequenceClassifierOutputWithPast(
1339
- loss=loss,
1340
- logits=pooled_logits,
1341
- past_key_values=transformer_outputs.past_key_values,
1342
- hidden_states=transformer_outputs.hidden_states,
1343
- attentions=transformer_outputs.attentions,
1344
- )
1345
-
1346
-
1347
- @add_start_docstrings(
1348
- """
1349
- Midm Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g. for
1350
- Named-Entity-Recognition (NER) tasks.
1351
- """,
1352
- MIDM_START_DOCSTRING,
1353
- )
1354
- class MidmForTokenClassification(MidmPreTrainedModel):
1355
- def __init__(self, config):
1356
- super().__init__(config)
1357
- self.num_labels = config.num_labels
1358
-
1359
- self.transformer = MidmModel(config)
1360
- if hasattr(config, "classifier_dropout") and config.classifier_dropout is not None:
1361
- classifier_dropout = config.classifier_dropout
1362
- elif hasattr(config, "hidden_dropout") and config.hidden_dropout is not None:
1363
- classifier_dropout = config.hidden_dropout
1364
- else:
1365
- classifier_dropout = 0.1
1366
- self.dropout = nn.Dropout(classifier_dropout)
1367
- self.classifier = nn.Linear(config.hidden_size, config.num_labels)
1368
-
1369
- self.init_weights()
1370
-
1371
- # Model parallel
1372
- self.model_parallel = False
1373
- self.device_map = None
1374
-
1375
- @add_start_docstrings_to_model_forward(MIDM_INPUTS_DOCSTRING)
1376
- def forward(
1377
- self,
1378
- input_ids=None,
1379
- past_key_values=None,
1380
- attention_mask=None,
1381
- token_type_ids=None,
1382
- position_ids=None,
1383
- head_mask=None,
1384
- inputs_embeds=None,
1385
- labels=None,
1386
- use_cache=None,
1387
- output_attentions=None,
1388
- output_hidden_states=None,
1389
- return_dict=None,
1390
- ):
1391
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1392
-
1393
- transformer_outputs = self.transformer(
1394
- input_ids,
1395
- past_key_values=past_key_values,
1396
- attention_mask=attention_mask,
1397
- token_type_ids=token_type_ids,
1398
- position_ids=position_ids,
1399
- head_mask=head_mask,
1400
- inputs_embeds=inputs_embeds,
1401
- use_cache=use_cache,
1402
- output_attentions=output_attentions,
1403
- output_hidden_states=output_hidden_states,
1404
- return_dict=return_dict,
1405
- )
1406
-
1407
- hidden_states = transformer_outputs[0]
1408
- hidden_states = self.dropout(hidden_states)
1409
- logits = self.classifier(hidden_states)
1410
-
1411
- loss = None
1412
- if labels is not None:
1413
- loss_fct = CrossEntropyLoss()
1414
- # Only keep active parts of the loss
1415
- if attention_mask is not None:
1416
- active_loss = attention_mask.view(-1) == 1
1417
- active_logits = logits.view(-1, self.num_labels)
1418
- active_labels = torch.where(
1419
- active_loss, labels.view(-1), torch.tensor(loss_fct.ignore_index).type_as(labels)
1420
- )
1421
- loss = loss_fct(active_logits, active_labels)
1422
- else:
1423
- loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
1424
-
1425
- if not return_dict:
1426
- output = (logits,) + transformer_outputs[2:]
1427
- return ((loss,) + output) if loss is not None else output
1428
-
1429
- return TokenClassifierOutput(
1430
- loss=loss,
1431
- logits=logits,
1432
- hidden_states=transformer_outputs.hidden_states,
1433
- attentions=transformer_outputs.attentions,
1434
- )
1435
-
1436
-
1437
- def get_submodule(module, target: str): # -> "Module":
1438
- if target == "":
1439
- return module
1440
-
1441
- atoms: List[str] = target.split(".")
1442
- mod: torch.nn.Module = module
1443
-
1444
- for item in atoms:
1445
- if not hasattr(mod, item):
1446
- raise AttributeError(mod._get_name() + " has no " "attribute `" + item + "`")
1447
-
1448
- mod = getattr(mod, item)
1449
-
1450
- if not isinstance(mod, torch.nn.Module):
1451
- raise AttributeError("`" + item + "` is not " "an nn.Module")
1452
-
1453
- return mod
1454
-
1455
-
1456
- def get_parameter(module, target: str): # -> "Parameter":
1457
- module_path, _, param_name = target.rpartition(".")
1458
-
1459
- mod: torch.nn.Module = get_submodule(module, module_path)
1460
-
1461
- if not hasattr(mod, param_name):
1462
- raise AttributeError(mod._get_name() + " has no attribute `" + param_name + "`")
1463
-
1464
- param: torch.nn.Parameter = getattr(mod, param_name)
1465
-
1466
- if not isinstance(param, torch.nn.Parameter):
1467
- raise AttributeError("`" + param_name + "` is not an " "nn.Parameter")
1468
-
1469
- return param