VarunGumma commited on
Commit
cdac1d3
1 Parent(s): 10c864a

Upload modeling_rotary_indictrans.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_rotary_indictrans.py +1794 -0
modeling_rotary_indictrans.py ADDED
@@ -0,0 +1,1794 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 The RotaryIndicTrans2 Authors and AI4Bharat team. 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 RotaryIndicTrans model."""
16
+
17
+
18
+ import math
19
+ from typing import List, Optional, Tuple, Union
20
+
21
+ import torch
22
+ import torch.nn as nn
23
+ from torch.nn import functional as F
24
+ from transformers.activations import ACT2FN
25
+
26
+ from transformers.modeling_attn_mask_utils import (
27
+ _prepare_4d_attention_mask,
28
+ _prepare_4d_attention_mask_for_sdpa,
29
+ _prepare_4d_causal_attention_mask,
30
+ _prepare_4d_causal_attention_mask_for_sdpa,
31
+ )
32
+
33
+ from transformers.integrations.deepspeed import is_deepspeed_zero3_enabled
34
+ from transformers.modeling_outputs import (
35
+ BaseModelOutput,
36
+ BaseModelOutputWithPastAndCrossAttentions,
37
+ Seq2SeqLMOutput,
38
+ Seq2SeqModelOutput,
39
+ )
40
+
41
+ from transformers.utils import (
42
+ logging,
43
+ is_flash_attn_2_available,
44
+ is_flash_attn_greater_or_equal_2_10,
45
+ )
46
+
47
+ from einops import rearrange
48
+ from transformers.modeling_utils import PreTrainedModel
49
+ from configuration_rotary_indictrans import RotaryIndicTransConfig
50
+
51
+ try:
52
+ from rotary_embedding_torch import RotaryEmbedding
53
+ except ImportError:
54
+ raise ImportError("Please install the rotary-embedding-torch>=0.6.4")
55
+
56
+
57
+ logger = logging.get_logger(__name__)
58
+
59
+ ROTARY_INDICTRANS_PRETRAINED_MODEL_ARCHIVE_LIST = [""]
60
+
61
+ try:
62
+ if is_flash_attn_2_available():
63
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
64
+ from flash_attn.bert_padding import (
65
+ index_first_axis,
66
+ pad_input,
67
+ unpad_input,
68
+ ) # noqa
69
+ except:
70
+ pass
71
+
72
+
73
+ # Copied from transformers.models.llama.modeling_llama._get_unpad_data
74
+ def _get_unpad_data(attention_mask):
75
+ seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
76
+ indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
77
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
78
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.int32), (1, 0))
79
+ return (
80
+ indices,
81
+ cu_seqlens,
82
+ max_seqlen_in_batch,
83
+ )
84
+
85
+
86
+ # Copied from transformers.models.bart.modeling_bart.shift_tokens_right
87
+ def shift_tokens_right(
88
+ input_ids: torch.Tensor, pad_token_id: int, decoder_start_token_id: int
89
+ ):
90
+ """
91
+ Shift input ids one token to the right.
92
+ """
93
+ shifted_input_ids = input_ids.new_zeros(input_ids.shape)
94
+ shifted_input_ids[:, 1:] = input_ids[:, :-1].clone()
95
+ shifted_input_ids[:, 0] = decoder_start_token_id
96
+
97
+ if pad_token_id is None:
98
+ raise ValueError("self.model.config.pad_token_id has to be defined.")
99
+ # replace possible -100 values in labels by `pad_token_id`
100
+ shifted_input_ids.masked_fill_(shifted_input_ids == -100, pad_token_id)
101
+
102
+ return shifted_input_ids
103
+
104
+
105
+ def create_position_ids_from_input_ids(
106
+ input_ids, padding_idx, past_key_values_length=0
107
+ ):
108
+ """
109
+ Replace non-padding symbols with their position numbers. Position numbers begin at padding_idx+1. Padding symbols
110
+ are ignored. This is modified from fairseq's `utils.make_positions`.
111
+ """
112
+ # The series of casts and type-conversions here are carefully balanced to both work with ONNX export and XLA.
113
+ mask = input_ids.ne(padding_idx).int()
114
+ incremental_indices = (
115
+ torch.cumsum(mask, dim=1).type_as(mask) + past_key_values_length
116
+ ) * mask
117
+ return incremental_indices.long() + padding_idx
118
+
119
+
120
+ # Copied from transformers.models.bart.modeling_bart.BartAttention with Bart->RotaryIndicTrans
121
+ class RotaryIndicTransAttention(nn.Module):
122
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
123
+
124
+ def __init__(
125
+ self,
126
+ embed_dim: int,
127
+ num_heads: int,
128
+ dropout: float = 0.0,
129
+ is_decoder: bool = False,
130
+ bias: bool = True,
131
+ is_causal: bool = False,
132
+ is_cross_attention: bool = False,
133
+ config: Optional[RotaryIndicTransConfig] = None,
134
+ ):
135
+ super().__init__()
136
+ self.embed_dim = embed_dim
137
+ self.num_heads = num_heads
138
+ self.dropout = dropout
139
+ self.head_dim = embed_dim // num_heads
140
+ self.config = config
141
+ self.rope_args = config.rope_args
142
+
143
+ if (self.head_dim * num_heads) != self.embed_dim:
144
+ raise ValueError(
145
+ f"embed_dim must be divisible by num_heads (got `embed_dim`: {self.embed_dim}"
146
+ f" and `num_heads`: {num_heads})."
147
+ )
148
+ self.scaling = self.head_dim**-0.5
149
+ self.is_decoder = is_decoder
150
+ self.is_causal = is_causal
151
+
152
+ self.xpos = self.rope_args.get("use_xpos", False)
153
+
154
+ # partial rotation in RoPE
155
+ self.rotary_pos_embed = (
156
+ RotaryEmbedding(
157
+ dim=self.head_dim // 2,
158
+ use_xpos=self.xpos,
159
+ theta=self.rope_args.get("theta", 10000),
160
+ xpos_scale_base=self.rope_args.get("xpos_scale_base", 512),
161
+ )
162
+ if not is_cross_attention
163
+ else None
164
+ )
165
+
166
+ self.k_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
167
+ self.v_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
168
+ self.q_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
169
+ self.out_proj = nn.Linear(embed_dim, embed_dim, bias=bias)
170
+
171
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
172
+ return (
173
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
174
+ .transpose(1, 2)
175
+ .contiguous()
176
+ )
177
+
178
+ def _apply_rotary_pos_emb(self, q, k, is_inference=False):
179
+ q = rearrange(q, "(b h) t d -> b h t d", h=self.num_heads)
180
+ k = rearrange(k, "(b h) t d -> b h t d", h=self.num_heads)
181
+
182
+ if is_inference:
183
+ q, k = self.rotary_pos_embed.rotate_queries_with_cached_keys(q, k)
184
+ else:
185
+ if not self.xpos:
186
+ q = self.rotary_pos_embed.rotate_queries_or_keys(q)
187
+ k = self.rotary_pos_embed.rotate_queries_or_keys(k)
188
+ else:
189
+ q, k = self.rotary_pos_embed.rotate_queries_and_keys(q, k)
190
+
191
+ q = rearrange(q, "b h t d -> (b h) t d")
192
+ k = rearrange(k, "b h t d -> (b h) t d")
193
+ return q, k
194
+
195
+ def forward(
196
+ self,
197
+ hidden_states: torch.Tensor,
198
+ key_value_states: Optional[torch.Tensor] = None,
199
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
200
+ attention_mask: Optional[torch.Tensor] = None,
201
+ layer_head_mask: Optional[torch.Tensor] = None,
202
+ output_attentions: bool = False,
203
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
204
+ """Input shape: Batch x Time x Channel"""
205
+
206
+ # if key_value_states are provided this layer is used as a cross-attention layer
207
+ # for the decoder
208
+ is_cross_attention = key_value_states is not None
209
+
210
+ bsz, tgt_len, _ = hidden_states.size()
211
+
212
+ # get query proj
213
+ query_states = self.q_proj(hidden_states) * self.scaling
214
+ # get key, value proj
215
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
216
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
217
+ # the provided `key_value_states` to support prefix tuning
218
+ if (
219
+ is_cross_attention
220
+ and past_key_value is not None
221
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
222
+ ):
223
+ # reuse k,v, cross_attentions
224
+ key_states = past_key_value[0]
225
+ value_states = past_key_value[1]
226
+ elif is_cross_attention:
227
+ # cross_attentions
228
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
229
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
230
+ elif past_key_value is not None:
231
+ # reuse k, v, self_attention
232
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
233
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
234
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
235
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
236
+ else:
237
+ # self_attention
238
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
239
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
240
+
241
+ if self.is_decoder:
242
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
243
+ # Further calls to cross_attention layer can then reuse all cross-attention
244
+ # key/value_states (first "if" case)
245
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
246
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
247
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
248
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
249
+ past_key_value = (key_states, value_states)
250
+
251
+ proj_shape = (bsz * self.num_heads, -1, self.head_dim)
252
+ query_states = self._shape(query_states, tgt_len, bsz).view(*proj_shape)
253
+ key_states = key_states.reshape(*proj_shape)
254
+ value_states = value_states.reshape(*proj_shape)
255
+
256
+ src_len = key_states.size(1)
257
+
258
+ if self.rotary_pos_embed is not None:
259
+ query_states, key_states = self._apply_rotary_pos_emb(
260
+ query_states, key_states, is_inference=past_key_value is not None
261
+ )
262
+
263
+ attn_weights = torch.bmm(query_states, key_states.transpose(1, 2))
264
+
265
+ if attn_weights.size() != (bsz * self.num_heads, tgt_len, src_len):
266
+ raise ValueError(
267
+ f"Attention weights should be of size {(bsz * self.num_heads, tgt_len, src_len)}, but is"
268
+ f" {attn_weights.size()}"
269
+ )
270
+
271
+ if attention_mask is not None:
272
+ if attention_mask.size() != (bsz, 1, tgt_len, src_len):
273
+ raise ValueError(
274
+ f"Attention mask should be of size {(bsz, 1, tgt_len, src_len)}, but is {attention_mask.size()}"
275
+ )
276
+ attn_weights = (
277
+ attn_weights.view(bsz, self.num_heads, tgt_len, src_len)
278
+ + attention_mask
279
+ )
280
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
281
+
282
+ attn_weights = F.softmax(attn_weights, dim=-1)
283
+
284
+ if layer_head_mask is not None:
285
+ if layer_head_mask.size() != (self.num_heads,):
286
+ raise ValueError(
287
+ f"Head mask for a single layer should be of size {(self.num_heads,)}, but is"
288
+ f" {layer_head_mask.size()}"
289
+ )
290
+ attn_weights = layer_head_mask.view(1, -1, 1, 1) * attn_weights.view(
291
+ bsz, self.num_heads, tgt_len, src_len
292
+ )
293
+ attn_weights = attn_weights.view(bsz * self.num_heads, tgt_len, src_len)
294
+
295
+ if output_attentions:
296
+ # this operation is a bit awkward, but it's required to
297
+ # make sure that attn_weights keeps its gradient.
298
+ # In order to do so, attn_weights have to be reshaped
299
+ # twice and have to be reused in the following
300
+ attn_weights_reshaped = attn_weights.view(
301
+ bsz, self.num_heads, tgt_len, src_len
302
+ )
303
+ attn_weights = attn_weights_reshaped.view(
304
+ bsz * self.num_heads, tgt_len, src_len
305
+ )
306
+ else:
307
+ attn_weights_reshaped = None
308
+
309
+ attn_probs = F.dropout(attn_weights, p=self.dropout, training=self.training)
310
+
311
+ attn_output = torch.bmm(attn_probs, value_states)
312
+
313
+ if attn_output.size() != (bsz * self.num_heads, tgt_len, self.head_dim):
314
+ raise ValueError(
315
+ f"`attn_output` should be of size {(bsz * self.num_heads, tgt_len, self.head_dim)}, but is"
316
+ f" {attn_output.size()}"
317
+ )
318
+
319
+ attn_output = attn_output.view(bsz, self.num_heads, tgt_len, self.head_dim)
320
+ attn_output = attn_output.transpose(1, 2)
321
+
322
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
323
+ # partitioned across GPUs when using tensor-parallelism.
324
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
325
+
326
+ attn_output = self.out_proj(attn_output)
327
+
328
+ return attn_output, attn_weights_reshaped, past_key_value
329
+
330
+
331
+ class RotaryIndicTransFlashAttention2(RotaryIndicTransAttention):
332
+ """
333
+ RotaryIndicTrans flash attention module. This module inherits from `RotaryIndicTransAttention` as the weights of the module stays
334
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
335
+ flash attention and deal with padding tokens in case the input contains any of them.
336
+ """
337
+
338
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2.__init__
339
+ def __init__(self, *args, **kwargs):
340
+ super().__init__(*args, **kwargs)
341
+
342
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
343
+ # 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. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
344
+ # Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
345
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
346
+
347
+ def _reshape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
348
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
349
+
350
+ def forward(
351
+ self,
352
+ hidden_states: torch.Tensor,
353
+ key_value_states: Optional[torch.Tensor] = None,
354
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
355
+ attention_mask: Optional[torch.Tensor] = None,
356
+ layer_head_mask: Optional[torch.Tensor] = None,
357
+ output_attentions: bool = False,
358
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
359
+ # RotaryIndicTransFlashAttention2 attention does not support output_attentions
360
+ if output_attentions:
361
+ raise ValueError(
362
+ "RotaryIndicTransFlashAttention2 attention does not support output_attentions"
363
+ )
364
+
365
+ # if key_value_states are provided this layer is used as a cross-attention layer
366
+ # for the decoder
367
+ is_cross_attention = key_value_states is not None
368
+
369
+ bsz, q_len, _ = hidden_states.size()
370
+
371
+ # get query proj
372
+ query_states = self._reshape(self.q_proj(hidden_states), -1, bsz)
373
+ # get key, value proj
374
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
375
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
376
+ # the provided `key_value_states` to support prefix tuning
377
+ if (
378
+ is_cross_attention
379
+ and past_key_value is not None
380
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
381
+ ):
382
+ # reuse k,v, cross_attentions
383
+ key_states = past_key_value[0].transpose(1, 2)
384
+ value_states = past_key_value[1].transpose(1, 2)
385
+ elif is_cross_attention:
386
+ # cross_attentions
387
+ key_states = self._reshape(self.k_proj(key_value_states), -1, bsz)
388
+ value_states = self._reshape(self.v_proj(key_value_states), -1, bsz)
389
+ elif past_key_value is not None:
390
+ # reuse k, v, self_attention
391
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
392
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
393
+ key_states = torch.cat(
394
+ [past_key_value[0].transpose(1, 2), key_states], dim=1
395
+ )
396
+ value_states = torch.cat(
397
+ [past_key_value[1].transpose(1, 2), value_states], dim=1
398
+ )
399
+ else:
400
+ # self_attention
401
+ key_states = self._reshape(self.k_proj(hidden_states), -1, bsz)
402
+ value_states = self._reshape(self.v_proj(hidden_states), -1, bsz)
403
+
404
+ if self.is_decoder:
405
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
406
+ # Further calls to cross_attention layer can then reuse all cross-attention
407
+ # key/value_states (first "if" case)
408
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
409
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
410
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
411
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
412
+ past_key_value = (key_states.transpose(1, 2), value_states.transpose(1, 2))
413
+
414
+ kv_seq_len = key_states.shape[-2]
415
+ if past_key_value is not None:
416
+ kv_seq_len += past_key_value[0].shape[-2]
417
+
418
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
419
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
420
+ # cast them back in the correct dtype just to be sure everything works as expected.
421
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
422
+ # in fp32. (LlamaRMSNorm handles it correctly)
423
+
424
+ input_dtype = query_states.dtype
425
+ if input_dtype == torch.float32:
426
+ if torch.is_autocast_enabled():
427
+ target_dtype = torch.get_autocast_gpu_dtype()
428
+ # Handle the case where the model is quantized
429
+ elif hasattr(self.config, "_pre_quantization_dtype"):
430
+ target_dtype = self.config._pre_quantization_dtype
431
+ else:
432
+ target_dtype = self.q_proj.weight.dtype
433
+
434
+ logger.warning_once(
435
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
436
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
437
+ f" {target_dtype}."
438
+ )
439
+
440
+ query_states = query_states.to(target_dtype)
441
+ key_states = key_states.to(target_dtype)
442
+ value_states = value_states.to(target_dtype)
443
+
444
+ if self.rotary_pos_embed is not None:
445
+ query_states, key_states = self._apply_rotary_pos_emb(
446
+ query_states, key_states, is_inference=past_key_value is not None
447
+ )
448
+
449
+ attn_output = self._flash_attention_forward(
450
+ query_states,
451
+ key_states,
452
+ value_states,
453
+ attention_mask,
454
+ q_len,
455
+ dropout=self.dropout,
456
+ )
457
+
458
+ attn_output = attn_output.reshape(bsz, q_len, -1)
459
+ attn_output = self.out_proj(attn_output)
460
+
461
+ if not output_attentions:
462
+ attn_weights = None
463
+
464
+ return attn_output, attn_weights, past_key_value
465
+
466
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._flash_attention_forward
467
+ def _flash_attention_forward(
468
+ self,
469
+ query_states,
470
+ key_states,
471
+ value_states,
472
+ attention_mask,
473
+ query_length,
474
+ dropout=0.0,
475
+ softmax_scale=None,
476
+ ):
477
+ """
478
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
479
+ first unpad the input, then computes the attention scores and pad the final attention scores.
480
+
481
+ Args:
482
+ query_states (`torch.Tensor`):
483
+ Input query states to be passed to Flash Attention API
484
+ key_states (`torch.Tensor`):
485
+ Input key states to be passed to Flash Attention API
486
+ value_states (`torch.Tensor`):
487
+ Input value states to be passed to Flash Attention API
488
+ attention_mask (`torch.Tensor`):
489
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
490
+ position of padding tokens and 1 for the position of non-padding tokens.
491
+ dropout (`float`):
492
+ Attention dropout
493
+ softmax_scale (`float`, *optional*):
494
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
495
+ """
496
+ if not self._flash_attn_uses_top_left_mask:
497
+ causal = self.is_causal
498
+ else:
499
+ # TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
500
+ causal = self.is_causal and query_length != 1
501
+
502
+ # Contains at least one padding token in the sequence
503
+ if attention_mask is not None:
504
+ batch_size = query_states.shape[0]
505
+ (
506
+ query_states,
507
+ key_states,
508
+ value_states,
509
+ indices_q,
510
+ cu_seq_lens,
511
+ max_seq_lens,
512
+ ) = self._upad_input(
513
+ query_states, key_states, value_states, attention_mask, query_length
514
+ )
515
+
516
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
517
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
518
+
519
+ attn_output_unpad = flash_attn_varlen_func(
520
+ query_states,
521
+ key_states,
522
+ value_states,
523
+ cu_seqlens_q=cu_seqlens_q,
524
+ cu_seqlens_k=cu_seqlens_k,
525
+ max_seqlen_q=max_seqlen_in_batch_q,
526
+ max_seqlen_k=max_seqlen_in_batch_k,
527
+ dropout_p=dropout,
528
+ softmax_scale=softmax_scale,
529
+ causal=causal,
530
+ )
531
+
532
+ attn_output = pad_input(
533
+ attn_output_unpad, indices_q, batch_size, query_length
534
+ )
535
+ else:
536
+ attn_output = flash_attn_func(
537
+ query_states,
538
+ key_states,
539
+ value_states,
540
+ dropout,
541
+ softmax_scale=softmax_scale,
542
+ causal=causal,
543
+ )
544
+
545
+ return attn_output
546
+
547
+ # Copied from transformers.models.llama.modeling_llama.LlamaFlashAttention2._upad_input
548
+ def _upad_input(
549
+ self, query_layer, key_layer, value_layer, attention_mask, query_length
550
+ ):
551
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
552
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
553
+
554
+ key_layer = index_first_axis(
555
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
556
+ indices_k,
557
+ )
558
+ value_layer = index_first_axis(
559
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim),
560
+ indices_k,
561
+ )
562
+ if query_length == kv_seq_len:
563
+ query_layer = index_first_axis(
564
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim),
565
+ indices_k,
566
+ )
567
+ cu_seqlens_q = cu_seqlens_k
568
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
569
+ indices_q = indices_k
570
+ elif query_length == 1:
571
+ max_seqlen_in_batch_q = 1
572
+ cu_seqlens_q = torch.arange(
573
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
574
+ ) # There is a memcpy here, that is very bad.
575
+ indices_q = cu_seqlens_q[:-1]
576
+ query_layer = query_layer.squeeze(1)
577
+ else:
578
+ # The -q_len: slice assumes left padding.
579
+ attention_mask = attention_mask[:, -query_length:]
580
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(
581
+ query_layer, attention_mask
582
+ )
583
+
584
+ return (
585
+ query_layer,
586
+ key_layer,
587
+ value_layer,
588
+ indices_q,
589
+ (cu_seqlens_q, cu_seqlens_k),
590
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
591
+ )
592
+
593
+
594
+ class RotaryIndicTransSdpaAttention(RotaryIndicTransAttention):
595
+ def forward(
596
+ self,
597
+ hidden_states: torch.Tensor,
598
+ key_value_states: Optional[torch.Tensor] = None,
599
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
600
+ attention_mask: Optional[torch.Tensor] = None,
601
+ layer_head_mask: Optional[torch.Tensor] = None,
602
+ output_attentions: bool = False,
603
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
604
+ """Input shape: Batch x Time x Channel"""
605
+ if output_attentions or layer_head_mask is not None:
606
+ # TODO: Improve this warning with e.g. `model.config._attn_implementation = "manual"` once this is implemented.
607
+ logger.warning_once(
608
+ "RotaryIndicTransModel is using RotaryIndicTransSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True` or `layer_head_mask` not None. Falling back to the manual attention"
609
+ ' implementation, 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.'
610
+ )
611
+ return super().forward(
612
+ hidden_states,
613
+ key_value_states=key_value_states,
614
+ past_key_value=past_key_value,
615
+ attention_mask=attention_mask,
616
+ layer_head_mask=layer_head_mask,
617
+ output_attentions=output_attentions,
618
+ )
619
+
620
+ # if key_value_states are provided this layer is used as a cross-attention layer
621
+ # for the decoder
622
+ is_cross_attention = key_value_states is not None
623
+
624
+ bsz, tgt_len, _ = hidden_states.size()
625
+
626
+ # get query proj
627
+ query_states = self.q_proj(hidden_states)
628
+ # get key, value proj
629
+ # `past_key_value[0].shape[2] == key_value_states.shape[1]`
630
+ # is checking that the `sequence_length` of the `past_key_value` is the same as
631
+ # the provided `key_value_states` to support prefix tuning
632
+ if (
633
+ is_cross_attention
634
+ and past_key_value is not None
635
+ and past_key_value[0].shape[2] == key_value_states.shape[1]
636
+ ):
637
+ # reuse k,v, cross_attentions
638
+ key_states = past_key_value[0]
639
+ value_states = past_key_value[1]
640
+ elif is_cross_attention:
641
+ # cross_attentions
642
+ key_states = self._shape(self.k_proj(key_value_states), -1, bsz)
643
+ value_states = self._shape(self.v_proj(key_value_states), -1, bsz)
644
+ elif past_key_value is not None:
645
+ # reuse k, v, self_attention
646
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
647
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
648
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
649
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
650
+ else:
651
+ # self_attention
652
+ key_states = self._shape(self.k_proj(hidden_states), -1, bsz)
653
+ value_states = self._shape(self.v_proj(hidden_states), -1, bsz)
654
+
655
+ if self.is_decoder:
656
+ # if cross_attention save Tuple(torch.Tensor, torch.Tensor) of all cross attention key/value_states.
657
+ # Further calls to cross_attention layer can then reuse all cross-attention
658
+ # key/value_states (first "if" case)
659
+ # if uni-directional self-attention (decoder) save Tuple(torch.Tensor, torch.Tensor) of
660
+ # all previous decoder key/value_states. Further calls to uni-directional self-attention
661
+ # can concat previous decoder key/value_states to current projected key/value_states (third "elif" case)
662
+ # if encoder bi-directional self-attention `past_key_value` is always `None`
663
+ past_key_value = (key_states, value_states)
664
+
665
+ query_states = self._shape(query_states, tgt_len, bsz)
666
+
667
+ if self.rotary_pos_embed is not None:
668
+ query_states, key_states = self._apply_rotary_pos_emb(
669
+ query_states, key_states, is_inference=past_key_value is not None
670
+ )
671
+
672
+ # NOTE: SDPA with memory-efficient backend is currently (torch==2.1.2) bugged when using non-contiguous inputs and a custom attn_mask,
673
+ # but we are fine here as `_shape` do call `.contiguous()`. Reference: https://github.com/pytorch/pytorch/issues/112577
674
+ attn_output = F.scaled_dot_product_attention(
675
+ query_states,
676
+ key_states,
677
+ value_states,
678
+ attn_mask=attention_mask,
679
+ dropout_p=self.dropout if self.training else 0.0,
680
+ # The tgt_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case tgt_len == 1.
681
+ is_causal=self.is_causal and attention_mask is None and tgt_len > 1,
682
+ )
683
+
684
+ if attn_output.size() != (bsz, self.num_heads, tgt_len, self.head_dim):
685
+ raise ValueError(
686
+ f"`attn_output` should be of size {(bsz, self.num_heads, tgt_len, self.head_dim)}, but is"
687
+ f" {attn_output.size()}"
688
+ )
689
+
690
+ attn_output = attn_output.transpose(1, 2)
691
+
692
+ # Use the `embed_dim` from the config (stored in the class) rather than `hidden_state` because `attn_output` can be
693
+ # partitioned across GPUs when using tensor-parallelism.
694
+ attn_output = attn_output.reshape(bsz, tgt_len, self.embed_dim)
695
+
696
+ attn_output = self.out_proj(attn_output)
697
+
698
+ return attn_output, None, past_key_value
699
+
700
+
701
+ ROTARY_INDICTRANS_ATTENTION_CLASSES = {
702
+ "eager": RotaryIndicTransAttention,
703
+ "sdpa": RotaryIndicTransSdpaAttention,
704
+ "flash_attention_2": RotaryIndicTransFlashAttention2,
705
+ }
706
+
707
+
708
+ # Copied from transformers.models.mbart.modeling_mbart.MBartEncoderLayer with MBart->RotaryIndicTrans
709
+ class RotaryIndicTransEncoderLayer(nn.Module):
710
+ def __init__(self, config: RotaryIndicTransConfig):
711
+ super().__init__()
712
+ self.embed_dim = config.encoder_embed_dim
713
+ self.self_attn = ROTARY_INDICTRANS_ATTENTION_CLASSES[
714
+ config._attn_implementation
715
+ ](
716
+ embed_dim=self.embed_dim,
717
+ num_heads=config.encoder_attention_heads,
718
+ dropout=config.attention_dropout,
719
+ config=config,
720
+ )
721
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
722
+ self.dropout = config.dropout
723
+ self.activation_fn = ACT2FN[config.activation_function]
724
+ self.activation_dropout = config.activation_dropout
725
+ self.fc1 = nn.Linear(self.embed_dim, config.encoder_ffn_dim)
726
+ self.fc2 = nn.Linear(config.encoder_ffn_dim, self.embed_dim)
727
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
728
+ self.normalize_before = config.encoder_normalize_before
729
+
730
+ def forward(
731
+ self,
732
+ hidden_states: torch.Tensor,
733
+ attention_mask: torch.Tensor,
734
+ layer_head_mask: torch.Tensor,
735
+ output_attentions: bool = False,
736
+ ) -> torch.Tensor:
737
+ """
738
+ Args:
739
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
740
+ attention_mask (`torch.FloatTensor`): attention mask of size
741
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
742
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
743
+ `(encoder_attention_heads,)`.
744
+ output_attentions (`bool`, *optional*):
745
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
746
+ returned tensors for more detail.
747
+ """
748
+ residual = hidden_states
749
+ if self.normalize_before:
750
+ hidden_states = self.self_attn_layer_norm(hidden_states)
751
+ hidden_states, attn_weights, _ = self.self_attn(
752
+ hidden_states=hidden_states,
753
+ attention_mask=attention_mask,
754
+ layer_head_mask=layer_head_mask,
755
+ output_attentions=output_attentions,
756
+ )
757
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
758
+ hidden_states = residual + hidden_states
759
+ if not self.normalize_before:
760
+ hidden_states = self.self_attn_layer_norm(hidden_states)
761
+
762
+ residual = hidden_states
763
+ if self.normalize_before:
764
+ hidden_states = self.final_layer_norm(hidden_states)
765
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
766
+ hidden_states = F.dropout(
767
+ hidden_states, p=self.activation_dropout, training=self.training
768
+ )
769
+ hidden_states = self.fc2(hidden_states)
770
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
771
+ hidden_states = residual + hidden_states
772
+ if not self.normalize_before:
773
+ hidden_states = self.final_layer_norm(hidden_states)
774
+
775
+ if hidden_states.dtype == torch.float16 and (
776
+ torch.isinf(hidden_states).any() or torch.isnan(hidden_states).any()
777
+ ):
778
+ clamp_value = torch.finfo(hidden_states.dtype).max - 1000
779
+ hidden_states = torch.clamp(
780
+ hidden_states, min=-clamp_value, max=clamp_value
781
+ )
782
+
783
+ outputs = (hidden_states,)
784
+
785
+ if output_attentions:
786
+ outputs += (attn_weights,)
787
+
788
+ return outputs
789
+
790
+
791
+ # Copied from transformers.models.mbart.modeling_mbart.MBartDecoderLayer with MBart->RotaryIndicTrans
792
+ class RotaryIndicTransDecoderLayer(nn.Module):
793
+ def __init__(self, config: RotaryIndicTransConfig):
794
+ super().__init__()
795
+ self.embed_dim = config.decoder_embed_dim
796
+
797
+ self.self_attn = ROTARY_INDICTRANS_ATTENTION_CLASSES[
798
+ config._attn_implementation
799
+ ](
800
+ embed_dim=self.embed_dim,
801
+ num_heads=config.decoder_attention_heads,
802
+ dropout=config.attention_dropout,
803
+ is_decoder=True,
804
+ is_causal=True,
805
+ config=config,
806
+ )
807
+ self.dropout = config.dropout
808
+ self.activation_fn = ACT2FN[config.activation_function]
809
+ self.activation_dropout = config.activation_dropout
810
+
811
+ self.self_attn_layer_norm = nn.LayerNorm(self.embed_dim)
812
+ self.encoder_attn = ROTARY_INDICTRANS_ATTENTION_CLASSES[
813
+ config._attn_implementation
814
+ ](
815
+ self.embed_dim,
816
+ config.decoder_attention_heads,
817
+ dropout=config.attention_dropout,
818
+ is_cross_attention=True,
819
+ is_decoder=True,
820
+ config=config,
821
+ )
822
+ self.encoder_attn_layer_norm = nn.LayerNorm(self.embed_dim)
823
+ self.fc1 = nn.Linear(self.embed_dim, config.decoder_ffn_dim)
824
+ self.fc2 = nn.Linear(config.decoder_ffn_dim, self.embed_dim)
825
+ self.final_layer_norm = nn.LayerNorm(self.embed_dim)
826
+ self.normalize_before = config.decoder_normalize_before
827
+
828
+ def forward(
829
+ self,
830
+ hidden_states: torch.Tensor,
831
+ attention_mask: Optional[torch.Tensor] = None,
832
+ encoder_hidden_states: Optional[torch.Tensor] = None,
833
+ encoder_attention_mask: Optional[torch.Tensor] = None,
834
+ layer_head_mask: Optional[torch.Tensor] = None,
835
+ cross_attn_layer_head_mask: Optional[torch.Tensor] = None,
836
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
837
+ output_attentions: Optional[bool] = False,
838
+ use_cache: Optional[bool] = True,
839
+ ) -> torch.Tensor:
840
+ """
841
+ Args:
842
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
843
+ attention_mask (`torch.FloatTensor`): attention mask of size
844
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
845
+ encoder_hidden_states (`torch.FloatTensor`):
846
+ cross attention input to the layer of shape `(batch, seq_len, embed_dim)`
847
+ encoder_attention_mask (`torch.FloatTensor`): encoder attention mask of size
848
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
849
+ layer_head_mask (`torch.FloatTensor`): mask for attention heads in a given layer of size
850
+ `(encoder_attention_heads,)`.
851
+ cross_attn_layer_head_mask (`torch.FloatTensor`): mask for cross-attention heads in a given layer of
852
+ size `(decoder_attention_heads,)`.
853
+ past_key_value (`Tuple(torch.FloatTensor)`): cached past key and value projection states
854
+ output_attentions (`bool`, *optional*):
855
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
856
+ returned tensors for more detail.
857
+ """
858
+ residual = hidden_states
859
+ if self.normalize_before:
860
+ hidden_states = self.self_attn_layer_norm(hidden_states)
861
+
862
+ # Self Attention
863
+ # decoder uni-directional self-attention cached key/values tuple is at positions 1,2
864
+ self_attn_past_key_value = (
865
+ past_key_value[:2] if past_key_value is not None else None
866
+ )
867
+ # add present self-attn cache to positions 1,2 of present_key_value tuple
868
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
869
+ hidden_states=hidden_states,
870
+ past_key_value=self_attn_past_key_value,
871
+ attention_mask=attention_mask,
872
+ layer_head_mask=layer_head_mask,
873
+ output_attentions=output_attentions,
874
+ )
875
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
876
+ hidden_states = residual + hidden_states
877
+ if not self.normalize_before:
878
+ hidden_states = self.self_attn_layer_norm(hidden_states)
879
+
880
+ # Cross-Attention Block
881
+ cross_attn_present_key_value = None
882
+ cross_attn_weights = None
883
+ if encoder_hidden_states is not None:
884
+ residual = hidden_states
885
+ if self.normalize_before:
886
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
887
+
888
+ # cross_attn cached key/values tuple is at positions 3,4 of present_key_value tuple
889
+ cross_attn_past_key_value = (
890
+ past_key_value[-2:] if past_key_value is not None else None
891
+ )
892
+ (
893
+ hidden_states,
894
+ cross_attn_weights,
895
+ cross_attn_present_key_value,
896
+ ) = self.encoder_attn(
897
+ hidden_states=hidden_states,
898
+ key_value_states=encoder_hidden_states,
899
+ attention_mask=encoder_attention_mask,
900
+ layer_head_mask=cross_attn_layer_head_mask,
901
+ past_key_value=cross_attn_past_key_value,
902
+ output_attentions=output_attentions,
903
+ )
904
+ hidden_states = F.dropout(
905
+ hidden_states, p=self.dropout, training=self.training
906
+ )
907
+ hidden_states = residual + hidden_states
908
+ if not self.normalize_before:
909
+ hidden_states = self.encoder_attn_layer_norm(hidden_states)
910
+
911
+ # add cross-attn to positions 3,4 of present_key_value tuple
912
+ present_key_value = present_key_value + cross_attn_present_key_value
913
+
914
+ # Fully Connected
915
+ residual = hidden_states
916
+ if self.normalize_before:
917
+ hidden_states = self.final_layer_norm(hidden_states)
918
+ hidden_states = self.activation_fn(self.fc1(hidden_states))
919
+ hidden_states = F.dropout(
920
+ hidden_states, p=self.activation_dropout, training=self.training
921
+ )
922
+ hidden_states = self.fc2(hidden_states)
923
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
924
+ hidden_states = residual + hidden_states
925
+ if not self.normalize_before:
926
+ hidden_states = self.final_layer_norm(hidden_states)
927
+
928
+ outputs = (hidden_states,)
929
+
930
+ if output_attentions:
931
+ outputs += (self_attn_weights, cross_attn_weights)
932
+
933
+ if use_cache:
934
+ outputs += (present_key_value,)
935
+
936
+ return outputs
937
+
938
+
939
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100PretrainedModel->RotaryIndicTrans
940
+ class RotaryIndicTransPreTrainedModel(PreTrainedModel):
941
+ config_class = RotaryIndicTransConfig
942
+ base_model_prefix = "model"
943
+ supports_gradient_checkpointing = True
944
+ _no_split_modules = ["RotaryIndicTransAttention"]
945
+
946
+ def _init_weights(self, module):
947
+ std = self.config.init_std
948
+ if isinstance(module, nn.Linear):
949
+ module.weight.data.normal_(mean=0.0, std=std)
950
+ if module.bias is not None:
951
+ module.bias.data.zero_()
952
+ elif isinstance(module, nn.Embedding):
953
+ module.weight.data.normal_(mean=0.0, std=std)
954
+ if module.padding_idx is not None:
955
+ module.weight.data[module.padding_idx].zero_()
956
+
957
+ def _set_gradient_checkpointing(self, module, value=False):
958
+ if isinstance(module, (RotaryIndicTransDecoder, RotaryIndicTransEncoder)):
959
+ module.gradient_checkpointing = value
960
+
961
+
962
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100EncoderLayer->RotaryIndicTrans
963
+ class RotaryIndicTransEncoder(RotaryIndicTransPreTrainedModel):
964
+ """
965
+ Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a
966
+ [`RotaryIndicTransEncoderLayer`].
967
+
968
+ Args:
969
+ config: RotaryIndicTransConfig
970
+ embed_tokens (nn.Embedding): output embedding
971
+ """
972
+
973
+ def __init__(
974
+ self,
975
+ config: RotaryIndicTransConfig,
976
+ embed_tokens: Optional[nn.Embedding] = None,
977
+ ):
978
+ super().__init__(config)
979
+
980
+ self.dropout = config.dropout
981
+ self.layerdrop = config.encoder_layerdrop
982
+
983
+ embed_dim = config.encoder_embed_dim
984
+ self.padding_idx = config.pad_token_id
985
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
986
+
987
+ self.embed_tokens = nn.Embedding(
988
+ config.encoder_vocab_size, embed_dim, self.padding_idx
989
+ )
990
+
991
+ if embed_tokens is not None:
992
+ self.embed_tokens.weight = embed_tokens.weight
993
+
994
+ self.layers = nn.ModuleList(
995
+ [RotaryIndicTransEncoderLayer(config) for _ in range(config.encoder_layers)]
996
+ )
997
+ self.layer_norm = (
998
+ nn.LayerNorm(embed_dim) if config.encoder_normalize_before else None
999
+ )
1000
+ self.layernorm_embedding = (
1001
+ nn.LayerNorm(embed_dim) if config.layernorm_embedding else None
1002
+ )
1003
+
1004
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1005
+ self._use_sdpa = config._attn_implementation == "sdpa"
1006
+
1007
+ self.gradient_checkpointing = False
1008
+ # Initialize weights and apply final processing
1009
+ self.post_init()
1010
+
1011
+ def forward(
1012
+ self,
1013
+ input_ids: Optional[torch.Tensor] = None,
1014
+ attention_mask: Optional[torch.Tensor] = None,
1015
+ head_mask: Optional[torch.Tensor] = None,
1016
+ inputs_embeds: Optional[torch.Tensor] = None,
1017
+ output_attentions: Optional[bool] = None,
1018
+ output_hidden_states: Optional[bool] = None,
1019
+ return_dict: Optional[bool] = None,
1020
+ ):
1021
+ r"""
1022
+ Args:
1023
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1024
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1025
+ provide it.
1026
+
1027
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1028
+ [`PreTrainedTokenizer.__call__`] for details.
1029
+
1030
+ [What are input IDs?](../glossary#input-ids)
1031
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1032
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1033
+
1034
+ - 1 for tokens that are **not masked**,
1035
+ - 0 for tokens that are **masked**.
1036
+
1037
+ [What are attention masks?](../glossary#attention-mask)
1038
+ head_mask (`torch.Tensor` of shape `(encoder_layers, encoder_attention_heads)`, *optional*):
1039
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1040
+
1041
+ - 1 indicates the head is **not masked**,
1042
+ - 0 indicates the head is **masked**.
1043
+
1044
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
1045
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation.
1046
+ This is useful if you want more control over how to convert `input_ids` indices into associated vectors
1047
+ than the model's internal embedding lookup matrix.
1048
+ output_attentions (`bool`, *optional*):
1049
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1050
+ returned tensors for more detail.
1051
+ output_hidden_states (`bool`, *optional*):
1052
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1053
+ for more detail.
1054
+ return_dict (`bool`, *optional*):
1055
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1056
+ """
1057
+ output_attentions = (
1058
+ output_attentions
1059
+ if output_attentions is not None
1060
+ else self.config.output_attentions
1061
+ )
1062
+ output_hidden_states = (
1063
+ output_hidden_states
1064
+ if output_hidden_states is not None
1065
+ else self.config.output_hidden_states
1066
+ )
1067
+ return_dict = (
1068
+ return_dict if return_dict is not None else self.config.use_return_dict
1069
+ )
1070
+
1071
+ # retrieve input_ids and inputs_embeds
1072
+ if input_ids is not None and inputs_embeds is not None:
1073
+ raise ValueError(
1074
+ "You cannot specify both input_ids and inputs_embeds at the same time"
1075
+ )
1076
+ elif input_ids is not None:
1077
+ self.warn_if_padding_and_no_attention_mask(input_ids, attention_mask)
1078
+ input_shape = input_ids.size()
1079
+ input_ids = input_ids.view(-1, input_shape[-1])
1080
+ elif inputs_embeds is not None:
1081
+ input_shape = inputs_embeds.size()[:-1]
1082
+ else:
1083
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
1084
+
1085
+ if inputs_embeds is None:
1086
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1087
+
1088
+ hidden_states = inputs_embeds
1089
+
1090
+ if self.layernorm_embedding is not None:
1091
+ hidden_states = self.layernorm_embedding(hidden_states)
1092
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
1093
+
1094
+ if attention_mask is not None:
1095
+ if self._use_flash_attention_2:
1096
+ attention_mask = attention_mask if 0 in attention_mask else None
1097
+ elif self._use_sdpa and head_mask is None and not output_attentions:
1098
+ # output_attentions=True & head_mask can not be supported when using SDPA, fall back to
1099
+ # the manual implementation that requires a 4D causal mask in all cases.
1100
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1101
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1102
+ attention_mask, inputs_embeds.dtype
1103
+ )
1104
+ else:
1105
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1106
+ attention_mask = _prepare_4d_attention_mask(
1107
+ attention_mask, inputs_embeds.dtype
1108
+ )
1109
+
1110
+ encoder_states = () if output_hidden_states else None
1111
+ all_attentions = () if output_attentions else None
1112
+
1113
+ # check if head_mask has a correct number of layers specified if desired
1114
+ if head_mask is not None:
1115
+ if head_mask.size()[0] != len(self.layers):
1116
+ raise ValueError(
1117
+ f"The head_mask should be specified for {len(self.layers)} layers, but it is for"
1118
+ f" {head_mask.size()[0]}."
1119
+ )
1120
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
1121
+
1122
+ for idx, encoder_layer in enumerate(self.layers):
1123
+ if output_hidden_states:
1124
+ encoder_states = encoder_states + (hidden_states,)
1125
+
1126
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1127
+ dropout_probability = torch.rand([])
1128
+
1129
+ skip_the_layer = (
1130
+ True
1131
+ if self.training and (dropout_probability < self.layerdrop)
1132
+ else False
1133
+ )
1134
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
1135
+ # under deepspeed zero3 all gpus must run in sync
1136
+
1137
+ if self.gradient_checkpointing and self.training:
1138
+ # create gradient checkpointing function
1139
+ def create_custom_forward(module):
1140
+ def custom_forward(*inputs):
1141
+ return module(*inputs, output_attentions)
1142
+
1143
+ return custom_forward
1144
+
1145
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1146
+ create_custom_forward(encoder_layer),
1147
+ hidden_states,
1148
+ attention_mask,
1149
+ (head_mask[idx] if head_mask is not None else None),
1150
+ )
1151
+ else:
1152
+ layer_outputs = encoder_layer(
1153
+ hidden_states,
1154
+ attention_mask,
1155
+ layer_head_mask=(
1156
+ head_mask[idx] if head_mask is not None else None
1157
+ ),
1158
+ output_attentions=output_attentions,
1159
+ )
1160
+
1161
+ hidden_states = layer_outputs[0]
1162
+
1163
+ if skip_the_layer:
1164
+ layer_outputs = (None, None)
1165
+
1166
+ if output_attentions:
1167
+ all_attentions = all_attentions + (layer_outputs[1],)
1168
+
1169
+ if self.layer_norm is not None:
1170
+ hidden_states = self.layer_norm(hidden_states)
1171
+
1172
+ if output_hidden_states:
1173
+ encoder_states = encoder_states + (hidden_states,)
1174
+
1175
+ if not return_dict:
1176
+ return tuple(
1177
+ v
1178
+ for v in [hidden_states, encoder_states, all_attentions]
1179
+ if v is not None
1180
+ )
1181
+ return BaseModelOutput(
1182
+ last_hidden_state=hidden_states,
1183
+ hidden_states=encoder_states,
1184
+ attentions=all_attentions,
1185
+ )
1186
+
1187
+
1188
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100DecoderLayer->RotaryIndicTrans
1189
+ class RotaryIndicTransDecoder(RotaryIndicTransPreTrainedModel):
1190
+ """
1191
+ Transformer decoder consisting of *config.decoder_layers* layers. Each layer is a [`RotaryIndicTransDecoderLayer`]
1192
+
1193
+ Args:
1194
+ config: RotaryIndicTransConfig
1195
+ embed_tokens (nn.Embedding): output embedding
1196
+ """
1197
+
1198
+ def __init__(
1199
+ self,
1200
+ config: RotaryIndicTransConfig,
1201
+ embed_tokens: Optional[nn.Embedding] = None,
1202
+ ):
1203
+ super().__init__(config)
1204
+ self.dropout = config.dropout
1205
+ self.layerdrop = config.decoder_layerdrop
1206
+
1207
+ embed_dim = config.encoder_embed_dim
1208
+ self.padding_idx = config.pad_token_id
1209
+ self.embed_scale = math.sqrt(embed_dim) if config.scale_embedding else 1.0
1210
+
1211
+ self.embed_tokens = nn.Embedding(
1212
+ config.decoder_vocab_size, embed_dim, self.padding_idx
1213
+ )
1214
+
1215
+ if embed_tokens is not None:
1216
+ self.embed_tokens.weight = embed_tokens.weight
1217
+
1218
+ self.layers = nn.ModuleList(
1219
+ [RotaryIndicTransDecoderLayer(config) for _ in range(config.decoder_layers)]
1220
+ )
1221
+ self.layer_norm = (
1222
+ nn.LayerNorm(embed_dim) if config.decoder_normalize_before else None
1223
+ )
1224
+ self.layernorm_embedding = (
1225
+ nn.LayerNorm(embed_dim) if config.layernorm_embedding else None
1226
+ )
1227
+
1228
+ self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
1229
+ self._use_sdpa = config._attn_implementation == "sdpa"
1230
+
1231
+ self.gradient_checkpointing = False
1232
+ # Initialize weights and apply final processing
1233
+ self.post_init()
1234
+
1235
+ def forward(
1236
+ self,
1237
+ input_ids: Optional[torch.Tensor] = None,
1238
+ attention_mask: Optional[torch.Tensor] = None,
1239
+ encoder_hidden_states: Optional[torch.Tensor] = None,
1240
+ encoder_attention_mask: Optional[torch.Tensor] = None,
1241
+ head_mask: Optional[torch.Tensor] = None,
1242
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1243
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1244
+ inputs_embeds: Optional[torch.Tensor] = None,
1245
+ use_cache: Optional[bool] = None,
1246
+ output_attentions: Optional[bool] = None,
1247
+ output_hidden_states: Optional[bool] = None,
1248
+ return_dict: Optional[bool] = None,
1249
+ ):
1250
+ r"""
1251
+ Args:
1252
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
1253
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you
1254
+ provide it.
1255
+
1256
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
1257
+ [`PreTrainedTokenizer.__call__`] for details.
1258
+
1259
+ [What are input IDs?](../glossary#input-ids)
1260
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
1261
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
1262
+
1263
+ - 1 for tokens that are **not masked**,
1264
+ - 0 for tokens that are **masked**.
1265
+
1266
+ [What are attention masks?](../glossary#attention-mask)
1267
+ encoder_hidden_states (`torch.FloatTensor` of shape `(batch_size, encoder_sequence_length, hidden_size)`, *optional*):
1268
+ Sequence of hidden-states at the output of the last layer of the encoder. Used in the cross-attention
1269
+ of the decoder.
1270
+ encoder_attention_mask (`torch.LongTensor` of shape `(batch_size, encoder_sequence_length)`, *optional*):
1271
+ Mask to avoid performing cross-attention on padding tokens indices of encoder input_ids. Mask values
1272
+ selected in `[0, 1]`:
1273
+
1274
+ - 1 for tokens that are **not masked**,
1275
+ - 0 for tokens that are **masked**.
1276
+
1277
+ [What are attention masks?](../glossary#attention-mask)
1278
+ head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1279
+ Mask to nullify selected heads of the attention modules. Mask values selected in `[0, 1]`:
1280
+
1281
+ - 1 indicates the head is **not masked**,
1282
+ - 0 indicates the head is **masked**.
1283
+
1284
+ cross_attn_head_mask (`torch.Tensor` of shape `(decoder_layers, decoder_attention_heads)`, *optional*):
1285
+ Mask to nullify selected heads of the cross-attention modules in the decoder to avoid performing
1286
+ cross-attention on hidden heads. Mask values selected in `[0, 1]`:
1287
+
1288
+ - 1 indicates the head is **not masked**,
1289
+ - 0 indicates the head is **masked**.
1290
+
1291
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
1292
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
1293
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of
1294
+ shape `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
1295
+
1296
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the
1297
+ cross-attention blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
1298
+
1299
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those
1300
+ that don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of
1301
+ all `decoder_input_ids` of shape `(batch_size, sequence_length)`. inputs_embeds (`torch.FloatTensor` of
1302
+ shape `(batch_size, sequence_length, hidden_size)`, *optional*): Optionally, instead of passing
1303
+ `input_ids` you can choose to directly pass an embedded representation. This is useful if you want more
1304
+ control over how to convert `input_ids` indices into associated vectors than the model's internal
1305
+ embedding lookup matrix.
1306
+ output_attentions (`bool`, *optional*):
1307
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
1308
+ returned tensors for more detail.
1309
+ output_hidden_states (`bool`, *optional*):
1310
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors
1311
+ for more detail.
1312
+ return_dict (`bool`, *optional*):
1313
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
1314
+ """
1315
+ output_attentions = (
1316
+ output_attentions
1317
+ if output_attentions is not None
1318
+ else self.config.output_attentions
1319
+ )
1320
+ output_hidden_states = (
1321
+ output_hidden_states
1322
+ if output_hidden_states is not None
1323
+ else self.config.output_hidden_states
1324
+ )
1325
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1326
+ return_dict = (
1327
+ return_dict if return_dict is not None else self.config.use_return_dict
1328
+ )
1329
+
1330
+ # retrieve input_ids and inputs_embeds
1331
+ if input_ids is not None and inputs_embeds is not None:
1332
+ raise ValueError(
1333
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
1334
+ )
1335
+ elif input_ids is not None:
1336
+ input_shape = input_ids.size()
1337
+ input_ids = input_ids.view(-1, input_shape[-1])
1338
+ elif inputs_embeds is not None:
1339
+ input_shape = inputs_embeds.size()[:-1]
1340
+ else:
1341
+ raise ValueError(
1342
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
1343
+ )
1344
+
1345
+ # past_key_values_length
1346
+ past_key_values_length = (
1347
+ past_key_values[0][0].shape[2] if past_key_values is not None else 0
1348
+ )
1349
+
1350
+ if inputs_embeds is None:
1351
+ inputs_embeds = self.embed_tokens(input_ids) * self.embed_scale
1352
+
1353
+ if self._use_flash_attention_2:
1354
+ # 2d mask is passed through the layers
1355
+ attention_mask = (
1356
+ attention_mask
1357
+ if (attention_mask is not None and 0 in attention_mask)
1358
+ else None
1359
+ )
1360
+ elif self._use_sdpa and not output_attentions and cross_attn_head_mask is None:
1361
+ # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
1362
+ # the manual implementation that requires a 4D causal mask in all cases.
1363
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1364
+ attention_mask,
1365
+ input_shape,
1366
+ inputs_embeds,
1367
+ past_key_values_length,
1368
+ )
1369
+ else:
1370
+ # 4d mask is passed through the layers
1371
+ attention_mask = _prepare_4d_causal_attention_mask(
1372
+ attention_mask, input_shape, inputs_embeds, past_key_values_length
1373
+ )
1374
+
1375
+ # expand encoder attention mask
1376
+ if encoder_hidden_states is not None and encoder_attention_mask is not None:
1377
+ if self._use_flash_attention_2:
1378
+ encoder_attention_mask = (
1379
+ encoder_attention_mask if 0 in encoder_attention_mask else None
1380
+ )
1381
+ elif (
1382
+ self._use_sdpa
1383
+ and cross_attn_head_mask is None
1384
+ and not output_attentions
1385
+ ):
1386
+ # output_attentions=True & cross_attn_head_mask can not be supported when using SDPA, and we fall back on
1387
+ # the manual implementation that requires a 4D causal mask in all cases.
1388
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1389
+ encoder_attention_mask = _prepare_4d_attention_mask_for_sdpa(
1390
+ encoder_attention_mask,
1391
+ inputs_embeds.dtype,
1392
+ tgt_len=input_shape[-1],
1393
+ )
1394
+ else:
1395
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
1396
+ encoder_attention_mask = _prepare_4d_attention_mask(
1397
+ encoder_attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
1398
+ )
1399
+
1400
+ hidden_states = inputs_embeds
1401
+
1402
+ if self.layernorm_embedding is not None:
1403
+ hidden_states = self.layernorm_embedding(hidden_states)
1404
+
1405
+ hidden_states = F.dropout(hidden_states, p=self.dropout, training=self.training)
1406
+
1407
+ if self.gradient_checkpointing and self.training:
1408
+ if use_cache:
1409
+ logger.warning_once(
1410
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting"
1411
+ " `use_cache=False`..."
1412
+ )
1413
+ use_cache = False
1414
+
1415
+ # decoder layers
1416
+ all_hidden_states = () if output_hidden_states else None
1417
+ all_self_attns = () if output_attentions else None
1418
+ all_cross_attentions = () if output_attentions else None
1419
+ next_decoder_cache = () if use_cache else None
1420
+
1421
+ # check if head_mask/cross_attn_head_mask has a correct number of layers specified if desired
1422
+ for attn_mask, mask_name in zip(
1423
+ [head_mask, cross_attn_head_mask], ["head_mask", "cross_attn_head_mask"]
1424
+ ):
1425
+ if attn_mask is not None:
1426
+ if attn_mask.size()[0] != len(self.layers):
1427
+ raise ValueError(
1428
+ f"The `{mask_name}` should be specified for {len(self.layers)} layers, but it is for"
1429
+ f" {head_mask.size()[0]}."
1430
+ )
1431
+ deepspeed_zero3_is_enabled = is_deepspeed_zero3_enabled()
1432
+
1433
+ for idx, decoder_layer in enumerate(self.layers):
1434
+ if output_hidden_states:
1435
+ all_hidden_states += (hidden_states,)
1436
+
1437
+ # add LayerDrop (see https://arxiv.org/abs/1909.11556 for description)
1438
+ dropout_probability = torch.rand([])
1439
+
1440
+ skip_the_layer = (
1441
+ True
1442
+ if self.training and (dropout_probability < self.layerdrop)
1443
+ else False
1444
+ )
1445
+ if not skip_the_layer or deepspeed_zero3_is_enabled:
1446
+ # under deepspeed zero3 all gpus must run in sync
1447
+
1448
+ past_key_value = (
1449
+ past_key_values[idx] if past_key_values is not None else None
1450
+ )
1451
+
1452
+ if self.gradient_checkpointing and self.training:
1453
+
1454
+ def create_custom_forward(module):
1455
+ def custom_forward(*inputs):
1456
+ # None for past_key_value
1457
+ return module(*inputs, output_attentions, use_cache)
1458
+
1459
+ return custom_forward
1460
+
1461
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1462
+ create_custom_forward(decoder_layer),
1463
+ hidden_states,
1464
+ attention_mask,
1465
+ encoder_hidden_states,
1466
+ encoder_attention_mask,
1467
+ head_mask[idx] if head_mask is not None else None,
1468
+ (
1469
+ cross_attn_head_mask[idx]
1470
+ if cross_attn_head_mask is not None
1471
+ else None
1472
+ ),
1473
+ None,
1474
+ )
1475
+ else:
1476
+ layer_outputs = decoder_layer(
1477
+ hidden_states,
1478
+ attention_mask=attention_mask,
1479
+ encoder_hidden_states=encoder_hidden_states,
1480
+ encoder_attention_mask=encoder_attention_mask,
1481
+ layer_head_mask=(
1482
+ head_mask[idx] if head_mask is not None else None
1483
+ ),
1484
+ cross_attn_layer_head_mask=(
1485
+ cross_attn_head_mask[idx]
1486
+ if cross_attn_head_mask is not None
1487
+ else None
1488
+ ),
1489
+ past_key_value=past_key_value,
1490
+ output_attentions=output_attentions,
1491
+ use_cache=use_cache,
1492
+ )
1493
+
1494
+ hidden_states = layer_outputs[0]
1495
+
1496
+ if skip_the_layer:
1497
+ continue
1498
+
1499
+ if use_cache:
1500
+ next_decoder_cache += (layer_outputs[3 if output_attentions else 1],)
1501
+
1502
+ if output_attentions:
1503
+ all_self_attns += (layer_outputs[1],)
1504
+ all_cross_attentions += (layer_outputs[2],)
1505
+
1506
+ if self.layer_norm is not None:
1507
+ hidden_states = self.layer_norm(hidden_states)
1508
+
1509
+ # add hidden states from the last decoder layer
1510
+ if output_hidden_states:
1511
+ all_hidden_states += (hidden_states,)
1512
+
1513
+ next_cache = next_decoder_cache if use_cache else None
1514
+ if not return_dict:
1515
+ return tuple(
1516
+ v
1517
+ for v in [
1518
+ hidden_states,
1519
+ next_cache,
1520
+ all_hidden_states,
1521
+ all_self_attns,
1522
+ all_cross_attentions,
1523
+ ]
1524
+ if v is not None
1525
+ )
1526
+ return BaseModelOutputWithPastAndCrossAttentions(
1527
+ last_hidden_state=hidden_states,
1528
+ past_key_values=next_cache,
1529
+ hidden_states=all_hidden_states,
1530
+ attentions=all_self_attns,
1531
+ cross_attentions=all_cross_attentions,
1532
+ )
1533
+
1534
+
1535
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100Model->RotaryIndicTrans
1536
+ class RotaryIndicTransModel(RotaryIndicTransPreTrainedModel):
1537
+ _tied_weights_keys = None
1538
+
1539
+ def __init__(self, config: RotaryIndicTransConfig):
1540
+ super().__init__(config)
1541
+
1542
+ self.encoder = RotaryIndicTransEncoder(config)
1543
+ self.decoder = RotaryIndicTransDecoder(config)
1544
+
1545
+ # Initialize weights and apply final processing
1546
+ self.post_init()
1547
+
1548
+ def get_encoder(self):
1549
+ return self.encoder
1550
+
1551
+ def get_decoder(self):
1552
+ return self.decoder
1553
+
1554
+ def forward(
1555
+ self,
1556
+ input_ids: Optional[torch.LongTensor] = None,
1557
+ attention_mask: Optional[torch.Tensor] = None,
1558
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1559
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1560
+ head_mask: Optional[torch.Tensor] = None,
1561
+ decoder_head_mask: Optional[torch.Tensor] = None,
1562
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1563
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1564
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1565
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1566
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1567
+ use_cache: Optional[bool] = None,
1568
+ output_attentions: Optional[bool] = None,
1569
+ output_hidden_states: Optional[bool] = None,
1570
+ return_dict: Optional[bool] = None,
1571
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqModelOutput]:
1572
+ output_attentions = (
1573
+ output_attentions
1574
+ if output_attentions is not None
1575
+ else self.config.output_attentions
1576
+ )
1577
+ output_hidden_states = (
1578
+ output_hidden_states
1579
+ if output_hidden_states is not None
1580
+ else self.config.output_hidden_states
1581
+ )
1582
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1583
+ return_dict = (
1584
+ return_dict if return_dict is not None else self.config.use_return_dict
1585
+ )
1586
+
1587
+ if encoder_outputs is None:
1588
+ encoder_outputs = self.encoder(
1589
+ input_ids=input_ids,
1590
+ attention_mask=attention_mask,
1591
+ head_mask=head_mask,
1592
+ inputs_embeds=inputs_embeds,
1593
+ output_attentions=output_attentions,
1594
+ output_hidden_states=output_hidden_states,
1595
+ return_dict=return_dict,
1596
+ )
1597
+ # If the user passed a tuple for encoder_outputs, we wrap it in a BaseModelOutput when return_dict=True
1598
+ elif return_dict and not isinstance(encoder_outputs, BaseModelOutput):
1599
+ encoder_outputs = BaseModelOutput(
1600
+ last_hidden_state=encoder_outputs[0],
1601
+ hidden_states=encoder_outputs[1] if len(encoder_outputs) > 1 else None,
1602
+ attentions=encoder_outputs[2] if len(encoder_outputs) > 2 else None,
1603
+ )
1604
+
1605
+ # decoder outputs consists of (dec_features, past_key_value, dec_hidden, dec_attn)
1606
+ decoder_outputs = self.decoder(
1607
+ input_ids=decoder_input_ids,
1608
+ attention_mask=decoder_attention_mask,
1609
+ encoder_hidden_states=encoder_outputs[0],
1610
+ encoder_attention_mask=attention_mask,
1611
+ head_mask=decoder_head_mask,
1612
+ cross_attn_head_mask=cross_attn_head_mask,
1613
+ past_key_values=past_key_values,
1614
+ inputs_embeds=decoder_inputs_embeds,
1615
+ use_cache=use_cache,
1616
+ output_attentions=output_attentions,
1617
+ output_hidden_states=output_hidden_states,
1618
+ return_dict=return_dict,
1619
+ )
1620
+
1621
+ if not return_dict:
1622
+ return decoder_outputs + encoder_outputs
1623
+
1624
+ return Seq2SeqModelOutput(
1625
+ last_hidden_state=decoder_outputs.last_hidden_state,
1626
+ past_key_values=decoder_outputs.past_key_values,
1627
+ decoder_hidden_states=decoder_outputs.hidden_states,
1628
+ decoder_attentions=decoder_outputs.attentions,
1629
+ cross_attentions=decoder_outputs.cross_attentions,
1630
+ encoder_last_hidden_state=encoder_outputs.last_hidden_state,
1631
+ encoder_hidden_states=encoder_outputs.hidden_states,
1632
+ encoder_attentions=encoder_outputs.attentions,
1633
+ )
1634
+
1635
+
1636
+ # Copied from transformers.models.m2m_100.modeling_m2m_100.M2M100ForConditionalGeneration->RotaryIndicTrans
1637
+ class RotaryIndicTransForConditionalGeneration(RotaryIndicTransPreTrainedModel):
1638
+ base_model_prefix = "model"
1639
+ _tied_weights_keys = None
1640
+ _label_smoothing = 0.0
1641
+
1642
+ def __init__(self, config: RotaryIndicTransConfig):
1643
+ super().__init__(config)
1644
+ self.model = RotaryIndicTransModel(config)
1645
+ self.lm_head = nn.Linear(
1646
+ config.decoder_embed_dim, config.decoder_vocab_size, bias=False
1647
+ )
1648
+
1649
+ if config.share_decoder_input_output_embed:
1650
+ self.lm_head.weight = self.model.decoder.embed_tokens.weight
1651
+
1652
+ self.post_init()
1653
+
1654
+ def tie_weights(self):
1655
+ pass
1656
+
1657
+ def get_encoder(self):
1658
+ return self.model.get_encoder()
1659
+
1660
+ def get_decoder(self):
1661
+ return self.model.get_decoder()
1662
+
1663
+ def get_output_embeddings(self):
1664
+ return self.lm_head
1665
+
1666
+ def set_output_embeddings(self, new_embeddings):
1667
+ self.lm_head = new_embeddings
1668
+
1669
+ def set_label_smoothing(self, label_smoothing):
1670
+ self._label_smoothing = label_smoothing
1671
+
1672
+ def forward(
1673
+ self,
1674
+ input_ids: Optional[torch.LongTensor] = None,
1675
+ attention_mask: Optional[torch.Tensor] = None,
1676
+ decoder_input_ids: Optional[torch.LongTensor] = None,
1677
+ decoder_attention_mask: Optional[torch.LongTensor] = None,
1678
+ head_mask: Optional[torch.Tensor] = None,
1679
+ decoder_head_mask: Optional[torch.Tensor] = None,
1680
+ cross_attn_head_mask: Optional[torch.Tensor] = None,
1681
+ encoder_outputs: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1682
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
1683
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1684
+ decoder_inputs_embeds: Optional[torch.FloatTensor] = None,
1685
+ labels: Optional[torch.LongTensor] = None,
1686
+ use_cache: Optional[bool] = None,
1687
+ output_attentions: Optional[bool] = None,
1688
+ output_hidden_states: Optional[bool] = None,
1689
+ return_dict: Optional[bool] = None,
1690
+ ) -> Union[Tuple[torch.Tensor], Seq2SeqLMOutput]:
1691
+ r"""
1692
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1693
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1694
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1695
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1696
+
1697
+ Returns:
1698
+ """
1699
+ return_dict = (
1700
+ return_dict if return_dict is not None else self.config.use_return_dict
1701
+ )
1702
+
1703
+ if labels is not None:
1704
+ if decoder_input_ids is None:
1705
+ decoder_input_ids = shift_tokens_right(
1706
+ labels, self.config.pad_token_id, self.config.decoder_start_token_id
1707
+ )
1708
+
1709
+ outputs = self.model(
1710
+ input_ids,
1711
+ attention_mask=attention_mask,
1712
+ decoder_input_ids=decoder_input_ids,
1713
+ encoder_outputs=encoder_outputs,
1714
+ decoder_attention_mask=decoder_attention_mask,
1715
+ head_mask=head_mask,
1716
+ decoder_head_mask=decoder_head_mask,
1717
+ cross_attn_head_mask=cross_attn_head_mask,
1718
+ past_key_values=past_key_values,
1719
+ inputs_embeds=inputs_embeds,
1720
+ decoder_inputs_embeds=decoder_inputs_embeds,
1721
+ use_cache=use_cache,
1722
+ output_attentions=output_attentions,
1723
+ output_hidden_states=output_hidden_states,
1724
+ return_dict=return_dict,
1725
+ )
1726
+ lm_logits = self.lm_head(outputs[0])
1727
+
1728
+ masked_lm_loss = None
1729
+ if labels is not None:
1730
+ # move labels to the correct device to enable PP
1731
+ labels = labels.to(lm_logits.device)
1732
+ masked_lm_loss = F.cross_entropy(
1733
+ input=lm_logits.view(-1, self.config.decoder_vocab_size),
1734
+ target=labels.view(-1),
1735
+ ignore_index=-100,
1736
+ label_smoothing=self._label_smoothing,
1737
+ )
1738
+
1739
+ if not return_dict:
1740
+ output = (lm_logits,) + outputs[1:]
1741
+ return (
1742
+ ((masked_lm_loss,) + output) if masked_lm_loss is not None else output
1743
+ )
1744
+
1745
+ return Seq2SeqLMOutput(
1746
+ loss=masked_lm_loss,
1747
+ logits=lm_logits,
1748
+ past_key_values=outputs.past_key_values,
1749
+ decoder_hidden_states=outputs.decoder_hidden_states,
1750
+ decoder_attentions=outputs.decoder_attentions,
1751
+ cross_attentions=outputs.cross_attentions,
1752
+ encoder_last_hidden_state=outputs.encoder_last_hidden_state,
1753
+ encoder_hidden_states=outputs.encoder_hidden_states,
1754
+ encoder_attentions=outputs.encoder_attentions,
1755
+ )
1756
+
1757
+ def prepare_inputs_for_generation(
1758
+ self,
1759
+ decoder_input_ids,
1760
+ past_key_values=None,
1761
+ attention_mask=None,
1762
+ head_mask=None,
1763
+ decoder_head_mask=None,
1764
+ cross_attn_head_mask=None,
1765
+ use_cache=None,
1766
+ encoder_outputs=None,
1767
+ **kwargs,
1768
+ ):
1769
+ # cut decoder_input_ids if past is used
1770
+ if past_key_values is not None:
1771
+ decoder_input_ids = decoder_input_ids[:, -1:]
1772
+
1773
+ return {
1774
+ "input_ids": None, # encoder_outputs is defined. input_ids not needed
1775
+ "encoder_outputs": encoder_outputs,
1776
+ "past_key_values": past_key_values,
1777
+ "decoder_input_ids": decoder_input_ids,
1778
+ "attention_mask": attention_mask,
1779
+ "head_mask": head_mask,
1780
+ "decoder_head_mask": decoder_head_mask,
1781
+ "cross_attn_head_mask": cross_attn_head_mask,
1782
+ "use_cache": use_cache, # change this to avoid caching (presumably for debugging)
1783
+ }
1784
+
1785
+ @staticmethod
1786
+ def _reorder_cache(past_key_values, beam_idx):
1787
+ reordered_past = ()
1788
+ for layer_past in past_key_values:
1789
+ reordered_past += (
1790
+ tuple(
1791
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1792
+ ),
1793
+ )
1794
+ return reordered_past