bjoernp commited on
Commit
5da55ee
1 Parent(s): abe8251

Create modeling_bitllama.py

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