rulins commited on
Commit
f37bf0d
1 Parent(s): 0d9185a

add personalized file

Browse files
Files changed (1) hide show
  1. modeling_llama.py +1665 -0
modeling_llama.py ADDED
@@ -0,0 +1,1665 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ import inspect
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+
29
+ from ...activations import ACT2FN
30
+ from ...cache_utils import Cache, DynamicCache, StaticCache
31
+ from ...modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa, _prepare_4d_attention_mask, _prepare_4d_attention_mask_for_sdpa
32
+ from ...generation import GenerationMixin
33
+ from ...modeling_attn_mask_utils import AttentionMaskConverter
34
+ from ...modeling_outputs import (
35
+ BaseModelOutputWithPast,
36
+ CausalLMOutputWithPast,
37
+ QuestionAnsweringModelOutput,
38
+ SequenceClassifierOutputWithPast,
39
+ TokenClassifierOutput,
40
+ )
41
+ from ...modeling_rope_utils import ROPE_INIT_FUNCTIONS
42
+ from ...modeling_utils import PreTrainedModel
43
+ from ...pytorch_utils import ALL_LAYERNORM_LAYERS
44
+ from ...utils import (
45
+ add_code_sample_docstrings,
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ is_flash_attn_2_available,
49
+ is_flash_attn_greater_or_equal_2_10,
50
+ logging,
51
+ replace_return_docstrings,
52
+ )
53
+ from .configuration_llama import LlamaConfig
54
+
55
+ if is_flash_attn_2_available():
56
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
57
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
58
+
59
+ _flash_supports_window_size = "window_size" in list(inspect.signature(flash_attn_func).parameters)
60
+
61
+ logger = logging.get_logger(__name__)
62
+
63
+ _CHECKPOINT_FOR_DOC = "meta-llama/Llama-2-7b-hf"
64
+ _CONFIG_FOR_DOC = "LlamaConfig"
65
+
66
+
67
+ class LlamaRMSNorm(nn.Module):
68
+ def __init__(self, hidden_size, eps=1e-6):
69
+ """
70
+ LlamaRMSNorm is equivalent to T5LayerNorm
71
+ """
72
+ super().__init__()
73
+ self.weight = nn.Parameter(torch.ones(hidden_size))
74
+ self.variance_epsilon = eps
75
+
76
+ def forward(self, hidden_states):
77
+ input_dtype = hidden_states.dtype
78
+ hidden_states = hidden_states.to(torch.float32)
79
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
80
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
81
+ return self.weight * hidden_states.to(input_dtype)
82
+
83
+ def extra_repr(self):
84
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
85
+
86
+
87
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
88
+
89
+
90
+ class LlamaRotaryEmbedding(nn.Module):
91
+ def __init__(
92
+ self,
93
+ dim=None,
94
+ max_position_embeddings=2048,
95
+ base=10000,
96
+ device=None,
97
+ scaling_factor=1.0,
98
+ rope_type="default",
99
+ config: Optional[LlamaConfig] = None,
100
+ ):
101
+ super().__init__()
102
+ # TODO (joao): remove the `if` below, only used for BC
103
+ self.rope_kwargs = {}
104
+ if config is None:
105
+ logger.warning_once(
106
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
107
+ "`config` argument. All other arguments will be removed in v4.46"
108
+ )
109
+ self.rope_kwargs = {
110
+ "rope_type": rope_type,
111
+ "factor": scaling_factor,
112
+ "dim": dim,
113
+ "base": base,
114
+ "max_position_embeddings": max_position_embeddings,
115
+ }
116
+ self.rope_type = rope_type
117
+ self.max_seq_len_cached = max_position_embeddings
118
+ self.original_max_seq_len = max_position_embeddings
119
+ else:
120
+ # BC: "rope_type" was originally "type"
121
+ if config.rope_scaling is not None:
122
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
123
+ else:
124
+ self.rope_type = "default"
125
+ self.max_seq_len_cached = config.max_position_embeddings
126
+ self.original_max_seq_len = config.max_position_embeddings
127
+
128
+ self.config = config
129
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
130
+
131
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
132
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
133
+ self.original_inv_freq = self.inv_freq
134
+
135
+ def _dynamic_frequency_update(self, position_ids, device):
136
+ """
137
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
138
+ 1 - growing beyond the cached sequence length (allow scaling)
139
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
140
+ """
141
+ seq_len = torch.max(position_ids) + 1
142
+ if seq_len > self.max_seq_len_cached: # growth
143
+ inv_freq, self.attention_scaling = self.rope_init_fn(
144
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
145
+ )
146
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
147
+ self.max_seq_len_cached = seq_len
148
+
149
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
150
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
151
+ self.max_seq_len_cached = self.original_max_seq_len
152
+
153
+ @torch.no_grad()
154
+ def forward(self, x, position_ids):
155
+ if "dynamic" in self.rope_type:
156
+ self._dynamic_frequency_update(position_ids, device=x.device)
157
+
158
+ # Core RoPE block
159
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
160
+ position_ids_expanded = position_ids[:, None, :].float()
161
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
162
+ device_type = x.device.type
163
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
164
+ with torch.autocast(device_type=device_type, enabled=False):
165
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
166
+ emb = torch.cat((freqs, freqs), dim=-1)
167
+ cos = emb.cos()
168
+ sin = emb.sin()
169
+
170
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
171
+ cos = cos * self.attention_scaling
172
+ sin = sin * self.attention_scaling
173
+
174
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
175
+
176
+
177
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
178
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
179
+
180
+ def __init__(self, *args, **kwargs):
181
+ logger.warning_once(
182
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
183
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
184
+ )
185
+ kwargs["rope_type"] = "linear"
186
+ super().__init__(*args, **kwargs)
187
+
188
+
189
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
190
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
191
+
192
+ def __init__(self, *args, **kwargs):
193
+ logger.warning_once(
194
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
195
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
196
+ "__init__)."
197
+ )
198
+ kwargs["rope_type"] = "dynamic"
199
+ super().__init__(*args, **kwargs)
200
+
201
+
202
+ def rotate_half(x):
203
+ """Rotates half the hidden dims of the input."""
204
+ x1 = x[..., : x.shape[-1] // 2]
205
+ x2 = x[..., x.shape[-1] // 2 :]
206
+ return torch.cat((-x2, x1), dim=-1)
207
+
208
+
209
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
210
+ """Applies Rotary Position Embedding to the query and key tensors.
211
+
212
+ Args:
213
+ q (`torch.Tensor`): The query tensor.
214
+ k (`torch.Tensor`): The key tensor.
215
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
216
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
217
+ position_ids (`torch.Tensor`, *optional*):
218
+ Deprecated and unused.
219
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
220
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
221
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
222
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
223
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
224
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
225
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
226
+ Returns:
227
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
228
+ """
229
+ cos = cos.unsqueeze(unsqueeze_dim)
230
+ sin = sin.unsqueeze(unsqueeze_dim)
231
+ q_embed = (q * cos) + (rotate_half(q) * sin)
232
+ k_embed = (k * cos) + (rotate_half(k) * sin)
233
+ return q_embed, k_embed
234
+
235
+
236
+ class LlamaMLP(nn.Module):
237
+ def __init__(self, config):
238
+ super().__init__()
239
+ self.config = config
240
+ self.hidden_size = config.hidden_size
241
+ self.intermediate_size = config.intermediate_size
242
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
243
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
244
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
245
+ self.act_fn = ACT2FN[config.hidden_act]
246
+
247
+ def forward(self, x):
248
+ if self.config.pretraining_tp > 1:
249
+ slice = self.intermediate_size // self.config.pretraining_tp
250
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
251
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
252
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
253
+
254
+ gate_proj = torch.cat(
255
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
256
+ )
257
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
258
+
259
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
260
+ down_proj = [
261
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
262
+ ]
263
+ down_proj = sum(down_proj)
264
+ else:
265
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
266
+
267
+ return down_proj
268
+
269
+
270
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
271
+ """
272
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
273
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
274
+ """
275
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
276
+ if n_rep == 1:
277
+ return hidden_states
278
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
279
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
280
+
281
+
282
+ class LlamaAttention(nn.Module):
283
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
284
+
285
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
286
+ super().__init__()
287
+ self.config = config
288
+ self.layer_idx = layer_idx
289
+ if layer_idx is None:
290
+ logger.warning_once(
291
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
292
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
293
+ "when creating this class."
294
+ )
295
+
296
+ self.attention_dropout = config.attention_dropout
297
+ self.hidden_size = config.hidden_size
298
+ self.num_heads = config.num_attention_heads
299
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
300
+ self.num_key_value_heads = config.num_key_value_heads
301
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
302
+ self.max_position_embeddings = config.max_position_embeddings
303
+ self.rope_theta = config.rope_theta
304
+
305
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
306
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
307
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
308
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
309
+
310
+ # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
311
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
312
+
313
+ def forward(
314
+ self,
315
+ hidden_states: torch.Tensor,
316
+ attention_mask: Optional[torch.Tensor] = None,
317
+ position_ids: Optional[torch.LongTensor] = None,
318
+ past_key_value: Optional[Cache] = None,
319
+ output_attentions: bool = False,
320
+ use_cache: bool = False,
321
+ cache_position: Optional[torch.LongTensor] = None,
322
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
323
+ **kwargs,
324
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
325
+ bsz, q_len, _ = hidden_states.size()
326
+
327
+ if self.config.pretraining_tp > 1:
328
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
329
+ query_slices = self.q_proj.weight.split(
330
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
331
+ )
332
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
333
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
334
+
335
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
336
+ query_states = torch.cat(query_states, dim=-1)
337
+
338
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
339
+ key_states = torch.cat(key_states, dim=-1)
340
+
341
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
342
+ value_states = torch.cat(value_states, dim=-1)
343
+
344
+ else:
345
+ query_states = self.q_proj(hidden_states)
346
+ key_states = self.k_proj(hidden_states)
347
+ value_states = self.v_proj(hidden_states)
348
+
349
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
350
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
351
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
352
+
353
+ if position_embeddings is None:
354
+ logger.warning_once(
355
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
356
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
357
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
358
+ "removed and `position_embeddings` will be mandatory."
359
+ )
360
+ cos, sin = self.rotary_emb(value_states, position_ids)
361
+ else:
362
+ cos, sin = position_embeddings
363
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
364
+
365
+ if past_key_value is not None:
366
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
367
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
368
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
369
+
370
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
371
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
372
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
373
+
374
+ if attention_mask is not None: # no matter the length, we just slice it
375
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
376
+ attn_weights = attn_weights + causal_mask
377
+
378
+ # upcast attention to fp32
379
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
380
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
381
+ attn_output = torch.matmul(attn_weights, value_states)
382
+
383
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
384
+ raise ValueError(
385
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
386
+ f" {attn_output.size()}"
387
+ )
388
+
389
+ attn_output = attn_output.transpose(1, 2).contiguous()
390
+
391
+ attn_output = attn_output.reshape(bsz, q_len, -1)
392
+
393
+ if self.config.pretraining_tp > 1:
394
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
395
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
396
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
397
+ else:
398
+ attn_output = self.o_proj(attn_output)
399
+
400
+ if not output_attentions:
401
+ attn_weights = None
402
+
403
+ return attn_output, attn_weights, past_key_value
404
+
405
+
406
+ class LlamaFlashAttention2(LlamaAttention):
407
+ """
408
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
409
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
410
+ flash attention and deal with padding tokens in case the input contains any of them.
411
+ """
412
+
413
+ def __init__(self, *args, **kwargs):
414
+ super().__init__(*args, **kwargs)
415
+
416
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
417
+ # 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.
418
+ # 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).
419
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
420
+
421
+ def _flash_attention_forward(
422
+ self,
423
+ query_states,
424
+ key_states,
425
+ value_states,
426
+ attention_mask,
427
+ query_length,
428
+ dropout=0.0,
429
+ softmax_scale=None,
430
+ use_sliding_windows=False,
431
+ is_causal=True,
432
+ ):
433
+ """
434
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
435
+ first unpad the input, then computes the attention scores and pad the final attention scores.
436
+
437
+ Args:
438
+ query_states (`torch.Tensor`):
439
+ Input query states to be passed to Flash Attention API
440
+ key_states (`torch.Tensor`):
441
+ Input key states to be passed to Flash Attention API
442
+ value_states (`torch.Tensor`):
443
+ Input value states to be passed to Flash Attention API
444
+ attention_mask (`torch.Tensor`):
445
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
446
+ position of padding tokens and 1 for the position of non-padding tokens.
447
+ dropout (`int`, *optional*):
448
+ Attention dropout
449
+ softmax_scale (`float`, *optional*):
450
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
451
+ use_sliding_windows (`bool`, *optional*):
452
+ Whether to activate sliding window attention.
453
+ """
454
+ if not self._flash_attn_uses_top_left_mask:
455
+ causal = is_causal
456
+ else:
457
+ # 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__.
458
+ causal = is_causal and query_length != 1
459
+
460
+ # Contains at least one padding token in the sequence
461
+ if attention_mask is not None:
462
+ batch_size = query_states.shape[0]
463
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
464
+ query_states, key_states, value_states, attention_mask, query_length
465
+ )
466
+
467
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
468
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
469
+
470
+ if not use_sliding_windows:
471
+ attn_output_unpad = flash_attn_varlen_func(
472
+ query_states,
473
+ key_states,
474
+ value_states,
475
+ cu_seqlens_q=cu_seqlens_q,
476
+ cu_seqlens_k=cu_seqlens_k,
477
+ max_seqlen_q=max_seqlen_in_batch_q,
478
+ max_seqlen_k=max_seqlen_in_batch_k,
479
+ dropout_p=dropout,
480
+ softmax_scale=softmax_scale,
481
+ causal=causal,
482
+ )
483
+ else:
484
+ attn_output_unpad = flash_attn_varlen_func(
485
+ query_states,
486
+ key_states,
487
+ value_states,
488
+ cu_seqlens_q=cu_seqlens_q,
489
+ cu_seqlens_k=cu_seqlens_k,
490
+ max_seqlen_q=max_seqlen_in_batch_q,
491
+ max_seqlen_k=max_seqlen_in_batch_k,
492
+ dropout_p=dropout,
493
+ softmax_scale=softmax_scale,
494
+ causal=causal,
495
+ window_size=(self.config.sliding_window, self.config.sliding_window),
496
+ )
497
+
498
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
499
+ else:
500
+ if not use_sliding_windows:
501
+ attn_output = flash_attn_func(
502
+ query_states,
503
+ key_states,
504
+ value_states,
505
+ dropout,
506
+ softmax_scale=softmax_scale,
507
+ causal=causal,
508
+ )
509
+ else:
510
+ attn_output = flash_attn_func(
511
+ query_states,
512
+ key_states,
513
+ value_states,
514
+ dropout,
515
+ softmax_scale=softmax_scale,
516
+ causal=causal,
517
+ window_size=(self.config.sliding_window, self.config.sliding_window),
518
+ )
519
+
520
+ return attn_output
521
+
522
+ def forward(
523
+ self,
524
+ hidden_states: torch.Tensor,
525
+ attention_mask: Optional[torch.LongTensor] = None,
526
+ position_ids: Optional[torch.LongTensor] = None,
527
+ past_key_value: Optional[Cache] = None,
528
+ output_attentions: bool = False,
529
+ use_cache: bool = False,
530
+ cache_position: Optional[torch.LongTensor] = None,
531
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
532
+ is_causal: bool = True,
533
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
534
+ if isinstance(past_key_value, StaticCache):
535
+ raise ValueError(
536
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
537
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
538
+ )
539
+ output_attentions = False
540
+
541
+ bsz, q_len, _ = hidden_states.size()
542
+
543
+ query_states = self.q_proj(hidden_states)
544
+ key_states = self.k_proj(hidden_states)
545
+ value_states = self.v_proj(hidden_states)
546
+
547
+ # Flash attention requires the input to have the shape
548
+ # batch_size x seq_length x head_dim x hidden_dim
549
+ # therefore we just need to keep the original shape
550
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
551
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
552
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
553
+
554
+ if position_embeddings is None:
555
+ logger.warning_once(
556
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
557
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
558
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
559
+ "removed and `position_embeddings` will be mandatory."
560
+ )
561
+ cos, sin = self.rotary_emb(value_states, position_ids)
562
+ else:
563
+ cos, sin = position_embeddings
564
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
565
+
566
+ if past_key_value is not None:
567
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
568
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
569
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
570
+
571
+ # 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
572
+ # to be able to avoid many of these transpose/reshape/view.
573
+ query_states = query_states.transpose(1, 2)
574
+ key_states = key_states.transpose(1, 2)
575
+ value_states = value_states.transpose(1, 2)
576
+
577
+ dropout_rate = self.attention_dropout if self.training else 0.0
578
+
579
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
580
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
581
+ # cast them back in the correct dtype just to be sure everything works as expected.
582
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
583
+ # in fp32. (LlamaRMSNorm handles it correctly)
584
+
585
+ input_dtype = query_states.dtype
586
+ if input_dtype == torch.float32:
587
+ if torch.is_autocast_enabled():
588
+ target_dtype = torch.get_autocast_gpu_dtype()
589
+ # Handle the case where the model is quantized
590
+ elif hasattr(self.config, "_pre_quantization_dtype"):
591
+ target_dtype = self.config._pre_quantization_dtype
592
+ else:
593
+ target_dtype = self.q_proj.weight.dtype
594
+
595
+ logger.warning_once(
596
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
597
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
598
+ f" {target_dtype}."
599
+ )
600
+
601
+ query_states = query_states.to(target_dtype)
602
+ key_states = key_states.to(target_dtype)
603
+ value_states = value_states.to(target_dtype)
604
+
605
+ kv_seq_len = key_states.shape[-2]
606
+ if past_key_value is not None:
607
+ if self.layer_idx is None:
608
+ raise ValueError(
609
+ f"The cache structure has changed since version v4.36. If you are using {self.__class__.__name__} "
610
+ "for auto-regressive decoding with k/v caching, please make sure to initialize the attention class "
611
+ "with a layer index."
612
+ )
613
+ kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
614
+
615
+ use_sliding_windows = (
616
+ _flash_supports_window_size
617
+ and getattr(self.config, "sliding_window", None) is not None
618
+ and kv_seq_len > self.config.sliding_window
619
+ )
620
+
621
+ attn_output = self._flash_attention_forward(
622
+ query_states,
623
+ key_states,
624
+ value_states,
625
+ attention_mask,
626
+ q_len,
627
+ dropout=dropout_rate,
628
+ use_sliding_windows=use_sliding_windows,
629
+ is_causal=is_causal,
630
+ )
631
+
632
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
633
+ attn_output = self.o_proj(attn_output)
634
+
635
+ if not output_attentions:
636
+ attn_weights = None
637
+
638
+ return attn_output, attn_weights, past_key_value
639
+
640
+
641
+ class LlamaSdpaAttention(LlamaAttention):
642
+ """
643
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
644
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
645
+ SDPA API.
646
+ """
647
+
648
+ # Adapted from LlamaAttention.forward
649
+ def forward(
650
+ self,
651
+ hidden_states: torch.Tensor,
652
+ attention_mask: Optional[torch.Tensor] = None,
653
+ position_ids: Optional[torch.LongTensor] = None,
654
+ past_key_value: Optional[Cache] = None,
655
+ output_attentions: bool = False,
656
+ use_cache: bool = False,
657
+ cache_position: Optional[torch.LongTensor] = None,
658
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
659
+ is_causal: bool = True,
660
+ **kwargs,
661
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
662
+ if output_attentions:
663
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
664
+ logger.warning_once(
665
+ "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, "
666
+ '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.'
667
+ )
668
+ return super().forward(
669
+ hidden_states=hidden_states,
670
+ attention_mask=attention_mask,
671
+ position_ids=position_ids,
672
+ past_key_value=past_key_value,
673
+ output_attentions=output_attentions,
674
+ use_cache=use_cache,
675
+ cache_position=cache_position,
676
+ position_embeddings=position_embeddings,
677
+ is_causal=is_causal,
678
+ )
679
+
680
+ bsz, q_len, _ = hidden_states.size()
681
+
682
+ query_states = self.q_proj(hidden_states)
683
+ key_states = self.k_proj(hidden_states)
684
+ value_states = self.v_proj(hidden_states)
685
+
686
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
687
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
688
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
689
+
690
+ if position_embeddings is None:
691
+ logger.warning_once(
692
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
693
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
694
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
695
+ "removed and `position_embeddings` will be mandatory."
696
+ )
697
+ cos, sin = self.rotary_emb(value_states, position_ids)
698
+ else:
699
+ cos, sin = position_embeddings
700
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
701
+
702
+ if past_key_value is not None:
703
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
704
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
705
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
706
+
707
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
708
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
709
+
710
+ causal_mask = attention_mask
711
+ if attention_mask is not None:
712
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
713
+
714
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
715
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
716
+ if query_states.device.type == "cuda" and causal_mask is not None:
717
+ query_states = query_states.contiguous()
718
+ key_states = key_states.contiguous()
719
+ value_states = value_states.contiguous()
720
+
721
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
722
+ query_states,
723
+ key_states,
724
+ value_states,
725
+ attn_mask=causal_mask,
726
+ dropout_p=self.attention_dropout if self.training else 0.0,
727
+ is_causal=is_causal if causal_mask is None and q_len > 1 else False,
728
+ )
729
+
730
+ attn_output = attn_output.transpose(1, 2).contiguous()
731
+ attn_output = attn_output.view(bsz, q_len, -1)
732
+
733
+ attn_output = self.o_proj(attn_output)
734
+
735
+ return attn_output, None, past_key_value
736
+
737
+
738
+ LLAMA_ATTENTION_CLASSES = {
739
+ "eager": LlamaAttention,
740
+ "flash_attention_2": LlamaFlashAttention2,
741
+ "sdpa": LlamaSdpaAttention,
742
+ }
743
+
744
+
745
+ class LlamaDecoderLayer(nn.Module):
746
+ def __init__(self, config: LlamaConfig, layer_idx: int):
747
+ super().__init__()
748
+ self.hidden_size = config.hidden_size
749
+
750
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
751
+
752
+ self.mlp = LlamaMLP(config)
753
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
754
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
755
+
756
+ def forward(
757
+ self,
758
+ hidden_states: torch.Tensor,
759
+ attention_mask: Optional[torch.Tensor] = None,
760
+ position_ids: Optional[torch.LongTensor] = None,
761
+ past_key_value: Optional[Cache] = None,
762
+ output_attentions: Optional[bool] = False,
763
+ use_cache: Optional[bool] = False,
764
+ cache_position: Optional[torch.LongTensor] = None,
765
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
766
+ is_causal: bool = True,
767
+ **kwargs,
768
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
769
+ """
770
+ Args:
771
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
772
+ attention_mask (`torch.FloatTensor`, *optional*):
773
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
774
+ query_sequence_length, key_sequence_length)` if default attention is used.
775
+ output_attentions (`bool`, *optional*):
776
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
777
+ returned tensors for more detail.
778
+ use_cache (`bool`, *optional*):
779
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
780
+ (see `past_key_values`).
781
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
782
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
783
+ Indices depicting the position of the input sequence tokens in the sequence
784
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
785
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
786
+ with `head_dim` being the embedding dimension of each attention head.
787
+ kwargs (`dict`, *optional*):
788
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
789
+ into the model
790
+ """
791
+ residual = hidden_states
792
+
793
+ hidden_states = self.input_layernorm(hidden_states)
794
+
795
+ # Self Attention
796
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
797
+ hidden_states=hidden_states,
798
+ attention_mask=attention_mask,
799
+ position_ids=position_ids,
800
+ past_key_value=past_key_value,
801
+ output_attentions=output_attentions,
802
+ use_cache=use_cache,
803
+ cache_position=cache_position,
804
+ position_embeddings=position_embeddings,
805
+ is_causal=is_causal,
806
+ **kwargs,
807
+ )
808
+ hidden_states = residual + hidden_states
809
+
810
+ # Fully Connected
811
+ residual = hidden_states
812
+ hidden_states = self.post_attention_layernorm(hidden_states)
813
+ hidden_states = self.mlp(hidden_states)
814
+ hidden_states = residual + hidden_states
815
+
816
+ outputs = (hidden_states,)
817
+
818
+ if output_attentions:
819
+ outputs += (self_attn_weights,)
820
+
821
+ if use_cache:
822
+ outputs += (present_key_value,)
823
+
824
+ return outputs
825
+
826
+
827
+ LLAMA_START_DOCSTRING = r"""
828
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
829
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
830
+ etc.)
831
+
832
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
833
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
834
+ and behavior.
835
+
836
+ Parameters:
837
+ config ([`LlamaConfig`]):
838
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
839
+ load the weights associated with the model, only the configuration. Check out the
840
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
841
+ """
842
+
843
+
844
+ @add_start_docstrings(
845
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
846
+ LLAMA_START_DOCSTRING,
847
+ )
848
+ class LlamaPreTrainedModel(PreTrainedModel):
849
+ config_class = LlamaConfig
850
+ base_model_prefix = "model"
851
+ supports_gradient_checkpointing = True
852
+ _no_split_modules = ["LlamaDecoderLayer"]
853
+ _skip_keys_device_placement = ["past_key_values"]
854
+ _supports_flash_attn_2 = True
855
+ _supports_sdpa = True
856
+ _supports_cache_class = True
857
+ _supports_quantized_cache = True
858
+ _supports_static_cache = True
859
+
860
+ def _init_weights(self, module):
861
+ std = self.config.initializer_range
862
+ if isinstance(module, nn.Linear):
863
+ module.weight.data.normal_(mean=0.0, std=std)
864
+ if module.bias is not None:
865
+ module.bias.data.zero_()
866
+ elif isinstance(module, nn.Embedding):
867
+ module.weight.data.normal_(mean=0.0, std=std)
868
+ if module.padding_idx is not None:
869
+ module.weight.data[module.padding_idx].zero_()
870
+
871
+
872
+ LLAMA_INPUTS_DOCSTRING = r"""
873
+ Args:
874
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
875
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
876
+ it.
877
+
878
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
879
+ [`PreTrainedTokenizer.__call__`] for details.
880
+
881
+ [What are input IDs?](../glossary#input-ids)
882
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
883
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
884
+
885
+ - 1 for tokens that are **not masked**,
886
+ - 0 for tokens that are **masked**.
887
+
888
+ [What are attention masks?](../glossary#attention-mask)
889
+
890
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
891
+ [`PreTrainedTokenizer.__call__`] for details.
892
+
893
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
894
+ `past_key_values`).
895
+
896
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
897
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
898
+ information on the default strategy.
899
+
900
+ - 1 indicates the head is **not masked**,
901
+ - 0 indicates the head is **masked**.
902
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
903
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
904
+ config.n_positions - 1]`.
905
+
906
+ [What are position IDs?](../glossary#position-ids)
907
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
908
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
909
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
910
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
911
+
912
+ Two formats are allowed:
913
+ - a [`~cache_utils.Cache`] instance, see our
914
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
915
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
916
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
917
+ cache format.
918
+
919
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
920
+ legacy cache format will be returned.
921
+
922
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
923
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
924
+ of shape `(batch_size, sequence_length)`.
925
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
926
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
927
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
928
+ model's internal embedding lookup matrix.
929
+ use_cache (`bool`, *optional*):
930
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
931
+ `past_key_values`).
932
+ output_attentions (`bool`, *optional*):
933
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
934
+ tensors for more detail.
935
+ output_hidden_states (`bool`, *optional*):
936
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
937
+ more detail.
938
+ return_dict (`bool`, *optional*):
939
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
940
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
941
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
942
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
943
+ the complete sequence length.
944
+ """
945
+
946
+
947
+ @add_start_docstrings(
948
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
949
+ LLAMA_START_DOCSTRING,
950
+ )
951
+ class LlamaModel(LlamaPreTrainedModel):
952
+ """
953
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
954
+
955
+ Args:
956
+ config: LlamaConfig
957
+ """
958
+
959
+ def __init__(self, config: LlamaConfig):
960
+ super().__init__(config)
961
+ self.padding_idx = config.pad_token_id
962
+ self.vocab_size = config.vocab_size
963
+
964
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
965
+ self.layers = nn.ModuleList(
966
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
967
+ )
968
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
969
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
970
+ self.gradient_checkpointing = False
971
+
972
+ # Initialize weights and apply final processing
973
+ self.post_init()
974
+
975
+ def get_input_embeddings(self):
976
+ return self.embed_tokens
977
+
978
+ def set_input_embeddings(self, value):
979
+ self.embed_tokens = value
980
+
981
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
982
+ def forward(
983
+ self,
984
+ input_ids: torch.LongTensor = None,
985
+ attention_mask: Optional[torch.Tensor] = None,
986
+ position_ids: Optional[torch.LongTensor] = None,
987
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
988
+ inputs_embeds: Optional[torch.FloatTensor] = None,
989
+ use_cache: Optional[bool] = None,
990
+ output_attentions: Optional[bool] = None,
991
+ output_hidden_states: Optional[bool] = None,
992
+ return_dict: Optional[bool] = None,
993
+ cache_position: Optional[torch.LongTensor] = None,
994
+ is_causal: Optional[bool] = True,
995
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
996
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
997
+ output_hidden_states = (
998
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
999
+ )
1000
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1001
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1002
+
1003
+ if (input_ids is None) ^ (inputs_embeds is not None):
1004
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
1005
+
1006
+ if self.gradient_checkpointing and self.training and use_cache:
1007
+ logger.warning_once(
1008
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
1009
+ )
1010
+ use_cache = False
1011
+
1012
+ if inputs_embeds is None:
1013
+ inputs_embeds = self.embed_tokens(input_ids)
1014
+
1015
+ # kept for BC (non `Cache` `past_key_values` inputs)
1016
+ return_legacy_cache = False
1017
+ if use_cache and not isinstance(past_key_values, Cache):
1018
+ return_legacy_cache = True
1019
+ if past_key_values is None:
1020
+ past_key_values = DynamicCache()
1021
+ else:
1022
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1023
+ logger.warning_once(
1024
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
1025
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
1026
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
1027
+ )
1028
+
1029
+ if cache_position is None:
1030
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
1031
+ cache_position = torch.arange(
1032
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
1033
+ )
1034
+ if position_ids is None:
1035
+ position_ids = cache_position.unsqueeze(0)
1036
+
1037
+ causal_mask = self._update_causal_mask(
1038
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions, is_causal
1039
+ )
1040
+ hidden_states = inputs_embeds
1041
+
1042
+ # create position embeddings to be shared across the decoder layers
1043
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
1044
+
1045
+ # decoder layers
1046
+ all_hidden_states = () if output_hidden_states else None
1047
+ all_self_attns = () if output_attentions else None
1048
+ next_decoder_cache = None
1049
+
1050
+ for decoder_layer in self.layers:
1051
+ if output_hidden_states:
1052
+ all_hidden_states += (hidden_states,)
1053
+
1054
+ if self.gradient_checkpointing and self.training:
1055
+ layer_outputs = self._gradient_checkpointing_func(
1056
+ decoder_layer.__call__,
1057
+ hidden_states,
1058
+ causal_mask,
1059
+ position_ids,
1060
+ past_key_values,
1061
+ output_attentions,
1062
+ use_cache,
1063
+ cache_position,
1064
+ position_embeddings,
1065
+ is_causal
1066
+ )
1067
+ else:
1068
+ layer_outputs = decoder_layer(
1069
+ hidden_states,
1070
+ attention_mask=causal_mask,
1071
+ position_ids=position_ids,
1072
+ past_key_value=past_key_values,
1073
+ output_attentions=output_attentions,
1074
+ use_cache=use_cache,
1075
+ cache_position=cache_position,
1076
+ position_embeddings=position_embeddings,
1077
+ is_causal=is_causal,
1078
+ )
1079
+
1080
+ hidden_states = layer_outputs[0]
1081
+
1082
+ if use_cache:
1083
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
1084
+
1085
+ if output_attentions:
1086
+ all_self_attns += (layer_outputs[1],)
1087
+
1088
+ hidden_states = self.norm(hidden_states)
1089
+
1090
+ # add hidden states from the last decoder layer
1091
+ if output_hidden_states:
1092
+ all_hidden_states += (hidden_states,)
1093
+
1094
+ next_cache = next_decoder_cache if use_cache else None
1095
+ if return_legacy_cache:
1096
+ next_cache = next_cache.to_legacy_cache()
1097
+
1098
+ if not return_dict:
1099
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
1100
+ return BaseModelOutputWithPast(
1101
+ last_hidden_state=hidden_states,
1102
+ past_key_values=next_cache,
1103
+ hidden_states=all_hidden_states,
1104
+ attentions=all_self_attns,
1105
+ )
1106
+
1107
+ def _update_causal_mask(
1108
+ self,
1109
+ attention_mask: torch.Tensor,
1110
+ input_tensor: torch.Tensor,
1111
+ cache_position: torch.Tensor,
1112
+ past_key_values: Cache,
1113
+ output_attentions: bool,
1114
+ is_causal: bool
1115
+ ):
1116
+ if self.config._attn_implementation == "flash_attention_2":
1117
+ if attention_mask is not None and 0.0 in attention_mask:
1118
+ return attention_mask
1119
+ return None
1120
+
1121
+ batch_size, seq_length, _ = input_tensor.shape
1122
+
1123
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
1124
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
1125
+ # to infer the attention mask.
1126
+ past_seen_tokens = past_key_values_length = past_key_values.get_seq_length() if past_key_values is not None else 0
1127
+ past_key_values = 0
1128
+ if past_key_values:
1129
+ use_legacy_cache = not isinstance(past_key_values, Cache)
1130
+ if use_legacy_cache:
1131
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
1132
+ past_key_values_length = past_key_values.get_usable_length(seq_length)
1133
+ using_static_cache = isinstance(past_key_values, StaticCache)
1134
+
1135
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1136
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1137
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1138
+ attention_mask,
1139
+ inputs_embeds=input_tensor,
1140
+ past_key_values_length=past_seen_tokens,
1141
+ is_training=self.training,
1142
+ ):
1143
+ return None
1144
+ if is_causal:
1145
+ attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
1146
+ attention_mask,
1147
+ (batch_size, seq_length),
1148
+ input_tensor,
1149
+ past_key_values_length,
1150
+ )
1151
+ else:
1152
+ attention_mask = _prepare_4d_attention_mask_for_sdpa(
1153
+ attention_mask, input_tensor.dtype
1154
+ )
1155
+ else:
1156
+ # 4d mask is passed through the layers
1157
+ if is_causal:
1158
+ # Causal mask with -3.3895e+38 where no attention should be
1159
+ attention_mask = _prepare_4d_causal_attention_mask(
1160
+ attention_mask,
1161
+ (batch_size, seq_length),
1162
+ input_tensor,
1163
+ past_key_values_length,
1164
+ sliding_window=self.config.sliding_window,
1165
+ )
1166
+ else:
1167
+ # Shape: batch_size, 1, query_length, key_value_length
1168
+ attention_mask = _prepare_4d_attention_mask(
1169
+ attention_mask, input_tensor.dtype
1170
+ )
1171
+
1172
+ dtype, device = input_tensor.dtype, input_tensor.device
1173
+ sequence_length = input_tensor.shape[1]
1174
+ if using_static_cache:
1175
+ target_length = past_key_values.get_max_cache_shape()
1176
+ else:
1177
+ target_length = (
1178
+ attention_mask.shape[-1]
1179
+ if isinstance(attention_mask, torch.Tensor)
1180
+ else past_seen_tokens + sequence_length + 1
1181
+ )
1182
+
1183
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1184
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1185
+ attention_mask,
1186
+ sequence_length=sequence_length,
1187
+ target_length=target_length,
1188
+ dtype=dtype,
1189
+ device=device,
1190
+ cache_position=cache_position,
1191
+ batch_size=input_tensor.shape[0],
1192
+ )
1193
+
1194
+ if (
1195
+ self.config._attn_implementation == "sdpa"
1196
+ and attention_mask is not None
1197
+ and attention_mask.device.type == "cuda"
1198
+ and not output_attentions
1199
+ ):
1200
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1201
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1202
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1203
+ min_dtype = torch.finfo(dtype).min
1204
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1205
+
1206
+ return causal_mask
1207
+
1208
+ @staticmethod
1209
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1210
+ attention_mask: torch.Tensor,
1211
+ sequence_length: int,
1212
+ target_length: int,
1213
+ dtype: torch.dtype,
1214
+ device: torch.device,
1215
+ cache_position: torch.Tensor,
1216
+ batch_size: int,
1217
+ **kwargs,
1218
+ ):
1219
+ """
1220
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1221
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1222
+
1223
+ Args:
1224
+ attention_mask (`torch.Tensor`):
1225
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1226
+ `(batch_size, 1, query_length, key_value_length)`.
1227
+ sequence_length (`int`):
1228
+ The sequence length being processed.
1229
+ target_length (`int`):
1230
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1231
+ to account for the 0 padding, the part of the cache that is not filled yet.
1232
+ dtype (`torch.dtype`):
1233
+ The dtype to use for the 4D attention mask.
1234
+ device (`torch.device`):
1235
+ The device to plcae the 4D attention mask on.
1236
+ cache_position (`torch.Tensor`):
1237
+ Indices depicting the position of the input sequence tokens in the sequence.
1238
+ batch_size (`torch.Tensor`):
1239
+ Batch size.
1240
+ """
1241
+ if attention_mask is not None and attention_mask.dim() == 4:
1242
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1243
+ causal_mask = attention_mask
1244
+ else:
1245
+ min_dtype = torch.finfo(dtype).min
1246
+ causal_mask = torch.full(
1247
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1248
+ )
1249
+ if sequence_length != 1:
1250
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1251
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1252
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1253
+ if attention_mask is not None:
1254
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1255
+ mask_length = attention_mask.shape[-1]
1256
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1257
+ padding_mask = padding_mask == 0
1258
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1259
+ padding_mask, min_dtype
1260
+ )
1261
+
1262
+ return causal_mask
1263
+
1264
+
1265
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
1266
+ _tied_weights_keys = ["lm_head.weight"]
1267
+
1268
+ def __init__(self, config):
1269
+ super().__init__(config)
1270
+ self.model = LlamaModel(config)
1271
+ self.vocab_size = config.vocab_size
1272
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1273
+
1274
+ # Initialize weights and apply final processing
1275
+ self.post_init()
1276
+
1277
+ def get_input_embeddings(self):
1278
+ return self.model.embed_tokens
1279
+
1280
+ def set_input_embeddings(self, value):
1281
+ self.model.embed_tokens = value
1282
+
1283
+ def get_output_embeddings(self):
1284
+ return self.lm_head
1285
+
1286
+ def set_output_embeddings(self, new_embeddings):
1287
+ self.lm_head = new_embeddings
1288
+
1289
+ def set_decoder(self, decoder):
1290
+ self.model = decoder
1291
+
1292
+ def get_decoder(self):
1293
+ return self.model
1294
+
1295
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1296
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1297
+ def forward(
1298
+ self,
1299
+ input_ids: torch.LongTensor = None,
1300
+ attention_mask: Optional[torch.Tensor] = None,
1301
+ position_ids: Optional[torch.LongTensor] = None,
1302
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1303
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1304
+ labels: Optional[torch.LongTensor] = None,
1305
+ use_cache: Optional[bool] = None,
1306
+ output_attentions: Optional[bool] = None,
1307
+ output_hidden_states: Optional[bool] = None,
1308
+ return_dict: Optional[bool] = None,
1309
+ cache_position: Optional[torch.LongTensor] = None,
1310
+ num_logits_to_keep: int = 0,
1311
+ **loss_kwargs,
1312
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1313
+ r"""
1314
+ Args:
1315
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1316
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1317
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1318
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1319
+
1320
+ num_logits_to_keep (`int`, *optional*):
1321
+ Calculate logits for the last `num_logits_to_keep` tokens. If `0`, calculate logits for all
1322
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
1323
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
1324
+
1325
+ Returns:
1326
+
1327
+ Example:
1328
+
1329
+ ```python
1330
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1331
+
1332
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
1333
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
1334
+
1335
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1336
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1337
+
1338
+ >>> # Generate
1339
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1340
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1341
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1342
+ ```"""
1343
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1344
+ output_hidden_states = (
1345
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1346
+ )
1347
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1348
+
1349
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1350
+ outputs = self.model(
1351
+ input_ids=input_ids,
1352
+ attention_mask=attention_mask,
1353
+ position_ids=position_ids,
1354
+ past_key_values=past_key_values,
1355
+ inputs_embeds=inputs_embeds,
1356
+ use_cache=use_cache,
1357
+ output_attentions=output_attentions,
1358
+ output_hidden_states=output_hidden_states,
1359
+ return_dict=return_dict,
1360
+ cache_position=cache_position,
1361
+ )
1362
+
1363
+ hidden_states = outputs[0]
1364
+ if self.config.pretraining_tp > 1:
1365
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1366
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1367
+ logits = torch.cat(logits, dim=-1)
1368
+ else:
1369
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
1370
+ logits = self.lm_head(hidden_states[:, -num_logits_to_keep:, :])
1371
+
1372
+ loss = None
1373
+ if labels is not None:
1374
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **loss_kwargs)
1375
+
1376
+ if not return_dict:
1377
+ output = (logits,) + outputs[1:]
1378
+ return (loss,) + output if loss is not None else output
1379
+
1380
+ return CausalLMOutputWithPast(
1381
+ loss=loss,
1382
+ logits=logits,
1383
+ past_key_values=outputs.past_key_values,
1384
+ hidden_states=outputs.hidden_states,
1385
+ attentions=outputs.attentions,
1386
+ )
1387
+
1388
+
1389
+ @add_start_docstrings(
1390
+ """
1391
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1392
+
1393
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1394
+ (e.g. GPT-2) do.
1395
+
1396
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1397
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1398
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1399
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1400
+ each row of the batch).
1401
+ """,
1402
+ LLAMA_START_DOCSTRING,
1403
+ )
1404
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1405
+ def __init__(self, config):
1406
+ super().__init__(config)
1407
+ self.num_labels = config.num_labels
1408
+ self.model = LlamaModel(config)
1409
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1410
+
1411
+ # Initialize weights and apply final processing
1412
+ self.post_init()
1413
+
1414
+ def get_input_embeddings(self):
1415
+ return self.model.embed_tokens
1416
+
1417
+ def set_input_embeddings(self, value):
1418
+ self.model.embed_tokens = value
1419
+
1420
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1421
+ def forward(
1422
+ self,
1423
+ input_ids: Optional[torch.LongTensor] = None,
1424
+ attention_mask: Optional[torch.Tensor] = None,
1425
+ position_ids: Optional[torch.LongTensor] = None,
1426
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1427
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1428
+ labels: Optional[torch.LongTensor] = None,
1429
+ use_cache: Optional[bool] = None,
1430
+ output_attentions: Optional[bool] = None,
1431
+ output_hidden_states: Optional[bool] = None,
1432
+ return_dict: Optional[bool] = None,
1433
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1434
+ r"""
1435
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1436
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1437
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1438
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1439
+ """
1440
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1441
+
1442
+ transformer_outputs = self.model(
1443
+ input_ids,
1444
+ attention_mask=attention_mask,
1445
+ position_ids=position_ids,
1446
+ past_key_values=past_key_values,
1447
+ inputs_embeds=inputs_embeds,
1448
+ use_cache=use_cache,
1449
+ output_attentions=output_attentions,
1450
+ output_hidden_states=output_hidden_states,
1451
+ return_dict=return_dict,
1452
+ )
1453
+ hidden_states = transformer_outputs[0]
1454
+ logits = self.score(hidden_states)
1455
+
1456
+ if input_ids is not None:
1457
+ batch_size = input_ids.shape[0]
1458
+ else:
1459
+ batch_size = inputs_embeds.shape[0]
1460
+
1461
+ if self.config.pad_token_id is None and batch_size != 1:
1462
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1463
+ if self.config.pad_token_id is None:
1464
+ sequence_lengths = -1
1465
+ else:
1466
+ if input_ids is not None:
1467
+ # if no pad token found, use modulo instead of reverse indexing for ONNX compatibility
1468
+ sequence_lengths = torch.eq(input_ids, self.config.pad_token_id).int().argmax(-1) - 1
1469
+ sequence_lengths = sequence_lengths % input_ids.shape[-1]
1470
+ sequence_lengths = sequence_lengths.to(logits.device)
1471
+ else:
1472
+ sequence_lengths = -1
1473
+
1474
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1475
+
1476
+ loss = None
1477
+ if labels is not None:
1478
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
1479
+
1480
+ if not return_dict:
1481
+ output = (pooled_logits,) + transformer_outputs[1:]
1482
+ return ((loss,) + output) if loss is not None else output
1483
+
1484
+ return SequenceClassifierOutputWithPast(
1485
+ loss=loss,
1486
+ logits=pooled_logits,
1487
+ past_key_values=transformer_outputs.past_key_values,
1488
+ hidden_states=transformer_outputs.hidden_states,
1489
+ attentions=transformer_outputs.attentions,
1490
+ )
1491
+
1492
+
1493
+ @add_start_docstrings(
1494
+ """
1495
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
1496
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
1497
+ """,
1498
+ LLAMA_START_DOCSTRING,
1499
+ )
1500
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
1501
+ base_model_prefix = "transformer"
1502
+
1503
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
1504
+ def __init__(self, config):
1505
+ super().__init__(config)
1506
+ self.transformer = LlamaModel(config)
1507
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1508
+
1509
+ # Initialize weights and apply final processing
1510
+ self.post_init()
1511
+
1512
+ def get_input_embeddings(self):
1513
+ return self.transformer.embed_tokens
1514
+
1515
+ def set_input_embeddings(self, value):
1516
+ self.transformer.embed_tokens = value
1517
+
1518
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1519
+ def forward(
1520
+ self,
1521
+ input_ids: Optional[torch.LongTensor] = None,
1522
+ attention_mask: Optional[torch.FloatTensor] = None,
1523
+ position_ids: Optional[torch.LongTensor] = None,
1524
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1525
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1526
+ start_positions: Optional[torch.LongTensor] = None,
1527
+ end_positions: Optional[torch.LongTensor] = None,
1528
+ output_attentions: Optional[bool] = None,
1529
+ output_hidden_states: Optional[bool] = None,
1530
+ return_dict: Optional[bool] = None,
1531
+ **kwargs,
1532
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1533
+ r"""
1534
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1535
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1536
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1537
+ are not taken into account for computing the loss.
1538
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1539
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1540
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1541
+ are not taken into account for computing the loss.
1542
+ """
1543
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1544
+
1545
+ outputs = self.transformer(
1546
+ input_ids,
1547
+ attention_mask=attention_mask,
1548
+ position_ids=position_ids,
1549
+ past_key_values=past_key_values,
1550
+ inputs_embeds=inputs_embeds,
1551
+ output_attentions=output_attentions,
1552
+ output_hidden_states=output_hidden_states,
1553
+ return_dict=return_dict,
1554
+ )
1555
+
1556
+ sequence_output = outputs[0]
1557
+
1558
+ logits = self.qa_outputs(sequence_output)
1559
+ start_logits, end_logits = logits.split(1, dim=-1)
1560
+ start_logits = start_logits.squeeze(-1).contiguous()
1561
+ end_logits = end_logits.squeeze(-1).contiguous()
1562
+
1563
+ loss = None
1564
+ if start_positions is not None and end_positions is not None:
1565
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1566
+
1567
+ if not return_dict:
1568
+ output = (start_logits, end_logits) + outputs[2:]
1569
+ return ((loss,) + output) if loss is not None else output
1570
+
1571
+ return QuestionAnsweringModelOutput(
1572
+ loss=loss,
1573
+ start_logits=start_logits,
1574
+ end_logits=end_logits,
1575
+ hidden_states=outputs.hidden_states,
1576
+ attentions=outputs.attentions,
1577
+ )
1578
+
1579
+
1580
+ @add_start_docstrings(
1581
+ """
1582
+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1583
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1584
+ """,
1585
+ LLAMA_START_DOCSTRING,
1586
+ )
1587
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
1588
+ def __init__(self, config):
1589
+ super().__init__(config)
1590
+ self.num_labels = config.num_labels
1591
+ self.model = LlamaModel(config)
1592
+ if getattr(config, "classifier_dropout", None) is not None:
1593
+ classifier_dropout = config.classifier_dropout
1594
+ elif getattr(config, "hidden_dropout", None) is not None:
1595
+ classifier_dropout = config.hidden_dropout
1596
+ else:
1597
+ classifier_dropout = 0.1
1598
+ self.dropout = nn.Dropout(classifier_dropout)
1599
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1600
+
1601
+ # Initialize weights and apply final processing
1602
+ self.post_init()
1603
+
1604
+ def get_input_embeddings(self):
1605
+ return self.model.embed_tokens
1606
+
1607
+ def set_input_embeddings(self, value):
1608
+ self.model.embed_tokens = value
1609
+
1610
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1611
+ @add_code_sample_docstrings(
1612
+ checkpoint=_CHECKPOINT_FOR_DOC,
1613
+ output_type=TokenClassifierOutput,
1614
+ config_class=_CONFIG_FOR_DOC,
1615
+ )
1616
+ def forward(
1617
+ self,
1618
+ input_ids: Optional[torch.LongTensor] = None,
1619
+ attention_mask: Optional[torch.Tensor] = None,
1620
+ position_ids: Optional[torch.LongTensor] = None,
1621
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1622
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1623
+ labels: Optional[torch.LongTensor] = None,
1624
+ use_cache: Optional[bool] = None,
1625
+ output_attentions: Optional[bool] = None,
1626
+ output_hidden_states: Optional[bool] = None,
1627
+ return_dict: Optional[bool] = None,
1628
+ ) -> Union[Tuple, TokenClassifierOutput]:
1629
+ r"""
1630
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1631
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1632
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1633
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1634
+ """
1635
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1636
+
1637
+ outputs = self.model(
1638
+ input_ids,
1639
+ attention_mask=attention_mask,
1640
+ position_ids=position_ids,
1641
+ past_key_values=past_key_values,
1642
+ inputs_embeds=inputs_embeds,
1643
+ use_cache=use_cache,
1644
+ output_attentions=output_attentions,
1645
+ output_hidden_states=output_hidden_states,
1646
+ return_dict=return_dict,
1647
+ )
1648
+ sequence_output = outputs[0]
1649
+ sequence_output = self.dropout(sequence_output)
1650
+ logits = self.score(sequence_output)
1651
+
1652
+ loss = None
1653
+ if labels is not None:
1654
+ loss = self.loss_function(logits, labels, self.config)
1655
+
1656
+ if not return_dict:
1657
+ output = (logits,) + outputs[2:]
1658
+ return ((loss,) + output) if loss is not None else output
1659
+
1660
+ return TokenClassifierOutput(
1661
+ loss=loss,
1662
+ logits=logits,
1663
+ hidden_states=outputs.hidden_states,
1664
+ attentions=outputs.attentions,
1665
+ )