Andrei Panferov commited on
Commit
5c0d7ef
1 Parent(s): cc25d01

inference and autoloading

Browse files
config.json CHANGED
@@ -1,8 +1,12 @@
1
  {
2
- "_name_or_path": "meta-llama/Llama-2-7b-hf",
3
  "architectures": [
4
- "LlamaForCausalLM"
5
  ],
 
 
 
 
 
6
  "bos_token_id": 1,
7
  "eos_token_id": 2,
8
  "hidden_act": "silu",
@@ -10,7 +14,7 @@
10
  "initializer_range": 0.02,
11
  "intermediate_size": 11008,
12
  "max_position_embeddings": 4096,
13
- "model_type": "llama",
14
  "num_attention_heads": 32,
15
  "num_hidden_layers": 32,
16
  "num_key_value_heads": 32,
@@ -22,7 +26,6 @@
22
  "transformers_version": "4.31.0.dev0",
23
  "use_cache": true,
24
  "vocab_size": 32000,
25
- "_commit_hash": "8cca527612d856d7d32bd94f8103728d614eb852",
26
  "aqlm": {
27
  "nbits_per_codebook": 16,
28
  "num_codebooks": 1,
 
1
  {
 
2
  "architectures": [
3
+ "LlamaForCausalLM_AQLM"
4
  ],
5
+ "auto_map": {
6
+ "AutoConfig": "configuration_llama.LlamaConfig",
7
+ "AutoModel": "modeling_llama.LlamaModel",
8
+ "AutoModelForCausalLM": "modeling_llama.LlamaForCausalLM"
9
+ },
10
  "bos_token_id": 1,
11
  "eos_token_id": 2,
12
  "hidden_act": "silu",
 
14
  "initializer_range": 0.02,
15
  "intermediate_size": 11008,
16
  "max_position_embeddings": 4096,
17
+ "model_type": "llama_aqlm",
18
  "num_attention_heads": 32,
19
  "num_hidden_layers": 32,
20
  "num_key_value_heads": 32,
 
26
  "transformers_version": "4.31.0.dev0",
27
  "use_cache": true,
28
  "vocab_size": 32000,
 
29
  "aqlm": {
30
  "nbits_per_codebook": 16,
31
  "num_codebooks": 1,
configuration_llama.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from transformers import LlamaConfig as OrigLlamaConfig
2
+
3
+
4
+ class LlamaConfig(OrigLlamaConfig):
5
+ model_type = "llama_aqlm"
6
+
7
+ def __init__(
8
+ self,
9
+ nbits_per_codebook: int = 16,
10
+ num_codebooks: int = 1,
11
+ out_group_size: int = 1,
12
+ in_group_size: int = 8,
13
+ **kwargs,
14
+ ):
15
+ super().__init__(**kwargs)
16
+ self.aqlm = {
17
+ "nbits_per_codebook": nbits_per_codebook,
18
+ "num_codebooks": num_codebooks,
19
+ "out_group_size": out_group_size,
20
+ "in_group_size": in_group_size,
21
+ }
modeling_llama.py ADDED
@@ -0,0 +1,1253 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.nn.functional as F
26
+ import torch.utils.checkpoint
27
+ from torch import nn
28
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
29
+ from transformers import LlamaConfig
30
+ from transformers.activations import ACT2FN
31
+ from transformers.modeling_outputs import (
32
+ BaseModelOutputWithPast,
33
+ CausalLMOutputWithPast,
34
+ SequenceClassifierOutputWithPast,
35
+ )
36
+ from transformers.modeling_utils import PreTrainedModel
37
+ from transformers.pytorch_utils import ALL_LAYERNORM_LAYERS
38
+ from transformers.utils import (
39
+ add_start_docstrings,
40
+ add_start_docstrings_to_model_forward,
41
+ is_flash_attn_available,
42
+ logging,
43
+ replace_return_docstrings,
44
+ )
45
+
46
+ from src.inference import FinalizedQuantizedLinear
47
+
48
+ if is_flash_attn_available():
49
+ from flash_attn import flash_attn_func, flash_attn_varlen_func
50
+ from flash_attn.bert_padding import index_first_axis, pad_input, unpad_input # noqa
51
+
52
+
53
+ logger = logging.get_logger(__name__)
54
+
55
+ _CONFIG_FOR_DOC = "LlamaConfig"
56
+
57
+
58
+ def _get_unpad_data(padding_mask):
59
+ seqlens_in_batch = padding_mask.sum(dim=-1, dtype=torch.int32)
60
+ indices = torch.nonzero(padding_mask.flatten(), as_tuple=False).flatten()
61
+ max_seqlen_in_batch = seqlens_in_batch.max().item()
62
+ cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
63
+ return (
64
+ indices,
65
+ cu_seqlens,
66
+ max_seqlen_in_batch,
67
+ )
68
+
69
+
70
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
71
+ def _make_causal_mask(
72
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
73
+ ):
74
+ """
75
+ Make causal mask used for bi-directional self-attention.
76
+ """
77
+ bsz, tgt_len = input_ids_shape
78
+ mask = torch.full((tgt_len, tgt_len), torch.finfo(dtype).min, device=device)
79
+ mask_cond = torch.arange(mask.size(-1), device=device)
80
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
81
+ mask = mask.to(dtype)
82
+
83
+ if past_key_values_length > 0:
84
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
85
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
86
+
87
+
88
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
89
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
90
+ """
91
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
92
+ """
93
+ bsz, src_len = mask.size()
94
+ tgt_len = tgt_len if tgt_len is not None else src_len
95
+
96
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
97
+
98
+ inverted_mask = 1.0 - expanded_mask
99
+
100
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
101
+
102
+
103
+ class LlamaRMSNorm(nn.Module):
104
+ def __init__(self, hidden_size, eps=1e-6):
105
+ """
106
+ LlamaRMSNorm is equivalent to T5LayerNorm
107
+ """
108
+ super().__init__()
109
+ self.weight = nn.Parameter(torch.ones(hidden_size))
110
+ self.variance_epsilon = eps
111
+
112
+ def forward(self, hidden_states):
113
+ input_dtype = hidden_states.dtype
114
+ hidden_states = hidden_states.to(torch.float32)
115
+ variance = hidden_states.pow(2).mean(-1, keepdim=True)
116
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
117
+ return self.weight * hidden_states.to(input_dtype)
118
+
119
+
120
+ ALL_LAYERNORM_LAYERS.append(LlamaRMSNorm)
121
+
122
+
123
+ class LlamaRotaryEmbedding(nn.Module):
124
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
125
+ super().__init__()
126
+
127
+ self.dim = dim
128
+ self.max_position_embeddings = max_position_embeddings
129
+ self.base = base
130
+ inv_freq = 1.0 / (self.base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
131
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
132
+
133
+ # Build here to make `torch.jit.trace` work.
134
+ self._set_cos_sin_cache(
135
+ seq_len=max_position_embeddings, device=self.inv_freq.device, dtype=torch.get_default_dtype()
136
+ )
137
+
138
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
139
+ self.max_seq_len_cached = seq_len
140
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
141
+
142
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
143
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
144
+ emb = torch.cat((freqs, freqs), dim=-1)
145
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
146
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
147
+
148
+ def forward(self, x, seq_len=None):
149
+ # x: [bs, num_attention_heads, seq_len, head_size]
150
+ if seq_len > self.max_seq_len_cached:
151
+ self._set_cos_sin_cache(seq_len=seq_len, device=x.device, dtype=x.dtype)
152
+
153
+ return (
154
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
155
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
156
+ )
157
+
158
+
159
+ class LlamaLinearScalingRotaryEmbedding(LlamaRotaryEmbedding):
160
+ """LlamaRotaryEmbedding extended with linear scaling. Credits to the Reddit user /u/kaiokendev"""
161
+
162
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
163
+ self.scaling_factor = scaling_factor
164
+ super().__init__(dim, max_position_embeddings, base, device)
165
+
166
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
167
+ self.max_seq_len_cached = seq_len
168
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
169
+ t = t / self.scaling_factor
170
+
171
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
172
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
173
+ emb = torch.cat((freqs, freqs), dim=-1)
174
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
175
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
176
+
177
+
178
+ class LlamaDynamicNTKScalingRotaryEmbedding(LlamaRotaryEmbedding):
179
+ """LlamaRotaryEmbedding extended with Dynamic NTK scaling. Credits to the Reddit users /u/bloc97 and /u/emozilla"""
180
+
181
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None, scaling_factor=1.0):
182
+ self.scaling_factor = scaling_factor
183
+ super().__init__(dim, max_position_embeddings, base, device)
184
+
185
+ def _set_cos_sin_cache(self, seq_len, device, dtype):
186
+ self.max_seq_len_cached = seq_len
187
+
188
+ if seq_len > self.max_position_embeddings:
189
+ base = self.base * (
190
+ (self.scaling_factor * seq_len / self.max_position_embeddings) - (self.scaling_factor - 1)
191
+ ) ** (self.dim / (self.dim - 2))
192
+ inv_freq = 1.0 / (base ** (torch.arange(0, self.dim, 2).float().to(device) / self.dim))
193
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
194
+
195
+ t = torch.arange(self.max_seq_len_cached, device=device, dtype=self.inv_freq.dtype)
196
+
197
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
198
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
199
+ emb = torch.cat((freqs, freqs), dim=-1)
200
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :].to(dtype), persistent=False)
201
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :].to(dtype), persistent=False)
202
+
203
+
204
+ def rotate_half(x):
205
+ """Rotates half the hidden dims of the input."""
206
+ x1 = x[..., : x.shape[-1] // 2]
207
+ x2 = x[..., x.shape[-1] // 2 :]
208
+ return torch.cat((-x2, x1), dim=-1)
209
+
210
+
211
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
212
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
213
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
214
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
215
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
216
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
217
+ q_embed = (q * cos) + (rotate_half(q) * sin)
218
+ k_embed = (k * cos) + (rotate_half(k) * sin)
219
+ return q_embed, k_embed
220
+
221
+
222
+ class LlamaMLP(nn.Module):
223
+ def __init__(self, config):
224
+ super().__init__()
225
+ self.config = config
226
+ self.hidden_size = config.hidden_size
227
+ self.intermediate_size = config.intermediate_size
228
+ self.gate_proj = FinalizedQuantizedLinear(self.hidden_size, self.intermediate_size, bias=False, **config.aqlm)
229
+ self.up_proj = FinalizedQuantizedLinear(self.hidden_size, self.intermediate_size, bias=False, **config.aqlm)
230
+ self.down_proj = FinalizedQuantizedLinear(self.intermediate_size, self.hidden_size, bias=False, **config.aqlm)
231
+ self.act_fn = ACT2FN[config.hidden_act]
232
+
233
+ def forward(self, x):
234
+ if self.config.pretraining_tp > 1:
235
+ slice = self.intermediate_size // self.config.pretraining_tp
236
+ gate_proj_slices = self.gate_proj.weight.split(slice, dim=0)
237
+ up_proj_slices = self.up_proj.weight.split(slice, dim=0)
238
+ down_proj_slices = self.down_proj.weight.split(slice, dim=1)
239
+
240
+ gate_proj = torch.cat([F.linear(x, gate_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
241
+ up_proj = torch.cat([F.linear(x, up_proj_slices[i]) for i in range(self.config.pretraining_tp)], dim=-1)
242
+
243
+ intermediate_states = (self.act_fn(gate_proj) * up_proj).split(slice, dim=2)
244
+ down_proj = [
245
+ F.linear(intermediate_states[i], down_proj_slices[i]) for i in range(self.config.pretraining_tp)
246
+ ]
247
+ down_proj = sum(down_proj)
248
+ else:
249
+ down_proj = self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
250
+
251
+ return down_proj
252
+
253
+
254
+ def repeat_kv(hidden_states: torch.Tensor, n_rep: int) -> torch.Tensor:
255
+ """
256
+ This is the equivalent of torch.repeat_interleave(x, dim=1, repeats=n_rep). The hidden states go from (batch,
257
+ num_key_value_heads, seqlen, head_dim) to (batch, num_attention_heads, seqlen, head_dim)
258
+ """
259
+ batch, num_key_value_heads, slen, head_dim = hidden_states.shape
260
+ if n_rep == 1:
261
+ return hidden_states
262
+ hidden_states = hidden_states[:, :, None, :, :].expand(batch, num_key_value_heads, n_rep, slen, head_dim)
263
+ return hidden_states.reshape(batch, num_key_value_heads * n_rep, slen, head_dim)
264
+
265
+
266
+ class LlamaAttention(nn.Module):
267
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
268
+
269
+ def __init__(self, config: LlamaConfig):
270
+ super().__init__()
271
+ self.config = config
272
+ self.hidden_size = config.hidden_size
273
+ self.num_heads = config.num_attention_heads
274
+ self.head_dim = self.hidden_size // self.num_heads
275
+ self.num_key_value_heads = config.num_key_value_heads
276
+ self.num_key_value_groups = self.num_heads // self.num_key_value_heads
277
+ self.max_position_embeddings = config.max_position_embeddings
278
+ self.rope_theta = config.rope_theta
279
+
280
+ if (self.head_dim * self.num_heads) != self.hidden_size:
281
+ raise ValueError(
282
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
283
+ f" and `num_heads`: {self.num_heads})."
284
+ )
285
+ self.q_proj = FinalizedQuantizedLinear(
286
+ self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
287
+ )
288
+ self.k_proj = FinalizedQuantizedLinear(
289
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
290
+ )
291
+ self.v_proj = FinalizedQuantizedLinear(
292
+ self.hidden_size, self.num_key_value_heads * self.head_dim, bias=config.attention_bias, **config.aqlm
293
+ )
294
+ self.o_proj = FinalizedQuantizedLinear(
295
+ self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias, **config.aqlm
296
+ )
297
+ self._init_rope()
298
+
299
+ def _init_rope(self):
300
+ if self.config.rope_scaling is None:
301
+ self.rotary_emb = LlamaRotaryEmbedding(
302
+ self.head_dim,
303
+ max_position_embeddings=self.max_position_embeddings,
304
+ base=self.rope_theta,
305
+ )
306
+ else:
307
+ scaling_type = self.config.rope_scaling["type"]
308
+ scaling_factor = self.config.rope_scaling["factor"]
309
+ if scaling_type == "linear":
310
+ self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
311
+ self.head_dim,
312
+ max_position_embeddings=self.max_position_embeddings,
313
+ scaling_factor=scaling_factor,
314
+ base=self.rope_theta,
315
+ )
316
+ elif scaling_type == "dynamic":
317
+ self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
318
+ self.head_dim,
319
+ max_position_embeddings=self.max_position_embeddings,
320
+ scaling_factor=scaling_factor,
321
+ base=self.rope_theta,
322
+ )
323
+ else:
324
+ raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
325
+
326
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
327
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
328
+
329
+ def forward(
330
+ self,
331
+ hidden_states: torch.Tensor,
332
+ attention_mask: Optional[torch.Tensor] = None,
333
+ position_ids: Optional[torch.LongTensor] = None,
334
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
335
+ output_attentions: bool = False,
336
+ use_cache: bool = False,
337
+ padding_mask: Optional[torch.LongTensor] = None,
338
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
339
+ bsz, q_len, _ = hidden_states.size()
340
+
341
+ if self.config.pretraining_tp > 1:
342
+ key_value_slicing = (self.num_key_value_heads * self.head_dim) // self.config.pretraining_tp
343
+ query_slices = self.q_proj.weight.split(
344
+ (self.num_heads * self.head_dim) // self.config.pretraining_tp, dim=0
345
+ )
346
+ key_slices = self.k_proj.weight.split(key_value_slicing, dim=0)
347
+ value_slices = self.v_proj.weight.split(key_value_slicing, dim=0)
348
+
349
+ query_states = [F.linear(hidden_states, query_slices[i]) for i in range(self.config.pretraining_tp)]
350
+ query_states = torch.cat(query_states, dim=-1)
351
+
352
+ key_states = [F.linear(hidden_states, key_slices[i]) for i in range(self.config.pretraining_tp)]
353
+ key_states = torch.cat(key_states, dim=-1)
354
+
355
+ value_states = [F.linear(hidden_states, value_slices[i]) for i in range(self.config.pretraining_tp)]
356
+ value_states = torch.cat(value_states, dim=-1)
357
+
358
+ else:
359
+ query_states = self.q_proj(hidden_states)
360
+ key_states = self.k_proj(hidden_states)
361
+ value_states = self.v_proj(hidden_states)
362
+
363
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
364
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
365
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
366
+
367
+ kv_seq_len = key_states.shape[-2]
368
+ if past_key_value is not None:
369
+ kv_seq_len += past_key_value[0].shape[-2]
370
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
371
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
372
+
373
+ if past_key_value is not None:
374
+ # reuse k, v, self_attention
375
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
376
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
377
+
378
+ past_key_value = (key_states, value_states) if use_cache else None
379
+
380
+ key_states = repeat_kv(key_states, self.num_key_value_groups)
381
+ value_states = repeat_kv(value_states, self.num_key_value_groups)
382
+
383
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
384
+
385
+ if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
386
+ raise ValueError(
387
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
388
+ f" {attn_weights.size()}"
389
+ )
390
+
391
+ if attention_mask is not None:
392
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
393
+ raise ValueError(
394
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
395
+ )
396
+ attn_weights = attn_weights + attention_mask
397
+
398
+ # upcast attention to fp32
399
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
400
+ attn_output = torch.matmul(attn_weights, value_states)
401
+
402
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
403
+ raise ValueError(
404
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
405
+ f" {attn_output.size()}"
406
+ )
407
+
408
+ attn_output = attn_output.transpose(1, 2).contiguous()
409
+
410
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
411
+
412
+ if self.config.pretraining_tp > 1:
413
+ attn_output = attn_output.split(self.hidden_size // self.config.pretraining_tp, dim=2)
414
+ o_proj_slices = self.o_proj.weight.split(self.hidden_size // self.config.pretraining_tp, dim=1)
415
+ attn_output = sum([F.linear(attn_output[i], o_proj_slices[i]) for i in range(self.config.pretraining_tp)])
416
+ else:
417
+ attn_output = self.o_proj(attn_output)
418
+
419
+ if not output_attentions:
420
+ attn_weights = None
421
+
422
+ return attn_output, attn_weights, past_key_value
423
+
424
+
425
+ class LlamaFlashAttention2(LlamaAttention):
426
+ """
427
+ Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
428
+ untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
429
+ flash attention and deal with padding tokens in case the input contains any of them.
430
+ """
431
+
432
+ def forward(
433
+ self,
434
+ hidden_states: torch.Tensor,
435
+ attention_mask: Optional[torch.Tensor] = None,
436
+ position_ids: Optional[torch.LongTensor] = None,
437
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
438
+ output_attentions: bool = False,
439
+ use_cache: bool = False,
440
+ padding_mask: Optional[torch.LongTensor] = None,
441
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
442
+ # LlamaFlashAttention2 attention does not support output_attentions
443
+ output_attentions = False
444
+
445
+ bsz, q_len, _ = hidden_states.size()
446
+
447
+ query_states = self.q_proj(hidden_states)
448
+ key_states = self.k_proj(hidden_states)
449
+ value_states = self.v_proj(hidden_states)
450
+
451
+ # Flash attention requires the input to have the shape
452
+ # batch_size x seq_length x head_dime x hidden_dim
453
+ # therefore we just need to keep the original shape
454
+ query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
455
+ key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
456
+ value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
457
+
458
+ kv_seq_len = key_states.shape[-2]
459
+ if past_key_value is not None:
460
+ kv_seq_len += past_key_value[0].shape[-2]
461
+
462
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
463
+
464
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
465
+
466
+ if past_key_value is not None:
467
+ # reuse k, v, self_attention
468
+ key_states = torch.cat([past_key_value[0], key_states], dim=2)
469
+ value_states = torch.cat([past_key_value[1], value_states], dim=2)
470
+
471
+ past_key_value = (key_states, value_states) if use_cache else None
472
+
473
+ query_states = query_states.transpose(1, 2)
474
+ key_states = key_states.transpose(1, 2)
475
+ value_states = value_states.transpose(1, 2)
476
+
477
+ # TODO: llama does not have dropout in the config??
478
+ # It is recommended to use dropout with FA according to the docs
479
+ # when training.
480
+ dropout_rate = 0.0 # if not self.training else self.attn_dropout
481
+
482
+ # In PEFT, usually we cast the layer norms in float32 for training stability reasons
483
+ # therefore the input hidden states gets silently casted in float32. Hence, we need
484
+ # cast them back in float16 just to be sure everything works as expected.
485
+ # This might slowdown training & inference so it is recommended to not cast the LayerNorms
486
+ # in fp32. (LlamaRMSNorm handles it correctly)
487
+ input_dtype = query_states.dtype
488
+ if input_dtype == torch.float32:
489
+ logger.warning_once(
490
+ "The input hidden states seems to be silently casted in float32, this might be related to"
491
+ " the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
492
+ " float16."
493
+ )
494
+
495
+ query_states = query_states.to(torch.float16)
496
+ key_states = key_states.to(torch.float16)
497
+ value_states = value_states.to(torch.float16)
498
+
499
+ attn_output = self._flash_attention_forward(
500
+ query_states, key_states, value_states, padding_mask, q_len, dropout=dropout_rate
501
+ )
502
+
503
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
504
+ attn_output = self.o_proj(attn_output)
505
+
506
+ if not output_attentions:
507
+ attn_weights = None
508
+
509
+ return attn_output, attn_weights, past_key_value
510
+
511
+ def _flash_attention_forward(
512
+ self, query_states, key_states, value_states, padding_mask, query_length, dropout=0.0, softmax_scale=None
513
+ ):
514
+ """
515
+ Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
516
+ first unpad the input, then computes the attention scores and pad the final attention scores.
517
+
518
+ Args:
519
+ query_states (`torch.Tensor`):
520
+ Input query states to be passed to Flash Attention API
521
+ key_states (`torch.Tensor`):
522
+ Input key states to be passed to Flash Attention API
523
+ value_states (`torch.Tensor`):
524
+ Input value states to be passed to Flash Attention API
525
+ padding_mask (`torch.Tensor`):
526
+ The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
527
+ position of padding tokens and 1 for the position of non-padding tokens.
528
+ dropout (`int`, *optional*):
529
+ Attention dropout
530
+ softmax_scale (`float`, *optional*):
531
+ The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
532
+ """
533
+ # Contains at least one padding token in the sequence
534
+ if padding_mask is not None:
535
+ batch_size = query_states.shape[0]
536
+ query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
537
+ query_states, key_states, value_states, padding_mask, query_length
538
+ )
539
+
540
+ cu_seqlens_q, cu_seqlens_k = cu_seq_lens
541
+ max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
542
+
543
+ attn_output_unpad = flash_attn_varlen_func(
544
+ query_states,
545
+ key_states,
546
+ value_states,
547
+ cu_seqlens_q=cu_seqlens_q,
548
+ cu_seqlens_k=cu_seqlens_k,
549
+ max_seqlen_q=max_seqlen_in_batch_q,
550
+ max_seqlen_k=max_seqlen_in_batch_k,
551
+ dropout_p=dropout,
552
+ softmax_scale=softmax_scale,
553
+ causal=True,
554
+ )
555
+
556
+ attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
557
+ else:
558
+ attn_output = flash_attn_func(
559
+ query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=True
560
+ )
561
+
562
+ return attn_output
563
+
564
+ def _upad_input(self, query_layer, key_layer, value_layer, padding_mask, query_length):
565
+ indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(padding_mask)
566
+ batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
567
+
568
+ key_layer = index_first_axis(
569
+ key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
570
+ )
571
+ value_layer = index_first_axis(
572
+ value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
573
+ )
574
+ if query_length == kv_seq_len:
575
+ query_layer = index_first_axis(
576
+ query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
577
+ )
578
+ cu_seqlens_q = cu_seqlens_k
579
+ max_seqlen_in_batch_q = max_seqlen_in_batch_k
580
+ indices_q = indices_k
581
+ elif query_length == 1:
582
+ max_seqlen_in_batch_q = 1
583
+ cu_seqlens_q = torch.arange(
584
+ batch_size + 1, dtype=torch.int32, device=query_layer.device
585
+ ) # There is a memcpy here, that is very bad.
586
+ indices_q = cu_seqlens_q[:-1]
587
+ query_layer = query_layer.squeeze(1)
588
+ else:
589
+ # The -q_len: slice assumes left padding.
590
+ padding_mask = padding_mask[:, -query_length:]
591
+ query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, padding_mask)
592
+
593
+ return (
594
+ query_layer,
595
+ key_layer,
596
+ value_layer,
597
+ indices_q,
598
+ (cu_seqlens_q, cu_seqlens_k),
599
+ (max_seqlen_in_batch_q, max_seqlen_in_batch_k),
600
+ )
601
+
602
+
603
+ class LlamaDecoderLayer(nn.Module):
604
+ def __init__(self, config: LlamaConfig):
605
+ super().__init__()
606
+ self.hidden_size = config.hidden_size
607
+ self.self_attn = (
608
+ LlamaAttention(config=config)
609
+ if not getattr(config, "_flash_attn_2_enabled", False)
610
+ else LlamaFlashAttention2(config=config)
611
+ )
612
+ self.mlp = LlamaMLP(config)
613
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
614
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
615
+
616
+ def forward(
617
+ self,
618
+ hidden_states: torch.Tensor,
619
+ attention_mask: Optional[torch.Tensor] = None,
620
+ position_ids: Optional[torch.LongTensor] = None,
621
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
622
+ output_attentions: Optional[bool] = False,
623
+ use_cache: Optional[bool] = False,
624
+ padding_mask: Optional[torch.LongTensor] = None,
625
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
626
+ """
627
+ Args:
628
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
629
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
630
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
631
+ output_attentions (`bool`, *optional*):
632
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
633
+ returned tensors for more detail.
634
+ use_cache (`bool`, *optional*):
635
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
636
+ (see `past_key_values`).
637
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
638
+ """
639
+
640
+ residual = hidden_states
641
+
642
+ hidden_states = self.input_layernorm(hidden_states)
643
+
644
+ # Self Attention
645
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
646
+ hidden_states=hidden_states,
647
+ attention_mask=attention_mask,
648
+ position_ids=position_ids,
649
+ past_key_value=past_key_value,
650
+ output_attentions=output_attentions,
651
+ use_cache=use_cache,
652
+ padding_mask=padding_mask,
653
+ )
654
+ hidden_states = residual + hidden_states
655
+
656
+ # Fully Connected
657
+ residual = hidden_states
658
+ hidden_states = self.post_attention_layernorm(hidden_states)
659
+ hidden_states = self.mlp(hidden_states)
660
+ hidden_states = residual + hidden_states
661
+
662
+ outputs = (hidden_states,)
663
+
664
+ if output_attentions:
665
+ outputs += (self_attn_weights,)
666
+
667
+ if use_cache:
668
+ outputs += (present_key_value,)
669
+
670
+ return outputs
671
+
672
+
673
+ LLAMA_START_DOCSTRING = r"""
674
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
675
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
676
+ etc.)
677
+
678
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
679
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
680
+ and behavior.
681
+
682
+ Parameters:
683
+ config ([`LlamaConfig`]):
684
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
685
+ load the weights associated with the model, only the configuration. Check out the
686
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
687
+ """
688
+
689
+
690
+ @add_start_docstrings(
691
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
692
+ LLAMA_START_DOCSTRING,
693
+ )
694
+ class LlamaPreTrainedModel(PreTrainedModel):
695
+ config_class = LlamaConfig
696
+ base_model_prefix = "model"
697
+ supports_gradient_checkpointing = True
698
+ _no_split_modules = ["LlamaDecoderLayer"]
699
+ _skip_keys_device_placement = "past_key_values"
700
+ _supports_flash_attn_2 = True
701
+
702
+ def _init_weights(self, module):
703
+ std = self.config.initializer_range
704
+ if isinstance(module, nn.Linear):
705
+ module.weight.data.normal_(mean=0.0, std=std)
706
+ if module.bias is not None:
707
+ module.bias.data.zero_()
708
+ elif isinstance(module, nn.Embedding):
709
+ module.weight.data.normal_(mean=0.0, std=std)
710
+ if module.padding_idx is not None:
711
+ module.weight.data[module.padding_idx].zero_()
712
+
713
+ def _set_gradient_checkpointing(self, module, value=False):
714
+ if isinstance(module, LlamaModel):
715
+ module.gradient_checkpointing = value
716
+
717
+
718
+ LLAMA_INPUTS_DOCSTRING = r"""
719
+ Args:
720
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
721
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
722
+ it.
723
+
724
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
725
+ [`PreTrainedTokenizer.__call__`] for details.
726
+
727
+ [What are input IDs?](../glossary#input-ids)
728
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
729
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
730
+
731
+ - 1 for tokens that are **not masked**,
732
+ - 0 for tokens that are **masked**.
733
+
734
+ [What are attention masks?](../glossary#attention-mask)
735
+
736
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
737
+ [`PreTrainedTokenizer.__call__`] for details.
738
+
739
+ If `past_key_values` is used, optionally only the last `input_ids` have to be input (see
740
+ `past_key_values`).
741
+
742
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
743
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
744
+ information on the default strategy.
745
+
746
+ - 1 indicates the head is **not masked**,
747
+ - 0 indicates the head is **masked**.
748
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
749
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
750
+ config.n_positions - 1]`.
751
+
752
+ [What are position IDs?](../glossary#position-ids)
753
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
754
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
755
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
756
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
757
+
758
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
759
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
760
+
761
+ If `past_key_values` are used, the user can optionally input only the last `input_ids` (those that don't
762
+ have their past key value states given to this model) of shape `(batch_size, 1)` instead of all `input_ids`
763
+ of shape `(batch_size, sequence_length)`.
764
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
765
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
766
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
767
+ model's internal embedding lookup matrix.
768
+ use_cache (`bool`, *optional*):
769
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
770
+ `past_key_values`).
771
+ output_attentions (`bool`, *optional*):
772
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
773
+ tensors for more detail.
774
+ output_hidden_states (`bool`, *optional*):
775
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
776
+ more detail.
777
+ return_dict (`bool`, *optional*):
778
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
779
+ """
780
+
781
+
782
+ @add_start_docstrings(
783
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
784
+ LLAMA_START_DOCSTRING,
785
+ )
786
+ class LlamaModel(LlamaPreTrainedModel):
787
+ """
788
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
789
+
790
+ Args:
791
+ config: LlamaConfig
792
+ """
793
+
794
+ def __init__(self, config: LlamaConfig):
795
+ super().__init__(config)
796
+ self.padding_idx = config.pad_token_id
797
+ self.vocab_size = config.vocab_size
798
+
799
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
800
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
801
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
802
+
803
+ self.gradient_checkpointing = False
804
+ # Initialize weights and apply final processing
805
+ self.post_init()
806
+
807
+ def get_input_embeddings(self):
808
+ return self.embed_tokens
809
+
810
+ def set_input_embeddings(self, value):
811
+ self.embed_tokens = value
812
+
813
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
814
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
815
+ # create causal mask
816
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
817
+ combined_attention_mask = None
818
+ if input_shape[-1] > 1:
819
+ combined_attention_mask = _make_causal_mask(
820
+ input_shape,
821
+ inputs_embeds.dtype,
822
+ device=inputs_embeds.device,
823
+ past_key_values_length=past_key_values_length,
824
+ )
825
+
826
+ if attention_mask is not None:
827
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
828
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
829
+ inputs_embeds.device
830
+ )
831
+ combined_attention_mask = (
832
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
833
+ )
834
+
835
+ return combined_attention_mask
836
+
837
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
838
+ def forward(
839
+ self,
840
+ input_ids: torch.LongTensor = None,
841
+ attention_mask: Optional[torch.Tensor] = None,
842
+ position_ids: Optional[torch.LongTensor] = None,
843
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
844
+ inputs_embeds: Optional[torch.FloatTensor] = None,
845
+ use_cache: Optional[bool] = None,
846
+ output_attentions: Optional[bool] = None,
847
+ output_hidden_states: Optional[bool] = None,
848
+ return_dict: Optional[bool] = None,
849
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
850
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
851
+ output_hidden_states = (
852
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
853
+ )
854
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
855
+
856
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
857
+
858
+ # retrieve input_ids and inputs_embeds
859
+ if input_ids is not None and inputs_embeds is not None:
860
+ raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
861
+ elif input_ids is not None:
862
+ batch_size, seq_length = input_ids.shape
863
+ elif inputs_embeds is not None:
864
+ batch_size, seq_length, _ = inputs_embeds.shape
865
+ else:
866
+ raise ValueError("You have to specify either input_ids or inputs_embeds")
867
+
868
+ seq_length_with_past = seq_length
869
+ past_key_values_length = 0
870
+
871
+ if past_key_values is not None:
872
+ past_key_values_length = past_key_values[0][0].shape[2]
873
+ seq_length_with_past = seq_length_with_past + past_key_values_length
874
+
875
+ if position_ids is None:
876
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
877
+ position_ids = torch.arange(
878
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
879
+ )
880
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
881
+ else:
882
+ position_ids = position_ids.view(-1, seq_length).long()
883
+
884
+ if inputs_embeds is None:
885
+ inputs_embeds = self.embed_tokens(input_ids)
886
+ # embed positions
887
+ if attention_mask is None:
888
+ attention_mask = torch.ones(
889
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
890
+ )
891
+ padding_mask = None
892
+ else:
893
+ if 0 in attention_mask:
894
+ padding_mask = attention_mask
895
+ else:
896
+ padding_mask = None
897
+
898
+ attention_mask = self._prepare_decoder_attention_mask(
899
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
900
+ )
901
+
902
+ hidden_states = inputs_embeds
903
+
904
+ if self.gradient_checkpointing and self.training:
905
+ if use_cache:
906
+ logger.warning_once(
907
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
908
+ )
909
+ use_cache = False
910
+
911
+ # decoder layers
912
+ all_hidden_states = () if output_hidden_states else None
913
+ all_self_attns = () if output_attentions else None
914
+ next_decoder_cache = () if use_cache else None
915
+
916
+ for idx, decoder_layer in enumerate(self.layers):
917
+ if output_hidden_states:
918
+ all_hidden_states += (hidden_states,)
919
+
920
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
921
+
922
+ if self.gradient_checkpointing and self.training:
923
+
924
+ def create_custom_forward(module):
925
+ def custom_forward(*inputs):
926
+ # None for past_key_value
927
+ return module(*inputs, past_key_value, output_attentions, padding_mask=padding_mask)
928
+
929
+ return custom_forward
930
+
931
+ layer_outputs = torch.utils.checkpoint.checkpoint(
932
+ create_custom_forward(decoder_layer), hidden_states, attention_mask, position_ids
933
+ )
934
+ else:
935
+ layer_outputs = decoder_layer(
936
+ hidden_states,
937
+ attention_mask=attention_mask,
938
+ position_ids=position_ids,
939
+ past_key_value=past_key_value,
940
+ output_attentions=output_attentions,
941
+ use_cache=use_cache,
942
+ padding_mask=padding_mask,
943
+ )
944
+
945
+ hidden_states = layer_outputs[0]
946
+
947
+ if use_cache:
948
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
949
+
950
+ if output_attentions:
951
+ all_self_attns += (layer_outputs[1],)
952
+
953
+ hidden_states = self.norm(hidden_states)
954
+
955
+ # add hidden states from the last decoder layer
956
+ if output_hidden_states:
957
+ all_hidden_states += (hidden_states,)
958
+
959
+ next_cache = next_decoder_cache if use_cache else None
960
+ if not return_dict:
961
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
962
+ return BaseModelOutputWithPast(
963
+ last_hidden_state=hidden_states,
964
+ past_key_values=next_cache,
965
+ hidden_states=all_hidden_states,
966
+ attentions=all_self_attns,
967
+ )
968
+
969
+
970
+ class LlamaForCausalLM(LlamaPreTrainedModel):
971
+ _tied_weights_keys = ["lm_head.weight"]
972
+
973
+ def __init__(self, config):
974
+ super().__init__(config)
975
+ self.model = LlamaModel(config)
976
+ self.vocab_size = config.vocab_size
977
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
978
+
979
+ # Initialize weights and apply final processing
980
+ self.post_init()
981
+
982
+ def get_input_embeddings(self):
983
+ return self.model.embed_tokens
984
+
985
+ def set_input_embeddings(self, value):
986
+ self.model.embed_tokens = value
987
+
988
+ def get_output_embeddings(self):
989
+ return self.lm_head
990
+
991
+ def set_output_embeddings(self, new_embeddings):
992
+ self.lm_head = new_embeddings
993
+
994
+ def set_decoder(self, decoder):
995
+ self.model = decoder
996
+
997
+ def get_decoder(self):
998
+ return self.model
999
+
1000
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1001
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
1002
+ def forward(
1003
+ self,
1004
+ input_ids: torch.LongTensor = None,
1005
+ attention_mask: Optional[torch.Tensor] = None,
1006
+ position_ids: Optional[torch.LongTensor] = None,
1007
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1008
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1009
+ labels: Optional[torch.LongTensor] = None,
1010
+ use_cache: Optional[bool] = None,
1011
+ output_attentions: Optional[bool] = None,
1012
+ output_hidden_states: Optional[bool] = None,
1013
+ return_dict: Optional[bool] = None,
1014
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1015
+ r"""
1016
+ Args:
1017
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1018
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1019
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1020
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1021
+
1022
+ Returns:
1023
+
1024
+ Example:
1025
+
1026
+ ```python
1027
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1028
+
1029
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1030
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1031
+
1032
+ >>> prompt = "Hey, are you conscious? Can you talk to me?"
1033
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1034
+
1035
+ >>> # Generate
1036
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1037
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1038
+ "Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
1039
+ ```"""
1040
+
1041
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
1042
+ output_hidden_states = (
1043
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
1044
+ )
1045
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1046
+
1047
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1048
+ outputs = self.model(
1049
+ input_ids=input_ids,
1050
+ attention_mask=attention_mask,
1051
+ position_ids=position_ids,
1052
+ past_key_values=past_key_values,
1053
+ inputs_embeds=inputs_embeds,
1054
+ use_cache=use_cache,
1055
+ output_attentions=output_attentions,
1056
+ output_hidden_states=output_hidden_states,
1057
+ return_dict=return_dict,
1058
+ )
1059
+
1060
+ hidden_states = outputs[0]
1061
+ if self.config.pretraining_tp > 1:
1062
+ lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
1063
+ logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
1064
+ logits = torch.cat(logits, dim=-1)
1065
+ else:
1066
+ logits = self.lm_head(hidden_states)
1067
+ logits = logits.float()
1068
+
1069
+ loss = None
1070
+ if labels is not None:
1071
+ # Shift so that tokens < n predict n
1072
+ shift_logits = logits[..., :-1, :].contiguous()
1073
+ shift_labels = labels[..., 1:].contiguous()
1074
+ # Flatten the tokens
1075
+ loss_fct = CrossEntropyLoss()
1076
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1077
+ shift_labels = shift_labels.view(-1)
1078
+ # Enable model parallelism
1079
+ shift_labels = shift_labels.to(shift_logits.device)
1080
+ loss = loss_fct(shift_logits, shift_labels)
1081
+
1082
+ if not return_dict:
1083
+ output = (logits,) + outputs[1:]
1084
+ return (loss,) + output if loss is not None else output
1085
+
1086
+ return CausalLMOutputWithPast(
1087
+ loss=loss,
1088
+ logits=logits,
1089
+ past_key_values=outputs.past_key_values,
1090
+ hidden_states=outputs.hidden_states,
1091
+ attentions=outputs.attentions,
1092
+ )
1093
+
1094
+ def prepare_inputs_for_generation(
1095
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1096
+ ):
1097
+ if past_key_values:
1098
+ input_ids = input_ids[:, -1:]
1099
+
1100
+ position_ids = kwargs.get("position_ids", None)
1101
+ if attention_mask is not None and position_ids is None:
1102
+ # create position_ids on the fly for batch generation
1103
+ position_ids = attention_mask.long().cumsum(-1) - 1
1104
+ position_ids.masked_fill_(attention_mask == 0, 1)
1105
+ if past_key_values:
1106
+ position_ids = position_ids[:, -1].unsqueeze(-1)
1107
+
1108
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1109
+ if inputs_embeds is not None and past_key_values is None:
1110
+ model_inputs = {"inputs_embeds": inputs_embeds}
1111
+ else:
1112
+ model_inputs = {"input_ids": input_ids}
1113
+
1114
+ model_inputs.update(
1115
+ {
1116
+ "position_ids": position_ids,
1117
+ "past_key_values": past_key_values,
1118
+ "use_cache": kwargs.get("use_cache"),
1119
+ "attention_mask": attention_mask,
1120
+ }
1121
+ )
1122
+ return model_inputs
1123
+
1124
+ @staticmethod
1125
+ def _reorder_cache(past_key_values, beam_idx):
1126
+ reordered_past = ()
1127
+ for layer_past in past_key_values:
1128
+ reordered_past += (
1129
+ tuple(past_state.index_select(0, beam_idx.to(past_state.device)) for past_state in layer_past),
1130
+ )
1131
+ return reordered_past
1132
+
1133
+
1134
+ @add_start_docstrings(
1135
+ """
1136
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1137
+
1138
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1139
+ (e.g. GPT-2) do.
1140
+
1141
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1142
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1143
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1144
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1145
+ each row of the batch).
1146
+ """,
1147
+ LLAMA_START_DOCSTRING,
1148
+ )
1149
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1150
+ def __init__(self, config):
1151
+ super().__init__(config)
1152
+ self.num_labels = config.num_labels
1153
+ self.model = LlamaModel(config)
1154
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1155
+
1156
+ # Initialize weights and apply final processing
1157
+ self.post_init()
1158
+
1159
+ def get_input_embeddings(self):
1160
+ return self.model.embed_tokens
1161
+
1162
+ def set_input_embeddings(self, value):
1163
+ self.model.embed_tokens = value
1164
+
1165
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1166
+ def forward(
1167
+ self,
1168
+ input_ids: torch.LongTensor = None,
1169
+ attention_mask: Optional[torch.Tensor] = None,
1170
+ position_ids: Optional[torch.LongTensor] = None,
1171
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1172
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1173
+ labels: Optional[torch.LongTensor] = None,
1174
+ use_cache: Optional[bool] = None,
1175
+ output_attentions: Optional[bool] = None,
1176
+ output_hidden_states: Optional[bool] = None,
1177
+ return_dict: Optional[bool] = None,
1178
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1179
+ r"""
1180
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1181
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1182
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1183
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1184
+ """
1185
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1186
+
1187
+ transformer_outputs = self.model(
1188
+ input_ids,
1189
+ attention_mask=attention_mask,
1190
+ position_ids=position_ids,
1191
+ past_key_values=past_key_values,
1192
+ inputs_embeds=inputs_embeds,
1193
+ use_cache=use_cache,
1194
+ output_attentions=output_attentions,
1195
+ output_hidden_states=output_hidden_states,
1196
+ return_dict=return_dict,
1197
+ )
1198
+ hidden_states = transformer_outputs[0]
1199
+ logits = self.score(hidden_states)
1200
+
1201
+ if input_ids is not None:
1202
+ batch_size = input_ids.shape[0]
1203
+ else:
1204
+ batch_size = inputs_embeds.shape[0]
1205
+
1206
+ if self.config.pad_token_id is None and batch_size != 1:
1207
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1208
+ if self.config.pad_token_id is None:
1209
+ sequence_lengths = -1
1210
+ else:
1211
+ if input_ids is not None:
1212
+ sequence_lengths = (torch.eq(input_ids, self.config.pad_token_id).long().argmax(-1) - 1).to(
1213
+ logits.device
1214
+ )
1215
+ else:
1216
+ sequence_lengths = -1
1217
+
1218
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1219
+
1220
+ loss = None
1221
+ if labels is not None:
1222
+ labels = labels.to(logits.device)
1223
+ if self.config.problem_type is None:
1224
+ if self.num_labels == 1:
1225
+ self.config.problem_type = "regression"
1226
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1227
+ self.config.problem_type = "single_label_classification"
1228
+ else:
1229
+ self.config.problem_type = "multi_label_classification"
1230
+
1231
+ if self.config.problem_type == "regression":
1232
+ loss_fct = MSELoss()
1233
+ if self.num_labels == 1:
1234
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1235
+ else:
1236
+ loss = loss_fct(pooled_logits, labels)
1237
+ elif self.config.problem_type == "single_label_classification":
1238
+ loss_fct = CrossEntropyLoss()
1239
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1240
+ elif self.config.problem_type == "multi_label_classification":
1241
+ loss_fct = BCEWithLogitsLoss()
1242
+ loss = loss_fct(pooled_logits, labels)
1243
+ if not return_dict:
1244
+ output = (pooled_logits,) + transformer_outputs[1:]
1245
+ return ((loss,) + output) if loss is not None else output
1246
+
1247
+ return SequenceClassifierOutputWithPast(
1248
+ loss=loss,
1249
+ logits=pooled_logits,
1250
+ past_key_values=transformer_outputs.past_key_values,
1251
+ hidden_states=transformer_outputs.hidden_states,
1252
+ attentions=transformer_outputs.attentions,
1253
+ )
src/__init__.py ADDED
File without changes
src/inference.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """ Core mathematics for Additive Quantization (AQ): initialization, reconstruction and beam search"""
2
+ import random
3
+ from typing import List, Optional, Tuple, Union
4
+
5
+ import torch
6
+ import torch.nn as nn
7
+ import torch.nn.functional as F
8
+
9
+ from src.inference_kernels.router import forward_pass_quantized_linear
10
+ from src.utils import _dequantize_weight, ellipsis, get_int_dtype, unpack_int_data
11
+
12
+
13
+ class FinalizedQuantizedLinear(nn.Module):
14
+ def __init__(
15
+ self,
16
+ in_features: int,
17
+ out_features: int,
18
+ in_group_size: int,
19
+ out_group_size: int,
20
+ num_codebooks: int,
21
+ nbits_per_codebook: int,
22
+ bias=True,
23
+ device=None,
24
+ dtype=None,
25
+ ):
26
+ factory_kwargs = {"device": device, "dtype": dtype}
27
+ super().__init__()
28
+ self.in_features = in_features
29
+ self.out_features = out_features
30
+
31
+ assert self.in_features % in_group_size == 0
32
+ assert self.out_features % out_group_size == 0
33
+ num_out_groups = out_features // out_group_size
34
+ num_in_groups = in_features // in_group_size
35
+ self.out_group_size, self.in_group_size = out_group_size, in_group_size
36
+ self.num_codebooks = num_codebooks
37
+ self.nbits_per_codebook = nbits_per_codebook
38
+ self.codebook_size = 2**nbits_per_codebook
39
+
40
+ # CODES & CODEBOOKS
41
+ self.codebooks = nn.Parameter(
42
+ torch.empty((num_codebooks, self.codebook_size, out_group_size, in_group_size), **factory_kwargs),
43
+ requires_grad=True,
44
+ ) # [num_codebooks, codebook_size, out_group_size, in_group_size]
45
+ self.codes = nn.Parameter(
46
+ torch.empty(
47
+ (num_out_groups, num_in_groups, num_codebooks), device=device, dtype=get_int_dtype(nbits_per_codebook)
48
+ ),
49
+ requires_grad=False,
50
+ ) # [num_out_groups, num_in_groups, num_codebooks]
51
+
52
+ # SCALES
53
+ self.scales = nn.Parameter(
54
+ torch.empty((num_out_groups, 1, 1, 1), **factory_kwargs), requires_grad=True
55
+ ) # [num_out_groups, num_in_groups, 1, 1] if scale_nbits > 0 else [num_out_groups, 1, 1, 1]
56
+
57
+ # BIAS
58
+ if bias:
59
+ self.bias = nn.Parameter(torch.empty(out_features, **factory_kwargs))
60
+ else:
61
+ self.register_parameter("bias", None)
62
+
63
+ def forward(self, input: torch.Tensor) -> torch.Tensor:
64
+ return forward_pass_quantized_linear(input, self.codes, self.codebooks, self.scales, self.bias)
src/inference_kernels/router.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+
7
+ from src.inference_kernels.triton_kernel import aqlm_gemm_stupid as triton_gemm
8
+ from src.utils import _dequantize_weight, unpack_int_data
9
+
10
+
11
+ def forward_pass_quantized_linear(
12
+ input: torch.Tensor,
13
+ codes: torch.IntTensor,
14
+ codebooks: torch.Tensor,
15
+ scales: torch.Tensor,
16
+ bias: Optional[torch.Tensor],
17
+ ) -> torch.Tensor:
18
+ if input.is_cuda:
19
+ matmul_result = triton_gemm(input, codes, codebooks, scales)
20
+ if bias is not None:
21
+ matmul_result += bias
22
+ return matmul_result
23
+ else:
24
+ dequantized_weight = _dequantize_weight(
25
+ unpack_int_data(codes, codebooks.shape[0].bit_length() - 1),
26
+ codebooks,
27
+ scales,
28
+ )
29
+ return F.linear(input, dequantized_weight, bias)
src/inference_kernels/triton_kernel.py ADDED
@@ -0,0 +1,170 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ import triton
3
+ import triton.language as tl
4
+ from torch.autograd import Function
5
+
6
+
7
+ @triton.autotune(
8
+ configs=[
9
+ triton.Config({"UNUSED": 1}, num_stages=num_stages, num_warps=num_warps)
10
+ for num_stages in (1, 2, 3, 4, 5)
11
+ for num_warps in (1, 2, 4, 8)
12
+ ],
13
+ key=[
14
+ "in_features",
15
+ "out_features",
16
+ "num_codebooks",
17
+ "codebook_size",
18
+ "out_group_size",
19
+ "in_group_size",
20
+ "num_input_groups",
21
+ "num_input_groups_next_power_of_2",
22
+ "compute_in_fp32",
23
+ ],
24
+ )
25
+ @triton.jit
26
+ def _aqlm_gemv_simple(
27
+ input_vec_ptr,
28
+ output_vec_ptr,
29
+ codes_i16_ptr,
30
+ codebooks_ptr,
31
+ scales_ptr,
32
+ in_features: tl.constexpr,
33
+ out_features: tl.constexpr,
34
+ num_codebooks: tl.constexpr,
35
+ codebook_size: tl.constexpr,
36
+ out_group_size: tl.constexpr,
37
+ in_group_size: tl.constexpr,
38
+ num_input_groups: tl.constexpr,
39
+ num_input_groups_next_power_of_2: tl.constexpr,
40
+ compute_in_fp32: tl.constexpr,
41
+ UNUSED: tl.constexpr,
42
+ ):
43
+ # variables ending with "_i" mean "for i-th output unit"
44
+ pid = tl.program_id(axis=0) # [0, 1, ... {out_features-1}]
45
+
46
+ # Stage 1: load input data
47
+ input_vec = tl.load(
48
+ input_vec_ptr
49
+ + tl.arange(0, num_input_groups_next_power_of_2)[:, None, None] * in_group_size
50
+ + tl.arange(0, in_group_size)[None, None, :],
51
+ mask=tl.arange(0, num_input_groups_next_power_of_2)[:, None, None] < num_input_groups,
52
+ )
53
+ # [in_features//in_group_size, 1, group_size]
54
+ # Note: we could simply load input_vec then reshape
55
+ # input_vec = tl.load(input_vec_ptr + tl.arange(0, in_features)) # [in_features]
56
+ # input_vec = tl.view(input_vec, [num_input_groups, 1, in_group_size])
57
+ # , but this does not work because tl.view may reorder elements arbitrarily; see its docstring
58
+
59
+ # Stage 2: load integer codes for the active row
60
+ # [in_features // in_group_size, num_codebooks]
61
+ codes_i_ptrs = (
62
+ codes_i16_ptr
63
+ + pid * num_input_groups * num_codebooks
64
+ + tl.arange(0, num_input_groups_next_power_of_2)[:, None] * num_codebooks
65
+ + tl.arange(0, num_codebooks)[None, :]
66
+ )
67
+ codes_i_mask_1d = tl.arange(0, num_input_groups_next_power_of_2) < num_input_groups
68
+
69
+ codes_i = tl.load(codes_i_ptrs, mask=codes_i_mask_1d[:, None]) # [in_features//in_group_size, num_codebooks]
70
+ if codes_i.dtype == tl.int16:
71
+ codes_i = codes_i.to(tl.int32)
72
+ codes_i = (codes_i) + (codes_i < 0) * codebook_size # aka 2 ** nbits_per_codebook
73
+ # ^-- (because codes are int16 tensors that contain uint data)
74
+
75
+ # The following alternative does not work:
76
+ # codes_i = codes_i.to(tl.int32) % codebook_size # aka 2 ** nbits_per_codebook
77
+ else:
78
+ codes_i = codes_i.to(tl.int32)
79
+
80
+ # shift codes_i so that codebooks after 0th point to correct indices in codebooks_ptr
81
+ codes_i += tl.arange(0, num_codebooks)[None, :] * codebook_size # aka 2 ** nbits_per_codebook
82
+ # ^-- [in_group_size, num_codebooks]
83
+
84
+ # Stage 3: convert codes to pointers to every individual (activated) weight in codebooks
85
+ # [in_features // in_group_size, num_codebooks, out_group_size, in_group_size]
86
+ out_group_ix = tl.arange(0, out_group_size)[None, None, :, None]
87
+ in_group_ix = tl.arange(0, in_group_size)[None, None, None, :]
88
+ weight_i_ptrs = (
89
+ codebooks_ptr
90
+ + codes_i[:, :, None, None] * out_group_size * in_group_size
91
+ + out_group_ix * in_group_size
92
+ + in_group_ix
93
+ )
94
+
95
+ # Stage 4: reconstruct weights, multiply by inputs and write out
96
+ weights_i = tl.load(weight_i_ptrs, mask=codes_i_mask_1d[:, None, None, None], other=0)
97
+ if compute_in_fp32:
98
+ weights_i = weights_i.to(tl.float32)
99
+ input_vec = input_vec.to(tl.float32)
100
+ # ^-- [in_features // in_group_size, num_codebooks, out_group_size, in_group_size]
101
+ weights_i = tl.sum(weights_i, axis=1) # sum codebooks as per additive quantization
102
+ # ^-- [in_features // in_group_size, out_group_size, in_group_size]
103
+
104
+ if out_group_size == 1:
105
+ scale = tl.load(scales_ptr + pid).to(weights_i.dtype) # scalar
106
+ output_i = tl.sum(weights_i * input_vec) * scale
107
+ tl.store(output_vec_ptr + pid, output_i.to(input_vec.dtype))
108
+ else:
109
+ output_i = tl.sum(tl.sum(weights_i * input_vec, axis=2), axis=0) # [out_group_size]
110
+ output_i *= tl.load(scales_ptr + pid).to(weights_i.dtype)
111
+ tl.store(output_vec_ptr + pid * out_group_size + tl.arange(0, out_group_size), output_i.to(input_vec.dtype))
112
+
113
+
114
+ def next_power_of_2(x):
115
+ return 1 if x == 0 else 2 ** (x - 1).bit_length()
116
+
117
+
118
+ def aqlm_gemv_simple(
119
+ input_vec: torch.Tensor,
120
+ codes_i16: torch.ShortTensor,
121
+ codebooks: torch.Tensor,
122
+ scales: torch.Tensor,
123
+ compute_in_fp32: bool = True,
124
+ ):
125
+
126
+ device, dtype = codebooks.device, codebooks.dtype
127
+ num_codebooks, codebook_size, out_group_size, in_group_size = codebooks.shape
128
+ in_features = input_vec.shape[1]
129
+ out_features = codes_i16.shape[0] * out_group_size
130
+ num_input_groups = codes_i16.shape[1]
131
+ assert input_vec.ndim == 2 and input_vec.shape[0] == 1, "do reshape; now!"
132
+ assert scales.shape == (out_features // out_group_size, 1, 1, 1)
133
+ assert in_features % in_group_size == 0
134
+ assert codebooks.shape[1] == 2**16
135
+
136
+ output_vec = torch.empty(1, out_features, device=device, dtype=dtype)
137
+ # 1D launch kernel where each block computes output unit
138
+ grid = lambda META: (out_features // out_group_size,)
139
+ _aqlm_gemv_simple[grid](
140
+ input_vec,
141
+ output_vec,
142
+ codes_i16,
143
+ codebooks,
144
+ scales,
145
+ in_features,
146
+ out_features,
147
+ num_codebooks,
148
+ codebook_size,
149
+ out_group_size,
150
+ in_group_size,
151
+ num_input_groups,
152
+ next_power_of_2(num_input_groups),
153
+ compute_in_fp32,
154
+ )
155
+
156
+ return output_vec
157
+
158
+
159
+ def aqlm_gemm_stupid(
160
+ input: torch.Tensor,
161
+ codes_i16: torch.ShortTensor,
162
+ codebooks: torch.Tensor,
163
+ scales: torch.Tensor,
164
+ compute_in_fp32: bool = True,
165
+ ):
166
+ original_shape = input.shape
167
+ input = input.reshape(-1, original_shape[-1])
168
+ return torch.cat(
169
+ [aqlm_gemv_simple(input_vec.unsqueeze(0), codes_i16, codebooks, scales, compute_in_fp32) for input_vec in input]
170
+ ).reshape(original_shape[:-1] + (-1,))
src/utils.py ADDED
@@ -0,0 +1,159 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+
3
+ import contextlib
4
+ import functools
5
+ import os
6
+ from typing import Callable, Iterator, Optional, Sequence
7
+
8
+ import torch
9
+ import torch.nn.functional as F
10
+
11
+ ellipsis = type(...)
12
+
13
+
14
+ def get_mean_nbits_by_codebook(codes: torch.IntTensor, huffman_group_size: int = 2):
15
+
16
+ """
17
+ Calculates average code length in codebooks.
18
+ :param codes: codebook codes
19
+ :param huffman_group_size: huffman compresssion dimension count
20
+ """
21
+ import huffman
22
+
23
+ _, codebook_size, num_codebooks = codes.shape
24
+ flat_codes_by_codebook = codes.permute(2, 0, 1).flatten(1, 2)
25
+ code_counts = torch.zeros(
26
+ num_codebooks, codebook_size, device=flat_codes_by_codebook.device, dtype=flat_codes_by_codebook.dtype
27
+ ).scatter_add(
28
+ -1, flat_codes_by_codebook, torch.ones_like(flat_codes_by_codebook)
29
+ ) # shape: [current beam_size, num_codebooks, codebook_size], initial beam_size = 1
30
+ code_probs = code_counts / code_counts.sum(dim=-1, keepdim=True).float()
31
+ code_probs = code_probs.cpu().numpy()
32
+ assert num_codebooks % huffman_group_size == 0
33
+
34
+ mean_code_lengths = []
35
+ for group_index in range(num_codebooks // huffman_group_size):
36
+ group_code_probs = {(): 1}
37
+
38
+ for codebook_index in range(group_index * huffman_group_size, (group_index + 1) * huffman_group_size):
39
+ new_group_code_probs = {}
40
+ for group, group_prob in group_code_probs.items():
41
+ for code, code_prob in tuple(enumerate(code_probs[codebook_index])):
42
+ new_group_code_probs[group + (code,)] = group_prob * code_prob
43
+ group_code_probs = new_group_code_probs
44
+
45
+ huffman_codebook_i = huffman.codebook(list(group_code_probs.items()))
46
+ codebook_mean_code_length_i = sum(
47
+ len(huffman_codebook_i[code]) * prob for code, prob in group_code_probs.items()
48
+ )
49
+ mean_code_lengths.append(codebook_mean_code_length_i)
50
+ return mean_code_lengths
51
+
52
+
53
+ def get_int_dtype(nbits: int) -> torch.dtype:
54
+ if nbits <= 8:
55
+ return torch.int8
56
+ if nbits <= 16:
57
+ return torch.int16
58
+ if nbits <= 32:
59
+ return torch.int32
60
+ if nbits <= 64:
61
+ return torch.int64
62
+ raise ValueError(f"No dtype available for {nbits}-bit codebooks")
63
+
64
+
65
+ @torch.inference_mode()
66
+ def pack_int_data(data: torch.IntTensor, nbits: int) -> torch.IntTensor:
67
+ data[data >= 2 ** (nbits - 1)] -= 2**nbits
68
+ return data.to(get_int_dtype(nbits))
69
+
70
+
71
+ @torch.inference_mode()
72
+ def unpack_int_data(data: torch.IntTensor, nbits: int) -> torch.IntTensor:
73
+ return data.to(torch.int64) % (2**nbits)
74
+
75
+
76
+ @functools.lru_cache()
77
+ def maybe_script(fn: callable) -> callable:
78
+ """Apply torch.jit.script to function unless one is using TPU. TPU does not support torch.jit.script."""
79
+ using_tpu = bool(os.environ.get("TPU_NAME"))
80
+ # this is a reserved variable that must be set to TPU address (e.g. grpc://11.22.33.44:1337) for TPU to function
81
+ should_script = int(os.environ.get("AQ_USE_JIT", not using_tpu))
82
+ return torch.jit.script(fn) if should_script else fn
83
+
84
+
85
+ @contextlib.contextmanager
86
+ def using_tf32(enabled: bool):
87
+ was_cudnn = torch.backends.cudnn.allow_tf32
88
+ was_matmul = torch.backends.cuda.matmul.allow_tf32
89
+ torch.backends.cudnn.allow_tf32 = enabled
90
+ torch.backends.cuda.matmul.allow_tf32 = enabled
91
+ yield
92
+ torch.backends.cudnn.allow_tf32 = was_cudnn
93
+ torch.backends.cuda.matmul.allow_tf32 = was_matmul
94
+
95
+
96
+ def iterate_minibatches(
97
+ *tensors: torch.Tensor,
98
+ batch_size: int,
99
+ allow_incomplete: bool = True,
100
+ device: Optional[torch.device] = None,
101
+ callback: Callable[[Sequence[torch.Tensor]], Sequence[torch.Tensor]] = lambda x: x,
102
+ ) -> Iterator[Sequence[torch.Tensor]]:
103
+ """
104
+ Samples data points *forever*, in random order, with less overhead than DataLoader;
105
+ Adapted from https://github.com/stanis-morozov/unq/blob/master/lib/utils.py
106
+ probably implemented over9000 times in transformers, torch, etc
107
+ :param tensors: one or more tensors with the same 0-th dimension
108
+ :param batch_size: sample this many points with each yield
109
+ :param allow_incomplete: if True and if dataset size is not divisible by batch size, the last batch
110
+ may have less than :batch_size: samples to cover the entire dataset. If False, the last batch is dropped
111
+ :param callback: optional function to be called on each batch of tensors before it is yielded to the user
112
+ :returns: generates a tuple of minibatches from each tensor, same length as input *tensors
113
+ If a batch contains only one tensor, this function will yield a tensor (and not a tuple/list with one tensor)
114
+ """
115
+ num_samples = len(tensors[0])
116
+ assert all(len(x) == num_samples for x in tensors)
117
+ indices = torch.randperm(num_samples, device=tensors[0].device)
118
+ while True:
119
+ prev_batch = None
120
+ for batch_start in range(0, len(indices), batch_size):
121
+ if not allow_incomplete and batch_start + batch_size > len(indices):
122
+ break
123
+ batch_ix = indices[batch_start : batch_start + batch_size]
124
+ batch = callback(tuple(tensor[batch_ix].to(device, non_blocking=True) for tensor in tensors))
125
+ if prev_batch is not None:
126
+ yield prev_batch
127
+ prev_batch = batch if isinstance(batch, (list, tuple)) and len(tensors) > 1 else batch[0]
128
+ del batch
129
+ yield prev_batch
130
+
131
+
132
+ @maybe_script
133
+ def _dequantize_weight(
134
+ codes: torch.Tensor, codebooks: torch.Tensor, scales: Optional[torch.Tensor] = None
135
+ ) -> torch.Tensor:
136
+ """
137
+ Decode float weights from quantization codes. Differentiable.
138
+ :param codes: tensor of integer quantization codes, shape [*dims, num_out_groups, num_in_groups, num_codebooks]
139
+ :param codebooks: tensor of vectors for each quantization code, [num_codebooks, codebook_size, out_group_size, in_group_size]
140
+ :param scales: weight will be multiplied by this factor, must be broadcastble with [*dims, out_groups, num_in_groups, out_group_size, in_group_size]
141
+ :return: reconstructed weight tensor of shape [*dims, num_in_groups*group_size]
142
+ """
143
+ num_out_groups, num_in_groups, num_codebooks = codes.shape[-3:]
144
+ num_codebooks, codebook_size, out_group_size, in_group_size = codebooks.shape
145
+ out_features = num_out_groups * out_group_size
146
+ in_features = num_in_groups * in_group_size
147
+ codebook_offsets = torch.arange(
148
+ 0, num_codebooks * codebook_size, codebook_size, device=codes.device
149
+ ) # shape: [num_codebooks]
150
+ reconstructed_weight_flat = F.embedding_bag(
151
+ codes.flatten(0, -2) + codebook_offsets, codebooks.flatten(0, 1).flatten(-2, -1), mode="sum"
152
+ ) # [prod(dims) * num_out_groups * num_in_groups, out_group_size * in_group_size]
153
+
154
+ reconstructed_weight_groupwise = reconstructed_weight_flat.view(
155
+ list(codes.shape[:-3]) + [num_out_groups, num_in_groups, out_group_size, in_group_size]
156
+ )
157
+ if scales is not None:
158
+ reconstructed_weight_groupwise = reconstructed_weight_groupwise.mul(scales)
159
+ return reconstructed_weight_groupwise.swapaxes(-3, -2).reshape(list(codes.shape[:-3]) + [out_features, in_features])