Chat-UniVi commited on
Commit
94af976
1 Parent(s): 4a092e7

Upload 7 files

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