Nanobit commited on
Commit
55b8542
·
1 Parent(s): febe902

Feat: Add landmark attention

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