AlexHT_Hung commited on
Commit
dc16c51
·
1 Parent(s): bfc346e

remove causal mask

Browse files
Files changed (1) hide show
  1. modeling_janus.py +1101 -0
modeling_janus.py ADDED
@@ -0,0 +1,1101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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 math
21
+ from typing import List, Optional, Tuple, Union
22
+
23
+ import torch
24
+ import torch.nn.functional as F
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+
28
+ from transformers.activations import ACT2FN
29
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
30
+ from transformers.generation import GenerationMixin
31
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
32
+ from transformers.modeling_flash_attention_utils import _flash_attention_forward
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ QuestionAnsweringModelOutput,
37
+ SequenceClassifierOutputWithPast,
38
+ TokenClassifierOutput,
39
+ )
40
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
41
+ from transformers.modeling_utils import PreTrainedModel
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ add_start_docstrings,
45
+ add_start_docstrings_to_model_forward,
46
+ is_flash_attn_greater_or_equal_2_10,
47
+ logging,
48
+ replace_return_docstrings,
49
+ )
50
+ from transformers import LlamaConfig
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "LlamaConfig"
56
+
57
+
58
+ class LlamaRMSNorm(nn.Module):
59
+ def __init__(self, hidden_size, eps=1e-6):
60
+ """
61
+ LlamaRMSNorm is equivalent to T5LayerNorm
62
+ """
63
+ super().__init__()
64
+ self.weight = nn.Parameter(torch.ones(hidden_size))
65
+ self.variance_epsilon = eps
66
+
67
+ def forward(self, hidden_states):
68
+ input_dtype = hidden_states.dtype
69
+ hidden_states = hidden_states.to(torch.float32)
70
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
71
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
72
+ return self.weight * hidden_states.to(input_dtype)
73
+
74
+ def extra_repr(self):
75
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
76
+
77
+
78
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
79
+
80
+
81
+ class LlamaRotaryEmbedding(nn.Module):
82
+ def __init__(
83
+ self,
84
+ dim=None,
85
+ max_position_embeddings=2048,
86
+ base=10000,
87
+ device=None,
88
+ scaling_factor=1.0,
89
+ rope_type="default",
90
+ config: Optional[LlamaConfig] = None,
91
+ ):
92
+ super().__init__()
93
+ # TODO (joao): remove the `if` below, only used for BC
94
+ self.rope_kwargs = {}
95
+ if config is None:
96
+ logger.warning_once(
97
+ "`LlamaRotaryEmbedding` can now be fully parameterized by passing the model config through the "
98
+ "`config` argument. All other arguments will be removed in v4.46"
99
+ )
100
+ self.rope_kwargs = {
101
+ "rope_type": rope_type,
102
+ "factor": scaling_factor,
103
+ "dim": dim,
104
+ "base": base,
105
+ "max_position_embeddings": max_position_embeddings,
106
+ }
107
+ self.rope_type = rope_type
108
+ self.max_seq_len_cached = max_position_embeddings
109
+ self.original_max_seq_len = max_position_embeddings
110
+ else:
111
+ # BC: "rope_type" was originally "type"
112
+ if config.rope_scaling is not None:
113
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
114
+ else:
115
+ self.rope_type = "default"
116
+ self.max_seq_len_cached = config.max_position_embeddings
117
+ self.original_max_seq_len = config.max_position_embeddings
118
+
119
+ self.config = config
120
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
121
+
122
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, **self.rope_kwargs)
123
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
124
+ self.original_inv_freq = self.inv_freq
125
+
126
+ def _dynamic_frequency_update(self, position_ids, device):
127
+ """
128
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
129
+ 1 - growing beyond the cached sequence length (allow scaling)
130
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
131
+ """
132
+ seq_len = torch.max(position_ids) + 1
133
+ if seq_len > self.max_seq_len_cached: # growth
134
+ inv_freq, self.attention_scaling = self.rope_init_fn(
135
+ self.config, device, seq_len=seq_len, **self.rope_kwargs
136
+ )
137
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
138
+ self.max_seq_len_cached = seq_len
139
+
140
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
141
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
142
+ self.max_seq_len_cached = self.original_max_seq_len
143
+
144
+ @torch.no_grad()
145
+ def forward(self, x, position_ids):
146
+ if "dynamic" in self.rope_type:
147
+ self._dynamic_frequency_update(position_ids, device=x.device)
148
+
149
+ # Core RoPE block
150
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
151
+ position_ids_expanded = position_ids[:, None, :].float()
152
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
153
+ device_type = x.device.type
154
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
155
+ with torch.autocast(device_type=device_type, enabled=False):
156
+ freqs = (inv_freq_expanded.float() @ position_ids_expanded.float()).transpose(1, 2)
157
+ emb = torch.cat((freqs, freqs), dim=-1)
158
+ cos = emb.cos()
159
+ sin = emb.sin()
160
+
161
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
162
+ cos = cos * self.attention_scaling
163
+ sin = sin * self.attention_scaling
164
+
165
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
166
+
167
+
168
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
169
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
170
+
171
+ def __init__(self, *args, **kwargs):
172
+ logger.warning_once(
173
+ "`LlamaLinearScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
174
+ "`LlamaRotaryEmbedding`, which now also does linear scaling (simply pass the model config to __init__)."
175
+ )
176
+ kwargs["rope_type"] = "linear"
177
+ super().__init__(*args, **kwargs)
178
+
179
+
180
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
181
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
182
+
183
+ def __init__(self, *args, **kwargs):
184
+ logger.warning_once(
185
+ "`LlamaDynamicNTKScalingRotaryEmbedding` is deprecated an will be removed in v4.46. Please use "
186
+ "`LlamaRotaryEmbedding`, which now also does dynamic ntk scaling (simply pass the model config to "
187
+ "__init__)."
188
+ )
189
+ kwargs["rope_type"] = "dynamic"
190
+ super().__init__(*args, **kwargs)
191
+
192
+
193
+ def rotate_half(x):
194
+ """Rotates half the hidden dims of the input."""
195
+ x1 = x[..., : x.shape[-1] // 2]
196
+ x2 = x[..., x.shape[-1] // 2 :]
197
+ return torch.cat((-x2, x1), dim=-1)
198
+
199
+
200
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
201
+ """Applies Rotary Position Embedding to the query and key tensors.
202
+
203
+ Args:
204
+ q (`torch.Tensor`): The query tensor.
205
+ k (`torch.Tensor`): The key tensor.
206
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
207
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
208
+ position_ids (`torch.Tensor`, *optional*):
209
+ Deprecated and unused.
210
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
211
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
212
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
213
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
214
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
215
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
216
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
217
+ Returns:
218
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
219
+ """
220
+ cos = cos.unsqueeze(unsqueeze_dim)
221
+ sin = sin.unsqueeze(unsqueeze_dim)
222
+ q_embed = (q * cos) + (rotate_half(q) * sin)
223
+ k_embed = (k * cos) + (rotate_half(k) * sin)
224
+ return q_embed, k_embed
225
+
226
+
227
+ class LlamaMLP(nn.Module):
228
+ def __init__(self, config):
229
+ super().__init__()
230
+ self.config = config
231
+ self.hidden_size = config.hidden_size
232
+ self.intermediate_size = config.intermediate_size
233
+ self.gate_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
234
+ self.up_proj = nn.Linear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
235
+ self.down_proj = nn.Linear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
236
+ self.act_fn = ACT2FN[config.hidden_act]
237
+
238
+ def forward(self, x):
239
+ if self.config.pretraining_tp > 1:
240
+ slice = self.intermediate_size // self.config.pretraining_tp
241
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
242
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
243
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
244
+
245
+ gate_proj = torch.cat(
246
+ [F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1
247
+ )
248
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
249
+
250
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
251
+ down_proj = [
252
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
253
+ ]
254
+ down_proj = sum(down_proj)
255
+ else:
256
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
257
+
258
+ return down_proj
259
+
260
+
261
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
262
+ """
263
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
264
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
265
+ """
266
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
267
+ if n_rep == 1:
268
+ return hidden_states
269
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
270
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
271
+
272
+
273
+ class LlamaAttention(nn.Module):
274
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
275
+
276
+ def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
277
+ super().__init__()
278
+ self.config = config
279
+ self.layer_idx = layer_idx
280
+ if layer_idx is None:
281
+ logger.warning_once(
282
+ f"Instantiating {self.__class__.__name__} without passing a `layer_idx` is not recommended and will "
283
+ "lead to errors during the forward call if caching is used. Please make sure to provide a `layer_idx` "
284
+ "when creating this class."
285
+ )
286
+
287
+ self.attention_dropout = config.attention_dropout
288
+ self.hidden_size = config.hidden_size
289
+ self.num_heads = config.num_attention_heads
290
+ self.head_dim = getattr(config, "head_dim", self.hidden_size // self.num_heads)
291
+ self.num_key_value_heads = config.num_key_value_heads
292
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
293
+ self.max_position_embeddings = config.max_position_embeddings
294
+ self.rope_theta = config.rope_theta
295
+ self.is_causal = False
296
+
297
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
298
+ self.k_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
299
+ self.v_proj = nn.Linear(self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
300
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
301
+
302
+ # TODO (joao): remove in v4.46 (RoPE is computed in the model, not in the decoder layers)
303
+ self.rotary_emb = LlamaRotaryEmbedding(config=self.config)
304
+
305
+ def forward(
306
+ self,
307
+ hidden_states: torch.Tensor,
308
+ attention_mask: Optional[torch.Tensor] = None,
309
+ position_ids: Optional[torch.LongTensor] = None,
310
+ past_key_value: Optional[Cache] = None,
311
+ output_attentions: bool = False,
312
+ use_cache: bool = False,
313
+ cache_position: Optional[torch.LongTensor] = None,
314
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
315
+ **kwargs,
316
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
317
+ bsz, q_len, _ = hidden_states.size()
318
+
319
+ if self.config.pretraining_tp > 1:
320
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
321
+ query_slices = self.q_proj.weight.split(
322
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
323
+ )
324
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
325
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
326
+
327
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
328
+ query_states = torch.cat(query_states, dim=-1)
329
+
330
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
331
+ key_states = torch.cat(key_states, dim=-1)
332
+
333
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
334
+ value_states = torch.cat(value_states, dim=-1)
335
+
336
+ else:
337
+ query_states = self.q_proj(hidden_states)
338
+ key_states = self.k_proj(hidden_states)
339
+ value_states = self.v_proj(hidden_states)
340
+
341
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
342
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
343
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
344
+
345
+ if position_embeddings is None:
346
+ logger.warning_once(
347
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
348
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
349
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
350
+ "removed and `position_embeddings` will be mandatory."
351
+ )
352
+ cos, sin = self.rotary_emb(value_states, position_ids)
353
+ else:
354
+ cos, sin = position_embeddings
355
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
356
+
357
+ if past_key_value is not None:
358
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
359
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
360
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
361
+
362
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
363
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
364
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
365
+
366
+ if attention_mask is not None: # no matter the length, we just slice it
367
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
368
+ attn_weights = attn_weights + causal_mask
369
+
370
+ # upcast attention to fp32
371
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
372
+ attn_weights = nn.functional.dropout(attn_weights, p=self.attention_dropout, training=self.training)
373
+ attn_output = torch.matmul(attn_weights, value_states)
374
+
375
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
376
+ raise ValueError(
377
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
378
+ f" {attn_output.size()}"
379
+ )
380
+
381
+ attn_output = attn_output.transpose(1, 2).contiguous()
382
+
383
+ attn_output = attn_output.reshape(bsz, q_len, -1)
384
+
385
+ if self.config.pretraining_tp > 1:
386
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
387
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
388
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
389
+ else:
390
+ attn_output = self.o_proj(attn_output)
391
+
392
+ if not output_attentions:
393
+ attn_weights = None
394
+
395
+ return attn_output, attn_weights, past_key_value
396
+
397
+
398
+ class LlamaFlashAttention2(LlamaAttention):
399
+ """
400
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
401
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
402
+ flash attention and deal with padding tokens in case the input contains any of them.
403
+ """
404
+
405
+ def __init__(self, *args, **kwargs):
406
+ super().__init__(*args, **kwargs)
407
+
408
+ # TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
409
+ # 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.
410
+ # 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).
411
+ self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
412
+
413
+ def forward(
414
+ self,
415
+ hidden_states: torch.Tensor,
416
+ attention_mask: Optional[torch.LongTensor] = None,
417
+ position_ids: Optional[torch.LongTensor] = None,
418
+ past_key_value: Optional[Cache] = None,
419
+ output_attentions: bool = False,
420
+ use_cache: bool = False,
421
+ cache_position: Optional[torch.LongTensor] = None,
422
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
423
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
424
+ if isinstance(past_key_value, StaticCache):
425
+ raise ValueError(
426
+ "`static` cache implementation is not compatible with `attn_implementation==flash_attention_2` "
427
+ "make sure to use `sdpa` in the mean time, and open an issue at https://github.com/huggingface/transformers"
428
+ )
429
+
430
+ output_attentions = False
431
+
432
+ bsz, q_len, _ = hidden_states.size()
433
+
434
+ query_states = self.q_proj(hidden_states)
435
+ key_states = self.k_proj(hidden_states)
436
+ value_states = self.v_proj(hidden_states)
437
+
438
+ # Flash attention requires the input to have the shape
439
+ # batch_size x seq_length x head_dim x hidden_dim
440
+ # therefore we just need to keep the original shape
441
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
442
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
443
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
444
+
445
+ if position_embeddings is None:
446
+ logger.warning_once(
447
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
448
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
449
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
450
+ "removed and `position_embeddings` will be mandatory."
451
+ )
452
+ cos, sin = self.rotary_emb(value_states, position_ids)
453
+ else:
454
+ cos, sin = position_embeddings
455
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
456
+
457
+ if past_key_value is not None:
458
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
459
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
460
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
461
+
462
+ # 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
463
+ # to be able to avoid many of these transpose/reshape/view.
464
+ query_states = query_states.transpose(1, 2)
465
+ key_states = key_states.transpose(1, 2)
466
+ value_states = value_states.transpose(1, 2)
467
+
468
+ dropout_rate = self.attention_dropout if self.training else 0.0
469
+
470
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
471
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
472
+ # cast them back in the correct dtype just to be sure everything works as expected.
473
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
474
+ # in fp32. (LlamaRMSNorm handles it correctly)
475
+
476
+ input_dtype = query_states.dtype
477
+ if input_dtype == torch.float32:
478
+ if torch.is_autocast_enabled():
479
+ target_dtype = torch.get_autocast_gpu_dtype()
480
+ # Handle the case where the model is quantized
481
+ elif hasattr(self.config, "_pre_quantization_dtype"):
482
+ target_dtype = self.config._pre_quantization_dtype
483
+ else:
484
+ target_dtype = self.q_proj.weight.dtype
485
+
486
+ logger.warning_once(
487
+ f"The input hidden states seems to be silently casted in float32, this might be related to"
488
+ f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
489
+ f" {target_dtype}."
490
+ )
491
+
492
+ query_states = query_states.to(target_dtype)
493
+ key_states = key_states.to(target_dtype)
494
+ value_states = value_states.to(target_dtype)
495
+
496
+ attn_output = _flash_attention_forward(
497
+ query_states,
498
+ key_states,
499
+ value_states,
500
+ attention_mask,
501
+ q_len,
502
+ position_ids=position_ids,
503
+ dropout=dropout_rate,
504
+ sliding_window=getattr(self, "sliding_window", None),
505
+ use_top_left_mask=self._flash_attn_uses_top_left_mask,
506
+ is_causal=self.is_causal,
507
+ )
508
+
509
+ attn_output = attn_output.reshape(bsz, q_len, -1).contiguous()
510
+ attn_output = self.o_proj(attn_output)
511
+
512
+ if not output_attentions:
513
+ attn_weights = None
514
+
515
+ return attn_output, attn_weights, past_key_value
516
+
517
+
518
+ class LlamaSdpaAttention(LlamaAttention):
519
+ """
520
+ Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
521
+ `LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
522
+ SDPA API.
523
+ """
524
+
525
+ # Adapted from LlamaAttention.forward
526
+ def forward(
527
+ self,
528
+ hidden_states: torch.Tensor,
529
+ attention_mask: Optional[torch.Tensor] = None,
530
+ position_ids: Optional[torch.LongTensor] = None,
531
+ past_key_value: Optional[Cache] = None,
532
+ output_attentions: bool = False,
533
+ use_cache: bool = False,
534
+ cache_position: Optional[torch.LongTensor] = None,
535
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
536
+ **kwargs,
537
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
538
+ if output_attentions:
539
+ # TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
540
+ logger.warning_once(
541
+ "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, "
542
+ '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.'
543
+ )
544
+ return super().forward(
545
+ hidden_states=hidden_states,
546
+ attention_mask=attention_mask,
547
+ position_ids=position_ids,
548
+ past_key_value=past_key_value,
549
+ output_attentions=output_attentions,
550
+ use_cache=use_cache,
551
+ cache_position=cache_position,
552
+ position_embeddings=position_embeddings,
553
+ )
554
+
555
+ bsz, q_len, _ = hidden_states.size()
556
+
557
+ query_states = self.q_proj(hidden_states)
558
+ key_states = self.k_proj(hidden_states)
559
+ value_states = self.v_proj(hidden_states)
560
+
561
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
562
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
563
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
564
+
565
+ if position_embeddings is None:
566
+ logger.warning_once(
567
+ "The attention layers in this model are transitioning from computing the RoPE embeddings internally "
568
+ "through `position_ids` (2D tensor with the indexes of the tokens), to using externally computed "
569
+ "`position_embeddings` (Tuple of tensors, containing cos and sin). In v4.46 `position_ids` will be "
570
+ "removed and `position_embeddings` will be mandatory."
571
+ )
572
+ cos, sin = self.rotary_emb(value_states, position_ids)
573
+ else:
574
+ cos, sin = position_embeddings
575
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
576
+
577
+ if past_key_value is not None:
578
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
579
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
580
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
581
+
582
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
583
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
584
+
585
+ causal_mask = attention_mask
586
+ if attention_mask is not None:
587
+ causal_mask = causal_mask[:, :, :, : key_states.shape[-2]]
588
+
589
+ # SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
590
+ # Reference: https://github.com/pytorch/pytorch/issues/112577.
591
+ if query_states.device.type == "cuda" and causal_mask is not None:
592
+ query_states = query_states.contiguous()
593
+ key_states = key_states.contiguous()
594
+ value_states = value_states.contiguous()
595
+
596
+ # We dispatch to SDPA's Flash Attention or Efficient kernels via this `is_causal` if statement instead of an inline conditional assignment
597
+ # in SDPA to support both torch.compile's dynamic shapes and full graph options. An inline conditional prevents dynamic shapes from compiling.
598
+ #is_causal = True if causal_mask is None and q_len > 1 else False
599
+ is_causal = False
600
+
601
+ attn_output = torch.nn.functional.scaled_dot_product_attention(
602
+ query_states,
603
+ key_states,
604
+ value_states,
605
+ attn_mask=causal_mask,
606
+ dropout_p=self.attention_dropout if self.training else 0.0,
607
+ is_causal=is_causal,
608
+ )
609
+
610
+ attn_output = attn_output.transpose(1, 2).contiguous()
611
+ attn_output = attn_output.view(bsz, q_len, -1)
612
+
613
+ attn_output = self.o_proj(attn_output)
614
+
615
+ return attn_output, None, past_key_value
616
+
617
+
618
+ LLAMA_ATTENTION_CLASSES = {
619
+ "eager": LlamaAttention,
620
+ "flash_attention_2": LlamaFlashAttention2,
621
+ "sdpa": LlamaSdpaAttention,
622
+ }
623
+
624
+
625
+ class LlamaDecoderLayer(nn.Module):
626
+ def __init__(self, config: LlamaConfig, layer_idx: int):
627
+ super().__init__()
628
+ self.hidden_size = config.hidden_size
629
+
630
+ self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
631
+
632
+ self.mlp = LlamaMLP(config)
633
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
634
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
635
+
636
+ def forward(
637
+ self,
638
+ hidden_states: torch.Tensor,
639
+ attention_mask: Optional[torch.Tensor] = None,
640
+ position_ids: Optional[torch.LongTensor] = None,
641
+ past_key_value: Optional[Cache] = None,
642
+ output_attentions: Optional[bool] = False,
643
+ use_cache: Optional[bool] = False,
644
+ cache_position: Optional[torch.LongTensor] = None,
645
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # will become mandatory in v4.46
646
+ **kwargs,
647
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
648
+ """
649
+ Args:
650
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
651
+ attention_mask (`torch.FloatTensor`, *optional*):
652
+ attention mask of size `(batch_size, sequence_length)` if flash attention is used or `(batch_size, 1,
653
+ query_sequence_length, key_sequence_length)` if default attention is used.
654
+ output_attentions (`bool`, *optional*):
655
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
656
+ returned tensors for more detail.
657
+ use_cache (`bool`, *optional*):
658
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
659
+ (see `past_key_values`).
660
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
661
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
662
+ Indices depicting the position of the input sequence tokens in the sequence
663
+ position_embeddings (`Tuple[torch.FloatTensor, torch.FloatTensor]`, *optional*):
664
+ Tuple containing the cosine and sine positional embeddings of shape `(batch_size, seq_len, head_dim)`,
665
+ with `head_dim` being the embedding dimension of each attention head.
666
+ kwargs (`dict`, *optional*):
667
+ Arbitrary kwargs to be ignored, used for FSDP and other methods that injects code
668
+ into the model
669
+ """
670
+ residual = hidden_states
671
+
672
+ hidden_states = self.input_layernorm(hidden_states)
673
+
674
+ # Self Attention
675
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
676
+ hidden_states=hidden_states,
677
+ attention_mask=attention_mask,
678
+ position_ids=position_ids,
679
+ past_key_value=past_key_value,
680
+ output_attentions=output_attentions,
681
+ use_cache=use_cache,
682
+ cache_position=cache_position,
683
+ position_embeddings=position_embeddings,
684
+ **kwargs,
685
+ )
686
+ hidden_states = residual + hidden_states
687
+
688
+ # Fully Connected
689
+ residual = hidden_states
690
+ hidden_states = self.post_attention_layernorm(hidden_states)
691
+ hidden_states = self.mlp(hidden_states)
692
+ hidden_states = residual + hidden_states
693
+
694
+ outputs = (hidden_states,)
695
+
696
+ if output_attentions:
697
+ outputs += (self_attn_weights,)
698
+
699
+ if use_cache:
700
+ outputs += (present_key_value,)
701
+
702
+ return outputs
703
+
704
+
705
+ LLAMA_START_DOCSTRING = r"""
706
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
707
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
708
+ etc.)
709
+
710
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
711
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
712
+ and behavior.
713
+
714
+ Parameters:
715
+ config ([`LlamaConfig`]):
716
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
717
+ load the weights associated with the model, only the configuration. Check out the
718
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
719
+ """
720
+
721
+
722
+ @add_start_docstrings(
723
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
724
+ LLAMA_START_DOCSTRING,
725
+ )
726
+ class LlamaPreTrainedModel(PreTrainedModel):
727
+ config_class = LlamaConfig
728
+ base_model_prefix = "model"
729
+ supports_gradient_checkpointing = True
730
+ _no_split_modules = ["LlamaDecoderLayer"]
731
+ _skip_keys_device_placement = ["past_key_values"]
732
+ _supports_flash_attn_2 = True
733
+ _supports_sdpa = True
734
+ _supports_cache_class = True
735
+ _supports_quantized_cache = True
736
+ _supports_static_cache = True
737
+
738
+ def _init_weights(self, module):
739
+ std = self.config.initializer_range
740
+ if isinstance(module, nn.Linear):
741
+ module.weight.data.normal_(mean=0.0, std=std)
742
+ if module.bias is not None:
743
+ module.bias.data.zero_()
744
+ elif isinstance(module, nn.Embedding):
745
+ module.weight.data.normal_(mean=0.0, std=std)
746
+ if module.padding_idx is not None:
747
+ module.weight.data[module.padding_idx].zero_()
748
+
749
+
750
+ LLAMA_INPUTS_DOCSTRING = r"""
751
+ Args:
752
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
753
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
754
+ it.
755
+
756
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
757
+ [`PreTrainedTokenizer.__call__`] for details.
758
+
759
+ [What are input IDs?](../glossary#input-ids)
760
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
761
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
762
+
763
+ - 1 for tokens that are **not masked**,
764
+ - 0 for tokens that are **masked**.
765
+
766
+ [What are attention masks?](../glossary#attention-mask)
767
+
768
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
769
+ [`PreTrainedTokenizer.__call__`] for details.
770
+
771
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
772
+ `past_key_values`).
773
+
774
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
775
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
776
+ information on the default strategy.
777
+
778
+ - 1 indicates the head is **not masked**,
779
+ - 0 indicates the head is **masked**.
780
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
781
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
782
+ config.n_positions - 1]`.
783
+
784
+ [What are position IDs?](../glossary#position-ids)
785
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
786
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
787
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
788
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
789
+
790
+ Two formats are allowed:
791
+ - a [`~cache_utils.Cache`] instance, see our
792
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
793
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
794
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
795
+ cache format.
796
+
797
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
798
+ legacy cache format will be returned.
799
+
800
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
801
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
802
+ of shape `(batch_size, sequence_length)`.
803
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
804
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
805
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
806
+ model's internal embedding lookup matrix.
807
+ use_cache (`bool`, *optional*):
808
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
809
+ `past_key_values`).
810
+ output_attentions (`bool`, *optional*):
811
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
812
+ tensors for more detail.
813
+ output_hidden_states (`bool`, *optional*):
814
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
815
+ more detail.
816
+ return_dict (`bool`, *optional*):
817
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
818
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
819
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
820
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
821
+ the complete sequence length.
822
+ """
823
+
824
+
825
+ @add_start_docstrings(
826
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
827
+ LLAMA_START_DOCSTRING,
828
+ )
829
+ class JanusModel(LlamaPreTrainedModel):
830
+ """
831
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
832
+
833
+ Args:
834
+ config: LlamaConfig
835
+ """
836
+
837
+ def __init__(self, config: LlamaConfig):
838
+ super().__init__(config)
839
+ self.padding_idx = config.pad_token_id
840
+ self.vocab_size = config.vocab_size
841
+
842
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
843
+ self.layers = nn.ModuleList(
844
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
845
+ )
846
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
847
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
848
+ self.gradient_checkpointing = False
849
+
850
+ # Initialize weights and apply final processing
851
+ self.post_init()
852
+
853
+ def get_input_embeddings(self):
854
+ return self.embed_tokens
855
+
856
+ def set_input_embeddings(self, value):
857
+ self.embed_tokens = value
858
+
859
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
860
+ def forward(
861
+ self,
862
+ input_ids: torch.LongTensor = None,
863
+ attention_mask: Optional[torch.Tensor] = None,
864
+ position_ids: Optional[torch.LongTensor] = None,
865
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
866
+ inputs_embeds: Optional[torch.FloatTensor] = None,
867
+ use_cache: Optional[bool] = None,
868
+ output_attentions: Optional[bool] = None,
869
+ output_hidden_states: Optional[bool] = None,
870
+ return_dict: Optional[bool] = None,
871
+ cache_position: Optional[torch.LongTensor] = None,
872
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
873
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
874
+ output_hidden_states = (
875
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
876
+ )
877
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
878
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
879
+
880
+ if (input_ids is None) ^ (inputs_embeds is not None):
881
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
882
+
883
+ if self.gradient_checkpointing and self.training and use_cache:
884
+ logger.warning_once(
885
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
886
+ )
887
+ use_cache = False
888
+
889
+ if inputs_embeds is None:
890
+ inputs_embeds = self.embed_tokens(input_ids)
891
+
892
+ # kept for BC (non `Cache` `past_key_values` inputs)
893
+ return_legacy_cache = False
894
+ if use_cache and not isinstance(past_key_values, Cache):
895
+ return_legacy_cache = True
896
+ if past_key_values is None:
897
+ past_key_values = DynamicCache()
898
+ else:
899
+ past_key_values = DynamicCache.from_legacy_cache(past_key_values)
900
+ logger.warning_once(
901
+ "We detected that you are passing `past_key_values` as a tuple of tuples. This is deprecated and "
902
+ "will be removed in v4.47. Please convert your cache or use an appropriate `Cache` class "
903
+ "(https://huggingface.co/docs/transformers/kv_cache#legacy-cache-format)"
904
+ )
905
+
906
+ if cache_position is None:
907
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
908
+ cache_position = torch.arange(
909
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
910
+ )
911
+ if position_ids is None:
912
+ position_ids = cache_position.unsqueeze(0)
913
+
914
+ causal_mask = self._update_causal_mask(
915
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
916
+ )
917
+ hidden_states = inputs_embeds
918
+
919
+ # create position embeddings to be shared across the decoder layers
920
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
921
+
922
+ # decoder layers
923
+ all_hidden_states = () if output_hidden_states else None
924
+ all_self_attns = () if output_attentions else None
925
+ next_decoder_cache = None
926
+
927
+ for decoder_layer in self.layers:
928
+ if output_hidden_states:
929
+ all_hidden_states += (hidden_states,)
930
+
931
+ if self.gradient_checkpointing and self.training:
932
+ layer_outputs = self._gradient_checkpointing_func(
933
+ decoder_layer.__call__,
934
+ hidden_states,
935
+ causal_mask,
936
+ position_ids,
937
+ past_key_values,
938
+ output_attentions,
939
+ use_cache,
940
+ cache_position,
941
+ position_embeddings,
942
+ )
943
+ else:
944
+ layer_outputs = decoder_layer(
945
+ hidden_states,
946
+ attention_mask=causal_mask,
947
+ position_ids=position_ids,
948
+ past_key_value=past_key_values,
949
+ output_attentions=output_attentions,
950
+ use_cache=use_cache,
951
+ cache_position=cache_position,
952
+ position_embeddings=position_embeddings,
953
+ )
954
+
955
+ hidden_states = layer_outputs[0]
956
+
957
+ if use_cache:
958
+ next_decoder_cache = layer_outputs[2 if output_attentions else 1]
959
+
960
+ if output_attentions:
961
+ all_self_attns += (layer_outputs[1],)
962
+
963
+ hidden_states = self.norm(hidden_states)
964
+
965
+ # add hidden states from the last decoder layer
966
+ if output_hidden_states:
967
+ all_hidden_states += (hidden_states,)
968
+
969
+ next_cache = next_decoder_cache if use_cache else None
970
+ if return_legacy_cache:
971
+ next_cache = next_cache.to_legacy_cache()
972
+
973
+ if not return_dict:
974
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
975
+ return BaseModelOutputWithPast(
976
+ last_hidden_state=hidden_states,
977
+ past_key_values=next_cache,
978
+ hidden_states=all_hidden_states,
979
+ attentions=all_self_attns,
980
+ )
981
+
982
+ def _update_causal_mask(
983
+ self,
984
+ attention_mask: torch.Tensor,
985
+ input_tensor: torch.Tensor,
986
+ cache_position: torch.Tensor,
987
+ past_key_values: Cache,
988
+ output_attentions: bool,
989
+ ):
990
+ if self.config._attn_implementation == "flash_attention_2":
991
+ if attention_mask is not None and 0.0 in attention_mask:
992
+ return attention_mask
993
+ return None
994
+
995
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
996
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
997
+ # to infer the attention mask.
998
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
999
+ using_static_cache = isinstance(past_key_values, StaticCache)
1000
+
1001
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
1002
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
1003
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
1004
+ attention_mask,
1005
+ inputs_embeds=input_tensor,
1006
+ past_key_values_length=past_seen_tokens,
1007
+ is_training=self.training,
1008
+ ):
1009
+ return None
1010
+
1011
+ dtype, device = input_tensor.dtype, input_tensor.device
1012
+ sequence_length = input_tensor.shape[1]
1013
+ if using_static_cache:
1014
+ target_length = past_key_values.get_max_cache_shape()
1015
+ else:
1016
+ target_length = (
1017
+ attention_mask.shape[-1]
1018
+ if isinstance(attention_mask, torch.Tensor)
1019
+ else past_seen_tokens + sequence_length + 1
1020
+ )
1021
+
1022
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
1023
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
1024
+ attention_mask,
1025
+ sequence_length=sequence_length,
1026
+ target_length=target_length,
1027
+ dtype=dtype,
1028
+ device=device,
1029
+ cache_position=cache_position,
1030
+ batch_size=input_tensor.shape[0],
1031
+ )
1032
+
1033
+ if (
1034
+ self.config._attn_implementation == "sdpa"
1035
+ and attention_mask is not None
1036
+ and attention_mask.device.type == "cuda"
1037
+ and not output_attentions
1038
+ ):
1039
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
1040
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
1041
+ # Details: https://github.com/pytorch/pytorch/issues/110213
1042
+ min_dtype = torch.finfo(dtype).min
1043
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
1044
+
1045
+ return causal_mask
1046
+
1047
+ @staticmethod
1048
+ def _prepare_4d_causal_attention_mask_with_cache_position(
1049
+ attention_mask: torch.Tensor,
1050
+ sequence_length: int,
1051
+ target_length: int,
1052
+ dtype: torch.dtype,
1053
+ device: torch.device,
1054
+ cache_position: torch.Tensor,
1055
+ batch_size: int,
1056
+ **kwargs,
1057
+ ):
1058
+ """
1059
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
1060
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
1061
+
1062
+ Args:
1063
+ attention_mask (`torch.Tensor`):
1064
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
1065
+ `(batch_size, 1, query_length, key_value_length)`.
1066
+ sequence_length (`int`):
1067
+ The sequence length being processed.
1068
+ target_length (`int`):
1069
+ The target length: when generating with static cache, the mask should be as long as the static cache,
1070
+ to account for the 0 padding, the part of the cache that is not filled yet.
1071
+ dtype (`torch.dtype`):
1072
+ The dtype to use for the 4D attention mask.
1073
+ device (`torch.device`):
1074
+ The device to plcae the 4D attention mask on.
1075
+ cache_position (`torch.Tensor`):
1076
+ Indices depicting the position of the input sequence tokens in the sequence.
1077
+ batch_size (`torch.Tensor`):
1078
+ Batch size.
1079
+ """
1080
+ if attention_mask is not None and attention_mask.dim() == 4:
1081
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
1082
+ causal_mask = attention_mask
1083
+ else:
1084
+ min_dtype = torch.finfo(dtype).min
1085
+ causal_mask = torch.full(
1086
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
1087
+ )
1088
+ if sequence_length != 1:
1089
+ causal_mask = torch.triu(causal_mask, diagonal=1)
1090
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
1091
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
1092
+ if attention_mask is not None:
1093
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
1094
+ mask_length = attention_mask.shape[-1]
1095
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :]
1096
+ padding_mask = padding_mask == 0
1097
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
1098
+ padding_mask, min_dtype
1099
+ )
1100
+
1101
+ return causal_mask