jordiclive commited on
Commit
30131af
·
1 Parent(s): c3d1d7e

Upload 2 files

Browse files
Files changed (2) hide show
  1. configuration_llama.py +18 -0
  2. modelling_llama.py +1035 -0
configuration_llama.py ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers.models.llama.configuration_llama import \
2
+ LlamaConfig as LlamaConfigOriginal
3
+
4
+
5
+ class LlamaConfig(LlamaConfigOriginal):
6
+ def __init__(
7
+ self,
8
+ use_xpos=False,
9
+ position_interpolation_scale=1,
10
+ ntk_alpha=None,
11
+ transformer_engine=None,
12
+ **kwargs
13
+ ):
14
+ self.use_xpos = use_xpos
15
+ self.position_interpolation_scale = position_interpolation_scale
16
+ self.transformer_engine = transformer_engine
17
+ self.ntk_alpha = ntk_alpha
18
+ super().__init__(**kwargs)
modelling_llama.py ADDED
@@ -0,0 +1,1035 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from einops import rearrange
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import (BaseModelOutputWithPast,
31
+ CausalLMOutputWithPast,
32
+ SequenceClassifierOutputWithPast)
33
+ from transformers.modeling_utils import PreTrainedModel
34
+ from transformers.utils import (add_start_docstrings,
35
+ add_start_docstrings_to_model_forward, logging,
36
+ replace_return_docstrings)
37
+
38
+ from .configuration_llama import LlamaConfig
39
+
40
+ try:
41
+ import transformer_engine.pytorch as te
42
+
43
+ te_installed = True
44
+ except ImportError:
45
+ te_installed = False
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "LlamaConfig"
50
+
51
+
52
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
53
+ def _make_causal_mask(
54
+ input_ids_shape: torch.Size,
55
+ dtype: torch.dtype,
56
+ device: torch.device,
57
+ past_key_values_length: int = 0,
58
+ ):
59
+ """
60
+ Make causal mask used for bi-directional self-attention.
61
+ """
62
+ bsz, tgt_len = input_ids_shape
63
+ mask = torch.full(
64
+ (tgt_len, tgt_len),
65
+ torch.tensor(torch.finfo(dtype).min, device=device),
66
+ device=device,
67
+ )
68
+ mask_cond = torch.arange(mask.size(-1), device=device)
69
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
70
+ mask = mask.to(dtype)
71
+
72
+ if past_key_values_length > 0:
73
+ mask = torch.cat(
74
+ [
75
+ torch.zeros(
76
+ tgt_len, past_key_values_length, dtype=dtype, device=device
77
+ ),
78
+ mask,
79
+ ],
80
+ dim=-1,
81
+ )
82
+ return mask[None, None, :, :].expand(
83
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
84
+ )
85
+
86
+
87
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
88
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
89
+ """
90
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
91
+ """
92
+ bsz, src_len = mask.size()
93
+ tgt_len = tgt_len if tgt_len is not None else src_len
94
+
95
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
96
+
97
+ inverted_mask = 1.0 - expanded_mask
98
+
99
+ return inverted_mask.masked_fill(
100
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
101
+ )
102
+
103
+
104
+ class LlamaRMSNorm(nn.Module):
105
+ def __init__(self, hidden_size, eps=1e-6):
106
+ """
107
+ LlamaRMSNorm is equivalent to T5LayerNorm
108
+ """
109
+ super().__init__()
110
+ self.weight = nn.Parameter(torch.ones(hidden_size))
111
+ self.variance_epsilon = eps
112
+
113
+ def forward(self, hidden_states):
114
+ input_dtype = hidden_states.dtype
115
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
116
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+
118
+ return (self.weight * hidden_states).to(input_dtype)
119
+
120
+
121
+ class LlamaXposRotaryEmbedding(torch.nn.Module):
122
+ def __init__(
123
+ self,
124
+ dim,
125
+ max_position_embeddings=2048,
126
+ base=10000,
127
+ device=None,
128
+ scale_base=2048,
129
+ use_xpos=True,
130
+ ):
131
+ super().__init__()
132
+ self.max_seq_len_cached = max_position_embeddings
133
+ self.scale_base = scale_base
134
+
135
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float() / dim))
136
+ t = torch.arange(self.max_seq_len_cached, device=device).type_as(inv_freq)
137
+ freqs = torch.einsum("i , j -> i j", t, inv_freq)
138
+ freqs = torch.cat((freqs, freqs), dim=-1)
139
+
140
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
141
+ self.register_buffer("freqs_cached", freqs, persistent=False)
142
+
143
+ if not use_xpos:
144
+ self.register_buffer("scale", None)
145
+ self.register_buffer("scale_cached", torch.ones(1))
146
+ return
147
+
148
+ scale = (torch.arange(0, dim, 2) + 0.4 * dim) / (1.4 * dim)
149
+ power = (t - (self.max_seq_len_cached // 2)) / self.scale_base
150
+ scale_cached = scale ** rearrange(power, "n -> n 1")
151
+ scale_cached = torch.cat((scale_cached, scale_cached), dim=-1)
152
+
153
+ self.register_buffer("scale", scale, persistent=False)
154
+ self.register_buffer("scale_cached", scale_cached, persistent=False)
155
+
156
+ def forward(
157
+ self,
158
+ x,
159
+ seq_len,
160
+ ):
161
+ if seq_len > self.max_seq_len_cached:
162
+ self.max_seq_len_cached = seq_len
163
+ t = torch.arange(self.max_seq_len_cached, device=x.device).type_as(
164
+ self.inv_freq
165
+ )
166
+ freqs = torch.einsum("i , j -> i j", t, self.inv_freq)
167
+ freqs = torch.cat((freqs, freqs), dim=-1).to(dtype=x.dtype)
168
+
169
+ self.register_buffer("freqs_cached", freqs)
170
+
171
+ if self.scale is None:
172
+ self.register_buffer(
173
+ "scale_cached", torch.ones(1, device=x.device).to(dtype=x.dtype)
174
+ )
175
+
176
+ return self.freqs_cached.to(dtype=x.dtype), self.scale_cached
177
+
178
+ power = (t - (seq_len // 2)) / self.scale_base
179
+ scale = self.scale ** rearrange(power, "n -> n 1")
180
+ scale = torch.cat((scale, scale), dim=-1).to(dtype=x.dtype)
181
+ self.register_buffer("scale_cached", scale)
182
+
183
+ return self.freqs_cached.to(dtype=x.dtype), self.scale_cached.to(dtype=x.dtype)
184
+
185
+ def rotate_half(x):
186
+ x1, x2 = x.chunk(2, dim=-1)
187
+ return torch.cat((-x2, x1), dim=-1)
188
+
189
+ def apply_rotary_pos_emb(self, q, k, freqs, scale=1, position_ids=None):
190
+ freqs = freqs[position_ids, :]
191
+ if scale.shape[-1] != 1:
192
+ scale = scale[position_ids, :]
193
+
194
+ q_embed = (q * freqs.cos() * scale) + (
195
+ LlamaXposRotaryEmbedding.rotate_half_xpos(q) * freqs.sin() * scale
196
+ )
197
+ k_embed = (k * freqs.cos() * 1 / scale) + (
198
+ LlamaXposRotaryEmbedding.rotate_half_xpos(k) * freqs.sin() * 1 / scale
199
+ )
200
+
201
+ return q_embed, k_embed
202
+
203
+
204
+ class LlamaScaledRotaryEmbedding(torch.nn.Module):
205
+ def __init__(
206
+ self,
207
+ dim,
208
+ max_position_embeddings=2048,
209
+ base=10000,
210
+ position_interpolation_scale=1,
211
+ ntk_alpha=None,
212
+ device=None,
213
+ ):
214
+ super().__init__()
215
+ self.position_interpolation_scale = position_interpolation_scale
216
+ if ntk_alpha:
217
+ base = base * ntk_alpha ** (dim / (dim - 2))
218
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
219
+ self.register_buffer("inv_freq", inv_freq)
220
+
221
+ # Build here to make `torch.jit.trace` work.
222
+ self.max_seq_len_cached = max_position_embeddings
223
+ t = torch.arange(
224
+ self.max_seq_len_cached,
225
+ device=self.inv_freq.device,
226
+ dtype=self.inv_freq.dtype,
227
+ )
228
+ t *= self.position_interpolation_scale
229
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
230
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
231
+ emb = torch.cat((freqs, freqs), dim=-1)
232
+ dtype = torch.get_default_dtype()
233
+ self.register_buffer(
234
+ "cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False
235
+ )
236
+ self.register_buffer(
237
+ "sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False
238
+ )
239
+
240
+ def forward(self, x, seq_len=None):
241
+ # x: [bs, num_attention_heads, seq_len, head_size]
242
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
243
+ if seq_len > self.max_seq_len_cached:
244
+ self.max_seq_len_cached = seq_len
245
+ t = torch.arange(
246
+ self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype
247
+ )
248
+ t *= self.position_interpolation_scale
249
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
250
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
251
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
252
+ self.register_buffer(
253
+ "cos_cached", emb.cos()[None, None, :, :].to(x.dtype), persistent=False
254
+ )
255
+ self.register_buffer(
256
+ "sin_cached", emb.sin()[None, None, :, :].to(x.dtype), persistent=False
257
+ )
258
+ return (
259
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
260
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
261
+ )
262
+
263
+ def rotate_half(x):
264
+ """Rotates half the hidden dims of the input."""
265
+ x1 = x[..., : x.shape[-1] // 2]
266
+ x2 = x[..., x.shape[-1] // 2 :]
267
+ return torch.cat((-x2, x1), dim=-1)
268
+
269
+ def apply_rotary_pos_emb(self, q, k, cos, sin, position_ids):
270
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
271
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
272
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
273
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
274
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
275
+ q_embed = (q * cos) + (LlamaScaledRotaryEmbedding.rotate_half(q) * sin)
276
+ k_embed = (k * cos) + (LlamaScaledRotaryEmbedding.rotate_half(k) * sin)
277
+ return q_embed, k_embed
278
+
279
+
280
+ class LlamaMLP(nn.Module):
281
+ def __init__(
282
+ self,
283
+ hidden_size: int,
284
+ intermediate_size: int,
285
+ hidden_act: str,
286
+ transformer_engine: Optional[bool],
287
+ ):
288
+ super().__init__()
289
+ self.transformer_engine = transformer_engine
290
+ if self.transformer_engine:
291
+ if not te_installed:
292
+ raise RuntimeError("TransformerEngine not installed")
293
+ self.gate_proj = te.Linear(
294
+ hidden_size,
295
+ intermediate_size,
296
+ bias=False,
297
+ params_dtype=torch.get_default_dtype(),
298
+ )
299
+ self.down_proj = te.Linear(
300
+ intermediate_size,
301
+ hidden_size,
302
+ bias=False,
303
+ params_dtype=torch.get_default_dtype(),
304
+ )
305
+ self.up_proj = te.Linear(
306
+ hidden_size,
307
+ intermediate_size,
308
+ bias=False,
309
+ params_dtype=torch.get_default_dtype(),
310
+ )
311
+ else:
312
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
313
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
314
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
315
+ self.act_fn = ACT2FN[hidden_act]
316
+
317
+ def forward(self, x):
318
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
319
+
320
+
321
+ class LlamaAttention(nn.Module):
322
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
323
+
324
+ def __init__(self, config: LlamaConfig):
325
+ super().__init__()
326
+ self.config = config
327
+ self.hidden_size = config.hidden_size
328
+ self.num_heads = config.num_attention_heads
329
+ self.head_dim = self.hidden_size // self.num_heads
330
+ self.max_position_embeddings = config.max_position_embeddings
331
+
332
+ if (self.head_dim * self.num_heads) != self.hidden_size:
333
+ raise ValueError(
334
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
335
+ f" and `num_heads`: {self.num_heads})."
336
+ )
337
+ self.q_proj = nn.Linear(
338
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
339
+ )
340
+ self.k_proj = nn.Linear(
341
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
342
+ )
343
+ self.v_proj = nn.Linear(
344
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
345
+ )
346
+ self.o_proj = nn.Linear(
347
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
348
+ )
349
+ self.rotary_emb = (
350
+ LlamaXposRotaryEmbedding(
351
+ self.head_dim, max_position_embeddings=self.max_position_embeddings
352
+ )
353
+ if config.use_xpos
354
+ else LlamaScaledRotaryEmbedding(
355
+ self.head_dim,
356
+ max_position_embeddings=self.max_position_embeddings,
357
+ position_interpolation_scale=config.position_interpolation_scale,
358
+ )
359
+ )
360
+
361
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
362
+ return (
363
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
364
+ .transpose(1, 2)
365
+ .contiguous()
366
+ )
367
+
368
+ def forward(
369
+ self,
370
+ hidden_states: torch.Tensor,
371
+ attention_mask: Optional[torch.Tensor] = None,
372
+ position_ids: Optional[torch.LongTensor] = None,
373
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
374
+ output_attentions: bool = False,
375
+ use_cache: bool = False,
376
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
377
+ bsz, q_len, _ = hidden_states.size()
378
+
379
+ query_states = (
380
+ self.q_proj(hidden_states)
381
+ .view(bsz, q_len, self.num_heads, self.head_dim)
382
+ .transpose(1, 2)
383
+ )
384
+ key_states = (
385
+ self.k_proj(hidden_states)
386
+ .view(bsz, q_len, self.num_heads, self.head_dim)
387
+ .transpose(1, 2)
388
+ )
389
+ value_states = (
390
+ self.v_proj(hidden_states)
391
+ .view(bsz, q_len, self.num_heads, self.head_dim)
392
+ .transpose(1, 2)
393
+ )
394
+
395
+ kv_seq_len = key_states.shape[-2]
396
+ if past_key_value is not None:
397
+ kv_seq_len += past_key_value[0].shape[-2]
398
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
399
+ (query_states, key_states,) = self.rotary_emb.apply_rotary_pos_emb(
400
+ query_states, key_states, cos, sin, position_ids
401
+ )
402
+ # [bsz, nh, t, hd]
403
+
404
+ if past_key_value is not None:
405
+ # reuse k, v, self_attention
406
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
407
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
408
+
409
+ past_key_value = (key_states, value_states) if use_cache else None
410
+
411
+ # We only apply sdp attention if we don't need to output the whole attention matrix
412
+ if not output_attentions:
413
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
414
+ query_states,
415
+ key_states,
416
+ value_states,
417
+ attn_mask=attention_mask,
418
+ is_causal=False,
419
+ )
420
+ attn_weights = None
421
+ else:
422
+ attn_weights = torch.matmul(
423
+ query_states, key_states.transpose(2, 3)
424
+ ) / math.sqrt(self.head_dim)
425
+
426
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
427
+ raise ValueError(
428
+ f"Attention weights should be of size {(bsz * self.num_heads, q_len, kv_seq_len)}, but is"
429
+ f" {attn_weights.size()}"
430
+ )
431
+
432
+ if attention_mask is not None:
433
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
434
+ raise ValueError(
435
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
436
+ )
437
+ attn_weights = attn_weights + attention_mask
438
+ attn_weights = torch.max(
439
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
440
+ )
441
+
442
+ # upcast attention to fp32
443
+ attn_weights = nn.functional.softmax(
444
+ attn_weights, dim=-1, dtype=torch.float32
445
+ ).to(query_states.dtype)
446
+ attn_output = torch.matmul(attn_weights, value_states)
447
+
448
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
449
+ raise ValueError(
450
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
451
+ f" {attn_output.size()}"
452
+ )
453
+
454
+ attn_output = attn_output.transpose(1, 2)
455
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
456
+
457
+ attn_output = self.o_proj(attn_output)
458
+
459
+ return attn_output, attn_weights, past_key_value
460
+
461
+
462
+ class LlamaDecoderLayer(nn.Module):
463
+ def __init__(self, config: LlamaConfig):
464
+ super().__init__()
465
+ self.hidden_size = config.hidden_size
466
+ self.self_attn = LlamaAttention(config=config)
467
+ self.mlp = LlamaMLP(
468
+ hidden_size=self.hidden_size,
469
+ intermediate_size=config.intermediate_size,
470
+ hidden_act=config.hidden_act,
471
+ transformer_engine=config.transformer_engine,
472
+ )
473
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
474
+ self.post_attention_layernorm = LlamaRMSNorm(
475
+ config.hidden_size, eps=config.rms_norm_eps
476
+ )
477
+
478
+ def forward(
479
+ self,
480
+ hidden_states: torch.Tensor,
481
+ attention_mask: Optional[torch.Tensor] = None,
482
+ position_ids: Optional[torch.LongTensor] = None,
483
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
484
+ output_attentions: Optional[bool] = False,
485
+ use_cache: Optional[bool] = False,
486
+ ) -> Tuple[
487
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
488
+ ]:
489
+ """
490
+ Args:
491
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
492
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
493
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
494
+ output_attentions (`bool`, *optional*):
495
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
496
+ returned tensors for more detail.
497
+ use_cache (`bool`, *optional*):
498
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
499
+ (see `past_key_values`).
500
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
501
+ """
502
+
503
+ residual = hidden_states
504
+
505
+ hidden_states = self.input_layernorm(hidden_states)
506
+
507
+ # Self Attention
508
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
509
+ hidden_states=hidden_states,
510
+ attention_mask=attention_mask,
511
+ position_ids=position_ids,
512
+ past_key_value=past_key_value,
513
+ output_attentions=output_attentions,
514
+ use_cache=use_cache,
515
+ )
516
+ hidden_states = residual + hidden_states
517
+
518
+ # Fully Connected
519
+ residual = hidden_states
520
+ hidden_states = self.post_attention_layernorm(hidden_states)
521
+ hidden_states = self.mlp(hidden_states)
522
+ hidden_states = residual + hidden_states
523
+
524
+ outputs = (hidden_states,)
525
+
526
+ if output_attentions:
527
+ outputs += (self_attn_weights,)
528
+
529
+ if use_cache:
530
+ outputs += (present_key_value,)
531
+
532
+ return outputs
533
+
534
+
535
+ LLAMA_START_DOCSTRING = r"""
536
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
537
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
538
+ etc.)
539
+
540
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
541
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
542
+ and behavior.
543
+
544
+ Parameters:
545
+ config ([`LlamaConfig`]):
546
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
547
+ load the weights associated with the model, only the configuration. Check out the
548
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
549
+ """
550
+
551
+
552
+ @add_start_docstrings(
553
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
554
+ LLAMA_START_DOCSTRING,
555
+ )
556
+ class LlamaPreTrainedModel(PreTrainedModel):
557
+ config_class = LlamaConfig
558
+ base_model_prefix = "model"
559
+ supports_gradient_checkpointing = True
560
+ _no_split_modules = ["LlamaDecoderLayer"]
561
+ _skip_keys_device_placement = "past_key_values"
562
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
563
+
564
+ def _init_weights(self, module):
565
+ std = self.config.initializer_range
566
+ if isinstance(module, nn.Linear):
567
+ module.weight.data.normal_(mean=0.0, std=std)
568
+ if module.bias is not None:
569
+ module.bias.data.zero_()
570
+ elif isinstance(module, nn.Embedding):
571
+ module.weight.data.normal_(mean=0.0, std=std)
572
+ if module.padding_idx is not None:
573
+ module.weight.data[module.padding_idx].zero_()
574
+
575
+ def _set_gradient_checkpointing(self, module, value=False):
576
+ if isinstance(module, LlamaModel):
577
+ module.gradient_checkpointing = value
578
+
579
+
580
+ LLAMA_INPUTS_DOCSTRING = r"""
581
+ Args:
582
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
583
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
584
+ it.
585
+
586
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
587
+ [`PreTrainedTokenizer.__call__`] for details.
588
+
589
+ [What are input IDs?](../glossary#input-ids)
590
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
591
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
592
+
593
+ - 1 for tokens that are **not masked**,
594
+ - 0 for tokens that are **masked**.
595
+
596
+ [What are attention masks?](../glossary#attention-mask)
597
+
598
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
599
+ [`PreTrainedTokenizer.__call__`] for details.
600
+
601
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
602
+ `past_key_values`).
603
+
604
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
605
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
606
+ information on the default strategy.
607
+
608
+ - 1 indicates the head is **not masked**,
609
+ - 0 indicates the head is **masked**.
610
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
611
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
612
+ config.n_positions - 1]`.
613
+
614
+ [What are position IDs?](../glossary#position-ids)
615
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
616
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
617
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
618
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
619
+
620
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
621
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
622
+
623
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
624
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
625
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
626
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
627
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
628
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
629
+ model's internal embedding lookup matrix.
630
+ use_cache (`bool`, *optional*):
631
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
632
+ `past_key_values`).
633
+ output_attentions (`bool`, *optional*):
634
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
635
+ tensors for more detail.
636
+ output_hidden_states (`bool`, *optional*):
637
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
638
+ more detail.
639
+ return_dict (`bool`, *optional*):
640
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
641
+ """
642
+
643
+
644
+ @add_start_docstrings(
645
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
646
+ LLAMA_START_DOCSTRING,
647
+ )
648
+ class LlamaModel(LlamaPreTrainedModel):
649
+ """
650
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
651
+
652
+ Args:
653
+ config: LlamaConfig
654
+ """
655
+
656
+ def __init__(self, config: LlamaConfig):
657
+ super().__init__(config)
658
+ self.padding_idx = config.pad_token_id
659
+ self.vocab_size = config.vocab_size
660
+
661
+ self.embed_tokens = nn.Embedding(
662
+ config.vocab_size, config.hidden_size, self.padding_idx
663
+ )
664
+ self.layers = nn.ModuleList(
665
+ [LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]
666
+ )
667
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
668
+
669
+ self.gradient_checkpointing = False
670
+ # Initialize weights and apply final processing
671
+ self.post_init()
672
+
673
+ def get_input_embeddings(self):
674
+ return self.embed_tokens
675
+
676
+ def set_input_embeddings(self, value):
677
+ self.embed_tokens = value
678
+
679
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
680
+ def _prepare_decoder_attention_mask(
681
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
682
+ ):
683
+ # create causal mask
684
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
685
+ combined_attention_mask = None
686
+ if input_shape[-1] > 1:
687
+ combined_attention_mask = _make_causal_mask(
688
+ input_shape,
689
+ inputs_embeds.dtype,
690
+ device=inputs_embeds.device,
691
+ past_key_values_length=past_key_values_length,
692
+ )
693
+
694
+ if attention_mask is not None:
695
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
696
+ expanded_attn_mask = _expand_mask(
697
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
698
+ ).to(inputs_embeds.device)
699
+ combined_attention_mask = (
700
+ expanded_attn_mask
701
+ if combined_attention_mask is None
702
+ else expanded_attn_mask + combined_attention_mask
703
+ )
704
+
705
+ return combined_attention_mask
706
+
707
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
708
+ def forward(
709
+ self,
710
+ input_ids: torch.LongTensor = None,
711
+ attention_mask: Optional[torch.Tensor] = None,
712
+ position_ids: Optional[torch.LongTensor] = None,
713
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
714
+ inputs_embeds: Optional[torch.FloatTensor] = None,
715
+ use_cache: Optional[bool] = None,
716
+ output_attentions: Optional[bool] = None,
717
+ output_hidden_states: Optional[bool] = None,
718
+ return_dict: Optional[bool] = None,
719
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
720
+ output_attentions = (
721
+ output_attentions
722
+ if output_attentions is not None
723
+ else self.config.output_attentions
724
+ )
725
+ output_hidden_states = (
726
+ output_hidden_states
727
+ if output_hidden_states is not None
728
+ else self.config.output_hidden_states
729
+ )
730
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
731
+
732
+ return_dict = (
733
+ return_dict if return_dict is not None else self.config.use_return_dict
734
+ )
735
+
736
+ # retrieve input_ids and inputs_embeds
737
+ if input_ids is not None and inputs_embeds is not None:
738
+ raise ValueError(
739
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
740
+ )
741
+ elif input_ids is not None:
742
+ batch_size, seq_length = input_ids.shape
743
+ elif inputs_embeds is not None:
744
+ batch_size, seq_length, _ = inputs_embeds.shape
745
+ else:
746
+ raise ValueError(
747
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
748
+ )
749
+
750
+ seq_length_with_past = seq_length
751
+ past_key_values_length = 0
752
+
753
+ if past_key_values is not None:
754
+ past_key_values_length = past_key_values[0][0].shape[2]
755
+ seq_length_with_past = seq_length_with_past + past_key_values_length
756
+
757
+ if position_ids is None:
758
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
759
+ position_ids = torch.arange(
760
+ past_key_values_length,
761
+ seq_length + past_key_values_length,
762
+ dtype=torch.long,
763
+ device=device,
764
+ )
765
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
766
+ else:
767
+ position_ids = position_ids.view(-1, seq_length).long()
768
+
769
+ if inputs_embeds is None:
770
+ inputs_embeds = self.embed_tokens(input_ids)
771
+ # embed positions
772
+ if attention_mask is None:
773
+ attention_mask = torch.ones(
774
+ (batch_size, seq_length_with_past),
775
+ dtype=torch.bool,
776
+ device=inputs_embeds.device,
777
+ )
778
+ attention_mask = self._prepare_decoder_attention_mask(
779
+ attention_mask,
780
+ (batch_size, seq_length),
781
+ inputs_embeds,
782
+ past_key_values_length,
783
+ )
784
+
785
+ hidden_states = inputs_embeds
786
+
787
+ if self.gradient_checkpointing and self.training:
788
+ if use_cache:
789
+ logger.warning_once(
790
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
791
+ )
792
+ use_cache = False
793
+
794
+ # decoder layers
795
+ all_hidden_states = () if output_hidden_states else None
796
+ all_self_attns = () if output_attentions else None
797
+ next_decoder_cache = () if use_cache else None
798
+
799
+ for idx, decoder_layer in enumerate(self.layers):
800
+ if output_hidden_states:
801
+ all_hidden_states += (hidden_states,)
802
+
803
+ past_key_value = (
804
+ past_key_values[idx] if past_key_values is not None else None
805
+ )
806
+
807
+ if self.gradient_checkpointing and self.training:
808
+
809
+ def create_custom_forward(module):
810
+ def custom_forward(*inputs):
811
+ # None for past_key_value
812
+ return module(*inputs, output_attentions, None)
813
+
814
+ return custom_forward
815
+
816
+ layer_outputs = torch.utils.checkpoint.checkpoint(
817
+ create_custom_forward(decoder_layer),
818
+ hidden_states,
819
+ attention_mask,
820
+ position_ids,
821
+ None,
822
+ )
823
+ else:
824
+ layer_outputs = decoder_layer(
825
+ hidden_states,
826
+ attention_mask=attention_mask,
827
+ position_ids=position_ids,
828
+ past_key_value=past_key_value,
829
+ output_attentions=output_attentions,
830
+ use_cache=use_cache,
831
+ )
832
+
833
+ hidden_states = layer_outputs[0]
834
+
835
+ if use_cache:
836
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
837
+
838
+ if output_attentions:
839
+ all_self_attns += (layer_outputs[1],)
840
+
841
+ hidden_states = self.norm(hidden_states)
842
+
843
+ # add hidden states from the last decoder layer
844
+ if output_hidden_states:
845
+ all_hidden_states += (hidden_states,)
846
+
847
+ next_cache = next_decoder_cache if use_cache else None
848
+ if not return_dict:
849
+ return tuple(
850
+ v
851
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
852
+ if v is not None
853
+ )
854
+ return BaseModelOutputWithPast(
855
+ last_hidden_state=hidden_states,
856
+ past_key_values=next_cache,
857
+ hidden_states=all_hidden_states,
858
+ attentions=all_self_attns,
859
+ )
860
+
861
+
862
+ class LlamaForCausalLM(LlamaPreTrainedModel):
863
+ _tied_weights_keys = ["lm_head.weight"]
864
+
865
+ def __init__(self, config):
866
+ super().__init__(config)
867
+ self.model = LlamaModel(config)
868
+
869
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
870
+
871
+ # Initialize weights and apply final processing
872
+ self.post_init()
873
+
874
+ def get_input_embeddings(self):
875
+ return self.model.embed_tokens
876
+
877
+ def set_input_embeddings(self, value):
878
+ self.model.embed_tokens = value
879
+
880
+ def get_output_embeddings(self):
881
+ return self.lm_head
882
+
883
+ def set_output_embeddings(self, new_embeddings):
884
+ self.lm_head = new_embeddings
885
+
886
+ def set_decoder(self, decoder):
887
+ self.model = decoder
888
+
889
+ def get_decoder(self):
890
+ return self.model
891
+
892
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
893
+ @replace_return_docstrings(
894
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
895
+ )
896
+ def forward(
897
+ self,
898
+ input_ids: torch.LongTensor = None,
899
+ attention_mask: Optional[torch.Tensor] = None,
900
+ position_ids: Optional[torch.LongTensor] = None,
901
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
902
+ inputs_embeds: Optional[torch.FloatTensor] = None,
903
+ labels: Optional[torch.LongTensor] = None,
904
+ use_cache: Optional[bool] = None,
905
+ output_attentions: Optional[bool] = None,
906
+ output_hidden_states: Optional[bool] = None,
907
+ return_dict: Optional[bool] = None,
908
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
909
+ r"""
910
+ Args:
911
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
912
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
913
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
914
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
915
+
916
+ Returns:
917
+
918
+ Example:
919
+
920
+ ```python
921
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
922
+
923
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
924
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
925
+
926
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
927
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
928
+
929
+ >>> # Generate
930
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
931
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
932
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
933
+ ```"""
934
+
935
+ output_attentions = (
936
+ output_attentions
937
+ if output_attentions is not None
938
+ else self.config.output_attentions
939
+ )
940
+ output_hidden_states = (
941
+ output_hidden_states
942
+ if output_hidden_states is not None
943
+ else self.config.output_hidden_states
944
+ )
945
+ return_dict = (
946
+ return_dict if return_dict is not None else self.config.use_return_dict
947
+ )
948
+
949
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
950
+ outputs = self.model(
951
+ input_ids=input_ids,
952
+ attention_mask=attention_mask,
953
+ position_ids=position_ids,
954
+ past_key_values=past_key_values,
955
+ inputs_embeds=inputs_embeds,
956
+ use_cache=use_cache,
957
+ output_attentions=output_attentions,
958
+ output_hidden_states=output_hidden_states,
959
+ return_dict=return_dict,
960
+ )
961
+
962
+ hidden_states = outputs[0]
963
+ logits = self.lm_head(hidden_states)
964
+
965
+ loss = None
966
+ if labels is not None:
967
+ # Shift so that tokens < n predict n
968
+ shift_logits = logits[..., :-1, :].contiguous()
969
+ shift_labels = labels[..., 1:].contiguous()
970
+ # Flatten the tokens
971
+ loss_fct = CrossEntropyLoss()
972
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
973
+ shift_labels = shift_labels.view(-1)
974
+ # Enable model parallelism
975
+ shift_labels = shift_labels.to(shift_logits.device)
976
+ loss = loss_fct(shift_logits, shift_labels)
977
+
978
+ if not return_dict:
979
+ output = (logits,) + outputs[1:]
980
+ return (loss,) + output if loss is not None else output
981
+
982
+ return CausalLMOutputWithPast(
983
+ loss=loss,
984
+ logits=logits,
985
+ past_key_values=outputs.past_key_values,
986
+ hidden_states=outputs.hidden_states,
987
+ attentions=outputs.attentions,
988
+ )
989
+
990
+ def prepare_inputs_for_generation(
991
+ self,
992
+ input_ids,
993
+ past_key_values=None,
994
+ attention_mask=None,
995
+ inputs_embeds=None,
996
+ **kwargs,
997
+ ):
998
+ if past_key_values:
999
+ input_ids = input_ids[:, -1:]
1000
+
1001
+ position_ids = kwargs.get("position_ids", None)
1002
+ if attention_mask is not None and position_ids is None:
1003
+ # create position_ids on the fly for batch generation
1004
+ position_ids = attention_mask.long().cumsum(-1) - 1
1005
+ position_ids.masked_fill_(attention_mask == 0, 1)
1006
+ if past_key_values:
1007
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1008
+
1009
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1010
+ if inputs_embeds is not None and past_key_values is None:
1011
+ model_inputs = {"inputs_embeds": inputs_embeds}
1012
+ else:
1013
+ model_inputs = {"input_ids": input_ids}
1014
+
1015
+ model_inputs.update(
1016
+ {
1017
+ "position_ids": position_ids,
1018
+ "past_key_values": past_key_values,
1019
+ "use_cache": kwargs.get("use_cache"),
1020
+ "attention_mask": attention_mask,
1021
+ }
1022
+ )
1023
+ return model_inputs
1024
+
1025
+ @staticmethod
1026
+ def _reorder_cache(past_key_values, beam_idx):
1027
+ reordered_past = ()
1028
+ for layer_past in past_key_values:
1029
+ reordered_past += (
1030
+ tuple(
1031
+ past_state.index_select(0, beam_idx.to(past_state.device))
1032
+ for past_state in layer_past
1033
+ ),
1034
+ )
1035
+ return reordered_past