qhduan commited on
Commit
a53fab2
1 Parent(s): b1422b9

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_gpt_jiang.py +122 -0
  2. modeling_gpt_jiang.py +807 -0
configuration_gpt_jiang.py ADDED
@@ -0,0 +1,122 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 EleutherAI The HuggingFace Inc. team. and KDF.ai 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
+ """ GPTJiang model configuration"""
16
+
17
+ from transformers.configuration_utils import PretrainedConfig
18
+ from transformers.utils import logging
19
+
20
+
21
+ logger = logging.get_logger(__name__)
22
+
23
+ GPT_JIANG_PRETRAINED_CONFIG_ARCHIVE_MAP = {}
24
+
25
+
26
+ class GPTJiangConfig(PretrainedConfig):
27
+ r"""
28
+ This is the configuration class to store the configuration of a [`GPTJiangModel`]. It is used to instantiate an
29
+ GPTJiang model according to the specified arguments, defining the model architecture. Instantiating a configuration
30
+ with the defaults will yield a similar configuration to that of the GPTJiang
31
+
32
+ Configuration objects inherit from [`PretrainedConfig`] and can be used to control the model outputs. Read the
33
+ documentation from [`PretrainedConfig`] for more information.
34
+
35
+
36
+ Args:
37
+ vocab_size (`int`, *optional*, defaults to 50432):
38
+ Vocabulary size of the GPTJiang model. Defines the number of different tokens that can be represented by the
39
+ `inputs_ids` passed when calling [`GPTJiangModel`].
40
+ hidden_size (`int`, *optional*, defaults to 6144):
41
+ Dimension of the encoder layers and the pooler layer.
42
+ num_hidden_layers (`int`, *optional*, defaults to 44):
43
+ Number of hidden layers in the Transformer encoder.
44
+ num_attention_heads (`int`, *optional*, defaults to 64):
45
+ Number of attention heads for each attention layer in the Transformer encoder.
46
+ intermediate_size (`int`, *optional*, defaults to 24576):
47
+ Dimension of the "intermediate" (i.e., feed-forward) layer in the Transformer encoder.
48
+ hidden_act (`str` or `function`, *optional*, defaults to `"gelu"`):
49
+ The non-linear activation function (function or string) in the encoder and pooler. If string, `"gelu"`,
50
+ `"relu"`, `"selu"` and `"gelu_new"` are supported.
51
+ rotary_pct (`float`, *optional*, defaults to 0.25):
52
+ percentage of hidden dimensions to allocate to rotary embeddings
53
+ rotary_emb_base (`int`, *optional*, defaults to 10000)
54
+ base for computing rotary embeddings frequency
55
+ max_position_embeddings (`int`, *optional*, defaults to 2048):
56
+ The maximum sequence length that this model might ever be used with. Typically set this to something large
57
+ just in case (e.g., 512 or 1024 or 2048).
58
+ initializer_range (`float`, *optional*, defaults to 1e-5):
59
+ The standard deviation of the truncated_normal_initializer for initializing all weight matrices.
60
+ layer_norm_eps (`float`, *optional*, defaults to 1e-12):
61
+ The epsilon used by the layer normalization layers.
62
+ use_cache (`bool`, *optional*, defaults to `True`):
63
+ Whether or not the model should return the last key/values attentions (not used by all models). Only
64
+ relevant if `config.is_decoder=True`.
65
+ use_parallel_residual (`bool`, *optional*, defaults to `True`):
66
+ Whether to use a "parallel" formulation in each Transformer layer, which can provide a slight training
67
+ speedup at large scales (e.g. 20B).
68
+ Example:
69
+
70
+ ```python
71
+ >>> from transformers import GPTJiangConfig, GPTJiangModel
72
+
73
+ >>> # Initializing a GPTJiang style configuration
74
+ >>> configuration = GPTJiangConfig()
75
+
76
+ >>> # Initializing a model (with random weights) from the gpt-jiang style configuration
77
+ >>> model = GPTJiangModel(configuration) # doctest: +SKIP
78
+
79
+ >>> # Accessing the model configuration
80
+ >>> configuration = model.config # doctest: +SKIP
81
+ ```"""
82
+ model_type = "gpt_jiang"
83
+
84
+ def __init__(
85
+ self,
86
+ vocab_size=57000,
87
+ hidden_size=5120,
88
+ num_hidden_layers=48,
89
+ num_attention_heads=40,
90
+ intermediate_size=12288,
91
+ hidden_act="gelu",
92
+ rotary_pct=1.0,
93
+ rotary_emb_base=10000,
94
+ max_position_embeddings=4096,
95
+ initializer_range=0.02,
96
+ layer_norm_eps=1e-5,
97
+ use_cache=True,
98
+ bos_token_id=0,
99
+ eos_token_id=2,
100
+ tie_word_embeddings=False,
101
+ use_parallel_residual=True,
102
+ gated=True,
103
+ mlp_bias=False,
104
+ **kwargs,
105
+ ):
106
+ super().__init__(bos_token_id=bos_token_id, eos_token_id=eos_token_id, **kwargs)
107
+ self.vocab_size = vocab_size
108
+ self.max_position_embeddings = max_position_embeddings
109
+ self.hidden_size = hidden_size
110
+ self.num_hidden_layers = num_hidden_layers
111
+ self.num_attention_heads = num_attention_heads
112
+ self.intermediate_size = intermediate_size
113
+ self.hidden_act = hidden_act
114
+ self.rotary_pct = rotary_pct
115
+ self.rotary_emb_base = rotary_emb_base
116
+ self.initializer_range = initializer_range
117
+ self.layer_norm_eps = layer_norm_eps
118
+ self.use_cache = use_cache
119
+ self.tie_word_embeddings = tie_word_embeddings
120
+ self.use_parallel_residual = use_parallel_residual
121
+ self.gated = gated
122
+ self.mlp_bias = mlp_bias
modeling_gpt_jiang.py ADDED
@@ -0,0 +1,807 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2023 EleutherAI The HuggingFace Inc. team. and JIANG.ai 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 GPTJiang model."""
16
+
17
+ from typing import Optional, Tuple, Union
18
+
19
+ import torch
20
+ import torch.utils.checkpoint
21
+ from torch import nn
22
+ from torch.nn import CrossEntropyLoss
23
+ import torch.nn.functional as F
24
+
25
+ from transformers.activations import ACT2FN
26
+ from transformers.file_utils import (
27
+ add_code_sample_docstrings,
28
+ add_start_docstrings,
29
+ add_start_docstrings_to_model_forward,
30
+ replace_return_docstrings,
31
+ )
32
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import logging
35
+ from .configuration_gpt_jiang import GPTJiangConfig
36
+
37
+
38
+ logger = logging.get_logger(__name__)
39
+
40
+ _CONFIG_FOR_DOC = "GPTJiangConfig"
41
+ GPT_JIANG_PRETRAINED_MODEL_ARCHIVE_LIST = []
42
+
43
+
44
+ class RMSNorm(torch.nn.Module):
45
+ def __init__(self, dim: int, eps: float=1e-5):
46
+ super().__init__()
47
+ self.eps = eps
48
+ self.weight = nn.Parameter(torch.ones(dim))
49
+
50
+ def _norm(self, x):
51
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
52
+
53
+ def forward(self, x):
54
+ output = self._norm(x.float()).type_as(x)
55
+ return output * self.weight
56
+
57
+
58
+ class GPTJiangPreTrainedModel(PreTrainedModel):
59
+ """
60
+ An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
61
+ models.
62
+ """
63
+ config_class = GPTJiangConfig
64
+ base_model_prefix = "gpt_jiang"
65
+ supports_gradient_checkpointing = True
66
+ _no_split_modules = ["GPTJiangLayer"]
67
+
68
+ def _init_weights(self, module):
69
+ """Initialize the weights"""
70
+ if isinstance(module, GatedLinear):
71
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
72
+ if module.bias is not None:
73
+ module.bias.data.fill_(1.0)
74
+ elif isinstance(module, nn.Linear):
75
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
76
+ if module.bias is not None:
77
+ module.bias.data.zero_()
78
+ elif isinstance(module, nn.Embedding):
79
+ module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
80
+ if module.padding_idx is not None:
81
+ module.weight.data[module.padding_idx].zero_()
82
+ elif isinstance(module, RMSNorm):
83
+ # module.bias.data.zero_()
84
+ module.weight.data.fill_(1.0)
85
+
86
+ def _set_gradient_checkpointing(self, module, value=False):
87
+ if isinstance(module, GPTJiangModel):
88
+ module.gradient_checkpointing = value
89
+
90
+
91
+ class GPTJiangAttention(nn.Module):
92
+ def __init__(self, config):
93
+ super().__init__()
94
+ self.max_position_embeddings = config.max_position_embeddings
95
+ self.num_attention_heads = config.num_attention_heads
96
+ self.hidden_size = config.hidden_size
97
+ self.head_size = self.hidden_size // self.num_attention_heads
98
+ self.rotary_ndims = int(self.head_size * config.rotary_pct)
99
+ self.rotary_emb = RotaryEmbedding(
100
+ self.rotary_ndims,
101
+ config.max_position_embeddings,
102
+ base=config.rotary_emb_base
103
+ )
104
+ self.query_key_value = nn.Linear(config.hidden_size, 3 * config.hidden_size)
105
+ self.dense = nn.Linear(config.hidden_size, config.hidden_size)
106
+ self.causal_mask_cached = None
107
+
108
+ def causal_mask(self, x, seq_len):
109
+ if self.causal_mask_cached is None or seq_len > self.causal_mask_cached.shape[2]:
110
+ cache_size = max(self.max_position_embeddings, seq_len)
111
+ self.causal_mask_cached = torch.ones(
112
+ cache_size,
113
+ cache_size,
114
+ dtype=torch.bool
115
+ ).tril().view(1, 1, cache_size, cache_size)
116
+ return self.causal_mask_cached[:, :, :seq_len, :seq_len].to(x.device)
117
+
118
+ def forward(
119
+ self,
120
+ hidden_states,
121
+ attention_mask,
122
+ head_mask=None,
123
+ layer_past=None,
124
+ use_cache=False,
125
+ output_attentions=False
126
+ ):
127
+ has_layer_past = layer_past is not None
128
+
129
+ # Compute QKV
130
+ # Attention heads [batch, seq_len, hidden_size]
131
+ # --> [batch, seq_len, (np * 3 * head_size)]
132
+ qkv = self.query_key_value(hidden_states)
133
+
134
+ # [batch, seq_len, (num_heads * 3 * head_size)]
135
+ # --> [batch, seq_len, num_heads, 3 * head_size]
136
+ new_qkv_shape = qkv.size()[:-1] + (self.num_attention_heads, 3 * self.head_size)
137
+ qkv = qkv.view(*new_qkv_shape)
138
+
139
+ # [batch, seq_len, num_attention_heads, 3 * head_size] --> 3 [batch, num_attention_heads, seq_len, head_size]
140
+ query = qkv[..., : self.head_size].permute(0, 2, 1, 3)
141
+ key = qkv[..., self.head_size : 2 * self.head_size].permute(0, 2, 1, 3)
142
+ value = qkv[..., 2 * self.head_size :].permute(0, 2, 1, 3)
143
+
144
+ # Compute rotary embeddings on rotary_ndims
145
+ # query_rot = query[..., : self.rotary_ndims]
146
+ # query_pass = query[..., self.rotary_ndims :]
147
+ # key_rot = key[..., : self.rotary_ndims]
148
+ # key_pass = key[..., self.rotary_ndims :]
149
+
150
+ # Compute token offset for rotary embeddings (when decoding)
151
+ seq_len = key.shape[-2]
152
+ offset = 0
153
+ if has_layer_past:
154
+ offset = layer_past[0].shape[-2]
155
+ seq_len += offset
156
+ cos, sin = self.rotary_emb(value, seq_len=seq_len)
157
+
158
+ query, key = apply_rotary_pos_emb(query, key, cos, sin, offset=offset)
159
+ # query, key = apply_rotary_pos_emb(query_rot, key_rot, cos, sin, offset=offset)
160
+ # query = torch.cat((query, query_pass), dim=-1)
161
+ # key = torch.cat((key, key_pass), dim=-1)
162
+
163
+ # Cache QKV values
164
+ if has_layer_past:
165
+ past_key = layer_past[0]
166
+ past_value = layer_past[1]
167
+ key = torch.cat((past_key, key), dim=-2)
168
+ value = torch.cat((past_value, value), dim=-2)
169
+ present = (key, value,) if use_cache else None
170
+
171
+ query = query.type_as(hidden_states)
172
+ key = key.type_as(hidden_states)
173
+ value = value.type_as(hidden_states)
174
+
175
+ if output_attentions:
176
+ # Use custom attention method to get attn_weights
177
+ attn_output, attn_weights = self._attn(
178
+ query, key, value,
179
+ attention_mask=attention_mask,
180
+ head_mask=head_mask
181
+ )
182
+ else:
183
+ if layer_past is not None and attention_mask is None:
184
+ # Must calculate attention_mask, or scaled_dot_product_attention will wrong
185
+ batch_size = query.size(0)
186
+ attention_mask = torch.ones(batch_size, seq_len, dtype=torch.bool)[:, None, None, :]
187
+
188
+ if attention_mask is not None:
189
+ attn_mask = attention_mask.transpose(2, 3) * attention_mask
190
+ query_length = query.size(-2)
191
+ key_length = key.size(-2)
192
+ if query_length > 1:
193
+ causal_mask = self.causal_mask(query, seq_len)
194
+ causal_mask = causal_mask[:, :, -query_length:, :]
195
+ attn_mask = (attn_mask[:, :, -query_length:, :] * causal_mask).to(torch.bool)
196
+ else:
197
+ attn_mask = attn_mask[:, :, -query_length:, :].to(torch.bool)
198
+
199
+ attn_output = F.scaled_dot_product_attention(
200
+ query,
201
+ key,
202
+ value,
203
+ attn_mask=attn_mask,
204
+ is_causal=False
205
+ )
206
+ else:
207
+ attn_output = F.scaled_dot_product_attention(
208
+ query,
209
+ key,
210
+ value,
211
+ attn_mask=None,
212
+ is_causal=True
213
+ )
214
+ attn_weights = None
215
+
216
+ # Reshape outputs
217
+ # attn_output == [bs, num_attention_heads, seq_len, attn_head_size]
218
+ attn_output = self._merge_heads(attn_output, self.num_attention_heads, self.head_size)
219
+ # tensor [bs, seq_len, num_attention_heads * attn_head_size]
220
+ attn_output = self.dense(attn_output)
221
+
222
+ outputs = (attn_output, present)
223
+ if output_attentions:
224
+ outputs += (attn_weights,)
225
+
226
+ return outputs
227
+
228
+ @classmethod
229
+ def _calculate_attn_output_loss(self, attn_output):
230
+ bs, num_attention_heads, seq_len, attn_head_size = attn_output.size()
231
+ attn_output_out = attn_output.view(bs, num_attention_heads, -1)
232
+ attn_output_out_norm = attn_output_out / torch.max(
233
+ attn_output_out.norm(dim=2, keepdim=True),
234
+ 1e-8 * torch.ones_like(attn_output_out)
235
+ )
236
+ sim = torch.bmm(attn_output_out_norm, attn_output_out_norm.permute(0, 2, 1))
237
+ attn_output_loss = sim.sum() / sim.numel()
238
+ return attn_output_loss
239
+
240
+ @classmethod
241
+ def _split_heads(cls, tensor, num_attention_heads, attn_head_size):
242
+ """
243
+ Splits hidden dim into attn_head_size and num_attention_heads
244
+ """
245
+ # tensor: [bs, seq_len, hidden_size]
246
+ new_shape = tensor.size()[:-1] + (num_attention_heads, attn_head_size)
247
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
248
+ tensor = tensor.view(new_shape)
249
+ # -> [bs, num_attention_heads, seq_len, attn_head_size]
250
+ tensor = tensor.permute(0, 2, 1, 3)
251
+ return tensor
252
+
253
+ @classmethod
254
+ def _merge_heads(cls, tensor, num_attention_heads, attn_head_size):
255
+ """
256
+ Merges attn_head_size dim and num_attn_heads dim into hidden dim
257
+ """
258
+ # tensor [bs, num_attention_heads, seq_len, attn_head_size]
259
+ tensor = tensor.permute(0, 2, 1, 3).contiguous()
260
+ # -> [bs, seq_len, num_attention_heads, attn_head_size]
261
+ tensor = tensor.view(tensor.size(0), tensor.size(1), num_attention_heads * attn_head_size)
262
+ # -> [bs, seq_len, hidden_size]
263
+ return tensor
264
+
265
+ def create_upper_triangular_matrix(self, q, k):
266
+ size = max(q, k)
267
+ # 创建一个单位矩阵
268
+ identity = torch.eye(size)
269
+ # 创建一个矩阵,其中每个元素都是它的行索引
270
+ row_indices = torch.arange(size).view(-1, 1).expand(size, size)
271
+ # 创建一个矩阵,其中每个元素都是它的列索引
272
+ col_indices = torch.arange(size).view(1, -1).expand(size, size)
273
+ # 比较行和列索引,如果行索引小于列索引,则0,否则1
274
+ upper_triangular_matrix = torch.where(row_indices < col_indices, 0, 1)
275
+ return upper_triangular_matrix[-q:, -k:].to(torch.bool)
276
+
277
+ def _attn(self, query, key, value, attention_mask=None, head_mask=None):
278
+ # q, k, v: [bs, num_attention_heads, seq_len, attn_head_size]
279
+ # compute causal mask from causal mask buffer
280
+ batch_size, num_attention_heads, query_length, attn_head_size = query.size()
281
+ key_length = key.size(-2)
282
+
283
+ # 避免使用tril
284
+ # causal_mask = torch.ones(
285
+ # query_length, key_length,
286
+ # dtype=torch.bool,
287
+ # device=query.device
288
+ # ).tril(
289
+ # diagonal=key_length - query_length
290
+ # ).view(1, 1, query_length, key_length)
291
+ causal_mask = self.create_upper_triangular_matrix(
292
+ query_length, key_length
293
+ ).view(1, 1, query_length, key_length).to(query.device)
294
+
295
+ query = query.view(batch_size * num_attention_heads, query_length, attn_head_size)
296
+ key = key.view(batch_size * num_attention_heads, key_length, attn_head_size)
297
+ attn_scores = torch.zeros(
298
+ batch_size * num_attention_heads,
299
+ query_length,
300
+ key_length,
301
+ dtype=query.dtype,
302
+ device=key.device,
303
+ )
304
+ norm_factor = self.head_size ** 0.5
305
+ attn_scores = torch.baddbmm(
306
+ attn_scores,
307
+ query,
308
+ key.transpose(1, 2),
309
+ beta=1.0,
310
+ alpha=(torch.tensor(1.0, dtype=query.dtype, device=query.device) / norm_factor),
311
+ )
312
+ attn_scores = attn_scores.view(batch_size, num_attention_heads, query_length, key_length)
313
+
314
+ mask_value = torch.finfo(attn_scores.dtype).min
315
+ # Need to be a tensor, otherwise we get error: `RuntimeError: expected scalar type float but found double`.
316
+ # Need to be on the same device, otherwise `RuntimeError: ..., x and y to be on the same device`
317
+ mask_value = torch.tensor(mask_value, dtype=attn_scores.dtype).to(attn_scores.device)
318
+ attn_scores = torch.where(causal_mask, attn_scores, mask_value)
319
+
320
+ if attention_mask is not None:
321
+ # Apply the attention mask
322
+ attn_scores = attn_scores + attention_mask
323
+
324
+ attn_weights = nn.functional.softmax(attn_scores.float(), dim=-1).type_as(value)
325
+
326
+ # Mask heads if we want to
327
+ if head_mask is not None:
328
+ attn_weights = attn_weights * head_mask
329
+
330
+ attn_output = torch.matmul(attn_weights, value)
331
+ return attn_output, attn_weights
332
+
333
+
334
+ class RotaryEmbedding(torch.nn.Module):
335
+ def __init__(self, dim, max_position_embeddings, base=10000, device=None):
336
+ super().__init__()
337
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
338
+ self.register_buffer("inv_freq", inv_freq)
339
+
340
+ # Build here to make `torch.jit.trace` work.
341
+ self.max_seq_len_cached = max_position_embeddings
342
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
343
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
344
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
345
+ emb = torch.cat((freqs, freqs), dim=-1)
346
+ self.cos_cached = emb.cos()[None, None, :, :]
347
+ self.sin_cached = emb.sin()[None, None, :, :]
348
+
349
+ def forward(self, x, seq_len=None):
350
+ # x: [bs, num_attention_heads, seq_len, head_size]
351
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
352
+ if seq_len > self.max_seq_len_cached:
353
+ self.max_seq_len_cached = seq_len
354
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
355
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
356
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
357
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
358
+ self.cos_cached = emb.cos()[None, None, :, :]
359
+ self.sin_cached = emb.sin()[None, None, :, :]
360
+ return self.cos_cached[:seq_len, ...].to(x.device), self.sin_cached[:seq_len, ...].to(x.device)
361
+
362
+
363
+ def rotate_half(x):
364
+ """Rotates half the hidden dims of the input."""
365
+ x1 = x[..., : x.shape[-1] // 2]
366
+ x2 = x[..., x.shape[-1] // 2 :]
367
+ return torch.cat((-x2, x1), dim=-1)
368
+
369
+
370
+ def apply_rotary_pos_emb(q, k, cos, sin, offset: int = 0):
371
+ cos = cos[..., offset : q.shape[-2] + offset, :]
372
+ sin = sin[..., offset : q.shape[-2] + offset, :]
373
+ q_embed = (q * cos) + (rotate_half(q) * sin)
374
+ k_embed = (k * cos) + (rotate_half(k) * sin)
375
+ return q_embed, k_embed
376
+
377
+
378
+ class GatedLinear(nn.Linear):
379
+ pass
380
+
381
+
382
+ class GPTJiangMLP(nn.Module):
383
+ def __init__(self, config):
384
+ super().__init__()
385
+ self.dense_h_to_4h = nn.Linear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
386
+ self.dense_4h_to_h = nn.Linear(config.intermediate_size, config.hidden_size, bias=config.mlp_bias)
387
+ self.gated = config.gated
388
+ if config.gated:
389
+ self.dense_h_to_4h_gate = GatedLinear(config.hidden_size, config.intermediate_size, bias=config.mlp_bias)
390
+ self.act = ACT2FN[config.hidden_act]
391
+
392
+ def forward(self, hidden_states):
393
+
394
+ if self.gated:
395
+ # pseudocode:
396
+ # g is activation function, W and V are weights, * is element-wised product
397
+ # x = g(Wx) * Vx
398
+ hidden_states = self.act(self.dense_h_to_4h(hidden_states)) * self.dense_h_to_4h_gate(hidden_states)
399
+ else:
400
+ # pseudocode:
401
+ # x = g(Wx)
402
+ hidden_states = self.act(self.dense_h_to_4h(hidden_states))
403
+ hidden_states = self.dense_4h_to_h(hidden_states)
404
+ return hidden_states
405
+
406
+
407
+ class GPTJiangLayer(nn.Module):
408
+ def __init__(self, config):
409
+ super().__init__()
410
+ self.use_parallel_residual = config.use_parallel_residual
411
+ self.input_layernorm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
412
+ self.post_attention_layernorm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
413
+ self.attention = GPTJiangAttention(config)
414
+ self.mlp = GPTJiangMLP(config)
415
+
416
+ def forward(
417
+ self,
418
+ hidden_states,
419
+ attention_mask=None,
420
+ head_mask=None,
421
+ use_cache=False,
422
+ layer_past=None,
423
+ output_attentions=False,
424
+ ):
425
+ attention_layer_outputs = self.attention(
426
+ self.input_layernorm(hidden_states),
427
+ attention_mask=attention_mask,
428
+ layer_past=layer_past,
429
+ head_mask=head_mask,
430
+ use_cache=use_cache,
431
+ output_attentions=output_attentions,
432
+ )
433
+ attn_output = attention_layer_outputs[0] # output_attn: attn_output, present, (attn_weights), (attentions_output_loss)
434
+ outputs = attention_layer_outputs[1:]
435
+
436
+ # Default True in multiple models, faster
437
+ if self.use_parallel_residual:
438
+ # pseudocode:
439
+ # x = x + attn(ln1(x)) + mlp(ln2(x))
440
+ mlp_output = self.mlp(self.post_attention_layernorm(hidden_states))
441
+ hidden_states = mlp_output + attn_output + hidden_states
442
+ else:
443
+ # pseudocode:
444
+ # x = x + attn(ln1(x))
445
+ # x = x + mlp(ln2(x))
446
+ attn_output = attn_output + hidden_states
447
+ mlp_output = self.mlp(self.post_attention_layernorm(attn_output))
448
+ hidden_states = mlp_output + attn_output
449
+
450
+ if use_cache:
451
+ outputs = (hidden_states,) + outputs # hidden_states, present, (attn_weights), (attentions_output_loss)
452
+ else:
453
+ outputs = (hidden_states,) + outputs[1:] # hidden_states, (attn_weights), (attentions_output_loss)
454
+
455
+ return outputs
456
+
457
+
458
+ GPT_JIANG_START_DOCSTRING = r"""
459
+ This model is a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) sub-class. Use
460
+ it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage and
461
+ behavior.
462
+
463
+ Parameters:
464
+ config ([`~GPTJiangConfig`]): Model configuration class with all the parameters of the model.
465
+ Initializing with a config file does not load the weights associated with the model, only the
466
+ configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
467
+ """
468
+
469
+ GPT_JIANG_INPUTS_DOCSTRING = r"""
470
+ Args:
471
+ input_ids (`torch.LongTensor` of shape `({0})`):
472
+ Indices of input sequence tokens in the vocabulary.
473
+
474
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
475
+ [`PreTrainedTokenizer.__call__`] for details.
476
+
477
+ [What are input IDs?](../glossary#input-ids)
478
+ attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
479
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
480
+
481
+ - 1 for tokens that are **not masked**,
482
+ - 0 for tokens that are **masked**.
483
+
484
+ [What are attention masks?](../glossary#attention-mask)
485
+ head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
486
+ Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
487
+
488
+ - 1 indicates the head is **not masked**,
489
+ - 0 indicates the head is **masked**.
490
+
491
+ inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
492
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
493
+ is useful if you want more control over how to convert *input_ids* indices into associated vectors than the
494
+ model's internal embedding lookup matrix.
495
+ output_attentions (`bool`, *optional*):
496
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
497
+ tensors for more detail.
498
+ output_hidden_states (`bool`, *optional*):
499
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
500
+ more detail.
501
+ return_dict (`bool`, *optional*):
502
+ Whether or not to return a [`~file_utils.ModelOutput`] instead of a plain tuple.
503
+ """
504
+
505
+
506
+ @add_start_docstrings(
507
+ "The bare GPTJiang Model transformer outputting raw hidden-states without any specific head on top.",
508
+ GPT_JIANG_START_DOCSTRING,
509
+ )
510
+ class GPTJiangModel(GPTJiangPreTrainedModel):
511
+ def __init__(self, config):
512
+ super().__init__(config)
513
+ self.config = config
514
+
515
+ self.embed_in = nn.Embedding(config.vocab_size, config.hidden_size)
516
+ self.layers = nn.ModuleList([GPTJiangLayer(config) for _ in range(config.num_hidden_layers)])
517
+ self.final_layer_norm = RMSNorm(config.hidden_size, eps=config.layer_norm_eps)
518
+
519
+ self.gradient_checkpointing = False
520
+
521
+ # Initialize weights and apply final processing
522
+ self.post_init()
523
+
524
+ def get_input_embeddings(self):
525
+ return self.embed_in
526
+
527
+ def set_input_embeddings(self, value):
528
+ self.embed_in = value
529
+
530
+ @add_start_docstrings_to_model_forward(GPT_JIANG_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
531
+ @add_code_sample_docstrings(
532
+ output_type=BaseModelOutputWithPast,
533
+ config_class=_CONFIG_FOR_DOC,
534
+ )
535
+ def forward(
536
+ self,
537
+ input_ids: Optional[torch.LongTensor] = None,
538
+ attention_mask: Optional[torch.FloatTensor] = None,
539
+ head_mask: Optional[torch.FloatTensor] = None,
540
+ inputs_embeds: Optional[torch.FloatTensor] = None,
541
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
542
+ use_cache: Optional[bool] = None,
543
+ output_attentions: Optional[bool] = None,
544
+ output_hidden_states: Optional[bool] = None,
545
+ return_dict: Optional[bool] = None,
546
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
547
+ r"""
548
+ past_key_values (`tuple(tuple(torch.FloatTensor))` of length `config.n_layers` with each tuple having 4 tensors of shape `(batch_size, num_heads, sequence_length - 1, embed_size_per_head)`):
549
+ Contains precomputed key and value hidden states of the attention blocks. Can be used to speed up decoding.
550
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
551
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
552
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
553
+ use_cache (`bool`, *optional*):
554
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see `past_key_values`).
555
+ """
556
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
557
+ output_hidden_states = (
558
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
559
+ )
560
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
561
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
562
+
563
+ if input_ids is not None and inputs_embeds is not None:
564
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
565
+ elif input_ids is not None:
566
+ input_shape = input_ids.size()
567
+ elif inputs_embeds is not None:
568
+ input_shape = inputs_embeds.size()[:-1]
569
+ else:
570
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
571
+
572
+ batch_size, seq_length = input_shape
573
+
574
+ if past_key_values is None:
575
+ past_key_values = tuple([None] * self.config.num_hidden_layers)
576
+
577
+ # Attention mask.
578
+ if attention_mask is not None:
579
+ assert batch_size > 0, "batch_size has to be defined and > 0"
580
+ attention_mask = attention_mask.view(batch_size, -1)
581
+ # We create a 3D attention mask from a 2D tensor mask.
582
+ # Sizes are [batch_size, 1, 1, to_seq_length]
583
+ # So we can broadcast to [batch_size, num_heads, from_seq_length, to_seq_length]
584
+ # this attention mask is more simple than the triangular masking of causal attention
585
+ # used in OpenAI GPT, we just need to prepare the broadcast dimension here.
586
+ attention_mask = attention_mask[:, None, None, :]
587
+
588
+ # Since attention_mask is 1.0 for positions we want to attend and 0.0 for
589
+ # masked positions, this operation will create a tensor which is 0.0 for
590
+ # positions we want to attend and the dtype's smallest value for masked positions.
591
+ # Since we are adding it to the raw scores before the softmax, this is
592
+ # effectively the same as removing these entirely.
593
+ attention_mask = attention_mask.to(dtype=self.dtype) # fp16 compatibility
594
+ # attention_mask = (1.0 - attention_mask) * torch.finfo(self.dtype).min
595
+
596
+ # Prepare head mask if needed
597
+ # 1.0 in head_mask indicate we keep the head
598
+ # attention_probs has shape bsz x n_heads x N x N
599
+ # input head_mask has shape [num_heads] or [num_hidden_layers x num_heads]
600
+ # and head_mask is converted to shape [num_hidden_layers x batch x num_heads x seq_length x seq_length]
601
+ head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
602
+
603
+ if inputs_embeds is None:
604
+ inputs_embeds = self.embed_in(input_ids)
605
+
606
+ hidden_states = inputs_embeds
607
+
608
+ if self.gradient_checkpointing and self.training:
609
+ if use_cache:
610
+ logger.warning(
611
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
612
+ )
613
+ use_cache = False
614
+
615
+ presents = () if use_cache else None
616
+ all_attentions = () if output_attentions else None
617
+ all_hidden_states = () if output_hidden_states else None
618
+ for i, (layer, layer_past) in enumerate(zip(self.layers, past_key_values)):
619
+
620
+ if output_hidden_states:
621
+ all_hidden_states = all_hidden_states + (hidden_states,)
622
+
623
+ if self.gradient_checkpointing and self.training:
624
+
625
+ def create_custom_forward(module):
626
+ def custom_forward(*inputs):
627
+ # None for layer_past
628
+ return module(*inputs, use_cache, None, output_attentions)
629
+
630
+ return custom_forward
631
+
632
+ outputs = torch.utils.checkpoint.checkpoint(
633
+ create_custom_forward(layer),
634
+ hidden_states,
635
+ attention_mask,
636
+ head_mask[i],
637
+ )
638
+ else:
639
+ outputs = layer(
640
+ hidden_states,
641
+ attention_mask=attention_mask,
642
+ head_mask=head_mask[i],
643
+ layer_past=layer_past,
644
+ use_cache=use_cache,
645
+ output_attentions=output_attentions,
646
+ )
647
+ hidden_states = outputs[0]
648
+ if use_cache is True:
649
+ presents = presents + (outputs[1],)
650
+ if output_attentions:
651
+ all_attentions = all_attentions + (outputs[2 if use_cache else 1],)
652
+
653
+ hidden_states = self.final_layer_norm(hidden_states)
654
+ # Add last hidden state
655
+ if output_hidden_states:
656
+ all_hidden_states = all_hidden_states + (hidden_states,)
657
+
658
+ if not return_dict:
659
+ return tuple(v for v in [hidden_states, presents, all_hidden_states, all_attentions] if v is not None)
660
+
661
+ ret = BaseModelOutputWithPast(
662
+ last_hidden_state=hidden_states,
663
+ past_key_values=presents,
664
+ hidden_states=all_hidden_states,
665
+ attentions=all_attentions,
666
+ )
667
+ return ret
668
+
669
+
670
+ @add_start_docstrings(
671
+ """GPTJiang Model with a `language modeling` head on top for CLM fine-tuning.""", GPT_JIANG_START_DOCSTRING
672
+ )
673
+ class GPTJiangForCausalLM(GPTJiangPreTrainedModel):
674
+ _keys_to_ignore_on_load_missing = [r"position_ids", r"predictions.decoder.bias"]
675
+
676
+ def __init__(self, config):
677
+ super().__init__(config)
678
+
679
+ self.gpt_kdf = GPTJiangModel(config)
680
+ self.embed_out = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
681
+
682
+ # Initialize weights and apply final processing
683
+ self.post_init()
684
+
685
+ def get_output_embeddings(self):
686
+ return self.embed_out
687
+
688
+ def set_output_embeddings(self, new_embeddings):
689
+ self.embed_out = new_embeddings
690
+
691
+ @add_start_docstrings_to_model_forward(GPT_JIANG_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
692
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
693
+ def forward(
694
+ self,
695
+ input_ids: Optional[torch.LongTensor] = None,
696
+ attention_mask: Optional[torch.FloatTensor] = None,
697
+ inputs_embeds: Optional[torch.FloatTensor] = None,
698
+ head_mask: Optional[torch.FloatTensor] = None,
699
+ past_key_values: Optional[Tuple[Tuple[torch.FloatTensor]]] = None,
700
+ labels: Optional[torch.LongTensor] = None,
701
+ use_cache: Optional[bool] = None,
702
+ output_attentions: Optional[bool] = None,
703
+ output_hidden_states: Optional[bool] = None,
704
+ return_dict: Optional[bool] = None,
705
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
706
+ r"""
707
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
708
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
709
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
710
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`. The two additional tensors are
711
+ only required when the model is used as a decoder in a Sequence to Sequence model.
712
+
713
+ Contains pre-computed hidden-states (key and values in the self-attention blocks that can be used (see
714
+ `past_key_values` input) to speed up sequential decoding.
715
+
716
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
717
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
718
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
719
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
720
+ Labels for computing the left-to-right language modeling loss (next word prediction). Indices should be in
721
+ `[-100, 0, ..., config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are
722
+ ignored (masked), the loss is only computed for the tokens with labels n `[0, ..., config.vocab_size]`.
723
+ use_cache (`bool`, *optional*):
724
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
725
+ `past_key_values`).
726
+
727
+ Returns:
728
+
729
+ Example:
730
+
731
+ ```python
732
+ >>> from transformers import AutoTokenizer, GPTJiangForCausalLM, GPTJiangConfig
733
+ >>> import torch
734
+
735
+ >>> tokenizer = AutoTokenizer.from_pretrained("EleutherAI/gpt-neox-20b")
736
+ >>> config = GPTJiangConfig.from_pretrained("EleutherAI/gpt-neox-20b")
737
+ >>> config.is_decoder = True
738
+ >>> model = GPTJiangForCausalLM.from_pretrained("EleutherAI/gpt-neox-20b", config=config)
739
+
740
+ >>> inputs = tokenizer("Hello, my dog is cute", return_tensors="pt")
741
+ >>> outputs = model(**inputs)
742
+
743
+ >>> prediction_logits = outputs.logits
744
+ ```"""
745
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
746
+
747
+ outputs = self.gpt_kdf(
748
+ input_ids,
749
+ attention_mask=attention_mask,
750
+ head_mask=head_mask,
751
+ inputs_embeds=inputs_embeds,
752
+ past_key_values=past_key_values,
753
+ use_cache=use_cache,
754
+ output_attentions=output_attentions,
755
+ output_hidden_states=output_hidden_states,
756
+ return_dict=return_dict,
757
+ )
758
+
759
+ hidden_states = outputs[0]
760
+ lm_logits = self.embed_out(hidden_states)
761
+
762
+ lm_loss = None
763
+ attn_output_loss = None
764
+ if labels is not None:
765
+ # we are doing next-token prediction; shift prediction scores and input ids by one
766
+ shift_logits = lm_logits[:, :-1, :].contiguous()
767
+ labels = labels[:, 1:].contiguous()
768
+ loss_fct = CrossEntropyLoss()
769
+ lm_loss = loss_fct(shift_logits.view(-1, shift_logits.size(-1)), labels.view(-1))
770
+
771
+ if not return_dict:
772
+ output = (lm_logits,) + outputs[1:]
773
+ return ((lm_loss,) + output) if lm_loss is not None else output
774
+
775
+ ret = CausalLMOutputWithPast(
776
+ loss=lm_loss,
777
+ logits=lm_logits,
778
+ past_key_values=outputs.past_key_values,
779
+ hidden_states=outputs.hidden_states,
780
+ attentions=outputs.attentions,
781
+ )
782
+ return ret
783
+
784
+ def prepare_inputs_for_generation(self, input_ids, past_key_values=None, attention_mask=None, **model_kwargs):
785
+ input_shape = input_ids.shape
786
+
787
+ # if model is used as a decoder in encoder-decoder model, the decoder attention mask is created on the fly
788
+ if attention_mask is None:
789
+ attention_mask = input_ids.new_ones(input_shape)
790
+
791
+ # cut decoder_input_ids if past is used
792
+ if past_key_values and past_key_values[0] is not None:
793
+ input_ids = input_ids[:, -1:]
794
+
795
+ return {
796
+ "input_ids": input_ids,
797
+ "attention_mask": attention_mask,
798
+ "past_key_values": past_key_values,
799
+ }
800
+
801
+ def _reorder_cache(self, past_key_values, beam_idx):
802
+ reordered_past = ()
803
+ for layer_past in past_key_values:
804
+ reordered_past += (
805
+ tuple(past_state.index_select(0, beam_idx) for past_state in layer_past[:2]) + layer_past[2:],
806
+ )
807
+ return reordered_past