xrxing commited on
Commit
a1d8010
·
verified ·
1 Parent(s): a35ec26

Upload folder using huggingface_hub

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