semran1 commited on
Commit
8798b9e
·
verified ·
1 Parent(s): 625f0e5

Upload folder using huggingface_hub

Browse files
Files changed (5) hide show
  1. config.json +32 -0
  2. generation_config.json +7 -0
  3. model.safetensors +3 -0
  4. modeling_qllama.py +1167 -0
  5. qlinear.py +48 -0
config.json ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "_name_or_path": "semran1/test3-quantized",
3
+ "architectures": [
4
+ "LlamaForCausalLM"
5
+ ],
6
+ "attention_bias": false,
7
+ "attention_dropout": 0.0,
8
+ "bos_token_id": 1,
9
+ "eos_token_id": 2,
10
+ "head_dim": 96,
11
+ "hidden_act": "silu",
12
+ "hidden_size": 1536,
13
+ "initializer_range": 0.02,
14
+ "intermediate_size": 4096,
15
+ "max_position_embeddings": 8192,
16
+ "mlp_bias": false,
17
+ "model_type": "llama",
18
+ "num_attention_heads": 16,
19
+ "num_hidden_layers": 16,
20
+ "num_key_value_heads": 8,
21
+ "pad_token_id": 0,
22
+ "pretraining_tp": 1,
23
+ "rms_norm_eps": 1e-05,
24
+ "rope_scaling": null,
25
+ "rope_theta": 100000,
26
+ "sliding_window": null,
27
+ "tie_word_embeddings": false,
28
+ "torch_dtype": "bfloat16",
29
+ "transformers_version": "4.48.3",
30
+ "use_cache": true,
31
+ "vocab_size": 32000
32
+ }
generation_config.json ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ {
2
+ "_from_model_config": true,
3
+ "bos_token_id": 1,
4
+ "eos_token_id": 2,
5
+ "pad_token_id": 0,
6
+ "transformers_version": "4.48.3"
7
+ }
model.safetensors ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:d4a52d005c4293b5610b03cd351eaa0b319f8a98239f2bbc0adf34f3eb0ec3d3
3
+ size 1027669176
modeling_qllama.py ADDED
@@ -0,0 +1,1167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import Callable, List, Optional, Tuple, Union
21
+
22
+ import torch
23
+ import torch.utils.checkpoint
24
+ from torch import nn
25
+ from qlinear import QLinear
26
+
27
+ from transformers.activations import ACT2FN
28
+ from transformers.cache_utils import Cache, DynamicCache, StaticCache
29
+ from transformers.generation import GenerationMixin
30
+ from transformers.modeling_attn_mask_utils import AttentionMaskConverter
31
+ from transformers.modeling_flash_attention_utils import FlashAttentionKwargs
32
+ from transformers.modeling_outputs import (
33
+ BaseModelOutputWithPast,
34
+ CausalLMOutputWithPast,
35
+ QuestionAnsweringModelOutput,
36
+ SequenceClassifierOutputWithPast,
37
+ TokenClassifierOutput,
38
+ )
39
+ from transformers.modeling_rope_utils import ROPE_INIT_FUNCTIONS
40
+ from transformers.modeling_utils import ALL_ATTENTION_FUNCTIONS, PreTrainedModel
41
+ from transformers.processing_utils import Unpack
42
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
43
+ from transformers.utils import (
44
+ LossKwargs,
45
+ add_code_sample_docstrings,
46
+ add_start_docstrings,
47
+ add_start_docstrings_to_model_forward,
48
+ logging,
49
+ replace_return_docstrings,
50
+ )
51
+ from transformers.utils.deprecation import deprecate_kwarg
52
+ from transformers.models.llama.configuration_llama import LlamaConfig
53
+
54
+
55
+ logger = logging.get_logger(__name__)
56
+
57
+ _CHECKPOINT_FOR_DOC = "meta-llama/Llama-2-7b-hf"
58
+ _CONFIG_FOR_DOC = "LlamaConfig"
59
+
60
+
61
+ class LlamaRMSNorm(nn.Module):
62
+ def __init__(self, hidden_size, eps=1e-6):
63
+ """
64
+ LlamaRMSNorm is equivalent to T5LayerNorm
65
+ """
66
+ super().__init__()
67
+ self.weight = nn.Parameter(torch.ones(hidden_size))
68
+ self.variance_epsilon = eps
69
+
70
+ def forward(self, hidden_states):
71
+ input_dtype = hidden_states.dtype
72
+ hidden_states = hidden_states.to(torch.float32)
73
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
74
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
75
+ return self.weight * hidden_states.to(input_dtype)
76
+
77
+ def extra_repr(self):
78
+ return f"{tuple(self.weight.shape)}, eps={self.variance_epsilon}"
79
+
80
+
81
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
82
+
83
+
84
+ class LlamaRotaryEmbedding(nn.Module):
85
+ def __init__(self, config: LlamaConfig, device=None):
86
+ super().__init__()
87
+ # BC: "rope_type" was originally "type"
88
+ if hasattr(config, "rope_scaling") and config.rope_scaling is not None:
89
+ self.rope_type = config.rope_scaling.get("rope_type", config.rope_scaling.get("type"))
90
+ else:
91
+ self.rope_type = "default"
92
+ self.max_seq_len_cached = config.max_position_embeddings
93
+ self.original_max_seq_len = config.max_position_embeddings
94
+
95
+ self.config = config
96
+ self.rope_init_fn = ROPE_INIT_FUNCTIONS[self.rope_type]
97
+
98
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device)
99
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
100
+ self.original_inv_freq = self.inv_freq
101
+
102
+ def _dynamic_frequency_update(self, position_ids, device):
103
+ """
104
+ dynamic RoPE layers should recompute `inv_freq` in the following situations:
105
+ 1 - growing beyond the cached sequence length (allow scaling)
106
+ 2 - the current sequence length is in the original scale (avoid losing precision with small sequences)
107
+ """
108
+ seq_len = torch.max(position_ids) + 1
109
+ if seq_len > self.max_seq_len_cached: # growth
110
+ inv_freq, self.attention_scaling = self.rope_init_fn(self.config, device, seq_len=seq_len)
111
+ self.register_buffer("inv_freq", inv_freq, persistent=False) # TODO joao: may break with compilation
112
+ self.max_seq_len_cached = seq_len
113
+
114
+ if seq_len < self.original_max_seq_len and self.max_seq_len_cached > self.original_max_seq_len: # reset
115
+ # This .to() is needed if the model has been moved to a device after being initialized (because
116
+ # the buffer is automatically moved, but not the original copy)
117
+ self.original_inv_freq = self.original_inv_freq.to(device)
118
+ self.register_buffer("inv_freq", self.original_inv_freq, persistent=False)
119
+ self.max_seq_len_cached = self.original_max_seq_len
120
+
121
+ @torch.no_grad()
122
+ def forward(self, x, position_ids):
123
+ if "dynamic" in self.rope_type:
124
+ self._dynamic_frequency_update(position_ids, device=x.device)
125
+
126
+ # Core RoPE block
127
+ inv_freq_expanded = self.inv_freq[None, :, None].float().expand(position_ids.shape[0], -1, 1)
128
+ position_ids_expanded = position_ids[:, None, :].float()
129
+ # Force float32 (see https://github.com/huggingface/transformers/pull/29285)
130
+ device_type = x.device.type
131
+ device_type = device_type if isinstance(device_type, str) and device_type != "mps" else "cpu"
132
+ with torch.autocast(device_type=device_type, enabled=False):
133
+ freqs = (inv_freq_expanded.float().to(x.device) @ position_ids_expanded.float()).transpose(1, 2)
134
+ emb = torch.cat((freqs, freqs), dim=-1)
135
+ cos = emb.cos()
136
+ sin = emb.sin()
137
+
138
+ # Advanced RoPE types (e.g. yarn) apply a post-processing scaling factor, equivalent to scaling attention
139
+ cos = cos * self.attention_scaling
140
+ sin = sin * self.attention_scaling
141
+
142
+ return cos.to(dtype=x.dtype), sin.to(dtype=x.dtype)
143
+
144
+
145
+ def rotate_half(x):
146
+ """Rotates half the hidden dims of the input."""
147
+ x1 = x[..., : x.shape[-1] // 2]
148
+ x2 = x[..., x.shape[-1] // 2 :]
149
+ return torch.cat((-x2, x1), dim=-1)
150
+
151
+
152
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids=None, unsqueeze_dim=1):
153
+ """Applies Rotary Position Embedding to the query and key tensors.
154
+
155
+ Args:
156
+ q (`torch.Tensor`): The query tensor.
157
+ k (`torch.Tensor`): The key tensor.
158
+ cos (`torch.Tensor`): The cosine part of the rotary embedding.
159
+ sin (`torch.Tensor`): The sine part of the rotary embedding.
160
+ position_ids (`torch.Tensor`, *optional*):
161
+ Deprecated and unused.
162
+ unsqueeze_dim (`int`, *optional*, defaults to 1):
163
+ The 'unsqueeze_dim' argument specifies the dimension along which to unsqueeze cos[position_ids] and
164
+ sin[position_ids] so that they can be properly broadcasted to the dimensions of q and k. For example, note
165
+ that cos[position_ids] and sin[position_ids] have the shape [batch_size, seq_len, head_dim]. Then, if q and
166
+ k have the shape [batch_size, heads, seq_len, head_dim], then setting unsqueeze_dim=1 makes
167
+ cos[position_ids] and sin[position_ids] broadcastable to the shapes of q and k. Similarly, if q and k have
168
+ the shape [batch_size, seq_len, heads, head_dim], then set unsqueeze_dim=2.
169
+ Returns:
170
+ `tuple(torch.Tensor)` comprising of the query and key tensors rotated using the Rotary Position Embedding.
171
+ """
172
+ cos = cos.unsqueeze(unsqueeze_dim)
173
+ sin = sin.unsqueeze(unsqueeze_dim)
174
+ q_embed = (q * cos) + (rotate_half(q) * sin)
175
+ k_embed = (k * cos) + (rotate_half(k) * sin)
176
+ return q_embed, k_embed
177
+
178
+
179
+ class LlamaMLP(nn.Module):
180
+ def __init__(self, config):
181
+ super().__init__()
182
+ self.config = config
183
+ self.hidden_size = config.hidden_size
184
+ self.intermediate_size = config.intermediate_size
185
+ self.gate_proj = QLinear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
186
+ self.up_proj = QLinear(self.hidden_size, self.intermediate_size, bias=config.mlp_bias)
187
+ self.down_proj = QLinear(self.intermediate_size, self.hidden_size, bias=config.mlp_bias)
188
+ self.act_fn = ACT2FN[config.hidden_act]
189
+
190
+ def forward(self, x):
191
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
192
+ return down_proj
193
+
194
+
195
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
196
+ """
197
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
198
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
199
+ """
200
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
201
+ if n_rep == 1:
202
+ return hidden_states
203
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
204
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
205
+
206
+
207
+ def eager_attention_forward(
208
+ module: nn.Module,
209
+ query: torch.Tensor,
210
+ key: torch.Tensor,
211
+ value: torch.Tensor,
212
+ attention_mask: Optional[torch.Tensor],
213
+ scaling: float,
214
+ dropout: float = 0.0,
215
+ **kwargs,
216
+ ):
217
+ key_states = repeat_kv(key, module.num_key_value_groups)
218
+ value_states = repeat_kv(value, module.num_key_value_groups)
219
+
220
+ attn_weights = torch.matmul(query, key_states.transpose(2, 3)) * scaling
221
+ if attention_mask is not None:
222
+ causal_mask = attention_mask[:, :, :, : key_states.shape[-2]]
223
+ attn_weights = attn_weights + causal_mask
224
+
225
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query.dtype)
226
+ attn_weights = nn.functional.dropout(attn_weights, p=dropout, training=module.training)
227
+ attn_output = torch.matmul(attn_weights, value_states)
228
+ attn_output = attn_output.transpose(1, 2).contiguous()
229
+
230
+ return attn_output, attn_weights
231
+
232
+
233
+ class LlamaAttention(nn.Module):
234
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
235
+
236
+ def __init__(self, config: LlamaConfig, layer_idx: int):
237
+ super().__init__()
238
+ self.config = config
239
+ self.layer_idx = layer_idx
240
+ self.head_dim = getattr(config, "head_dim", config.hidden_size // config.num_attention_heads)
241
+ self.num_key_value_groups = config.num_attention_heads // config.num_key_value_heads
242
+ self.scaling = self.head_dim**-0.5
243
+ self.attention_dropout = config.attention_dropout
244
+ self.is_causal = True
245
+
246
+ self.q_proj = QLinear(
247
+ config.hidden_size, config.num_attention_heads * self.head_dim, bias=config.attention_bias
248
+ )
249
+ self.k_proj = QLinear(
250
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
251
+ )
252
+ self.v_proj = QLinear(
253
+ config.hidden_size, config.num_key_value_heads * self.head_dim, bias=config.attention_bias
254
+ )
255
+ self.o_proj = QLinear(
256
+ config.num_attention_heads * self.head_dim, config.hidden_size, bias=config.attention_bias
257
+ )
258
+
259
+ def forward(
260
+ self,
261
+ hidden_states: torch.Tensor,
262
+ position_embeddings: Tuple[torch.Tensor, torch.Tensor],
263
+ attention_mask: Optional[torch.Tensor],
264
+ past_key_value: Optional[Cache] = None,
265
+ cache_position: Optional[torch.LongTensor] = None,
266
+ **kwargs: Unpack[FlashAttentionKwargs],
267
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
268
+ input_shape = hidden_states.shape[:-1]
269
+ hidden_shape = (*input_shape, -1, self.head_dim)
270
+
271
+ query_states = self.q_proj(hidden_states).view(hidden_shape).transpose(1, 2)
272
+ key_states = self.k_proj(hidden_states).view(hidden_shape).transpose(1, 2)
273
+ value_states = self.v_proj(hidden_states).view(hidden_shape).transpose(1, 2)
274
+
275
+ cos, sin = position_embeddings
276
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin)
277
+
278
+ if past_key_value is not None:
279
+ # sin and cos are specific to RoPE models; cache_position needed for the static cache
280
+ cache_kwargs = {"sin": sin, "cos": cos, "cache_position": cache_position}
281
+ key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
282
+
283
+ attention_interface: Callable = eager_attention_forward
284
+ if self.config._attn_implementation != "eager":
285
+ if self.config._attn_implementation == "sdpa" and kwargs.get("output_attentions", False):
286
+ logger.warning_once(
287
+ "`torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to "
288
+ 'eager attention. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
289
+ )
290
+ else:
291
+ attention_interface = ALL_ATTENTION_FUNCTIONS[self.config._attn_implementation]
292
+
293
+ attn_output, attn_weights = attention_interface(
294
+ self,
295
+ query_states,
296
+ key_states,
297
+ value_states,
298
+ attention_mask,
299
+ dropout=0.0 if not self.training else self.attention_dropout,
300
+ scaling=self.scaling,
301
+ **kwargs,
302
+ )
303
+
304
+ attn_output = attn_output.reshape(*input_shape, -1).contiguous()
305
+ attn_output = self.o_proj(attn_output)
306
+ return attn_output, attn_weights
307
+
308
+
309
+ class LlamaDecoderLayer(nn.Module):
310
+ def __init__(self, config: LlamaConfig, layer_idx: int):
311
+ super().__init__()
312
+ self.hidden_size = config.hidden_size
313
+
314
+ self.self_attn = LlamaAttention(config=config, layer_idx=layer_idx)
315
+
316
+ self.mlp = LlamaMLP(config)
317
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
318
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
319
+
320
+ def forward(
321
+ self,
322
+ hidden_states: torch.Tensor,
323
+ attention_mask: Optional[torch.Tensor] = None,
324
+ position_ids: Optional[torch.LongTensor] = None,
325
+ past_key_value: Optional[Cache] = None,
326
+ output_attentions: Optional[bool] = False,
327
+ use_cache: Optional[bool] = False,
328
+ cache_position: Optional[torch.LongTensor] = None,
329
+ position_embeddings: Optional[Tuple[torch.Tensor, torch.Tensor]] = None, # necessary, but kept here for BC
330
+ **kwargs: Unpack[FlashAttentionKwargs],
331
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
332
+ residual = hidden_states
333
+
334
+ hidden_states = self.input_layernorm(hidden_states)
335
+
336
+ # Self Attention
337
+ hidden_states, self_attn_weights = self.self_attn(
338
+ hidden_states=hidden_states,
339
+ attention_mask=attention_mask,
340
+ position_ids=position_ids,
341
+ past_key_value=past_key_value,
342
+ output_attentions=output_attentions,
343
+ use_cache=use_cache,
344
+ cache_position=cache_position,
345
+ position_embeddings=position_embeddings,
346
+ **kwargs,
347
+ )
348
+ hidden_states = residual + hidden_states
349
+
350
+ # Fully Connected
351
+ residual = hidden_states
352
+ hidden_states = self.post_attention_layernorm(hidden_states)
353
+ hidden_states = self.mlp(hidden_states)
354
+ hidden_states = residual + hidden_states
355
+
356
+ outputs = (hidden_states,)
357
+ if output_attentions:
358
+ outputs += (self_attn_weights,)
359
+
360
+ return outputs
361
+
362
+
363
+ LLAMA_START_DOCSTRING = r"""
364
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
365
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
366
+ etc.)
367
+
368
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
369
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
370
+ and behavior.
371
+
372
+ Parameters:
373
+ config ([`LlamaConfig`]):
374
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
375
+ load the weights associated with the model, only the configuration. Check out the
376
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
377
+ """
378
+
379
+
380
+ @add_start_docstrings(
381
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
382
+ LLAMA_START_DOCSTRING,
383
+ )
384
+ class LlamaPreTrainedModel(PreTrainedModel):
385
+ config_class = LlamaConfig
386
+ base_model_prefix = "model"
387
+ supports_gradient_checkpointing = True
388
+ _no_split_modules = ["LlamaDecoderLayer"]
389
+ _skip_keys_device_placement = ["past_key_values"]
390
+ _supports_flash_attn_2 = True
391
+ _supports_sdpa = True
392
+ _supports_flex_attn = True
393
+ _supports_cache_class = True
394
+ _supports_quantized_cache = True
395
+ _supports_static_cache = True
396
+ _supports_attention_backend = True
397
+
398
+ def _init_weights(self, module):
399
+ std = self.config.initializer_range
400
+ if isinstance(module, nn.Linear):
401
+ module.weight.data.normal_(mean=0.0, std=std)
402
+ if module.bias is not None:
403
+ module.bias.data.zero_()
404
+ elif isinstance(module, nn.Embedding):
405
+ module.weight.data.normal_(mean=0.0, std=std)
406
+ if module.padding_idx is not None:
407
+ module.weight.data[module.padding_idx].zero_()
408
+
409
+
410
+ LLAMA_INPUTS_DOCSTRING = r"""
411
+ Args:
412
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
413
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
414
+ it.
415
+
416
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
417
+ [`PreTrainedTokenizer.__call__`] for details.
418
+
419
+ [What are input IDs?](../glossary#input-ids)
420
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
421
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
422
+
423
+ - 1 for tokens that are **not masked**,
424
+ - 0 for tokens that are **masked**.
425
+
426
+ [What are attention masks?](../glossary#attention-mask)
427
+
428
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
429
+ [`PreTrainedTokenizer.__call__`] for details.
430
+
431
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
432
+ `past_key_values`).
433
+
434
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
435
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
436
+ information on the default strategy.
437
+
438
+ - 1 indicates the head is **not masked**,
439
+ - 0 indicates the head is **masked**.
440
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
441
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
442
+ config.n_positions - 1]`.
443
+
444
+ [What are position IDs?](../glossary#position-ids)
445
+ past_key_values (`Cache` or `tuple(tuple(torch.FloatTensor))`, *optional*):
446
+ Pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
447
+ blocks) that can be used to speed up sequential decoding. This typically consists in the `past_key_values`
448
+ returned by the model at a previous stage of decoding, when `use_cache=True` or `config.use_cache=True`.
449
+
450
+ Two formats are allowed:
451
+ - a [`~cache_utils.Cache`] instance, see our
452
+ [kv cache guide](https://huggingface.co/docs/transformers/en/kv_cache);
453
+ - Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of
454
+ shape `(batch_size, num_heads, sequence_length, embed_size_per_head)`). This is also known as the legacy
455
+ cache format.
456
+
457
+ The model will output the same cache format that is fed as input. If no `past_key_values` are passed, the
458
+ legacy cache format will be returned.
459
+
460
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
461
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
462
+ of shape `(batch_size, sequence_length)`.
463
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
464
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
465
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
466
+ model's internal embedding lookup matrix.
467
+ use_cache (`bool`, *optional*):
468
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
469
+ `past_key_values`).
470
+ output_attentions (`bool`, *optional*):
471
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
472
+ tensors for more detail.
473
+ output_hidden_states (`bool`, *optional*):
474
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
475
+ more detail.
476
+ return_dict (`bool`, *optional*):
477
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
478
+ cache_position (`torch.LongTensor` of shape `(sequence_length)`, *optional*):
479
+ Indices depicting the position of the input sequence tokens in the sequence. Contrarily to `position_ids`,
480
+ this tensor is not affected by padding. It is used to update the cache in the correct position and to infer
481
+ the complete sequence length.
482
+ """
483
+
484
+
485
+ @add_start_docstrings(
486
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
487
+ LLAMA_START_DOCSTRING,
488
+ )
489
+ class LlamaModel(LlamaPreTrainedModel):
490
+ """
491
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
492
+
493
+ Args:
494
+ config: LlamaConfig
495
+ """
496
+
497
+ def __init__(self, config: LlamaConfig):
498
+ super().__init__(config)
499
+ self.padding_idx = config.pad_token_id
500
+ self.vocab_size = config.vocab_size
501
+
502
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
503
+ self.layers = nn.ModuleList(
504
+ [LlamaDecoderLayer(config, layer_idx) for layer_idx in range(config.num_hidden_layers)]
505
+ )
506
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
507
+ self.rotary_emb = LlamaRotaryEmbedding(config=config)
508
+ self.gradient_checkpointing = False
509
+
510
+ # Initialize weights and apply final processing
511
+ self.post_init()
512
+
513
+ def get_input_embeddings(self):
514
+ return self.embed_tokens
515
+
516
+ def set_input_embeddings(self, value):
517
+ self.embed_tokens = value
518
+
519
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
520
+ def forward(
521
+ self,
522
+ input_ids: torch.LongTensor = None,
523
+ attention_mask: Optional[torch.Tensor] = None,
524
+ position_ids: Optional[torch.LongTensor] = None,
525
+ past_key_values: Optional[Cache] = None,
526
+ inputs_embeds: Optional[torch.FloatTensor] = None,
527
+ use_cache: Optional[bool] = None,
528
+ output_attentions: Optional[bool] = None,
529
+ output_hidden_states: Optional[bool] = None,
530
+ return_dict: Optional[bool] = None,
531
+ cache_position: Optional[torch.LongTensor] = None,
532
+ **flash_attn_kwargs: Unpack[FlashAttentionKwargs],
533
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
534
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
535
+ output_hidden_states = (
536
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
537
+ )
538
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
539
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
540
+
541
+ if (input_ids is None) ^ (inputs_embeds is not None):
542
+ raise ValueError("You must specify exactly one of input_ids or inputs_embeds")
543
+
544
+ if self.gradient_checkpointing and self.training and use_cache:
545
+ logger.warning_once(
546
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`."
547
+ )
548
+ use_cache = False
549
+
550
+ if inputs_embeds is None:
551
+ inputs_embeds = self.embed_tokens(input_ids)
552
+
553
+ if use_cache and past_key_values is None:
554
+ past_key_values = DynamicCache()
555
+
556
+ if cache_position is None:
557
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
558
+ cache_position = torch.arange(
559
+ past_seen_tokens, past_seen_tokens + inputs_embeds.shape[1], device=inputs_embeds.device
560
+ )
561
+
562
+ if position_ids is None:
563
+ position_ids = cache_position.unsqueeze(0)
564
+
565
+ causal_mask = self._update_causal_mask(
566
+ attention_mask, inputs_embeds, cache_position, past_key_values, output_attentions
567
+ )
568
+
569
+ hidden_states = inputs_embeds
570
+
571
+ # create position embeddings to be shared across the decoder layers
572
+ position_embeddings = self.rotary_emb(hidden_states, position_ids)
573
+
574
+ # decoder layers
575
+ all_hidden_states = () if output_hidden_states else None
576
+ all_self_attns = () if output_attentions else None
577
+
578
+ for decoder_layer in self.layers[: self.config.num_hidden_layers]:
579
+ if output_hidden_states:
580
+ all_hidden_states += (hidden_states,)
581
+
582
+ if self.gradient_checkpointing and self.training:
583
+ layer_outputs = self._gradient_checkpointing_func(
584
+ decoder_layer.__call__,
585
+ hidden_states,
586
+ causal_mask,
587
+ position_ids,
588
+ past_key_values,
589
+ output_attentions,
590
+ use_cache,
591
+ cache_position,
592
+ position_embeddings,
593
+ )
594
+ else:
595
+ layer_outputs = decoder_layer(
596
+ hidden_states,
597
+ attention_mask=causal_mask,
598
+ position_ids=position_ids,
599
+ past_key_value=past_key_values,
600
+ output_attentions=output_attentions,
601
+ use_cache=use_cache,
602
+ cache_position=cache_position,
603
+ position_embeddings=position_embeddings,
604
+ **flash_attn_kwargs,
605
+ )
606
+
607
+ hidden_states = layer_outputs[0]
608
+
609
+ if output_attentions:
610
+ all_self_attns += (layer_outputs[1],)
611
+
612
+ hidden_states = self.norm(hidden_states)
613
+
614
+ # add hidden states from the last decoder layer
615
+ if output_hidden_states:
616
+ all_hidden_states += (hidden_states,)
617
+
618
+ output = BaseModelOutputWithPast(
619
+ last_hidden_state=hidden_states,
620
+ past_key_values=past_key_values if use_cache else None,
621
+ hidden_states=all_hidden_states,
622
+ attentions=all_self_attns,
623
+ )
624
+ return output if return_dict else output.to_tuple()
625
+
626
+ def _update_causal_mask(
627
+ self,
628
+ attention_mask: torch.Tensor,
629
+ input_tensor: torch.Tensor,
630
+ cache_position: torch.Tensor,
631
+ past_key_values: Cache,
632
+ output_attentions: bool,
633
+ ):
634
+ if self.config._attn_implementation == "flash_attention_2":
635
+ if attention_mask is not None and (attention_mask == 0.0).any():
636
+ return attention_mask
637
+ return None
638
+
639
+ # For SDPA, when possible, we will rely on its `is_causal` argument instead of its `attn_mask` argument, in
640
+ # order to dispatch on Flash Attention 2. This feature is not compatible with static cache, as SDPA will fail
641
+ # to infer the attention mask.
642
+ past_seen_tokens = past_key_values.get_seq_length() if past_key_values is not None else 0
643
+ using_static_cache = isinstance(past_key_values, StaticCache)
644
+
645
+ # When output attentions is True, sdpa implementation's forward method calls the eager implementation's forward
646
+ if self.config._attn_implementation == "sdpa" and not using_static_cache and not output_attentions:
647
+ if AttentionMaskConverter._ignore_causal_mask_sdpa(
648
+ attention_mask,
649
+ inputs_embeds=input_tensor,
650
+ past_key_values_length=past_seen_tokens,
651
+ is_training=self.training,
652
+ ):
653
+ return None
654
+
655
+ dtype, device = input_tensor.dtype, input_tensor.device
656
+ sequence_length = input_tensor.shape[1]
657
+ if using_static_cache:
658
+ target_length = past_key_values.get_max_cache_shape()
659
+ else:
660
+ target_length = (
661
+ attention_mask.shape[-1]
662
+ if isinstance(attention_mask, torch.Tensor)
663
+ else past_seen_tokens + sequence_length + 1
664
+ )
665
+
666
+ # In case the provided `attention` mask is 2D, we generate a causal mask here (4D).
667
+ causal_mask = self._prepare_4d_causal_attention_mask_with_cache_position(
668
+ attention_mask,
669
+ sequence_length=sequence_length,
670
+ target_length=target_length,
671
+ dtype=dtype,
672
+ device=device,
673
+ cache_position=cache_position,
674
+ batch_size=input_tensor.shape[0],
675
+ )
676
+
677
+ if (
678
+ self.config._attn_implementation == "sdpa"
679
+ and attention_mask is not None
680
+ and attention_mask.device.type in ["cuda", "xpu"]
681
+ and not output_attentions
682
+ ):
683
+ # Attend to all tokens in fully masked rows in the causal_mask, for example the relevant first rows when
684
+ # using left padding. This is required by F.scaled_dot_product_attention memory-efficient attention path.
685
+ # Details: https://github.com/pytorch/pytorch/issues/110213
686
+ min_dtype = torch.finfo(dtype).min
687
+ causal_mask = AttentionMaskConverter._unmask_unattended(causal_mask, min_dtype)
688
+
689
+ return causal_mask
690
+
691
+ @staticmethod
692
+ def _prepare_4d_causal_attention_mask_with_cache_position(
693
+ attention_mask: torch.Tensor,
694
+ sequence_length: int,
695
+ target_length: int,
696
+ dtype: torch.dtype,
697
+ device: torch.device,
698
+ cache_position: torch.Tensor,
699
+ batch_size: int,
700
+ **kwargs,
701
+ ):
702
+ """
703
+ Creates a causal 4D mask of shape `(batch_size, 1, query_length, key_value_length)` from a 2D mask of shape
704
+ `(batch_size, key_value_length)`, or if the input `attention_mask` is already 4D, do nothing.
705
+
706
+ Args:
707
+ attention_mask (`torch.Tensor`):
708
+ A 2D attention mask of shape `(batch_size, key_value_length)` or a 4D attention mask of shape
709
+ `(batch_size, 1, query_length, key_value_length)`.
710
+ sequence_length (`int`):
711
+ The sequence length being processed.
712
+ target_length (`int`):
713
+ The target length: when generating with static cache, the mask should be as long as the static cache,
714
+ to account for the 0 padding, the part of the cache that is not filled yet.
715
+ dtype (`torch.dtype`):
716
+ The dtype to use for the 4D attention mask.
717
+ device (`torch.device`):
718
+ The device to plcae the 4D attention mask on.
719
+ cache_position (`torch.Tensor`):
720
+ Indices depicting the position of the input sequence tokens in the sequence.
721
+ batch_size (`torch.Tensor`):
722
+ Batch size.
723
+ """
724
+ if attention_mask is not None and attention_mask.dim() == 4:
725
+ # In this case we assume that the mask comes already in inverted form and requires no inversion or slicing.
726
+ causal_mask = attention_mask
727
+ else:
728
+ min_dtype = torch.finfo(dtype).min
729
+ causal_mask = torch.full(
730
+ (sequence_length, target_length), fill_value=min_dtype, dtype=dtype, device=device
731
+ )
732
+ if sequence_length != 1:
733
+ causal_mask = torch.triu(causal_mask, diagonal=1)
734
+ causal_mask *= torch.arange(target_length, device=device) > cache_position.reshape(-1, 1)
735
+ causal_mask = causal_mask[None, None, :, :].expand(batch_size, 1, -1, -1)
736
+ if attention_mask is not None:
737
+ causal_mask = causal_mask.clone() # copy to contiguous memory for in-place edit
738
+ mask_length = attention_mask.shape[-1]
739
+ padding_mask = causal_mask[:, :, :, :mask_length] + attention_mask[:, None, None, :].to(
740
+ causal_mask.device
741
+ )
742
+ padding_mask = padding_mask == 0
743
+ causal_mask[:, :, :, :mask_length] = causal_mask[:, :, :, :mask_length].masked_fill(
744
+ padding_mask, min_dtype
745
+ )
746
+
747
+ return causal_mask
748
+
749
+
750
+ class KwargsForCausalLM(FlashAttentionKwargs, LossKwargs): ...
751
+
752
+
753
+ class LlamaForCausalLM(LlamaPreTrainedModel, GenerationMixin):
754
+ _tied_weights_keys = ["lm_head.weight"]
755
+ _tp_plan = {"lm_head": "colwise_rep"}
756
+ _pp_plan = {"lm_head": (["hidden_states"], ["logits"])}
757
+
758
+ def __init__(self, config):
759
+ super().__init__(config)
760
+ self.model = LlamaModel(config)
761
+ self.vocab_size = config.vocab_size
762
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
763
+
764
+ # Initialize weights and apply final processing
765
+ self.post_init()
766
+
767
+ def get_input_embeddings(self):
768
+ return self.model.embed_tokens
769
+
770
+ def set_input_embeddings(self, value):
771
+ self.model.embed_tokens = value
772
+
773
+ def get_output_embeddings(self):
774
+ return self.lm_head
775
+
776
+ def set_output_embeddings(self, new_embeddings):
777
+ self.lm_head = new_embeddings
778
+
779
+ def set_decoder(self, decoder):
780
+ self.model = decoder
781
+
782
+ def get_decoder(self):
783
+ return self.model
784
+
785
+ @deprecate_kwarg("num_logits_to_keep", version="4.50", new_name="logits_to_keep")
786
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
787
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
788
+ def forward(
789
+ self,
790
+ input_ids: torch.LongTensor = None,
791
+ attention_mask: Optional[torch.Tensor] = None,
792
+ position_ids: Optional[torch.LongTensor] = None,
793
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
794
+ inputs_embeds: Optional[torch.FloatTensor] = None,
795
+ labels: Optional[torch.LongTensor] = None,
796
+ use_cache: Optional[bool] = None,
797
+ output_attentions: Optional[bool] = None,
798
+ output_hidden_states: Optional[bool] = None,
799
+ return_dict: Optional[bool] = None,
800
+ cache_position: Optional[torch.LongTensor] = None,
801
+ logits_to_keep: Union[int, torch.Tensor] = 0,
802
+ **kwargs: Unpack[KwargsForCausalLM],
803
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
804
+ r"""
805
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
806
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
807
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
808
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
809
+
810
+ logits_to_keep (`int` or `torch.Tensor`, *optional*):
811
+ If an `int`, compute logits for the last `logits_to_keep` tokens. If `0`, calculate logits for all
812
+ `input_ids` (special case). Only last token logits are needed for generation, and calculating them only for that
813
+ token can save memory, which becomes pretty significant for long sequences or large vocabulary size.
814
+ If a `torch.Tensor`, must be 1D corresponding to the indices to keep in the sequence length dimension.
815
+ This is useful when using packed tensor format (single dimension for batch and sequence length).
816
+
817
+ Returns:
818
+
819
+ Example:
820
+
821
+ ```python
822
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
823
+
824
+ >>> model = LlamaForCausalLM.from_pretrained("meta-llama/Llama-2-7b-hf")
825
+ >>> tokenizer = AutoTokenizer.from_pretrained("meta-llama/Llama-2-7b-hf")
826
+
827
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
828
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
829
+
830
+ >>> # Generate
831
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
832
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
833
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
834
+ ```"""
835
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
836
+ output_hidden_states = (
837
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
838
+ )
839
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
840
+
841
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
842
+ outputs = self.model(
843
+ input_ids=input_ids,
844
+ attention_mask=attention_mask,
845
+ position_ids=position_ids,
846
+ past_key_values=past_key_values,
847
+ inputs_embeds=inputs_embeds,
848
+ use_cache=use_cache,
849
+ output_attentions=output_attentions,
850
+ output_hidden_states=output_hidden_states,
851
+ return_dict=return_dict,
852
+ cache_position=cache_position,
853
+ **kwargs,
854
+ )
855
+
856
+ hidden_states = outputs[0]
857
+ # Only compute necessary logits, and do not upcast them to float if we are not computing the loss
858
+ slice_indices = slice(-logits_to_keep, None) if isinstance(logits_to_keep, int) else logits_to_keep
859
+ logits = self.lm_head(hidden_states[:, slice_indices, :])
860
+
861
+ loss = None
862
+ if labels is not None:
863
+ loss = self.loss_function(logits=logits, labels=labels, vocab_size=self.config.vocab_size, **kwargs)
864
+
865
+ if not return_dict:
866
+ output = (logits,) + outputs[1:]
867
+ return (loss,) + output if loss is not None else output
868
+
869
+ return CausalLMOutputWithPast(
870
+ loss=loss,
871
+ logits=logits,
872
+ past_key_values=outputs.past_key_values,
873
+ hidden_states=outputs.hidden_states,
874
+ attentions=outputs.attentions,
875
+ )
876
+
877
+
878
+ @add_start_docstrings(
879
+ """
880
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
881
+
882
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
883
+ (e.g. GPT-2) do.
884
+
885
+ Since it does classification on the last token, it requires to know the position of the last token. If a
886
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
887
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
888
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
889
+ each row of the batch).
890
+ """,
891
+ LLAMA_START_DOCSTRING,
892
+ )
893
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
894
+ def __init__(self, config):
895
+ super().__init__(config)
896
+ self.num_labels = config.num_labels
897
+ self.model = LlamaModel(config)
898
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
899
+
900
+ # Initialize weights and apply final processing
901
+ self.post_init()
902
+
903
+ def get_input_embeddings(self):
904
+ return self.model.embed_tokens
905
+
906
+ def set_input_embeddings(self, value):
907
+ self.model.embed_tokens = value
908
+
909
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
910
+ def forward(
911
+ self,
912
+ input_ids: Optional[torch.LongTensor] = None,
913
+ attention_mask: Optional[torch.Tensor] = None,
914
+ position_ids: Optional[torch.LongTensor] = None,
915
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
916
+ inputs_embeds: Optional[torch.FloatTensor] = None,
917
+ labels: Optional[torch.LongTensor] = None,
918
+ use_cache: Optional[bool] = None,
919
+ output_attentions: Optional[bool] = None,
920
+ output_hidden_states: Optional[bool] = None,
921
+ return_dict: Optional[bool] = None,
922
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
923
+ r"""
924
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
925
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
926
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
927
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
928
+ """
929
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
930
+
931
+ transformer_outputs = self.model(
932
+ input_ids,
933
+ attention_mask=attention_mask,
934
+ position_ids=position_ids,
935
+ past_key_values=past_key_values,
936
+ inputs_embeds=inputs_embeds,
937
+ use_cache=use_cache,
938
+ output_attentions=output_attentions,
939
+ output_hidden_states=output_hidden_states,
940
+ return_dict=return_dict,
941
+ )
942
+ hidden_states = transformer_outputs[0]
943
+ logits = self.score(hidden_states)
944
+
945
+ if input_ids is not None:
946
+ batch_size = input_ids.shape[0]
947
+ else:
948
+ batch_size = inputs_embeds.shape[0]
949
+
950
+ if self.config.pad_token_id is None and batch_size != 1:
951
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
952
+ if self.config.pad_token_id is None:
953
+ last_non_pad_token = -1
954
+ elif input_ids is not None:
955
+ # To handle both left- and right- padding, we take the rightmost token that is not equal to pad_token_id
956
+ non_pad_mask = (input_ids != self.config.pad_token_id).to(logits.device, torch.int32)
957
+ token_indices = torch.arange(input_ids.shape[-1], device=logits.device)
958
+ last_non_pad_token = (token_indices * non_pad_mask).argmax(-1)
959
+ else:
960
+ last_non_pad_token = -1
961
+ logger.warning_once(
962
+ f"{self.__class__.__name__} will not detect padding tokens in `inputs_embeds`. Results may be "
963
+ "unexpected if using padding tokens in conjunction with `inputs_embeds.`"
964
+ )
965
+
966
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), last_non_pad_token]
967
+
968
+ loss = None
969
+ if labels is not None:
970
+ loss = self.loss_function(logits=logits, labels=labels, pooled_logits=pooled_logits, config=self.config)
971
+
972
+ if not return_dict:
973
+ output = (pooled_logits,) + transformer_outputs[1:]
974
+ return ((loss,) + output) if loss is not None else output
975
+
976
+ return SequenceClassifierOutputWithPast(
977
+ loss=loss,
978
+ logits=pooled_logits,
979
+ past_key_values=transformer_outputs.past_key_values,
980
+ hidden_states=transformer_outputs.hidden_states,
981
+ attentions=transformer_outputs.attentions,
982
+ )
983
+
984
+
985
+ @add_start_docstrings(
986
+ """
987
+ The Llama Model transformer with a span classification head on top for extractive question-answering tasks like
988
+ SQuAD (a linear layer on top of the hidden-states output to compute `span start logits` and `span end logits`).
989
+ """,
990
+ LLAMA_START_DOCSTRING,
991
+ )
992
+ class LlamaForQuestionAnswering(LlamaPreTrainedModel):
993
+ base_model_prefix = "transformer"
994
+
995
+ # Copied from transformers.models.bloom.modeling_bloom.BloomForQuestionAnswering.__init__ with Bloom->Llama
996
+ def __init__(self, config):
997
+ super().__init__(config)
998
+ self.transformer = LlamaModel(config)
999
+ self.qa_outputs = nn.Linear(config.hidden_size, 2)
1000
+
1001
+ # Initialize weights and apply final processing
1002
+ self.post_init()
1003
+
1004
+ def get_input_embeddings(self):
1005
+ return self.transformer.embed_tokens
1006
+
1007
+ def set_input_embeddings(self, value):
1008
+ self.transformer.embed_tokens = value
1009
+
1010
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1011
+ def forward(
1012
+ self,
1013
+ input_ids: Optional[torch.LongTensor] = None,
1014
+ attention_mask: Optional[torch.FloatTensor] = None,
1015
+ position_ids: Optional[torch.LongTensor] = None,
1016
+ past_key_values: Optional[Union[Cache, List[torch.FloatTensor]]] = None,
1017
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1018
+ start_positions: Optional[torch.LongTensor] = None,
1019
+ end_positions: Optional[torch.LongTensor] = None,
1020
+ output_attentions: Optional[bool] = None,
1021
+ output_hidden_states: Optional[bool] = None,
1022
+ return_dict: Optional[bool] = None,
1023
+ **kwargs,
1024
+ ) -> Union[Tuple, QuestionAnsweringModelOutput]:
1025
+ r"""
1026
+ start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1027
+ Labels for position (index) of the start of the labelled span for computing the token classification loss.
1028
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1029
+ are not taken into account for computing the loss.
1030
+ end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1031
+ Labels for position (index) of the end of the labelled span for computing the token classification loss.
1032
+ Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
1033
+ are not taken into account for computing the loss.
1034
+ """
1035
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1036
+
1037
+ outputs = self.transformer(
1038
+ input_ids,
1039
+ attention_mask=attention_mask,
1040
+ position_ids=position_ids,
1041
+ past_key_values=past_key_values,
1042
+ inputs_embeds=inputs_embeds,
1043
+ output_attentions=output_attentions,
1044
+ output_hidden_states=output_hidden_states,
1045
+ return_dict=return_dict,
1046
+ )
1047
+
1048
+ sequence_output = outputs[0]
1049
+
1050
+ logits = self.qa_outputs(sequence_output)
1051
+ start_logits, end_logits = logits.split(1, dim=-1)
1052
+ start_logits = start_logits.squeeze(-1).contiguous()
1053
+ end_logits = end_logits.squeeze(-1).contiguous()
1054
+
1055
+ loss = None
1056
+ if start_positions is not None and end_positions is not None:
1057
+ loss = self.loss_function(start_logits, end_logits, start_positions, end_positions, **kwargs)
1058
+
1059
+ if not return_dict:
1060
+ output = (start_logits, end_logits) + outputs[2:]
1061
+ return ((loss,) + output) if loss is not None else output
1062
+
1063
+ return QuestionAnsweringModelOutput(
1064
+ loss=loss,
1065
+ start_logits=start_logits,
1066
+ end_logits=end_logits,
1067
+ hidden_states=outputs.hidden_states,
1068
+ attentions=outputs.attentions,
1069
+ )
1070
+
1071
+
1072
+ @add_start_docstrings(
1073
+ """
1074
+ The Llama Model transformer with a token classification head on top (a linear layer on top of the hidden-states
1075
+ output) e.g. for Named-Entity-Recognition (NER) tasks.
1076
+ """,
1077
+ LLAMA_START_DOCSTRING,
1078
+ )
1079
+ class LlamaForTokenClassification(LlamaPreTrainedModel):
1080
+ def __init__(self, config):
1081
+ super().__init__(config)
1082
+ self.num_labels = config.num_labels
1083
+ self.model = LlamaModel(config)
1084
+ if getattr(config, "classifier_dropout", None) is not None:
1085
+ classifier_dropout = config.classifier_dropout
1086
+ elif getattr(config, "hidden_dropout", None) is not None:
1087
+ classifier_dropout = config.hidden_dropout
1088
+ else:
1089
+ classifier_dropout = 0.1
1090
+ self.dropout = nn.Dropout(classifier_dropout)
1091
+ self.score = nn.Linear(config.hidden_size, config.num_labels)
1092
+
1093
+ # Initialize weights and apply final processing
1094
+ self.post_init()
1095
+
1096
+ def get_input_embeddings(self):
1097
+ return self.model.embed_tokens
1098
+
1099
+ def set_input_embeddings(self, value):
1100
+ self.model.embed_tokens = value
1101
+
1102
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1103
+ @add_code_sample_docstrings(
1104
+ checkpoint=_CHECKPOINT_FOR_DOC,
1105
+ output_type=TokenClassifierOutput,
1106
+ config_class=_CONFIG_FOR_DOC,
1107
+ )
1108
+ def forward(
1109
+ self,
1110
+ input_ids: Optional[torch.LongTensor] = None,
1111
+ attention_mask: Optional[torch.Tensor] = None,
1112
+ position_ids: Optional[torch.LongTensor] = None,
1113
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1114
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1115
+ labels: Optional[torch.LongTensor] = None,
1116
+ use_cache: Optional[bool] = None,
1117
+ output_attentions: Optional[bool] = None,
1118
+ output_hidden_states: Optional[bool] = None,
1119
+ return_dict: Optional[bool] = None,
1120
+ ) -> Union[Tuple, TokenClassifierOutput]:
1121
+ r"""
1122
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1123
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1124
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1125
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1126
+ """
1127
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1128
+
1129
+ outputs = self.model(
1130
+ input_ids,
1131
+ attention_mask=attention_mask,
1132
+ position_ids=position_ids,
1133
+ past_key_values=past_key_values,
1134
+ inputs_embeds=inputs_embeds,
1135
+ use_cache=use_cache,
1136
+ output_attentions=output_attentions,
1137
+ output_hidden_states=output_hidden_states,
1138
+ return_dict=return_dict,
1139
+ )
1140
+ sequence_output = outputs[0]
1141
+ sequence_output = self.dropout(sequence_output)
1142
+ logits = self.score(sequence_output)
1143
+
1144
+ loss = None
1145
+ if labels is not None:
1146
+ loss = self.loss_function(logits, labels, self.config)
1147
+
1148
+ if not return_dict:
1149
+ output = (logits,) + outputs[2:]
1150
+ return ((loss,) + output) if loss is not None else output
1151
+
1152
+ return TokenClassifierOutput(
1153
+ loss=loss,
1154
+ logits=logits,
1155
+ hidden_states=outputs.hidden_states,
1156
+ attentions=outputs.attentions,
1157
+ )
1158
+
1159
+
1160
+ __all__ = [
1161
+ "LlamaForCausalLM",
1162
+ "LlamaModel",
1163
+ "LlamaPreTrainedModel",
1164
+ "LlamaForSequenceClassification",
1165
+ "LlamaForQuestionAnswering",
1166
+ "LlamaForTokenClassification",
1167
+ ]
qlinear.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from torch import nn
3
+ import torch.nn.functional as F
4
+
5
+ def modified_weight_quant(w):
6
+ """ Per−tensor quantization to 1.58 bits. No grouping is needed for quantization.
7
+ Args:
8
+ w: a weight tensor with shape [d, k]
9
+ Returns:
10
+ u: a quantized weight with shape [d, k]
11
+ """
12
+ u = w.clamp(-1, 1).round()
13
+ return u
14
+
15
+ def normalize(w):
16
+ w = w / torch.norm(w, dim=1, keepdim=True)
17
+ return w
18
+
19
+ class QLinear(nn.Linear):
20
+ def __init__(self,
21
+ *kargs,
22
+ **kwargs
23
+ ):
24
+ super(QLinear, self).__init__(*kargs, **kwargs)
25
+ """
26
+ This is only for training, and kernel optimization is needed for efficiency.
27
+ """
28
+ self.scales = nn.Parameter(torch.ones(self.out_features))
29
+ self.quantizer = modified_weight_quant
30
+
31
+
32
+ def forward(self, x):
33
+ """i
34
+ Args:
35
+ x: an input tensor with shape [n, d]
36
+ Returns:
37
+ y: an output tensor with shape [n, d]
38
+ """
39
+ w_quant = self.weight
40
+ x = x.to(w_quant.device)
41
+ # STE weight quantization
42
+ w_quant = w_quant + (self.quantizer(w_quant) - w_quant).detach()
43
+ y = F.linear(x, w_quant)
44
+ # apply scales post matmul
45
+ y = y * self.scales
46
+ if self.bias is not None:
47
+ y = y + self.bias
48
+ return y