Wendy commited on
Commit
8605824
·
verified ·
1 Parent(s): 01162d3

Upload 4 files

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