AlexWortega commited on
Commit
c452071
1 Parent(s): e0e65c4

Delete modeling_llama_aqlm.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. modeling_llama_aqlm.py +0 -1426
modeling_llama_aqlm.py DELETED
@@ -1,1426 +0,0 @@
1
- # coding=utf-8
2
- # This code is a modification of transformers/models/llama/modeling_llama.py , which is has the following copyright:
3
- # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
- #
5
- # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
- # and OPT implementations in this library. It has been modified from its
7
- # original forms to accommodate minor architectural differences compared
8
- # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
- #
10
- # Licensed under the Apache License, Version 2.0 (the "License");
11
- # you may not use this file except in compliance with the License.
12
- # You may obtain a copy of the License at
13
- #
14
- # http://www.apache.org/licenses/LICENSE-2.0
15
- #
16
- # Unless required by applicable law or agreed to in writing, software
17
- # distributed under the License is distributed on an "AS IS" BASIS,
18
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
- # See the License for the specific language governing permissions and
20
- # limitations under the License.
21
- """ PyTorch LLaMA model."""
22
- import math
23
- import warnings
24
- from typing import List, Optional, Tuple, Union
25
-
26
- import torch
27
- import torch.nn.functional as F
28
- import torch.utils.checkpoint
29
- from aqlm import QuantizedLinear
30
- from torch import nn
31
- from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
- from transformers.activations import ACT2FN
33
- from transformers.cache_utils import Cache, DynamicCache
34
- from transformers.modeling_attn_mask_utils import (
35
- AttentionMaskConverter,
36
- _prepare_4d_attention_mask,
37
- _prepare_4d_causal_attention_mask,
38
- _prepare_4d_causal_attention_mask_for_sdpa,
39
- )
40
- from transformers.modeling_outputs import (
41
- BaseModelOutputWithPast,
42
- CausalLMOutputWithPast,
43
- SequenceClassifierOutputWithPast,
44
- )
45
- from transformers.modeling_utils import PreTrainedModel
46
- from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS, is_torch_greater_or_equal_than_1_13
47
- from transformers.utils import (
48
- add_start_docstrings,
49
- add_start_docstrings_to_model_forward,
50
- is_flash_attn_2_available,
51
- is_flash_attn_greater_or_equal_2_10,
52
- logging,
53
- replace_return_docstrings,
54
- )
55
- from transformers.utils.import_utils import is_torch_fx_available
56
-
57
- from .configuration_llama_aqlm import LlamaConfig
58
-
59
- if is_flash_attn_2_available():
60
- try:
61
- from flash_attn import flash_attn_func, flash_attn_varlen_func
62
- from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
63
- except:
64
- pass
65
-
66
-
67
- # This makes `_prepare_4d_causal_attention_mask` a leaf function in the FX graph.
68
- # It means that the function will not be traced through and simply appear as a node in the graph.
69
- if is_torch_fx_available():
70
- if not is_torch_greater_or_equal_than_1_13:
71
- import torch.fx
72
-
73
- _prepare_4d_causal_attention_mask = torch.fx.wrap(_prepare_4d_causal_attention_mask)
74
-
75
-
76
- logger = logging.get_logger(__name__)
77
-
78
- _CONFIG_FOR_DOC = "LlamaConfig"
79
-
80
-
81
- def _get_unpad_data(attention_mask):
82
- seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
83
- indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
84
- max_seqlen_in_batch = seqlens_in_batch.max().item()
85
- cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
86
- return (
87
- indices,
88
- cu_seqlens,
89
- max_seqlen_in_batch,
90
- )
91
-
92
-
93
- def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
94
- warnings.warn(
95
- "Calling `transformers.models.llama.modeling_llama._prepare_4d_attention_mask` is deprecated and will be removed in v4.37. Use `transformers.modeling_attn_mask_utils._prepare_4d_attention_mask"
96
- )
97
- return _prepare_4d_attention_mask(mask=mask, dtype=dtype, tgt_len=tgt_len)
98
-
99
-
100
- def _make_causal_mask(
101
- input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
102
- ):
103
- warnings.warn(
104
- "Calling `transformers.models.llama.modeling_llama._make_causal_mask` is deprecated and will be removed in v4.37. Use `transformers.models.llama.modeling_llama.AttentionMaskConverter._make_causal_mask"
105
- )
106
- return AttentionMaskConverter._make_causal_mask(
107
- input_ids_shape=input_ids_shape, dtype=dtype, device=device, past_key_values_length=past_key_values_length
108
- )
109
-
110
-
111
- class LlamaRMSNorm(nn.Module):
112
- def __init__(self, hidden_size, eps=1e-6):
113
- """
114
- LlamaRMSNorm is equivalent to T5LayerNorm
115
- """
116
- super().__init__()
117
- self.weight = nn.Parameter(torch.ones(hidden_size))
118
- self.variance_epsilon = eps
119
-
120
- def forward(self, hidden_states):
121
- input_dtype = hidden_states.dtype
122
- hidden_states = hidden_states.to(torch.float32)
123
- variance = hidden_states.pow(2).mean(-1, keepdim=True)
124
- hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
125
- return self.weight * hidden_states.to(input_dtype)
126
-
127
-
128
- ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
129
-
130
-
131
- class LlamaRotaryEmbedding(nn.Module):
132
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
133
- super().__init__()
134
-
135
- self.dim = dim
136
- self.max_position_embeddings = max_position_embeddings
137
- self.base = base
138
- inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
139
- self.register_buffer("inv_freq", inv_freq, persistent=False)
140
-
141
- # Build here to make `torch.jit.trace` work.
142
- self._set_cos_sin_cache(
143
- seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
144
- )
145
-
146
- def _set_cos_sin_cache(self, seq_len, device, dtype):
147
- self.max_seq_len_cached = seq_len
148
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
149
-
150
- freqs = torch.outer(t, self.inv_freq)
151
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
152
- emb = torch.cat((freqs, freqs), dim=-1)
153
- self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
154
- self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
155
-
156
- def forward(self, x, seq_len=None):
157
- # x: [bs, num_attention_heads, seq_len, head_size]
158
- if seq_len > self.max_seq_len_cached:
159
- self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
160
-
161
- return (
162
- self.cos_cached[:seq_len].to(dtype=x.dtype),
163
- self.sin_cached[:seq_len].to(dtype=x.dtype),
164
- )
165
-
166
-
167
- class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
168
- """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
169
-
170
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
171
- self.scaling_factor = scaling_factor
172
- super().__init__(dim, max_position_embeddings, base, device)
173
-
174
- def _set_cos_sin_cache(self, seq_len, device, dtype):
175
- self.max_seq_len_cached = seq_len
176
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
177
- t = t / self.scaling_factor
178
-
179
- freqs = torch.outer(t, self.inv_freq)
180
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
181
- emb = torch.cat((freqs, freqs), dim=-1)
182
- self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
183
- self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
184
-
185
-
186
- class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
187
- """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
188
-
189
- def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
190
- self.scaling_factor = scaling_factor
191
- super().__init__(dim, max_position_embeddings, base, device)
192
-
193
- def _set_cos_sin_cache(self, seq_len, device, dtype):
194
- self.max_seq_len_cached = seq_len
195
-
196
- if seq_len > self.max_position_embeddings:
197
- base = self.base * (
198
- (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
199
- ) ** (self.dim / (self.dim - 2))
200
- inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
201
- self.register_buffer("inv_freq", inv_freq, persistent=False)
202
-
203
- t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
204
-
205
- freqs = torch.outer(t, self.inv_freq)
206
- # Different from paper, but it uses a different permutation in order to obtain the same calculation
207
- emb = torch.cat((freqs, freqs), dim=-1)
208
- self.register_buffer("cos_cached", emb.cos().to(dtype), persistent=False)
209
- self.register_buffer("sin_cached", emb.sin().to(dtype), persistent=False)
210
-
211
-
212
- def rotate_half(x):
213
- """Rotates half the hidden dims of the input."""
214
- x1 = x[..., : x.shape[-1] // 2]
215
- x2 = x[..., x.shape[-1] // 2 :]
216
- return torch.cat((-x2, x1), dim=-1)
217
-
218
-
219
- def apply_rotary_pos_emb(q, k, cos, sin, position_ids, unsqueeze_dim=1):
220
- """Applies Rotary Position Embedding to the query and key tensors.
221
-
222
- Args:
223
- q (`torch.Tensor`): The query tensor.
224
- k (`torch.Tensor`): The key tensor.
225
- cos (`torch.Tensor`): The cosine part of the rotary embedding.
226
- sin (`torch.Tensor`): The sine part of the rotary embedding.
227
- position_ids (`torch.Tensor`):
228
- The position indices of the tokens corresponding to the query and key tensors. For example, this can be
229
- used to pass offsetted position ids when working with a KV-cache.
230
- unsqueeze_dim (`int`, *optional*, defaults to 1):
231
- The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
232
- sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
233
- that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
234
- k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
235
- cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
236
- the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
237
- Returns:
238
- `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
239
- """
240
- cos = cos[position_ids].unsqueeze(unsqueeze_dim)
241
- sin = sin[position_ids].unsqueeze(unsqueeze_dim)
242
- q_embed = (q * cos) + (rotate_half(q) * sin)
243
- k_embed = (k * cos) + (rotate_half(k) * sin)
244
- return q_embed, k_embed
245
-
246
-
247
- class LlamaMLP(nn.Module):
248
- def __init__(self, config):
249
- super().__init__()
250
- self.config = config
251
- self.hidden_size = config.hidden_size
252
- self.intermediate_size = config.intermediate_size
253
- self.gate_proj = QuantizedLinear(self.hidden_size, self.intermediate_size, bias=False, **config.aqlm)
254
- self.up_proj = QuantizedLinear(self.hidden_size, self.intermediate_size, bias=False, **config.aqlm)
255
- self.down_proj = QuantizedLinear(self.intermediate_size, self.hidden_size, bias=False, **config.aqlm)
256
- self.act_fn = ACT2FN[config.hidden_act]
257
-
258
- def forward(self, x):
259
- if self.config.pretraining_tp > 1:
260
- slice = self.intermediate_size // self.config.pretraining_tp
261
- gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
262
- up_proj_slices = self.up_proj.weight.split(slice, dim=0)
263
- down_proj_slices = self.down_proj.weight.split(slice, dim=1)
264
-
265
- gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
266
- up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
267
-
268
- intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
269
- down_proj = [
270
- F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
271
- ]
272
- down_proj = sum(down_proj)
273
- else:
274
- down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
275
-
276
- return down_proj
277
-
278
-
279
- def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
280
- """
281
- This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
282
- num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
283
- """
284
- batch, num_key_value_heads, slen, head_dim = hidden_states.shape
285
- if n_rep == 1:
286
- return hidden_states
287
- hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
288
- return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
289
-
290
-
291
- class LlamaAttention(nn.Module):
292
- """Multi-headed attention from 'Attention Is All You Need' paper"""
293
-
294
- def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
295
- super().__init__()
296
- self.config = config
297
- self.layer_idx = layer_idx
298
- if layer_idx is None:
299
- logger.warning_once(
300
- f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
301
- "to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
302
- "when creating this class."
303
- )
304
-
305
- self.attention_dropout = config.attention_dropout
306
- self.hidden_size = config.hidden_size
307
- self.num_heads = config.num_attention_heads
308
- self.head_dim = self.hidden_size // self.num_heads
309
- self.num_key_value_heads = config.num_key_value_heads
310
- self.num_key_value_groups = self.num_heads // self.num_key_value_heads
311
- self.max_position_embeddings = config.max_position_embeddings
312
- self.rope_theta = config.rope_theta
313
- self.is_causal = True
314
-
315
- if (self.head_dim * self.num_heads) != self.hidden_size:
316
- raise ValueError(
317
- f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
318
- f" and `num_heads`: {self.num_heads})."
319
- )
320
-
321
- self.q_proj = QuantizedLinear(
322
- self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
323
- )
324
- self.k_proj = QuantizedLinear(
325
- self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
326
- )
327
- self.v_proj = QuantizedLinear(
328
- self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
329
- )
330
- self.o_proj = QuantizedLinear(
331
- self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias, **config.aqlm
332
- )
333
- self._init_rope()
334
-
335
- def _init_rope(self):
336
- if self.config.rope_scaling is None:
337
- self.rotary_emb = LlamaRotaryEmbedding(
338
- self.head_dim,
339
- max_position_embeddings=self.max_position_embeddings,
340
- base=self.rope_theta,
341
- )
342
- else:
343
- scaling_type = self.config.rope_scaling["type"]
344
- scaling_factor = self.config.rope_scaling["factor"]
345
- if scaling_type == "linear":
346
- self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
347
- self.head_dim,
348
- max_position_embeddings=self.max_position_embeddings,
349
- scaling_factor=scaling_factor,
350
- base=self.rope_theta,
351
- )
352
- elif scaling_type == "dynamic":
353
- self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
354
- self.head_dim,
355
- max_position_embeddings=self.max_position_embeddings,
356
- scaling_factor=scaling_factor,
357
- base=self.rope_theta,
358
- )
359
- else:
360
- raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
361
-
362
- def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
363
- return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
364
-
365
- def forward(
366
- self,
367
- hidden_states: torch.Tensor,
368
- attention_mask: Optional[torch.Tensor] = None,
369
- position_ids: Optional[torch.LongTensor] = None,
370
- past_key_value: Optional[Cache] = None,
371
- output_attentions: bool = False,
372
- use_cache: bool = False,
373
- **kwargs,
374
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
375
- if "padding_mask" in kwargs:
376
- warnings.warn(
377
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
378
- )
379
-
380
- bsz, q_len, _ = hidden_states.size()
381
-
382
- if self.config.pretraining_tp > 1:
383
- key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
384
- query_slices = self.q_proj.weight.split(
385
- (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
386
- )
387
- key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
388
- value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
389
-
390
- query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
391
- query_states = torch.cat(query_states, dim=-1)
392
-
393
- key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
394
- key_states = torch.cat(key_states, dim=-1)
395
-
396
- value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
397
- value_states = torch.cat(value_states, dim=-1)
398
-
399
- else:
400
- query_states = self.q_proj(hidden_states)
401
- key_states = self.k_proj(hidden_states)
402
- value_states = self.v_proj(hidden_states)
403
-
404
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
405
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
406
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
407
-
408
- kv_seq_len = key_states.shape[-2]
409
- if past_key_value is not None:
410
- if self.layer_idx is None:
411
- raise ValueError(
412
- f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
413
- "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
414
- "with a layer index."
415
- )
416
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
417
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
418
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
419
-
420
- if past_key_value is not None:
421
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
422
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
423
-
424
- key_states = repeat_kv(key_states, self.num_key_value_groups)
425
- value_states = repeat_kv(value_states, self.num_key_value_groups)
426
-
427
- attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
428
-
429
- if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
430
- raise ValueError(
431
- f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
432
- f" {attn_weights.size()}"
433
- )
434
-
435
- if attention_mask is not None:
436
- if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
437
- raise ValueError(
438
- f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
439
- )
440
- attn_weights = attn_weights + attention_mask
441
-
442
- # upcast attention to fp32
443
- attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
444
- attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
445
- attn_output = torch.matmul(attn_weights, value_states)
446
-
447
- if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
448
- raise ValueError(
449
- f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
450
- f" {attn_output.size()}"
451
- )
452
-
453
- attn_output = attn_output.transpose(1, 2).contiguous()
454
-
455
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
456
-
457
- if self.config.pretraining_tp > 1:
458
- attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
459
- o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
460
- attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
461
- else:
462
- attn_output = self.o_proj(attn_output)
463
-
464
- if not output_attentions:
465
- attn_weights = None
466
-
467
- return attn_output, attn_weights, past_key_value
468
-
469
-
470
- class LlamaFlashAttention2(LlamaAttention):
471
- """
472
- Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
473
- untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
474
- flash attention and deal with padding tokens in case the input contains any of them.
475
- """
476
-
477
- def __init__(self, *args, **kwargs):
478
- super().__init__(*args, **kwargs)
479
-
480
- # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
481
- # 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.
482
- # 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).
483
- self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
484
-
485
- def forward(
486
- self,
487
- hidden_states: torch.Tensor,
488
- attention_mask: Optional[torch.LongTensor] = None,
489
- position_ids: Optional[torch.LongTensor] = None,
490
- past_key_value: Optional[Cache] = None,
491
- output_attentions: bool = False,
492
- use_cache: bool = False,
493
- **kwargs,
494
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
495
- # LlamaFlashAttention2 attention does not support output_attentions
496
- if "padding_mask" in kwargs:
497
- warnings.warn(
498
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
499
- )
500
-
501
- # overwrite attention_mask with padding_mask
502
- attention_mask = kwargs.pop("padding_mask")
503
-
504
- output_attentions = False
505
-
506
- bsz, q_len, _ = hidden_states.size()
507
-
508
- query_states = self.q_proj(hidden_states)
509
- key_states = self.k_proj(hidden_states)
510
- value_states = self.v_proj(hidden_states)
511
-
512
- # Flash attention requires the input to have the shape
513
- # batch_size x seq_length x head_dim x hidden_dim
514
- # therefore we just need to keep the original shape
515
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
516
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
517
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
518
-
519
- kv_seq_len = key_states.shape[-2]
520
- if past_key_value is not None:
521
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
522
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
523
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
524
-
525
- if past_key_value is not None:
526
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
527
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
528
-
529
- # TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
530
- # to be able to avoid many of these transpose/reshape/view.
531
- query_states = query_states.transpose(1, 2)
532
- key_states = key_states.transpose(1, 2)
533
- value_states = value_states.transpose(1, 2)
534
-
535
- dropout_rate = self.attention_dropout if self.training else 0.0
536
-
537
- # In PEFT, usually we cast the layer norms in float32 for training stability reasons
538
- # therefore the input hidden states gets silently casted in float32. Hence, we need
539
- # cast them back in the correct dtype just to be sure everything works as expected.
540
- # This might slowdown training & inference so it is recommended to not cast the LayerNorms
541
- # in fp32. (LlamaRMSNorm handles it correctly)
542
-
543
- input_dtype = query_states.dtype
544
- if input_dtype == torch.float32:
545
- # Handle the case where the model is quantized
546
- if hasattr(self.config, "_pre_quantization_dtype"):
547
- target_dtype = self.config._pre_quantization_dtype
548
- else:
549
- target_dtype = self.q_proj.weight.dtype
550
-
551
- logger.warning_once(
552
- f"The input hidden states seems to be silently casted in float32, this might be related to"
553
- f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
554
- f" {target_dtype}."
555
- )
556
-
557
- query_states = query_states.to(target_dtype)
558
- key_states = key_states.to(target_dtype)
559
- value_states = value_states.to(target_dtype)
560
-
561
- attn_output = self._flash_attention_forward(
562
- query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
563
- )
564
-
565
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
566
- attn_output = self.o_proj(attn_output)
567
-
568
- if not output_attentions:
569
- attn_weights = None
570
-
571
- return attn_output, attn_weights, past_key_value
572
-
573
- def _flash_attention_forward(
574
- self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
575
- ):
576
- """
577
- Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
578
- first unpad the input, then computes the attention scores and pad the final attention scores.
579
-
580
- Args:
581
- query_states (`torch.Tensor`):
582
- Input query states to be passed to Flash Attention API
583
- key_states (`torch.Tensor`):
584
- Input key states to be passed to Flash Attention API
585
- value_states (`torch.Tensor`):
586
- Input value states to be passed to Flash Attention API
587
- attention_mask (`torch.Tensor`):
588
- The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
589
- position of padding tokens and 1 for the position of non-padding tokens.
590
- dropout (`int`, *optional*):
591
- Attention dropout
592
- softmax_scale (`float`, *optional*):
593
- The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
594
- """
595
- if not self._flash_attn_uses_top_left_mask:
596
- causal = self.is_causal
597
- else:
598
- # 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__.
599
- causal = self.is_causal and query_length != 1
600
-
601
- # Contains at least one padding token in the sequence
602
- if attention_mask is not None:
603
- batch_size = query_states.shape[0]
604
- query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
605
- query_states, key_states, value_states, attention_mask, query_length
606
- )
607
-
608
- cu_seqlens_q, cu_seqlens_k = cu_seq_lens
609
- max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
610
-
611
- attn_output_unpad = flash_attn_varlen_func(
612
- query_states,
613
- key_states,
614
- value_states,
615
- cu_seqlens_q=cu_seqlens_q,
616
- cu_seqlens_k=cu_seqlens_k,
617
- max_seqlen_q=max_seqlen_in_batch_q,
618
- max_seqlen_k=max_seqlen_in_batch_k,
619
- dropout_p=dropout,
620
- softmax_scale=softmax_scale,
621
- causal=causal,
622
- )
623
-
624
- attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
625
- else:
626
- attn_output = flash_attn_func(
627
- query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
628
- )
629
-
630
- return attn_output
631
-
632
- def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
633
- indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
634
- batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
635
-
636
- key_layer = index_first_axis(
637
- key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
638
- )
639
- value_layer = index_first_axis(
640
- value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
641
- )
642
- if query_length == kv_seq_len:
643
- query_layer = index_first_axis(
644
- query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
645
- )
646
- cu_seqlens_q = cu_seqlens_k
647
- max_seqlen_in_batch_q = max_seqlen_in_batch_k
648
- indices_q = indices_k
649
- elif query_length == 1:
650
- max_seqlen_in_batch_q = 1
651
- cu_seqlens_q = torch.arange(
652
- batch_size + 1, dtype=torch.int32, device=query_layer.device
653
- ) # There is a memcpy here, that is very bad.
654
- indices_q = cu_seqlens_q[:-1]
655
- query_layer = query_layer.squeeze(1)
656
- else:
657
- # The -q_len: slice assumes left padding.
658
- attention_mask = attention_mask[:, -query_length:]
659
- query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
660
-
661
- return (
662
- query_layer,
663
- key_layer,
664
- value_layer,
665
- indices_q,
666
- (cu_seqlens_q, cu_seqlens_k),
667
- (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
668
- )
669
-
670
-
671
- class LlamaSdpaAttention(LlamaAttention):
672
- """
673
- Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
674
- `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
675
- SDPA API.
676
- """
677
-
678
- # Adapted from LlamaAttention.forward
679
- def forward(
680
- self,
681
- hidden_states: torch.Tensor,
682
- attention_mask: Optional[torch.Tensor] = None,
683
- position_ids: Optional[torch.LongTensor] = None,
684
- past_key_value: Optional[Cache] = None,
685
- output_attentions: bool = False,
686
- use_cache: bool = False,
687
- ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
688
- if output_attentions:
689
- # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
690
- logger.warning_once(
691
- "LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
692
- '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.'
693
- )
694
- return super().forward(
695
- hidden_states=hidden_states,
696
- attention_mask=attention_mask,
697
- position_ids=position_ids,
698
- past_key_value=past_key_value,
699
- output_attentions=output_attentions,
700
- use_cache=use_cache,
701
- )
702
-
703
- bsz, q_len, _ = hidden_states.size()
704
-
705
- query_states = self.q_proj(hidden_states)
706
- key_states = self.k_proj(hidden_states)
707
- value_states = self.v_proj(hidden_states)
708
-
709
- query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
710
- key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
711
- value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
712
-
713
- kv_seq_len = key_states.shape[-2]
714
- if past_key_value is not None:
715
- kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
716
- cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
717
-
718
- query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
719
-
720
- if past_key_value is not None:
721
- cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
722
- key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
723
-
724
- key_states = repeat_kv(key_states, self.num_key_value_groups)
725
- value_states = repeat_kv(value_states, self.num_key_value_groups)
726
-
727
- if attention_mask is not None:
728
- if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
729
- raise ValueError(
730
- f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
731
- )
732
-
733
- # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
734
- # Reference: https://github.com/pytorch/pytorch/issues/112577.
735
- if query_states.device.type == "cuda" and attention_mask is not None:
736
- query_states = query_states.contiguous()
737
- key_states = key_states.contiguous()
738
- value_states = value_states.contiguous()
739
-
740
- attn_output = torch.nn.functional.scaled_dot_product_attention(
741
- query_states,
742
- key_states,
743
- value_states,
744
- attn_mask=attention_mask,
745
- dropout_p=self.attention_dropout if self.training else 0.0,
746
- # The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
747
- is_causal=self.is_causal and attention_mask is None and q_len > 1,
748
- )
749
-
750
- attn_output = attn_output.transpose(1, 2).contiguous()
751
- attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
752
-
753
- attn_output = self.o_proj(attn_output)
754
-
755
- return attn_output, None, past_key_value
756
-
757
-
758
- LLAMA_ATTENTION_CLASSES = {
759
- "eager": LlamaAttention,
760
- "flash_attention_2": LlamaFlashAttention2,
761
- "sdpa": LlamaSdpaAttention,
762
- }
763
-
764
-
765
- class LlamaDecoderLayer(nn.Module):
766
- def __init__(self, config: LlamaConfig, layer_idx: int):
767
- super().__init__()
768
- self.hidden_size = config.hidden_size
769
-
770
- self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
771
-
772
- self.mlp = LlamaMLP(config)
773
- self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
774
- self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
775
-
776
- def forward(
777
- self,
778
- hidden_states: torch.Tensor,
779
- attention_mask: Optional[torch.Tensor] = None,
780
- position_ids: Optional[torch.LongTensor] = None,
781
- past_key_value: Optional[Tuple[torch.Tensor]] = None,
782
- output_attentions: Optional[bool] = False,
783
- use_cache: Optional[bool] = False,
784
- **kwargs,
785
- ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
786
- """
787
- Args:
788
- hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
789
- attention_mask (`torch.FloatTensor`, *optional*):
790
- attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
791
- query_sequence_length, key_sequence_length)` if default attention is used.
792
- output_attentions (`bool`, *optional*):
793
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under
794
- returned tensors for more detail.
795
- use_cache (`bool`, *optional*):
796
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
797
- (see `past_key_values`).
798
- past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
799
- """
800
- if "padding_mask" in kwargs:
801
- warnings.warn(
802
- "Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
803
- )
804
-
805
- residual = hidden_states
806
-
807
- hidden_states = self.input_layernorm(hidden_states)
808
-
809
- # Self Attention
810
- hidden_states, self_attn_weights, present_key_value = self.self_attn(
811
- hidden_states=hidden_states,
812
- attention_mask=attention_mask,
813
- position_ids=position_ids,
814
- past_key_value=past_key_value,
815
- output_attentions=output_attentions,
816
- use_cache=use_cache,
817
- **kwargs,
818
- )
819
- hidden_states = residual + hidden_states
820
-
821
- # Fully Connected
822
- residual = hidden_states
823
- hidden_states = self.post_attention_layernorm(hidden_states)
824
- hidden_states = self.mlp(hidden_states)
825
- hidden_states = residual + hidden_states
826
-
827
- outputs = (hidden_states,)
828
-
829
- if output_attentions:
830
- outputs += (self_attn_weights,)
831
-
832
- if use_cache:
833
- outputs += (present_key_value,)
834
-
835
- return outputs
836
-
837
-
838
- LLAMA_START_DOCSTRING = r"""
839
- This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
840
- library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
841
- etc.)
842
-
843
- This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
844
- Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
845
- and behavior.
846
-
847
- Parameters:
848
- config ([`LlamaConfig`]):
849
- Model configuration class with all the parameters of the model. Initializing with a config file does not
850
- load the weights associated with the model, only the configuration. Check out the
851
- [`~PreTrainedModel.from_pretrained`] method to load the model weights.
852
- """
853
-
854
-
855
- @add_start_docstrings(
856
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
857
- LLAMA_START_DOCSTRING,
858
- )
859
- class LlamaPreTrainedModel(PreTrainedModel):
860
- config_class = LlamaConfig
861
- base_model_prefix = "model"
862
- supports_gradient_checkpointing = True
863
- _no_split_modules = ["LlamaDecoderLayer"]
864
- _skip_keys_device_placement = "past_key_values"
865
- _supports_flash_attn_2 = True
866
- _supports_sdpa = True
867
- _supports_cache_class = True
868
-
869
- def _init_weights(self, module):
870
- std = self.config.initializer_range
871
- if isinstance(module, nn.Linear):
872
- module.weight.data.normal_(mean=0.0, std=std)
873
- if module.bias is not None:
874
- module.bias.data.zero_()
875
- elif isinstance(module, nn.Embedding):
876
- module.weight.data.normal_(mean=0.0, std=std)
877
- if module.padding_idx is not None:
878
- module.weight.data[module.padding_idx].zero_()
879
-
880
-
881
- LLAMA_INPUTS_DOCSTRING = r"""
882
- Args:
883
- input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
884
- Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
885
- it.
886
-
887
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
888
- [`PreTrainedTokenizer.__call__`] for details.
889
-
890
- [What are input IDs?](../glossary#input-ids)
891
- attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
892
- Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
893
-
894
- - 1 for tokens that are **not masked**,
895
- - 0 for tokens that are **masked**.
896
-
897
- [What are attention masks?](../glossary#attention-mask)
898
-
899
- Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
900
- [`PreTrainedTokenizer.__call__`] for details.
901
-
902
- If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
903
- `past_key_values`).
904
-
905
- If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
906
- and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
907
- information on the default strategy.
908
-
909
- - 1 indicates the head is **not masked**,
910
- - 0 indicates the head is **masked**.
911
- position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
912
- Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
913
- config.n_positions - 1]`.
914
-
915
- [What are position IDs?](../glossary#position-ids)
916
- past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
917
- Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
918
- blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
919
- returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
920
-
921
- Two formats are allowed:
922
- - a [`~cache_utils.Cache`] instance;
923
- - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
924
- shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
925
- cache format.
926
-
927
- The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
928
- legacy cache format will be returned.
929
-
930
- If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
931
- have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
932
- of shape `(batch_size, sequence_length)`.
933
- inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
934
- Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
935
- is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
936
- model's internal embedding lookup matrix.
937
- use_cache (`bool`, *optional*):
938
- If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
939
- `past_key_values`).
940
- output_attentions (`bool`, *optional*):
941
- Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
942
- tensors for more detail.
943
- output_hidden_states (`bool`, *optional*):
944
- Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
945
- more detail.
946
- return_dict (`bool`, *optional*):
947
- Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
948
- """
949
-
950
-
951
- @add_start_docstrings(
952
- "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
953
- LLAMA_START_DOCSTRING,
954
- )
955
- class LlamaModel(LlamaPreTrainedModel):
956
- """
957
- Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
958
-
959
- Args:
960
- config: LlamaConfig
961
- """
962
-
963
- def __init__(self, config: LlamaConfig):
964
- super().__init__(config)
965
- self.padding_idx = config.pad_token_id
966
- self.vocab_size = config.vocab_size
967
-
968
- self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
969
- self.layers = nn.ModuleList(
970
- [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
971
- )
972
- self._use_sdpa = config._attn_implementation == "sdpa"
973
- self._use_flash_attention_2 = config._attn_implementation == "flash_attention_2"
974
- self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
975
-
976
- self.gradient_checkpointing = False
977
- # Initialize weights and apply final processing
978
- self.post_init()
979
-
980
- def get_input_embeddings(self):
981
- return self.embed_tokens
982
-
983
- def set_input_embeddings(self, value):
984
- self.embed_tokens = value
985
-
986
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
987
- def forward(
988
- self,
989
- input_ids: torch.LongTensor = None,
990
- attention_mask: Optional[torch.Tensor] = None,
991
- position_ids: Optional[torch.LongTensor] = None,
992
- past_key_values: Optional[List[torch.FloatTensor]] = None,
993
- inputs_embeds: Optional[torch.FloatTensor] = None,
994
- use_cache: Optional[bool] = None,
995
- output_attentions: Optional[bool] = None,
996
- output_hidden_states: Optional[bool] = None,
997
- return_dict: Optional[bool] = None,
998
- ) -> Union[Tuple, BaseModelOutputWithPast]:
999
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1000
- output_hidden_states = (
1001
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1002
- )
1003
- use_cache = use_cache if use_cache is not None else self.config.use_cache
1004
-
1005
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1006
-
1007
- # retrieve input_ids and inputs_embeds
1008
- if input_ids is not None and inputs_embeds is not None:
1009
- raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
1010
- elif input_ids is not None:
1011
- batch_size, seq_length = input_ids.shape[:2]
1012
- elif inputs_embeds is not None:
1013
- batch_size, seq_length = inputs_embeds.shape[:2]
1014
- else:
1015
- raise ValueError("You have to specify either input_ids or inputs_embeds")
1016
-
1017
- if self.gradient_checkpointing and self.training:
1018
- if use_cache:
1019
- logger.warning_once(
1020
- "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1021
- )
1022
- use_cache = False
1023
-
1024
- past_key_values_length = 0
1025
- if use_cache:
1026
- use_legacy_cache = not isinstance(past_key_values, Cache)
1027
- if use_legacy_cache:
1028
- past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1029
- past_key_values_length = past_key_values.get_usable_length(seq_length)
1030
-
1031
- if position_ids is None:
1032
- device = input_ids.device if input_ids is not None else inputs_embeds.device
1033
- position_ids = torch.arange(
1034
- past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
1035
- )
1036
- position_ids = position_ids.unsqueeze(0)
1037
-
1038
- if inputs_embeds is None:
1039
- inputs_embeds = self.embed_tokens(input_ids)
1040
-
1041
- if self._use_flash_attention_2:
1042
- # 2d mask is passed through the layers
1043
- attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
1044
- elif self._use_sdpa and not output_attentions:
1045
- # output_attentions=True can not be supported when using SDPA, and we fall back on
1046
- # the manual implementation that requires a 4D causal mask in all cases.
1047
- attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1048
- attention_mask,
1049
- (batch_size, seq_length),
1050
- inputs_embeds,
1051
- past_key_values_length,
1052
- )
1053
- else:
1054
- # 4d mask is passed through the layers
1055
- attention_mask = _prepare_4d_causal_attention_mask(
1056
- attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
1057
- )
1058
-
1059
- # embed positions
1060
- hidden_states = inputs_embeds
1061
-
1062
- # decoder layers
1063
- all_hidden_states = () if output_hidden_states else None
1064
- all_self_attns = () if output_attentions else None
1065
- next_decoder_cache = None
1066
-
1067
- for decoder_layer in self.layers:
1068
- if output_hidden_states:
1069
- all_hidden_states += (hidden_states,)
1070
-
1071
- if self.gradient_checkpointing and self.training:
1072
- layer_outputs = self._gradient_checkpointing_func(
1073
- decoder_layer.__call__,
1074
- hidden_states,
1075
- attention_mask,
1076
- position_ids,
1077
- past_key_values,
1078
- output_attentions,
1079
- use_cache,
1080
- )
1081
- else:
1082
- layer_outputs = decoder_layer(
1083
- hidden_states,
1084
- attention_mask=attention_mask,
1085
- position_ids=position_ids,
1086
- past_key_value=past_key_values,
1087
- output_attentions=output_attentions,
1088
- use_cache=use_cache,
1089
- )
1090
-
1091
- hidden_states = layer_outputs[0]
1092
-
1093
- if use_cache:
1094
- next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1095
-
1096
- if output_attentions:
1097
- all_self_attns += (layer_outputs[1],)
1098
-
1099
- hidden_states = self.norm(hidden_states)
1100
-
1101
- # add hidden states from the last decoder layer
1102
- if output_hidden_states:
1103
- all_hidden_states += (hidden_states,)
1104
-
1105
- next_cache = None
1106
- if use_cache:
1107
- next_cache = next_decoder_cache.to_legacy_cache() if use_legacy_cache else next_decoder_cache
1108
- if not return_dict:
1109
- return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1110
- return BaseModelOutputWithPast(
1111
- last_hidden_state=hidden_states,
1112
- past_key_values=next_cache,
1113
- hidden_states=all_hidden_states,
1114
- attentions=all_self_attns,
1115
- )
1116
-
1117
-
1118
- class LlamaForCausalLM(LlamaPreTrainedModel):
1119
- _tied_weights_keys = ["lm_head.weight"]
1120
-
1121
- def __init__(self, config):
1122
- super().__init__(config)
1123
- self.model = LlamaModel(config)
1124
- self.vocab_size = config.vocab_size
1125
- self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1126
-
1127
- # Initialize weights and apply final processing
1128
- self.post_init()
1129
-
1130
- def get_input_embeddings(self):
1131
- return self.model.embed_tokens
1132
-
1133
- def set_input_embeddings(self, value):
1134
- self.model.embed_tokens = value
1135
-
1136
- def get_output_embeddings(self):
1137
- return self.lm_head
1138
-
1139
- def set_output_embeddings(self, new_embeddings):
1140
- self.lm_head = new_embeddings
1141
-
1142
- def set_decoder(self, decoder):
1143
- self.model = decoder
1144
-
1145
- def get_decoder(self):
1146
- return self.model
1147
-
1148
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1149
- @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1150
- def forward(
1151
- self,
1152
- input_ids: torch.LongTensor = None,
1153
- attention_mask: Optional[torch.Tensor] = None,
1154
- position_ids: Optional[torch.LongTensor] = None,
1155
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1156
- inputs_embeds: Optional[torch.FloatTensor] = None,
1157
- labels: Optional[torch.LongTensor] = None,
1158
- use_cache: Optional[bool] = None,
1159
- output_attentions: Optional[bool] = None,
1160
- output_hidden_states: Optional[bool] = None,
1161
- return_dict: Optional[bool] = None,
1162
- ) -> Union[Tuple, CausalLMOutputWithPast]:
1163
- r"""
1164
- Args:
1165
- labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1166
- Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1167
- config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1168
- (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1169
-
1170
- Returns:
1171
-
1172
- Example:
1173
-
1174
- ```python
1175
- >>> from transformers import AutoTokenizer, LlamaForCausalLM
1176
-
1177
- >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1178
- >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1179
-
1180
- >>> prompt = "Hey, are you conscious? Can you talk to me?"
1181
- >>> inputs = tokenizer(prompt, return_tensors="pt")
1182
-
1183
- >>> # Generate
1184
- >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1185
- >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1186
- "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1187
- ```"""
1188
- output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1189
- output_hidden_states = (
1190
- output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1191
- )
1192
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1193
-
1194
- # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1195
- outputs = self.model(
1196
- input_ids=input_ids,
1197
- attention_mask=attention_mask,
1198
- position_ids=position_ids,
1199
- past_key_values=past_key_values,
1200
- inputs_embeds=inputs_embeds,
1201
- use_cache=use_cache,
1202
- output_attentions=output_attentions,
1203
- output_hidden_states=output_hidden_states,
1204
- return_dict=return_dict,
1205
- )
1206
-
1207
- hidden_states = outputs[0]
1208
- if self.config.pretraining_tp > 1:
1209
- lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1210
- logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1211
- logits = torch.cat(logits, dim=-1)
1212
- else:
1213
- logits = self.lm_head(hidden_states)
1214
- logits = logits.float()
1215
-
1216
- loss = None
1217
- if labels is not None:
1218
- # Shift so that tokens < n predict n
1219
- shift_logits = logits[..., :-1, :].contiguous()
1220
- shift_labels = labels[..., 1:].contiguous()
1221
- # Flatten the tokens
1222
- loss_fct = CrossEntropyLoss()
1223
- shift_logits = shift_logits.view(-1, self.config.vocab_size)
1224
- shift_labels = shift_labels.view(-1)
1225
- # Enable model parallelism
1226
- shift_labels = shift_labels.to(shift_logits.device)
1227
- loss = loss_fct(shift_logits, shift_labels)
1228
-
1229
- if not return_dict:
1230
- output = (logits,) + outputs[1:]
1231
- return (loss,) + output if loss is not None else output
1232
-
1233
- return CausalLMOutputWithPast(
1234
- loss=loss,
1235
- logits=logits,
1236
- past_key_values=outputs.past_key_values,
1237
- hidden_states=outputs.hidden_states,
1238
- attentions=outputs.attentions,
1239
- )
1240
-
1241
- def prepare_inputs_for_generation(
1242
- self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1243
- ):
1244
- if past_key_values is not None:
1245
- if isinstance(past_key_values, Cache):
1246
- cache_length = past_key_values.get_seq_length()
1247
- past_length = past_key_values.seen_tokens
1248
- max_cache_length = past_key_values.get_max_length()
1249
- else:
1250
- cache_length = past_length = past_key_values[0][0].shape[2]
1251
- max_cache_length = None
1252
-
1253
- # Keep only the unprocessed tokens:
1254
- # 1 - If the length of the attention_mask exceeds the length of input_ids, then we are in a setting where
1255
- # some of the inputs are exclusivelly passed as part of the cache (e.g. when passing input_embeds as
1256
- # input)
1257
- if attention_mask is not None and attention_mask.shape[1] > input_ids.shape[1]:
1258
- input_ids = input_ids[:, -(attention_mask.shape[1] - past_length) :]
1259
- # 2 - If the past_length is smaller than input_ids', then input_ids holds all input tokens. We can discard
1260
- # input_ids based on the past_length.
1261
- elif past_length < input_ids.shape[1]:
1262
- input_ids = input_ids[:, past_length:]
1263
- # 3 - Otherwise (past_length >= input_ids.shape[1]), let's assume input_ids only has unprocessed tokens.
1264
-
1265
- # If we are about to go beyond the maximum cache length, we need to crop the input attention mask.
1266
- if (
1267
- max_cache_length is not None
1268
- and attention_mask is not None
1269
- and cache_length + input_ids.shape[1] > max_cache_length
1270
- ):
1271
- attention_mask = attention_mask[:, -max_cache_length:]
1272
-
1273
- position_ids = kwargs.get("position_ids", None)
1274
- if attention_mask is not None and position_ids is None:
1275
- # create position_ids on the fly for batch generation
1276
- position_ids = attention_mask.long().cumsum(-1) - 1
1277
- position_ids.masked_fill_(attention_mask == 0, 1)
1278
- if past_key_values:
1279
- position_ids = position_ids[:, -input_ids.shape[1] :]
1280
-
1281
- # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1282
- if inputs_embeds is not None and past_key_values is None:
1283
- model_inputs = {"inputs_embeds": inputs_embeds}
1284
- else:
1285
- model_inputs = {"input_ids": input_ids}
1286
-
1287
- model_inputs.update(
1288
- {
1289
- "position_ids": position_ids,
1290
- "past_key_values": past_key_values,
1291
- "use_cache": kwargs.get("use_cache"),
1292
- "attention_mask": attention_mask,
1293
- }
1294
- )
1295
- return model_inputs
1296
-
1297
- @staticmethod
1298
- def _reorder_cache(past_key_values, beam_idx):
1299
- reordered_past = ()
1300
- for layer_past in past_key_values:
1301
- reordered_past += (
1302
- tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1303
- )
1304
- return reordered_past
1305
-
1306
-
1307
- @add_start_docstrings(
1308
- """
1309
- The LLaMa Model transformer with a sequence classification head on top (linear layer).
1310
-
1311
- [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1312
- (e.g. GPT-2) do.
1313
-
1314
- Since it does classification on the last token, it requires to know the position of the last token. If a
1315
- `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1316
- no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1317
- padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1318
- each row of the batch).
1319
- """,
1320
- LLAMA_START_DOCSTRING,
1321
- )
1322
- class LlamaForSequenceClassification(LlamaPreTrainedModel):
1323
- def __init__(self, config):
1324
- super().__init__(config)
1325
- self.num_labels = config.num_labels
1326
- self.model = LlamaModel(config)
1327
- self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1328
-
1329
- # Initialize weights and apply final processing
1330
- self.post_init()
1331
-
1332
- def get_input_embeddings(self):
1333
- return self.model.embed_tokens
1334
-
1335
- def set_input_embeddings(self, value):
1336
- self.model.embed_tokens = value
1337
-
1338
- @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1339
- def forward(
1340
- self,
1341
- input_ids: torch.LongTensor = None,
1342
- attention_mask: Optional[torch.Tensor] = None,
1343
- position_ids: Optional[torch.LongTensor] = None,
1344
- past_key_values: Optional[List[torch.FloatTensor]] = None,
1345
- inputs_embeds: Optional[torch.FloatTensor] = None,
1346
- labels: Optional[torch.LongTensor] = None,
1347
- use_cache: Optional[bool] = None,
1348
- output_attentions: Optional[bool] = None,
1349
- output_hidden_states: Optional[bool] = None,
1350
- return_dict: Optional[bool] = None,
1351
- ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1352
- r"""
1353
- labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1354
- Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1355
- config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1356
- `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1357
- """
1358
- return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1359
-
1360
- transformer_outputs = self.model(
1361
- input_ids,
1362
- attention_mask=attention_mask,
1363
- position_ids=position_ids,
1364
- past_key_values=past_key_values,
1365
- inputs_embeds=inputs_embeds,
1366
- use_cache=use_cache,
1367
- output_attentions=output_attentions,
1368
- output_hidden_states=output_hidden_states,
1369
- return_dict=return_dict,
1370
- )
1371
- hidden_states = transformer_outputs[0]
1372
- logits = self.score(hidden_states)
1373
-
1374
- if input_ids is not None:
1375
- batch_size = input_ids.shape[0]
1376
- else:
1377
- batch_size = inputs_embeds.shape[0]
1378
-
1379
- if self.config.pad_token_id is None and batch_size != 1:
1380
- raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1381
- if self.config.pad_token_id is None:
1382
- sequence_lengths = -1
1383
- else:
1384
- if input_ids is not None:
1385
- sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1).to(
1386
- logits.device
1387
- )
1388
- else:
1389
- sequence_lengths = -1
1390
-
1391
- pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1392
-
1393
- loss = None
1394
- if labels is not None:
1395
- labels = labels.to(logits.device)
1396
- if self.config.problem_type is None:
1397
- if self.num_labels == 1:
1398
- self.config.problem_type = "regression"
1399
- elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1400
- self.config.problem_type = "single_label_classification"
1401
- else:
1402
- self.config.problem_type = "multi_label_classification"
1403
-
1404
- if self.config.problem_type == "regression":
1405
- loss_fct = MSELoss()
1406
- if self.num_labels == 1:
1407
- loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1408
- else:
1409
- loss = loss_fct(pooled_logits, labels)
1410
- elif self.config.problem_type == "single_label_classification":
1411
- loss_fct = CrossEntropyLoss()
1412
- loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1413
- elif self.config.problem_type == "multi_label_classification":
1414
- loss_fct = BCEWithLogitsLoss()
1415
- loss = loss_fct(pooled_logits, labels)
1416
- if not return_dict:
1417
- output = (pooled_logits,) + transformer_outputs[1:]
1418
- return ((loss,) + output) if loss is not None else output
1419
-
1420
- return SequenceClassifierOutputWithPast(
1421
- loss=loss,
1422
- logits=pooled_logits,
1423
- past_key_values=transformer_outputs.past_key_values,
1424
- hidden_states=transformer_outputs.hidden_states,
1425
- attentions=transformer_outputs.attentions,
1426
- )