Nanobit commited on
Commit
b5aa8d8
·
unverified ·
2 Parent(s): 4d6490b 2a801b0

Merge pull request #169 from NanoCode012/feat/landmark

Browse files
README.md CHANGED
@@ -417,6 +417,8 @@ flash_attention: # require a100 for llama
417
  # whether to use scaled-dot-product attention
418
  # https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
419
  sdp_attention:
 
 
420
 
421
  # resume from a specific checkpoint dir
422
  resume_from_checkpoint:
 
417
  # whether to use scaled-dot-product attention
418
  # https://pytorch.org/docs/stable/generated/torch.nn.functional.scaled_dot_product_attention.html
419
  sdp_attention:
420
+ # Landmark attention (only llama)
421
+ landmark_attention:
422
 
423
  # resume from a specific checkpoint dir
424
  resume_from_checkpoint:
src/axolotl/monkeypatch/llama_landmark_attn.py ADDED
@@ -0,0 +1,1595 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # pylint: skip-file
2
+ # coding=utf-8
3
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
4
+ #
5
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
6
+ # and OPT implementations in this library. It has been modified from its
7
+ # original forms to accommodate minor architectural differences compared
8
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
9
+ #
10
+ # Licensed under the Apache License, Version 2.0 (the "License");
11
+ # you may not use this file except in compliance with the License.
12
+ # You may obtain a copy of the License at
13
+ #
14
+ # http://www.apache.org/licenses/LICENSE-2.0
15
+ #
16
+ # Unless required by applicable law or agreed to in writing, software
17
+ # distributed under the License is distributed on an "AS IS" BASIS,
18
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ # See the License for the specific language governing permissions and
20
+ # limitations under the License.
21
+ """
22
+ PyTorch LLaMA model.
23
+ Taken from https://github.com/epfml/landmark-attention/blob/main/llama/llama_mem.py and modified.
24
+ """
25
+ import math
26
+ from typing import List, Optional, Tuple, Union
27
+
28
+ import torch
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
32
+ from transformers.activations import ACT2FN
33
+ from transformers.modeling_outputs import (
34
+ BaseModelOutputWithPast,
35
+ CausalLMOutputWithPast,
36
+ SequenceClassifierOutputWithPast,
37
+ )
38
+ from transformers.modeling_utils import PreTrainedModel
39
+ from transformers.models.llama.configuration_llama import LlamaConfig
40
+ from transformers.utils import (
41
+ add_start_docstrings,
42
+ add_start_docstrings_to_model_forward,
43
+ logging,
44
+ replace_return_docstrings,
45
+ )
46
+
47
+ logger = logging.get_logger(__name__)
48
+
49
+ _CONFIG_FOR_DOC = "LlamaConfig"
50
+
51
+ MEM_TOKEN = "<landmark>" # nosec
52
+
53
+
54
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
55
+ def _make_causal_mask(
56
+ input_ids_shape: torch.Size,
57
+ dtype: torch.dtype,
58
+ device: torch.device,
59
+ past_key_values_length: int = 0,
60
+ ):
61
+ """
62
+ Make causal mask used for bi-directional self-attention.
63
+ """
64
+ bsz, tgt_len = input_ids_shape
65
+ mask = torch.full(
66
+ (tgt_len, tgt_len),
67
+ torch.tensor(torch.finfo(dtype).min, device=device),
68
+ device=device,
69
+ )
70
+ mask_cond = torch.arange(mask.size(-1), device=device)
71
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
72
+ mask = mask.to(dtype)
73
+
74
+ if past_key_values_length > 0:
75
+ mask = torch.cat(
76
+ [
77
+ torch.zeros(
78
+ tgt_len, past_key_values_length, dtype=dtype, device=device
79
+ ),
80
+ mask,
81
+ ],
82
+ dim=-1,
83
+ )
84
+ return mask[None, None, :, :].expand(
85
+ bsz, 1, tgt_len, tgt_len + past_key_values_length
86
+ )
87
+
88
+
89
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
90
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
91
+ """
92
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
93
+ """
94
+ bsz, src_len = mask.size()
95
+ tgt_len = tgt_len if tgt_len is not None else src_len
96
+
97
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
98
+
99
+ inverted_mask = 1.0 - expanded_mask
100
+
101
+ return inverted_mask.masked_fill(
102
+ inverted_mask.to(torch.bool), torch.finfo(dtype).min
103
+ )
104
+
105
+
106
+ class LlamaRMSNorm(nn.Module):
107
+ def __init__(self, hidden_size, eps=1e-6):
108
+ """
109
+ LlamaRMSNorm is equivalent to T5LayerNorm
110
+ """
111
+ super().__init__()
112
+ self.weight = nn.Parameter(torch.ones(hidden_size))
113
+ self.variance_epsilon = eps
114
+
115
+ def forward(self, hidden_states):
116
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
117
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
118
+
119
+ # convert into half-precision if necessary
120
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
121
+ hidden_states = hidden_states.to(self.weight.dtype)
122
+
123
+ return self.weight * hidden_states
124
+
125
+
126
+ class LlamaRotaryEmbedding(torch.nn.Module):
127
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
128
+ super().__init__()
129
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
130
+ self.register_buffer("inv_freq", inv_freq)
131
+
132
+ # Build here to make `torch.jit.trace` work.
133
+ self.max_seq_len_cached = max_position_embeddings
134
+ t = torch.arange(
135
+ self.max_seq_len_cached,
136
+ device=self.inv_freq.device,
137
+ dtype=self.inv_freq.dtype,
138
+ )
139
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
140
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
141
+ emb = torch.cat((freqs, freqs), dim=-1)
142
+ self.register_buffer(
143
+ "cos_cached", emb.cos()[None, None, :, :], persistent=False
144
+ )
145
+ self.register_buffer(
146
+ "sin_cached", emb.sin()[None, None, :, :], persistent=False
147
+ )
148
+
149
+ def forward(self, x, seq_len=None):
150
+ # x: [bs, num_attention_heads, seq_len, head_size]
151
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
152
+ if seq_len > self.max_seq_len_cached:
153
+ self.max_seq_len_cached = seq_len
154
+ t = torch.arange(
155
+ self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype
156
+ )
157
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
158
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
159
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
160
+ self.register_buffer(
161
+ "cos_cached", emb.cos()[None, None, :, :], persistent=False
162
+ )
163
+ self.register_buffer(
164
+ "sin_cached", emb.sin()[None, None, :, :], persistent=False
165
+ )
166
+ return (
167
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
168
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
169
+ )
170
+
171
+
172
+ def rotate_half(x):
173
+ """Rotates half the hidden dims of the input."""
174
+ x1 = x[..., : x.shape[-1] // 2]
175
+ x2 = x[..., x.shape[-1] // 2 :]
176
+ return torch.cat((-x2, x1), dim=-1)
177
+
178
+
179
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
180
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
181
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
182
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
183
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
184
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
185
+ if q is None:
186
+ q_embed = None
187
+ else:
188
+ q_embed = (q * cos) + (rotate_half(q) * sin)
189
+ k_embed = (k * cos) + (rotate_half(k) * sin)
190
+ return q_embed, k_embed
191
+
192
+
193
+ class LlamaMLP(nn.Module):
194
+ def __init__(
195
+ self,
196
+ hidden_size: int,
197
+ intermediate_size: int,
198
+ hidden_act: str,
199
+ ):
200
+ super().__init__()
201
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
202
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
203
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
204
+ self.act_fn = ACT2FN[hidden_act]
205
+
206
+ def forward(self, x):
207
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
208
+
209
+
210
+ class LandmarkGroupedSoftmaxFunction(torch.autograd.Function):
211
+ # Note that forward, setup_context, and backward are @staticmethods
212
+ @staticmethod
213
+ def forward(ctx, x, dim, mem_cnt, resp_mem_idx):
214
+ new_shape = list(x.shape)
215
+ new_shape[dim] = mem_cnt # max_mem_cnt.item()
216
+ max_by_group = x.new_zeros((*new_shape,))
217
+ max_by_group.scatter_reduce_(
218
+ src=x, index=resp_mem_idx, dim=dim, reduce="amax", include_self=False
219
+ )
220
+
221
+ maxes = torch.gather(max_by_group, dim, resp_mem_idx)
222
+ # x_exp = torch.exp(x - torch.where(torch.isinf(maxes), 0, maxes))
223
+ x_exp = torch.exp((x - maxes).to(torch.float32))
224
+
225
+ cumsum_by_group = torch.zeros_like(max_by_group, dtype=x_exp.dtype)
226
+
227
+ cumsum_by_group.scatter_add_(
228
+ dim,
229
+ resp_mem_idx,
230
+ x_exp,
231
+ )
232
+ denom = torch.gather(cumsum_by_group, dim, resp_mem_idx)
233
+
234
+ # probs = torch.where(denom < 0.5, 0, x_exp / denom)
235
+ probs = x_exp / denom
236
+
237
+ ctx.mem_cnt = mem_cnt
238
+ ctx.dim = dim
239
+ ctx.save_for_backward(resp_mem_idx, probs)
240
+
241
+ return probs
242
+
243
+ @staticmethod
244
+ def backward(ctx, grad_probs):
245
+ mem_cnt = ctx.mem_cnt
246
+ dim = ctx.dim
247
+ resp_mem_idx, probs = ctx.saved_tensors
248
+ grad_x = grad_dim = grad_mem_cnt = grad_resp_mem_idx = None
249
+
250
+ if ctx.needs_input_grad[0] or ctx.needs_input_grad[4]:
251
+ grad_pair = grad_probs * probs
252
+
253
+ new_shape = list(probs.shape)
254
+ new_shape[dim] = mem_cnt # max_mem_cnt.item()
255
+ cumsum_by_group = grad_pair.new_zeros((*new_shape,))
256
+ cumsum_by_group.scatter_add_(dim, resp_mem_idx, grad_pair)
257
+
258
+ if ctx.needs_input_grad[0]:
259
+ grad_sum = torch.gather(cumsum_by_group, dim, resp_mem_idx)
260
+ grad_x = grad_pair - probs * grad_sum
261
+ assert not ctx.needs_input_grad[1]
262
+ assert not ctx.needs_input_grad[2]
263
+ assert not ctx.needs_input_grad[3]
264
+
265
+ return grad_x, grad_dim, grad_mem_cnt, grad_resp_mem_idx
266
+
267
+
268
+ def landmark_grouped_softmax(x, dim, is_mem, last_section_mask):
269
+ last_and_rest_mask = last_section_mask # | mask
270
+
271
+ full_access_mask = is_mem | last_and_rest_mask
272
+
273
+ max_mem_cnt = 16
274
+ mem_group_idx = torch.cumsum(is_mem, dim=dim)
275
+ mem_bucket_id = max_mem_cnt - 1
276
+ resp_mem_idx = torch.where(
277
+ last_and_rest_mask,
278
+ max_mem_cnt - 1,
279
+ torch.where(is_mem, mem_bucket_id, mem_group_idx),
280
+ )
281
+ probs = LandmarkGroupedSoftmaxFunction.apply(x, dim, max_mem_cnt, resp_mem_idx)
282
+
283
+ new_shape = list(x.shape)
284
+ new_shape[dim] = max_mem_cnt
285
+ group_prob = probs.new_zeros((*new_shape,))
286
+ group_prob.scatter_(
287
+ dim, torch.where(is_mem, mem_group_idx - 1, max_mem_cnt - 1), probs
288
+ )
289
+ probs = probs.mul(
290
+ torch.where(
291
+ full_access_mask,
292
+ last_section_mask,
293
+ torch.gather(group_prob, dim, resp_mem_idx),
294
+ )
295
+ )
296
+
297
+ return probs
298
+
299
+
300
+ class LlamaAttention(nn.Module):
301
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
302
+
303
+ def __init__(self, config: LlamaConfig):
304
+ super().__init__()
305
+ self.config = config
306
+ self.hidden_size = config.hidden_size
307
+ self.num_heads = config.num_attention_heads
308
+ self.head_dim = self.hidden_size // self.num_heads
309
+ self.max_position_embeddings = config.max_position_embeddings
310
+
311
+ if (self.head_dim * self.num_heads) != self.hidden_size:
312
+ raise ValueError(
313
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
314
+ f" and `num_heads`: {self.num_heads})."
315
+ )
316
+ self.q_proj = nn.Linear(
317
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
318
+ )
319
+ self.k_proj = nn.Linear(
320
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
321
+ )
322
+ self.v_proj = nn.Linear(
323
+ self.hidden_size, self.num_heads * self.head_dim, bias=False
324
+ )
325
+ self.o_proj = nn.Linear(
326
+ self.num_heads * self.head_dim, self.hidden_size, bias=False
327
+ )
328
+ self.rotary_emb = LlamaRotaryEmbedding(
329
+ self.head_dim, max_position_embeddings=self.max_position_embeddings
330
+ )
331
+
332
+ self.mem_freq = None
333
+ self.top_k = None
334
+ self.max_cache_size = None
335
+
336
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
337
+ return (
338
+ tensor.view(bsz, seq_len, self.num_heads, self.head_dim)
339
+ .transpose(1, 2)
340
+ .contiguous()
341
+ )
342
+
343
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
344
+ self.mem_freq = mem_freq
345
+ self.top_k = top_k
346
+ self.max_cache_size = max_cache_size
347
+
348
+ def forward(
349
+ self,
350
+ hidden_states: torch.Tensor,
351
+ attention_mask: Optional[torch.Tensor] = None,
352
+ position_ids: Optional[torch.LongTensor] = None,
353
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
354
+ output_attentions: bool = False,
355
+ use_cache: bool = False,
356
+ is_mem: Optional[torch.Tensor] = None,
357
+ last_section_mask: Optional[torch.Tensor] = None,
358
+ offload_cache_to_cpu: bool = False,
359
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
360
+ bsz, q_len, _ = hidden_states.size()
361
+
362
+ query_states = (
363
+ self.q_proj(hidden_states)
364
+ .view(bsz, q_len, self.num_heads, self.head_dim)
365
+ .transpose(1, 2)
366
+ )
367
+ key_states = (
368
+ self.k_proj(hidden_states)
369
+ .view(bsz, q_len, self.num_heads, self.head_dim)
370
+ .transpose(1, 2)
371
+ )
372
+ value_states = (
373
+ self.v_proj(hidden_states)
374
+ .view(bsz, q_len, self.num_heads, self.head_dim)
375
+ .transpose(1, 2)
376
+ )
377
+
378
+ kv_seq_len = key_states.shape[-2]
379
+ if past_key_value is not None:
380
+ kv_seq_len += past_key_value[0].shape[-2]
381
+ if len(past_key_value) > 2:
382
+ kv_seq_len += past_key_value[3].shape[2] * past_key_value[3].shape[3]
383
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
384
+ key_states_before_pos = key_states
385
+ query_states, key_states = apply_rotary_pos_emb(
386
+ query_states, key_states, cos, sin, position_ids
387
+ )
388
+ # [bsz, nh, t, hd]
389
+
390
+ attn_prefix = None
391
+ if past_key_value is not None:
392
+ # reuse k, v, self_attention
393
+ if self.mem_freq is None:
394
+ cache_len = past_key_value[0].shape[2]
395
+ if self.max_cache_size is not None:
396
+ cache_len = min(cache_len, self.max_cache_size)
397
+ if is_mem is not None:
398
+ is_mem = torch.cat(
399
+ (is_mem.new_zeros((1, 1, q_len, cache_len)), is_mem), dim=-1
400
+ )
401
+ last_section_mask = torch.cat(
402
+ (
403
+ last_section_mask.new_ones((1, 1, q_len, cache_len)),
404
+ last_section_mask,
405
+ ),
406
+ dim=-1,
407
+ )
408
+
409
+ past_key_states = torch.cat([past_key_value[0], key_states], dim=2)
410
+ past_value_states = torch.cat([past_key_value[1], value_states], dim=2)
411
+ key_states = past_key_states[:, :, -(q_len + cache_len) :]
412
+ value_states = past_value_states[:, :, -(q_len + cache_len) :]
413
+ expected_att_size = (bsz, self.num_heads, q_len, cache_len + q_len)
414
+ else:
415
+ orig_value_states = value_states
416
+
417
+ incomplete_len = past_key_value[0].shape[2] % (self.mem_freq + 1)
418
+ full_len = past_key_value[0].shape[2] - incomplete_len
419
+ past_key_mem, past_key_incomplete = torch.split(
420
+ past_key_value[0], (full_len, incomplete_len), dim=2
421
+ )
422
+ past_value_mem, past_value_incomplete = torch.split(
423
+ past_key_value[1], (full_len, incomplete_len), dim=2
424
+ )
425
+
426
+ if offload_cache_to_cpu:
427
+ past_key_value = (
428
+ past_key_incomplete,
429
+ past_value_incomplete,
430
+ *past_key_value[2:],
431
+ )
432
+
433
+ if incomplete_len > 0:
434
+ assert q_len + incomplete_len <= (self.mem_freq + 1)
435
+ is_mem = torch.cat(
436
+ (is_mem.new_zeros((1, 1, q_len, incomplete_len)), is_mem), dim=-1
437
+ )
438
+ last_section_mask = torch.cat(
439
+ (
440
+ last_section_mask.new_ones((1, 1, q_len, incomplete_len)),
441
+ last_section_mask,
442
+ ),
443
+ dim=-1,
444
+ )
445
+
446
+ if len(past_key_value) > 2:
447
+ full_len += past_key_value[3].shape[2] * past_key_value[3].shape[3]
448
+ past_key_incomplete_pos = torch.arange(
449
+ full_len,
450
+ full_len + incomplete_len,
451
+ dtype=torch.long,
452
+ device=position_ids.device,
453
+ ).unsqueeze(0)
454
+ _, past_key_incomplete = apply_rotary_pos_emb(
455
+ None, past_key_incomplete, cos, sin, past_key_incomplete_pos
456
+ )
457
+ key_states = torch.cat((past_key_incomplete, key_states), dim=2)
458
+ value_states = torch.cat((past_value_incomplete, value_states), dim=2)
459
+
460
+ past_key_mem = past_key_mem.view(
461
+ bsz, self.num_heads, -1, self.mem_freq + 1, self.head_dim
462
+ )
463
+ past_value_mem = past_value_mem.view(
464
+ bsz, self.num_heads, -1, self.mem_freq + 1, self.head_dim
465
+ )
466
+
467
+ if len(past_key_value) > 2:
468
+ mem_key_nopos = torch.cat(
469
+ (
470
+ past_key_value[2],
471
+ past_key_mem.select(dim=3, index=self.mem_freq),
472
+ ),
473
+ dim=2,
474
+ )
475
+ past_key_mem_offload = past_key_value[3]
476
+ past_key_mem = torch.cat(
477
+ (
478
+ past_key_mem_offload,
479
+ past_key_mem.to(past_key_mem_offload.device),
480
+ ),
481
+ dim=2,
482
+ )
483
+ past_value_mem = torch.cat(
484
+ (
485
+ past_key_value[4],
486
+ past_value_mem.to(past_key_mem_offload.device),
487
+ ),
488
+ dim=2,
489
+ )
490
+ else:
491
+ mem_key_nopos = past_key_mem.select(dim=3, index=self.mem_freq)
492
+
493
+ num_mems = past_key_mem.shape[2]
494
+ top_k = min(self.top_k, num_mems)
495
+ prefix_len = full_len - (top_k + 1) * (self.mem_freq + 1)
496
+ mem_indices = torch.cat(
497
+ (
498
+ position_ids.new_zeros((max(0, num_mems - top_k),)),
499
+ torch.arange(
500
+ 1,
501
+ top_k + 1,
502
+ device=query_states.device,
503
+ dtype=position_ids.dtype,
504
+ ),
505
+ ),
506
+ dim=0,
507
+ )
508
+ mem_pos = (mem_indices * (self.mem_freq + 1) + self.mem_freq).unsqueeze(
509
+ 0
510
+ ).expand(bsz, -1) + prefix_len
511
+ _, mem_key = apply_rotary_pos_emb(
512
+ None, mem_key_nopos, cos, sin, mem_pos
513
+ )
514
+ mem_attn_weights = torch.matmul(
515
+ query_states, mem_key.transpose(2, 3)
516
+ ) / math.sqrt(self.head_dim)
517
+
518
+ if offload_cache_to_cpu:
519
+ aggregate = "max_over_tokens"
520
+ else:
521
+ aggregate = None
522
+ if aggregate == "max_over_tokens":
523
+ token_retrievers = 1
524
+ head_retrievers = self.num_heads
525
+ mem_attn_weights = torch.nn.functional.softmax(
526
+ mem_attn_weights, dim=-1
527
+ )
528
+ mem_attn_weights = mem_attn_weights.amax(dim=2, keepdim=True)
529
+ elif aggregate is None:
530
+ token_retrievers = q_len
531
+ head_retrievers = self.num_heads
532
+ else:
533
+ raise NotImplementedError()
534
+
535
+ mem_selected_idx = (
536
+ mem_attn_weights.topk(dim=-1, k=top_k)[1]
537
+ .sort(dim=-1)[0]
538
+ .view(bsz, head_retrievers, token_retrievers, top_k)
539
+ )
540
+
541
+ selected_indices = torch.arange(
542
+ 0,
543
+ top_k * (self.mem_freq + 1),
544
+ device=query_states.device,
545
+ dtype=position_ids.dtype,
546
+ )
547
+ selected_indices = torch.where(
548
+ mem_selected_idx >= num_mems - top_k, self.mem_freq + 1, 0
549
+ ).unsqueeze(-1) + selected_indices.view(
550
+ 1, 1, 1, top_k, self.mem_freq + 1
551
+ )
552
+ selected_indices = (
553
+ selected_indices.view(
554
+ bsz, head_retrievers, token_retrievers, -1
555
+ ).expand(bsz, self.num_heads, q_len, -1)
556
+ + prefix_len
557
+ )
558
+
559
+ mem_selected_idx = mem_selected_idx.to(past_key_mem.device)
560
+
561
+ mem_selected_idx = mem_selected_idx.view(
562
+ bsz, self.num_heads, token_retrievers, top_k, 1, 1
563
+ ).expand(
564
+ bsz,
565
+ self.num_heads,
566
+ token_retrievers,
567
+ top_k,
568
+ self.mem_freq + 1,
569
+ self.head_dim,
570
+ )
571
+ selected_keys = past_key_mem.unsqueeze(2).expand(
572
+ bsz,
573
+ self.num_heads,
574
+ token_retrievers,
575
+ -1,
576
+ self.mem_freq + 1,
577
+ self.head_dim,
578
+ )
579
+ selected_keys = selected_keys.take_along_dim(
580
+ mem_selected_idx, dim=3
581
+ ).to(query_states.device)
582
+ selected_values = (
583
+ past_value_mem.unsqueeze(2)
584
+ .expand(
585
+ bsz,
586
+ self.num_heads,
587
+ token_retrievers,
588
+ -1,
589
+ self.mem_freq + 1,
590
+ self.head_dim,
591
+ )
592
+ .take_along_dim(mem_selected_idx, dim=3)
593
+ .to(query_states.device)
594
+ )
595
+
596
+ selected_keys = selected_keys.view(
597
+ bsz, self.num_heads, token_retrievers, -1, self.head_dim
598
+ ).expand(bsz, self.num_heads, q_len, -1, self.head_dim)
599
+ selected_keys = apply_rotary_pos_emb(
600
+ None, selected_keys.unsqueeze(1), cos, sin, selected_indices
601
+ )[1].squeeze(1)
602
+ selected_values = selected_values.view(
603
+ bsz, self.num_heads, token_retrievers, -1, self.head_dim
604
+ ).expand(bsz, self.num_heads, q_len, -1, self.head_dim)
605
+ attn_prefix = torch.matmul(
606
+ query_states.unsqueeze(3), selected_keys.transpose(3, 4)
607
+ ).squeeze(3) / math.sqrt(self.head_dim)
608
+ is_mem_prefix = (
609
+ torch.cat(
610
+ (is_mem.new_zeros((self.mem_freq,)), is_mem.new_ones((1,)))
611
+ )
612
+ .unsqueeze(0)
613
+ .repeat((top_k, 1))
614
+ )
615
+ is_mem_prefix = is_mem_prefix.view(1, 1, 1, -1).expand(1, 1, q_len, -1)
616
+ is_mem = torch.cat((is_mem_prefix, is_mem), dim=-1)
617
+ last_section_mask = torch.cat(
618
+ (
619
+ last_section_mask.new_zeros(
620
+ (1, 1, q_len, top_k * (self.mem_freq + 1))
621
+ ),
622
+ last_section_mask,
623
+ ),
624
+ dim=-1,
625
+ )
626
+ expected_att_size = (bsz, self.num_heads, q_len, q_len + incomplete_len)
627
+
628
+ past_key_states = torch.cat(
629
+ [past_key_value[0], key_states_before_pos], dim=2
630
+ )
631
+ past_value_states = torch.cat(
632
+ [past_key_value[1], orig_value_states], dim=2
633
+ )
634
+
635
+ if offload_cache_to_cpu:
636
+ past_key_value = (
637
+ (
638
+ past_key_states,
639
+ past_value_states,
640
+ mem_key_nopos,
641
+ past_key_mem.to("cpu"),
642
+ past_value_mem.to("cpu"),
643
+ *past_key_value[5:],
644
+ )
645
+ if use_cache
646
+ else None
647
+ )
648
+ else:
649
+ past_key_value = (
650
+ (past_key_states, past_value_states) if use_cache else None
651
+ )
652
+
653
+ else:
654
+ if self.mem_freq is None:
655
+ past_key_states = key_states
656
+ else:
657
+ past_key_states = key_states_before_pos
658
+ past_value_states = value_states
659
+ expected_att_size = (bsz, self.num_heads, q_len, kv_seq_len)
660
+ past_key_value = (past_key_states, past_value_states) if use_cache else None
661
+
662
+ attn_weights = torch.matmul(
663
+ query_states, key_states.transpose(2, 3)
664
+ ) / math.sqrt(self.head_dim)
665
+ if attn_weights.size() != expected_att_size:
666
+ raise ValueError(
667
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
668
+ f" {attn_weights.size()}"
669
+ )
670
+
671
+ if attention_mask is not None:
672
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
673
+ raise ValueError(
674
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
675
+ )
676
+ attn_weights = attn_weights + attention_mask[..., -attn_weights.shape[-1] :]
677
+ attn_weights = torch.max(
678
+ attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min)
679
+ )
680
+ if attn_prefix is not None:
681
+ attn_weights = torch.cat((attn_prefix, attn_weights), dim=-1)
682
+ # upcast attention to fp32
683
+ if is_mem is None:
684
+ raise ValueError("Don't use this without landmarks")
685
+ # attn_weights = nn.functional.softmax(
686
+ # attn_weights, dim=-1, dtype=torch.float32
687
+ # ).to(query_states.dtype)
688
+ else:
689
+ attn_weights = landmark_grouped_softmax(
690
+ attn_weights,
691
+ dim=-1,
692
+ is_mem=is_mem.expand(-1, self.num_heads, -1, -1),
693
+ last_section_mask=last_section_mask,
694
+ ).to(query_states.dtype)
695
+ if attn_prefix is not None:
696
+ attn_prefix, attn_weights = torch.split(
697
+ attn_weights,
698
+ (attn_prefix.shape[-1], attn_weights.shape[-1] - attn_prefix.shape[-1]),
699
+ dim=-1,
700
+ )
701
+ attn_output = torch.matmul(attn_weights, value_states)
702
+ if attn_prefix is not None:
703
+ attn_output += torch.matmul(
704
+ attn_prefix.unsqueeze(3), selected_values
705
+ ).squeeze(3)
706
+
707
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
708
+ raise ValueError(
709
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
710
+ f" {attn_output.size()}"
711
+ )
712
+
713
+ attn_output = attn_output.transpose(1, 2)
714
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
715
+
716
+ attn_output = self.o_proj(attn_output)
717
+
718
+ if not output_attentions:
719
+ attn_weights = None
720
+
721
+ return attn_output, attn_weights, past_key_value
722
+
723
+
724
+ class LlamaDecoderLayer(nn.Module):
725
+ def __init__(self, config: LlamaConfig):
726
+ super().__init__()
727
+ self.hidden_size = config.hidden_size
728
+ self.self_attn = LlamaAttention(config=config)
729
+ self.mlp = LlamaMLP(
730
+ hidden_size=self.hidden_size,
731
+ intermediate_size=config.intermediate_size,
732
+ hidden_act=config.hidden_act,
733
+ )
734
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
735
+ self.post_attention_layernorm = LlamaRMSNorm(
736
+ config.hidden_size, eps=config.rms_norm_eps
737
+ )
738
+
739
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
740
+ self.self_attn.set_mem_cache_args(mem_freq, top_k, max_cache_size)
741
+
742
+ def forward(
743
+ self,
744
+ hidden_states: torch.Tensor,
745
+ attention_mask: Optional[torch.Tensor] = None,
746
+ position_ids: Optional[torch.LongTensor] = None,
747
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
748
+ output_attentions: Optional[bool] = False,
749
+ use_cache: Optional[bool] = False,
750
+ is_mem: Optional[torch.Tensor] = None,
751
+ last_section_mask: Optional[torch.Tensor] = None,
752
+ offload_cache_to_cpu: bool = False,
753
+ ) -> Tuple[
754
+ torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]
755
+ ]:
756
+ """
757
+ Args:
758
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
759
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
760
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
761
+ output_attentions (`bool`, *optional*):
762
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
763
+ returned tensors for more detail.
764
+ use_cache (`bool`, *optional*):
765
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
766
+ (see `past_key_values`).
767
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
768
+ """
769
+
770
+ residual = hidden_states
771
+
772
+ hidden_states = self.input_layernorm(hidden_states)
773
+
774
+ # Self Attention
775
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
776
+ hidden_states=hidden_states,
777
+ attention_mask=attention_mask,
778
+ position_ids=position_ids,
779
+ past_key_value=past_key_value,
780
+ output_attentions=output_attentions,
781
+ use_cache=use_cache,
782
+ is_mem=is_mem,
783
+ last_section_mask=last_section_mask,
784
+ offload_cache_to_cpu=offload_cache_to_cpu,
785
+ )
786
+ hidden_states = residual + hidden_states
787
+
788
+ # Fully Connected
789
+ residual = hidden_states
790
+ hidden_states = self.post_attention_layernorm(hidden_states)
791
+ hidden_states = self.mlp(hidden_states)
792
+ hidden_states = residual + hidden_states
793
+
794
+ outputs = (hidden_states,)
795
+
796
+ if output_attentions:
797
+ outputs += (self_attn_weights,)
798
+
799
+ if use_cache:
800
+ outputs += (present_key_value,)
801
+
802
+ return outputs
803
+
804
+
805
+ LLAMA_START_DOCSTRING = r"""
806
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
807
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
808
+ etc.)
809
+
810
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
811
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
812
+ and behavior.
813
+
814
+ Parameters:
815
+ config ([`LlamaConfig`]):
816
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
817
+ load the weights associated with the model, only the configuration. Check out the
818
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
819
+ """
820
+
821
+
822
+ @add_start_docstrings(
823
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
824
+ LLAMA_START_DOCSTRING,
825
+ )
826
+ class LlamaPreTrainedModel(PreTrainedModel):
827
+ config_class = LlamaConfig
828
+ base_model_prefix = "model"
829
+ supports_gradient_checkpointing = True
830
+ _no_split_modules = ["LlamaDecoderLayer"]
831
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
832
+
833
+ def _init_weights(self, module):
834
+ std = self.config.initializer_range
835
+ if isinstance(module, nn.Linear):
836
+ module.weight.data.normal_(mean=0.0, std=std)
837
+ if module.bias is not None:
838
+ module.bias.data.zero_()
839
+ elif isinstance(module, nn.Embedding):
840
+ module.weight.data.normal_(mean=0.0, std=std)
841
+ if module.padding_idx is not None:
842
+ module.weight.data[module.padding_idx].zero_()
843
+
844
+ def _set_gradient_checkpointing(self, module, value=False):
845
+ if isinstance(module, LlamaModel):
846
+ module.gradient_checkpointing = value
847
+
848
+
849
+ LLAMA_INPUTS_DOCSTRING = r"""
850
+ Args:
851
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
852
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
853
+ it.
854
+
855
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
856
+ [`PreTrainedTokenizer.__call__`] for details.
857
+
858
+ [What are input IDs?](../glossary#input-ids)
859
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
860
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
861
+
862
+ - 1 for tokens that are **not masked**,
863
+ - 0 for tokens that are **masked**.
864
+
865
+ [What are attention masks?](../glossary#attention-mask)
866
+
867
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
868
+ [`PreTrainedTokenizer.__call__`] for details.
869
+
870
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
871
+ `past_key_values`).
872
+
873
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
874
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
875
+ information on the default strategy.
876
+
877
+ - 1 indicates the head is **not masked**,
878
+ - 0 indicates the head is **masked**.
879
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
880
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
881
+ config.n_positions - 1]`.
882
+
883
+ [What are position IDs?](../glossary#position-ids)
884
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
885
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
886
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
887
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
888
+
889
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
890
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
891
+
892
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
893
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
894
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
895
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
896
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
897
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
898
+ model's internal embedding lookup matrix.
899
+ use_cache (`bool`, *optional*):
900
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
901
+ `past_key_values`).
902
+ output_attentions (`bool`, *optional*):
903
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
904
+ tensors for more detail.
905
+ output_hidden_states (`bool`, *optional*):
906
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
907
+ more detail.
908
+ return_dict (`bool`, *optional*):
909
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
910
+ """
911
+
912
+
913
+ @add_start_docstrings(
914
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
915
+ LLAMA_START_DOCSTRING,
916
+ )
917
+ class LlamaModel(LlamaPreTrainedModel):
918
+ """
919
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
920
+
921
+ Args:
922
+ config: LlamaConfig
923
+ """
924
+
925
+ def __init__(self, config: LlamaConfig):
926
+ super().__init__(config)
927
+ self.padding_idx = config.pad_token_id
928
+ self.vocab_size = config.vocab_size
929
+
930
+ self.embed_tokens = nn.Embedding(
931
+ config.vocab_size, config.hidden_size, self.padding_idx
932
+ )
933
+ self.layers = nn.ModuleList(
934
+ [LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)]
935
+ )
936
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
937
+
938
+ self.mem_id = None
939
+
940
+ self.gradient_checkpointing = False
941
+ # Initialize weights and apply final processing
942
+ self.post_init()
943
+
944
+ def get_input_embeddings(self):
945
+ return self.embed_tokens
946
+
947
+ def set_input_embeddings(self, value):
948
+ self.embed_tokens = value
949
+
950
+ def set_mem_id(self, mem_id):
951
+ self.mem_id = mem_id
952
+
953
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
954
+ for layer in self.layers:
955
+ layer.set_mem_cache_args(mem_freq, top_k, max_cache_size)
956
+
957
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
958
+ def _prepare_decoder_attention_mask(
959
+ self, attention_mask, input_shape, inputs_embeds, past_key_values_length
960
+ ):
961
+ # create causal mask
962
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
963
+ combined_attention_mask = None
964
+ if input_shape[-1] > 1:
965
+ combined_attention_mask = _make_causal_mask(
966
+ input_shape,
967
+ inputs_embeds.dtype,
968
+ device=inputs_embeds.device,
969
+ past_key_values_length=past_key_values_length,
970
+ )
971
+
972
+ if attention_mask is not None:
973
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
974
+ expanded_attn_mask = _expand_mask(
975
+ attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]
976
+ ).to(inputs_embeds.device)
977
+ combined_attention_mask = (
978
+ expanded_attn_mask
979
+ if combined_attention_mask is None
980
+ else expanded_attn_mask + combined_attention_mask
981
+ )
982
+
983
+ return combined_attention_mask
984
+
985
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
986
+ def forward(
987
+ self,
988
+ input_ids: torch.LongTensor = None,
989
+ attention_mask: Optional[torch.Tensor] = None,
990
+ position_ids: Optional[torch.LongTensor] = None,
991
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
992
+ inputs_embeds: Optional[torch.FloatTensor] = None,
993
+ use_cache: Optional[bool] = None,
994
+ output_attentions: Optional[bool] = None,
995
+ output_hidden_states: Optional[bool] = None,
996
+ return_dict: Optional[bool] = None,
997
+ offload_cache_to_cpu: Optional[bool] = None,
998
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
999
+ output_attentions = (
1000
+ output_attentions
1001
+ if output_attentions is not None
1002
+ else self.config.output_attentions
1003
+ )
1004
+ output_hidden_states = (
1005
+ output_hidden_states
1006
+ if output_hidden_states is not None
1007
+ else self.config.output_hidden_states
1008
+ )
1009
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
1010
+
1011
+ return_dict = (
1012
+ return_dict if return_dict is not None else self.config.use_return_dict
1013
+ )
1014
+
1015
+ # retrieve input_ids and inputs_embeds
1016
+ is_mem = None
1017
+ if input_ids is not None and inputs_embeds is not None:
1018
+ raise ValueError(
1019
+ "You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time"
1020
+ )
1021
+ elif input_ids is not None:
1022
+ batch_size, seq_length = input_ids.shape
1023
+ if self.mem_id is not None:
1024
+ with torch.no_grad():
1025
+ is_mem = input_ids == self.mem_id
1026
+ elif inputs_embeds is not None:
1027
+ batch_size, seq_length, _ = inputs_embeds.shape
1028
+ if self.mem_id is not None:
1029
+ raise NotImplementedError
1030
+ else:
1031
+ raise ValueError(
1032
+ "You have to specify either decoder_input_ids or decoder_inputs_embeds"
1033
+ )
1034
+
1035
+ seq_length_with_past = seq_length
1036
+ past_key_values_length = 0
1037
+
1038
+ if past_key_values is not None:
1039
+ if is_mem is not None:
1040
+ pass
1041
+ # raise NotImplementedError
1042
+ past_key_values_length = past_key_values[0][0].shape[2]
1043
+ if len(past_key_values[0]) > 2:
1044
+ past_key_values_length += (
1045
+ past_key_values[0][3].shape[2] * past_key_values[0][3].shape[3]
1046
+ )
1047
+ seq_length_with_past = seq_length_with_past + past_key_values_length
1048
+
1049
+ if position_ids is None:
1050
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
1051
+ position_ids = torch.arange(
1052
+ past_key_values_length,
1053
+ seq_length + past_key_values_length,
1054
+ dtype=torch.long,
1055
+ device=device,
1056
+ )
1057
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
1058
+ else:
1059
+ position_ids = position_ids.view(-1, seq_length).long()
1060
+
1061
+ if inputs_embeds is None:
1062
+ inputs_embeds = self.embed_tokens(input_ids)
1063
+ # embed positions
1064
+ if attention_mask is None:
1065
+ attention_mask = torch.ones(
1066
+ (batch_size, seq_length_with_past),
1067
+ dtype=torch.bool,
1068
+ device=inputs_embeds.device,
1069
+ )
1070
+ attention_mask = self._prepare_decoder_attention_mask(
1071
+ attention_mask,
1072
+ (batch_size, seq_length),
1073
+ inputs_embeds,
1074
+ past_key_values_length,
1075
+ )
1076
+
1077
+ last_section_mask = None
1078
+ if is_mem is not None:
1079
+ is_mem = is_mem.unsqueeze(1).unsqueeze(2)
1080
+ current_len = input_ids.shape[1]
1081
+ mem_ids = torch.where(
1082
+ attention_mask[..., -current_len:] < -1,
1083
+ 0,
1084
+ torch.cumsum(is_mem, -1) - is_mem.int(),
1085
+ )
1086
+ last_section_mask = torch.amax(mem_ids, -1, keepdim=True) == mem_ids
1087
+ attention_mask[..., -current_len:].masked_fill_(
1088
+ last_section_mask & is_mem,
1089
+ torch.tensor(
1090
+ torch.finfo(inputs_embeds.dtype).min, device=inputs_embeds.device
1091
+ ),
1092
+ )
1093
+ last_section_mask.logical_and_(attention_mask[..., -current_len:] > -1)
1094
+ is_mem = is_mem.logical_and(attention_mask[..., -current_len:] > -1)
1095
+
1096
+ hidden_states = inputs_embeds
1097
+
1098
+ if self.gradient_checkpointing and self.training:
1099
+ if use_cache:
1100
+ logger.warning_once(
1101
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
1102
+ )
1103
+ use_cache = False
1104
+
1105
+ # decoder layers
1106
+ all_hidden_states = () if output_hidden_states else None
1107
+ all_self_attns = () if output_attentions else None
1108
+ next_decoder_cache = () if use_cache else None
1109
+
1110
+ for idx, decoder_layer in enumerate(self.layers):
1111
+ if output_hidden_states:
1112
+ all_hidden_states += (hidden_states,)
1113
+
1114
+ past_key_value = (
1115
+ past_key_values[idx] if past_key_values is not None else None
1116
+ )
1117
+
1118
+ if self.gradient_checkpointing and self.training:
1119
+
1120
+ def create_custom_forward(module):
1121
+ def custom_forward(*inputs):
1122
+ # None for past_key_value
1123
+ return module(*inputs)
1124
+
1125
+ return custom_forward
1126
+
1127
+ layer_outputs = torch.utils.checkpoint.checkpoint(
1128
+ create_custom_forward(decoder_layer),
1129
+ hidden_states,
1130
+ attention_mask,
1131
+ position_ids,
1132
+ None,
1133
+ output_attentions,
1134
+ None,
1135
+ is_mem,
1136
+ last_section_mask,
1137
+ )
1138
+ else:
1139
+ layer_outputs = decoder_layer(
1140
+ hidden_states,
1141
+ attention_mask=attention_mask,
1142
+ position_ids=position_ids,
1143
+ past_key_value=past_key_value,
1144
+ output_attentions=output_attentions,
1145
+ use_cache=use_cache,
1146
+ is_mem=is_mem,
1147
+ last_section_mask=last_section_mask,
1148
+ offload_cache_to_cpu=offload_cache_to_cpu,
1149
+ )
1150
+
1151
+ hidden_states = layer_outputs[0]
1152
+
1153
+ if use_cache:
1154
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
1155
+
1156
+ if output_attentions:
1157
+ all_self_attns += (layer_outputs[1],)
1158
+
1159
+ hidden_states = self.norm(hidden_states)
1160
+
1161
+ # add hidden states from the last decoder layer
1162
+ if output_hidden_states:
1163
+ all_hidden_states += (hidden_states,)
1164
+
1165
+ next_cache = next_decoder_cache if use_cache else None
1166
+ if not return_dict:
1167
+ return tuple(
1168
+ v
1169
+ for v in [hidden_states, next_cache, all_hidden_states, all_self_attns]
1170
+ if v is not None
1171
+ )
1172
+ return BaseModelOutputWithPast(
1173
+ last_hidden_state=hidden_states,
1174
+ past_key_values=next_cache,
1175
+ hidden_states=all_hidden_states,
1176
+ attentions=all_self_attns,
1177
+ )
1178
+
1179
+
1180
+ class LlamaForCausalLM(LlamaPreTrainedModel):
1181
+ def __init__(self, config):
1182
+ super().__init__(config)
1183
+ self.model = LlamaModel(config)
1184
+
1185
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
1186
+
1187
+ self.mem_id = None
1188
+ self.mem_freq = None
1189
+ self.top_k = None
1190
+ self.max_seq_len = None
1191
+
1192
+ # Initialize weights and apply final processing
1193
+ self.post_init()
1194
+
1195
+ def get_input_embeddings(self):
1196
+ return self.model.embed_tokens
1197
+
1198
+ def set_input_embeddings(self, value):
1199
+ self.model.embed_tokens = value
1200
+
1201
+ def get_output_embeddings(self):
1202
+ return self.lm_head
1203
+
1204
+ def set_output_embeddings(self, new_embeddings):
1205
+ self.lm_head = new_embeddings
1206
+
1207
+ def set_decoder(self, decoder):
1208
+ self.model = decoder
1209
+
1210
+ def get_decoder(self):
1211
+ return self.model
1212
+
1213
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1214
+ @replace_return_docstrings(
1215
+ output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC
1216
+ )
1217
+ def forward(
1218
+ self,
1219
+ input_ids: torch.LongTensor = None,
1220
+ attention_mask: Optional[torch.Tensor] = None,
1221
+ position_ids: Optional[torch.LongTensor] = None,
1222
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1223
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1224
+ labels: Optional[torch.LongTensor] = None,
1225
+ use_cache: Optional[bool] = None,
1226
+ output_attentions: Optional[bool] = None,
1227
+ output_hidden_states: Optional[bool] = None,
1228
+ return_dict: Optional[bool] = None,
1229
+ offload_cache_to_cpu: Optional[bool] = None,
1230
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
1231
+ r"""
1232
+ Args:
1233
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
1234
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
1235
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
1236
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
1237
+
1238
+ Returns:
1239
+
1240
+ Example:
1241
+
1242
+ ```python
1243
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
1244
+
1245
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
1246
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
1247
+
1248
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
1249
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
1250
+
1251
+ >>> # Generate
1252
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
1253
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
1254
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
1255
+ ```"""
1256
+
1257
+ output_attentions = (
1258
+ output_attentions
1259
+ if output_attentions is not None
1260
+ else self.config.output_attentions
1261
+ )
1262
+ output_hidden_states = (
1263
+ output_hidden_states
1264
+ if output_hidden_states is not None
1265
+ else self.config.output_hidden_states
1266
+ )
1267
+ return_dict = (
1268
+ return_dict if return_dict is not None else self.config.use_return_dict
1269
+ )
1270
+
1271
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
1272
+ window_len = self.max_seq_len or input_ids.shape[1]
1273
+ last_logits = None
1274
+ for _, idx in enumerate(range(0, input_ids.shape[1], window_len)):
1275
+ if idx >= 1:
1276
+ if output_attentions or output_hidden_states:
1277
+ raise NotImplementedError
1278
+ if not use_cache:
1279
+ raise NotImplementedError
1280
+ outputs = self.model(
1281
+ input_ids=input_ids[:, idx : idx + window_len],
1282
+ attention_mask=attention_mask[
1283
+ :, : idx + window_len + attention_mask.shape[1] - input_ids.shape[1]
1284
+ ]
1285
+ if attention_mask is not None
1286
+ else None,
1287
+ position_ids=position_ids[:, idx : idx + window_len]
1288
+ if position_ids is not None
1289
+ else None,
1290
+ past_key_values=past_key_values,
1291
+ inputs_embeds=inputs_embeds[:, idx : idx + window_len]
1292
+ if inputs_embeds is not None
1293
+ else None,
1294
+ use_cache=use_cache,
1295
+ output_attentions=output_attentions,
1296
+ output_hidden_states=output_hidden_states,
1297
+ return_dict=return_dict,
1298
+ offload_cache_to_cpu=offload_cache_to_cpu,
1299
+ )
1300
+ past_key_values = outputs.past_key_values
1301
+ if last_logits is not None:
1302
+ last_logits = torch.cat((last_logits, outputs[0]), dim=-2)
1303
+ last_logits = outputs[0]
1304
+
1305
+ hidden_states = last_logits
1306
+ logits = self.lm_head(hidden_states)
1307
+
1308
+ loss = None
1309
+ if labels is not None:
1310
+ # Shift so that tokens < n predict n
1311
+ shift_logits = logits[..., :-1, :].contiguous()
1312
+ shift_labels = labels[..., 1:].contiguous()
1313
+ # Flatten the tokens
1314
+ loss_fct = CrossEntropyLoss()
1315
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
1316
+ shift_labels = shift_labels.view(-1)
1317
+ # Enable model parallelism
1318
+ shift_labels = shift_labels.to(shift_logits.device)
1319
+ loss = loss_fct(shift_logits, shift_labels)
1320
+
1321
+ if not return_dict:
1322
+ output = (logits,) + outputs[1:]
1323
+ return (loss,) + output if loss is not None else output
1324
+
1325
+ return CausalLMOutputWithPast(
1326
+ loss=loss,
1327
+ logits=logits,
1328
+ past_key_values=outputs.past_key_values,
1329
+ hidden_states=outputs.hidden_states,
1330
+ attentions=outputs.attentions,
1331
+ )
1332
+
1333
+ def set_mem_id(self, mem_id):
1334
+ self.mem_id = mem_id
1335
+ self.model.set_mem_id(mem_id)
1336
+
1337
+ def set_mem_cache_args(self, max_seq_len, mem_freq, top_k, max_cache_size):
1338
+ self.mem_freq = mem_freq
1339
+ self.top_k = top_k
1340
+ self.max_seq_len = max_seq_len
1341
+ if self.max_seq_len is not None:
1342
+ assert self.max_seq_len % (self.mem_freq + 1) == 0
1343
+ self.model.set_mem_cache_args(mem_freq, top_k, max_cache_size)
1344
+
1345
+ def prepare_inputs_for_generation(
1346
+ self,
1347
+ input_ids,
1348
+ past_key_values=None,
1349
+ attention_mask=None,
1350
+ inputs_embeds=None,
1351
+ **kwargs,
1352
+ ):
1353
+ total_len = input_ids.shape[1]
1354
+ if past_key_values:
1355
+ prev_len = input_ids.shape[1] - 1
1356
+ else:
1357
+ prev_len = 0
1358
+
1359
+ position_ids = kwargs.get("position_ids", None)
1360
+
1361
+ if self.mem_freq is not None:
1362
+ if position_ids is not None:
1363
+ raise NotImplementedError
1364
+ # T = input_ids.shape[1]
1365
+
1366
+ prev_incomplete_len = prev_len % self.mem_freq
1367
+ prev_complete_len = prev_len - prev_incomplete_len
1368
+ incomplete_len = total_len % self.mem_freq
1369
+ new_full_len = total_len - prev_complete_len - incomplete_len
1370
+
1371
+ prev_input, input_ids_with_mem, input_ids_without_mem = torch.split(
1372
+ input_ids, (prev_complete_len, new_full_len, incomplete_len), dim=-1
1373
+ )
1374
+
1375
+ bsz, _ = input_ids.size()
1376
+ input_ids_with_mem = input_ids_with_mem.view(bsz, -1, self.mem_freq)
1377
+ input_ids_with_mem = torch.cat(
1378
+ (
1379
+ input_ids_with_mem,
1380
+ input_ids_with_mem.new_full(
1381
+ (bsz, input_ids_with_mem.shape[1], 1), self.mem_id
1382
+ ),
1383
+ ),
1384
+ dim=-1,
1385
+ ).view(bsz, -1)
1386
+ input_ids = torch.cat(
1387
+ (prev_input, input_ids_with_mem, input_ids_without_mem), dim=-1
1388
+ )
1389
+ if attention_mask is not None:
1390
+ attention_mask_with_mem, attention_mask_without_mem = torch.split(
1391
+ attention_mask,
1392
+ (prev_complete_len + new_full_len, incomplete_len),
1393
+ dim=-1,
1394
+ )
1395
+ attention_mask_with_mem = attention_mask_with_mem.view(
1396
+ bsz, -1, self.mem_freq
1397
+ )
1398
+ attention_mask_with_mem = torch.cat(
1399
+ (
1400
+ attention_mask_with_mem,
1401
+ attention_mask_with_mem.new_ones(
1402
+ (bsz, attention_mask_with_mem.shape[1], 1)
1403
+ ),
1404
+ ),
1405
+ dim=-1,
1406
+ ).view(bsz, -1)
1407
+ attention_mask = torch.cat(
1408
+ (attention_mask_with_mem, attention_mask_without_mem), dim=-1
1409
+ )
1410
+
1411
+ input_ids = input_ids[:, prev_len:]
1412
+ if attention_mask is not None and position_ids is None:
1413
+ # create position_ids on the fly for batch generation
1414
+ position_ids = attention_mask.long().cumsum(-1) - 1
1415
+ position_ids.masked_fill_(attention_mask == 0, 1)
1416
+ position_ids = position_ids[:, -input_ids.shape[1] :].unsqueeze(-1)
1417
+
1418
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1419
+ if (
1420
+ inputs_embeds is not None
1421
+ and past_key_values is None
1422
+ and self.mem_freq is None
1423
+ ):
1424
+ model_inputs = {"inputs_embeds": inputs_embeds}
1425
+ else:
1426
+ model_inputs = {"input_ids": input_ids}
1427
+
1428
+ model_inputs.update(
1429
+ {
1430
+ "position_ids": position_ids,
1431
+ "past_key_values": past_key_values,
1432
+ "use_cache": kwargs.get("use_cache"),
1433
+ "attention_mask": attention_mask,
1434
+ "offload_cache_to_cpu": kwargs.get("offload_cache_to_cpu"),
1435
+ }
1436
+ )
1437
+ return model_inputs
1438
+
1439
+ @staticmethod
1440
+ def _reorder_cache(past_key_values, beam_idx):
1441
+ reordered_past = ()
1442
+ for layer_past in past_key_values:
1443
+ reordered_past += (
1444
+ tuple(
1445
+ past_state.index_select(0, beam_idx) for past_state in layer_past
1446
+ ),
1447
+ )
1448
+ return reordered_past
1449
+
1450
+
1451
+ @add_start_docstrings(
1452
+ """
1453
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1454
+
1455
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1456
+ (e.g. GPT-2) do.
1457
+
1458
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1459
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1460
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1461
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1462
+ each row of the batch).
1463
+ """,
1464
+ LLAMA_START_DOCSTRING,
1465
+ )
1466
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1467
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1468
+
1469
+ def __init__(self, config):
1470
+ super().__init__(config)
1471
+ self.num_labels = config.num_labels
1472
+ self.model = LlamaModel(config)
1473
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1474
+
1475
+ # Initialize weights and apply final processing
1476
+ self.post_init()
1477
+
1478
+ def get_input_embeddings(self):
1479
+ return self.model.embed_tokens
1480
+
1481
+ def set_input_embeddings(self, value):
1482
+ self.model.embed_tokens = value
1483
+
1484
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1485
+ def forward(
1486
+ self,
1487
+ input_ids: torch.LongTensor = None,
1488
+ attention_mask: Optional[torch.Tensor] = None,
1489
+ position_ids: Optional[torch.LongTensor] = None,
1490
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1491
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1492
+ labels: Optional[torch.LongTensor] = None,
1493
+ use_cache: Optional[bool] = None,
1494
+ output_attentions: Optional[bool] = None,
1495
+ output_hidden_states: Optional[bool] = None,
1496
+ return_dict: Optional[bool] = None,
1497
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1498
+ r"""
1499
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1500
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1501
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1502
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1503
+ """
1504
+ return_dict = (
1505
+ return_dict if return_dict is not None else self.config.use_return_dict
1506
+ )
1507
+
1508
+ transformer_outputs = self.model(
1509
+ input_ids,
1510
+ attention_mask=attention_mask,
1511
+ position_ids=position_ids,
1512
+ past_key_values=past_key_values,
1513
+ inputs_embeds=inputs_embeds,
1514
+ use_cache=use_cache,
1515
+ output_attentions=output_attentions,
1516
+ output_hidden_states=output_hidden_states,
1517
+ return_dict=return_dict,
1518
+ )
1519
+ hidden_states = transformer_outputs[0]
1520
+ logits = self.score(hidden_states)
1521
+
1522
+ if input_ids is not None:
1523
+ batch_size = input_ids.shape[0]
1524
+ else:
1525
+ batch_size = inputs_embeds.shape[0]
1526
+
1527
+ if self.config.pad_token_id is None and batch_size != 1:
1528
+ raise ValueError(
1529
+ "Cannot handle batch sizes > 1 if no padding token is defined."
1530
+ )
1531
+ if self.config.pad_token_id is None:
1532
+ sequence_lengths = -1
1533
+ else:
1534
+ if input_ids is not None:
1535
+ sequence_lengths = (
1536
+ torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1
1537
+ ).to(logits.device)
1538
+ else:
1539
+ sequence_lengths = -1
1540
+
1541
+ pooled_logits = logits[
1542
+ torch.arange(batch_size, device=logits.device), sequence_lengths
1543
+ ]
1544
+
1545
+ loss = None
1546
+ if labels is not None:
1547
+ labels = labels.to(logits.device)
1548
+ if self.config.problem_type is None:
1549
+ if self.num_labels == 1:
1550
+ self.config.problem_type = "regression"
1551
+ elif self.num_labels > 1 and (
1552
+ labels.dtype == torch.long or labels.dtype == torch.int
1553
+ ):
1554
+ self.config.problem_type = "single_label_classification"
1555
+ else:
1556
+ self.config.problem_type = "multi_label_classification"
1557
+
1558
+ if self.config.problem_type == "regression":
1559
+ loss_fct = MSELoss()
1560
+ if self.num_labels == 1:
1561
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1562
+ else:
1563
+ loss = loss_fct(pooled_logits, labels)
1564
+ elif self.config.problem_type == "single_label_classification":
1565
+ loss_fct = CrossEntropyLoss()
1566
+ loss = loss_fct(
1567
+ pooled_logits.view(-1, self.num_labels), labels.view(-1)
1568
+ )
1569
+ elif self.config.problem_type == "multi_label_classification":
1570
+ loss_fct = BCEWithLogitsLoss()
1571
+ loss = loss_fct(pooled_logits, labels)
1572
+ if not return_dict:
1573
+ output = (pooled_logits,) + transformer_outputs[1:]
1574
+ return ((loss,) + output) if loss is not None else output
1575
+
1576
+ return SequenceClassifierOutputWithPast(
1577
+ loss=loss,
1578
+ logits=pooled_logits,
1579
+ past_key_values=transformer_outputs.past_key_values,
1580
+ hidden_states=transformer_outputs.hidden_states,
1581
+ attentions=transformer_outputs.attentions,
1582
+ )
1583
+
1584
+
1585
+ def add_mem_tokens(example, mem_freq, mem_id):
1586
+ x = example["input_ids"]
1587
+ ret = []
1588
+ prev_idx = 0
1589
+ for t_idx in range(mem_freq, len(x), mem_freq):
1590
+ ret.extend(x[prev_idx:t_idx])
1591
+ ret.append(mem_id)
1592
+ prev_idx = t_idx
1593
+ ret.extend(x[prev_idx:])
1594
+ # drop attention_mask
1595
+ return {"input_ids": ret}
src/axolotl/utils/models.py CHANGED
@@ -20,7 +20,9 @@ from transformers import ( # noqa: F401
20
  )
21
 
22
  try:
23
- from transformers import LlamaForCausalLM
 
 
24
  except ImportError:
25
  logging.warning(
26
  "This version of transformers does not support Llama. Consider upgrading."
@@ -83,37 +85,47 @@ def load_model(
83
  adapter="lora",
84
  inference=False,
85
  ):
86
- # type: (str, str, str, str, DictDefault, Optional[str], bool) -> Tuple[PreTrainedModel, Optional[PeftConfig]]
87
  """
88
  Load a model from a base model and a model type.
89
  """
90
 
91
  # TODO refactor as a kwarg
92
  load_in_8bit = cfg.load_in_8bit
93
- is_llama_derived_model = "llama" in base_model or (
94
  cfg.model_type and "llama" in cfg.model_type.lower()
95
  )
96
 
97
- if is_llama_derived_model and cfg.flash_attention:
98
  if cfg.device not in ["mps", "cpu"] and inference is False:
99
  from axolotl.flash_attn import replace_llama_attn_with_flash_attn
100
 
101
  logging.info("patching with flash attention")
102
  replace_llama_attn_with_flash_attn()
103
- elif is_llama_derived_model and cfg.xformers_attention:
104
  from axolotl.monkeypatch.llama_attn_hijack_xformers import (
105
  hijack_llama_attention,
106
  )
107
 
108
  logging.info("patching with xformers attention")
109
  hijack_llama_attention()
110
- elif is_llama_derived_model and cfg.sdp_attention:
111
  from axolotl.monkeypatch.llama_attn_hijack_xformers import (
112
  hijack_llama_sdp_attention,
113
  )
114
 
115
  logging.info("patching with sdp attention")
116
  hijack_llama_sdp_attention()
 
 
 
 
 
 
 
 
 
 
117
 
118
  if cfg.bf16:
119
  torch_dtype = torch.bfloat16
@@ -145,7 +157,7 @@ def load_model(
145
  bnb_4bit_quant_type="nf4",
146
  )
147
  try:
148
- if cfg.gptq and is_llama_derived_model:
149
  from alpaca_lora_4bit.autograd_4bit import load_llama_model_4bit_low_ram
150
  from huggingface_hub import snapshot_download
151
 
@@ -183,7 +195,7 @@ def load_model(
183
  else True,
184
  )
185
  load_in_8bit = False
186
- elif is_llama_derived_model and "LlamaForCausalLM" in globals():
187
  config = LlamaConfig.from_pretrained(base_model_config)
188
  model = LlamaForCausalLM.from_pretrained(
189
  base_model,
 
20
  )
21
 
22
  try:
23
+ from transformers import ( # pylint: disable=unused-import # noqa: F401
24
+ LlamaForCausalLM,
25
+ )
26
  except ImportError:
27
  logging.warning(
28
  "This version of transformers does not support Llama. Consider upgrading."
 
85
  adapter="lora",
86
  inference=False,
87
  ):
88
+ # type: (str, str, str, AutoTokenizer, DictDefault, Optional[str], bool) -> Tuple[PreTrainedModel, Optional[PeftConfig]]
89
  """
90
  Load a model from a base model and a model type.
91
  """
92
 
93
  # TODO refactor as a kwarg
94
  load_in_8bit = cfg.load_in_8bit
95
+ cfg.is_llama_derived_model = "llama" in base_model or (
96
  cfg.model_type and "llama" in cfg.model_type.lower()
97
  )
98
 
99
+ if cfg.is_llama_derived_model and cfg.flash_attention:
100
  if cfg.device not in ["mps", "cpu"] and inference is False:
101
  from axolotl.flash_attn import replace_llama_attn_with_flash_attn
102
 
103
  logging.info("patching with flash attention")
104
  replace_llama_attn_with_flash_attn()
105
+ elif cfg.is_llama_derived_model and cfg.xformers_attention:
106
  from axolotl.monkeypatch.llama_attn_hijack_xformers import (
107
  hijack_llama_attention,
108
  )
109
 
110
  logging.info("patching with xformers attention")
111
  hijack_llama_attention()
112
+ elif cfg.is_llama_derived_model and cfg.sdp_attention:
113
  from axolotl.monkeypatch.llama_attn_hijack_xformers import (
114
  hijack_llama_sdp_attention,
115
  )
116
 
117
  logging.info("patching with sdp attention")
118
  hijack_llama_sdp_attention()
119
+ elif cfg.is_llama_derived_model and cfg.landmark_attention:
120
+ from axolotl.monkeypatch.llama_landmark_attn import ( # pylint: disable=redefined-outer-name # noqa: F811
121
+ MEM_TOKEN,
122
+ LlamaForCausalLM,
123
+ )
124
+
125
+ logging.info("patching with landmark attention")
126
+
127
+ # TODO: Check if this would overwrite previous additional_special_tokens
128
+ tokenizer.add_special_tokens({"additional_special_tokens": [MEM_TOKEN]})
129
 
130
  if cfg.bf16:
131
  torch_dtype = torch.bfloat16
 
157
  bnb_4bit_quant_type="nf4",
158
  )
159
  try:
160
+ if cfg.gptq and cfg.is_llama_derived_model:
161
  from alpaca_lora_4bit.autograd_4bit import load_llama_model_4bit_low_ram
162
  from huggingface_hub import snapshot_download
163
 
 
195
  else True,
196
  )
197
  load_in_8bit = False
198
+ elif cfg.is_llama_derived_model and "LlamaForCausalLM" in globals():
199
  config = LlamaConfig.from_pretrained(base_model_config)
200
  model = LlamaForCausalLM.from_pretrained(
201
  base_model,
src/axolotl/utils/trainer.py CHANGED
@@ -1,6 +1,7 @@
1
  """Module containing the Trainer class and related functions"""
2
 
3
  import importlib
 
4
  import math
5
  import os
6
  import sys
@@ -235,6 +236,23 @@ def setup_trainer(cfg, train_dataset, eval_dataset, model, tokenizer):
235
  else:
236
  data_collator_kwargs["pad_to_multiple_of"] = 8
237
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
238
  trainer_cls = (
239
  OneCycleLRSchedulerTrainer
240
  if cfg.lr_scheduler == "one_cycle" and (cfg.fsdp or cfg.adapter == "qlora")
 
1
  """Module containing the Trainer class and related functions"""
2
 
3
  import importlib
4
+ import logging
5
  import math
6
  import os
7
  import sys
 
236
  else:
237
  data_collator_kwargs["pad_to_multiple_of"] = 8
238
 
239
+ if cfg.is_llama_derived_model and cfg.landmark_attention:
240
+ from functools import partial
241
+
242
+ from axolotl.monkeypatch.llama_landmark_attn import MEM_TOKEN, add_mem_tokens
243
+
244
+ mem_id = tokenizer.convert_tokens_to_ids(MEM_TOKEN)
245
+ model.set_mem_id(mem_id)
246
+
247
+ logging.info("Adding landmark attention tokens to dataset")
248
+
249
+ for dataset in [train_dataset, eval_dataset]:
250
+ dataset = dataset.map(
251
+ partial(add_mem_tokens, mem_freq=50, mem_id=mem_id),
252
+ batched=False,
253
+ num_proc=32,
254
+ )
255
+
256
  trainer_cls = (
257
  OneCycleLRSchedulerTrainer
258
  if cfg.lr_scheduler == "one_cycle" and (cfg.fsdp or cfg.adapter == "qlora")