Wendy commited on
Commit
bb4b24b
·
verified ·
1 Parent(s): 2fffd02

Upload supp_modeling_llama.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. supp_modeling_llama.py +1440 -0
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
+ )