eugenepentland commited on
Commit
f823e16
1 Parent(s): 1d272b0

updated readme

Browse files
README.md CHANGED
@@ -1,3 +1,13 @@
1
  ---
2
  license: other
3
  ---
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  license: other
3
  ---
4
+ WizardLM-7B with 10k+ context using Landmark Attention.
5
+
6
+ Model generated using Landmark-Attention-QLoRA
7
+ https://github.com/eugenepentland/landmark-attention-qlora
8
+
9
+ A merge of the following models:
10
+ https://huggingface.co/TheBloke/wizardLM-7B-HF
11
+ https://huggingface.co/eugenepentland/WizardLM-7B-Landmark-Attention-QLoRA
12
+
13
+ Can be loaded in using oobooga, make sure to have the --trust-remote-code option on for it to function.
config.json CHANGED
@@ -3,6 +3,12 @@
3
  "architectures": [
4
  "LlamaForCausalLM"
5
  ],
 
 
 
 
 
 
6
  "bos_token_id": 1,
7
  "eos_token_id": 2,
8
  "hidden_act": "silu",
 
3
  "architectures": [
4
  "LlamaForCausalLM"
5
  ],
6
+ "auto_map": {
7
+ "AutoConfig": "configuration_landmark_llama.LlamaConfig",
8
+ "AutoModel": "modelling_landmark_llama.LlamaModel",
9
+ "AutoModelForCausalLM": "modelling_landmark_llama.LlamaForCausalLM",
10
+ "AutoModelForSequenceClassification": "modelling_landmark_llama.LlamaForSequenceClassification"
11
+ },
12
  "bos_token_id": 1,
13
  "eos_token_id": 2,
14
  "hidden_act": "silu",
configuration_landmark_llama.py ADDED
@@ -0,0 +1,46 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ LLaMA model configuration"""
21
+
22
+ from transformers import LlamaConfig as HFLlamaConfig
23
+ from transformers.utils import logging
24
+
25
+
26
+ logger = logging.get_logger(__name__)
27
+
28
+
29
+ class LlamaConfig(HFLlamaConfig):
30
+ model_type = "llama"
31
+
32
+ def __init__(
33
+ self,
34
+ mem_id=32001,
35
+ mem_freq=50,
36
+ mem_top_k=5,
37
+ mem_max_seq_len=255,
38
+ mem_max_cache_size=None,
39
+ **kwargs,
40
+ ):
41
+ self.mem_id = mem_id
42
+ self.mem_freq = mem_freq
43
+ self.mem_top_k = mem_top_k
44
+ self.mem_max_seq_len = mem_max_seq_len
45
+ self.mem_max_cache_size = mem_max_cache_size
46
+ super().__init__(**kwargs)
modelling_landmark_llama.py ADDED
@@ -0,0 +1,1217 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # coding=utf-8
2
+ # Copyright 2022 EleutherAI and the HuggingFace Inc. team. All rights reserved.
3
+ #
4
+ # This code is based on EleutherAI's GPT-NeoX library and the GPT-NeoX
5
+ # and OPT implementations in this library. It has been modified from its
6
+ # original forms to accommodate minor architectural differences compared
7
+ # to GPT-NeoX and OPT used by the Meta AI team that trained the model.
8
+ #
9
+ # Licensed under the Apache License, Version 2.0 (the "License");
10
+ # you may not use this file except in compliance with the License.
11
+ # You may obtain a copy of the License at
12
+ #
13
+ # http://www.apache.org/licenses/LICENSE-2.0
14
+ #
15
+ # Unless required by applicable law or agreed to in writing, software
16
+ # distributed under the License is distributed on an "AS IS" BASIS,
17
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18
+ # See the License for the specific language governing permissions and
19
+ # limitations under the License.
20
+ """ PyTorch LLaMA model."""
21
+ import math
22
+ from typing import List, Optional, Tuple, Union
23
+
24
+ import torch
25
+ import torch.utils.checkpoint
26
+ from torch import nn
27
+ from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
28
+
29
+ from transformers.activations import ACT2FN
30
+ from transformers.modeling_outputs import BaseModelOutputWithPast, CausalLMOutputWithPast, SequenceClassifierOutputWithPast
31
+ from transformers.modeling_utils import PreTrainedModel
32
+ from transformers.utils import add_start_docstrings, add_start_docstrings_to_model_forward, logging, replace_return_docstrings
33
+ from transformers.models.llama.configuration_llama import LlamaConfig
34
+
35
+
36
+ logger = logging.get_logger(__name__)
37
+
38
+ _CONFIG_FOR_DOC = "LlamaConfig"
39
+
40
+
41
+ # Copied from transformers.models.bart.modeling_bart._make_causal_mask
42
+ def _make_causal_mask(
43
+ input_ids_shape: torch.Size, dtype: torch.dtype, device: torch.device, past_key_values_length: int = 0
44
+ ):
45
+ """
46
+ Make causal mask used for bi-directional self-attention.
47
+ """
48
+ bsz, tgt_len = input_ids_shape
49
+ mask = torch.full((tgt_len, tgt_len), torch.tensor(torch.finfo(dtype).min, device=device), device=device)
50
+ mask_cond = torch.arange(mask.size(-1), device=device)
51
+ mask.masked_fill_(mask_cond < (mask_cond + 1).view(mask.size(-1), 1), 0)
52
+ mask = mask.to(dtype)
53
+
54
+ if past_key_values_length > 0:
55
+ mask = torch.cat([torch.zeros(tgt_len, past_key_values_length, dtype=dtype, device=device), mask], dim=-1)
56
+ return mask[None, None, :, :].expand(bsz, 1, tgt_len, tgt_len + past_key_values_length)
57
+
58
+
59
+ # Copied from transformers.models.bart.modeling_bart._expand_mask
60
+ def _expand_mask(mask: torch.Tensor, dtype: torch.dtype, tgt_len: Optional[int] = None):
61
+ """
62
+ Expands attention_mask from `[bsz, seq_len]` to `[bsz, 1, tgt_seq_len, src_seq_len]`.
63
+ """
64
+ bsz, src_len = mask.size()
65
+ tgt_len = tgt_len if tgt_len is not None else src_len
66
+
67
+ expanded_mask = mask[:, None, None, :].expand(bsz, 1, tgt_len, src_len).to(dtype)
68
+
69
+ inverted_mask = 1.0 - expanded_mask
70
+
71
+ return inverted_mask.masked_fill(inverted_mask.to(torch.bool), torch.finfo(dtype).min)
72
+
73
+
74
+ class LlamaRMSNorm(nn.Module):
75
+ def __init__(self, hidden_size, eps=1e-6):
76
+ """
77
+ LlamaRMSNorm is equivalent to T5LayerNorm
78
+ """
79
+ super().__init__()
80
+ self.weight = nn.Parameter(torch.ones(hidden_size))
81
+ self.variance_epsilon = eps
82
+
83
+ def forward(self, hidden_states):
84
+ variance = hidden_states.to(torch.float32).pow(2).mean(-1, keepdim=True)
85
+ hidden_states = hidden_states * torch.rsqrt(variance + self.variance_epsilon)
86
+
87
+ # convert into half-precision if necessary
88
+ if self.weight.dtype in [torch.float16, torch.bfloat16]:
89
+ hidden_states = hidden_states.to(self.weight.dtype)
90
+
91
+ return self.weight * hidden_states
92
+
93
+
94
+ class LlamaRotaryEmbedding(torch.nn.Module):
95
+ def __init__(self, dim, max_position_embeddings=2048, base=10000, device=None):
96
+ super().__init__()
97
+ inv_freq = 1.0 / (base ** (torch.arange(0, dim, 2).float().to(device) / dim))
98
+ self.register_buffer("inv_freq", inv_freq)
99
+
100
+ # Build here to make `torch.jit.trace` work.
101
+ self.max_seq_len_cached = max_position_embeddings
102
+ t = torch.arange(self.max_seq_len_cached, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
103
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
104
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
105
+ emb = torch.cat((freqs, freqs), dim=-1)
106
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
107
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
108
+
109
+ def forward(self, x, seq_len=None):
110
+ # x: [bs, num_attention_heads, seq_len, head_size]
111
+ # This `if` block is unlikely to be run after we build sin/cos in `__init__`. Keep the logic here just in case.
112
+ if seq_len > self.max_seq_len_cached:
113
+ self.max_seq_len_cached = seq_len
114
+ t = torch.arange(self.max_seq_len_cached, device=x.device, dtype=self.inv_freq.dtype)
115
+ freqs = torch.einsum("i,j->ij", t, self.inv_freq)
116
+ # Different from paper, but it uses a different permutation in order to obtain the same calculation
117
+ emb = torch.cat((freqs, freqs), dim=-1).to(x.device)
118
+ self.register_buffer("cos_cached", emb.cos()[None, None, :, :], persistent=False)
119
+ self.register_buffer("sin_cached", emb.sin()[None, None, :, :], persistent=False)
120
+ return (
121
+ self.cos_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
122
+ self.sin_cached[:, :, :seq_len, ...].to(dtype=x.dtype),
123
+ )
124
+
125
+
126
+ def rotate_half(x):
127
+ """Rotates half the hidden dims of the input."""
128
+ x1 = x[..., : x.shape[-1] // 2]
129
+ x2 = x[..., x.shape[-1] // 2 :]
130
+ return torch.cat((-x2, x1), dim=-1)
131
+
132
+
133
+ def apply_rotary_pos_emb(q, k, cos, sin, position_ids):
134
+ # The first two dimensions of cos and sin are always 1, so we can `squeeze` them.
135
+ cos = cos.squeeze(1).squeeze(0) # [seq_len, dim]
136
+ sin = sin.squeeze(1).squeeze(0) # [seq_len, dim]
137
+ cos = cos[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
138
+ sin = sin[position_ids].unsqueeze(1) # [bs, 1, seq_len, dim]
139
+ if q is None:
140
+ q_embed = None
141
+ else:
142
+ q_embed = (q * cos) + (rotate_half(q) * sin)
143
+ k_embed = (k * cos) + (rotate_half(k) * sin)
144
+ return q_embed, k_embed
145
+
146
+
147
+ class LlamaMLP(nn.Module):
148
+ def __init__(
149
+ self,
150
+ hidden_size: int,
151
+ intermediate_size: int,
152
+ hidden_act: str,
153
+ ):
154
+ super().__init__()
155
+ self.gate_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
156
+ self.down_proj = nn.Linear(intermediate_size, hidden_size, bias=False)
157
+ self.up_proj = nn.Linear(hidden_size, intermediate_size, bias=False)
158
+ self.act_fn = ACT2FN[hidden_act]
159
+
160
+ def forward(self, x):
161
+ return self.down_proj(self.act_fn(self.gate_proj(x)) * self.up_proj(x))
162
+
163
+ class LandmarkGroupedSoftmaxFunction(torch.autograd.Function):
164
+
165
+ # Note that forward, setup_context, and backward are @staticmethods
166
+ @staticmethod
167
+ def forward(ctx, x, dim, mem_cnt, resp_mem_idx):
168
+ new_shape = list(x.shape)
169
+ new_shape[dim] = mem_cnt # max_mem_cnt.item()
170
+ max_by_group = x.new_zeros((*new_shape,))
171
+ max_by_group.scatter_reduce_(src=x, index=resp_mem_idx, dim=dim, reduce="amax", include_self=False)
172
+
173
+ maxes = torch.gather(max_by_group, dim, resp_mem_idx)
174
+ #x_exp = torch.exp(x - torch.where(torch.isinf(maxes), 0, maxes))
175
+ x_exp = torch.exp((x - maxes).to(torch.float32))
176
+
177
+ cumsum_by_group = torch.zeros_like(max_by_group, dtype=x_exp.dtype)
178
+
179
+ cumsum_by_group.scatter_add_(dim, resp_mem_idx, x_exp, )
180
+ denom = torch.gather(cumsum_by_group, dim, resp_mem_idx)
181
+
182
+ #probs = torch.where(denom < 0.5, 0, x_exp / denom)
183
+ probs = x_exp / denom
184
+
185
+
186
+ ctx.mem_cnt = mem_cnt
187
+ ctx.dim = dim
188
+ ctx.save_for_backward(resp_mem_idx, probs)
189
+
190
+ return probs
191
+
192
+ @staticmethod
193
+ def backward(ctx, grad_probs):
194
+ mem_cnt = ctx.mem_cnt
195
+ dim = ctx.dim
196
+ resp_mem_idx, probs = ctx.saved_tensors
197
+ grad_x = grad_dim = grad_mem_cnt = grad_resp_mem_idx = None
198
+
199
+ if ctx.needs_input_grad[0] or ctx.needs_input_grad[4]:
200
+ grad_pair = grad_probs * probs
201
+
202
+ new_shape = list(probs.shape)
203
+ new_shape[dim] = mem_cnt # max_mem_cnt.item()
204
+ cumsum_by_group = grad_pair.new_zeros((*new_shape,))
205
+ cumsum_by_group.scatter_add_(dim, resp_mem_idx, grad_pair)
206
+
207
+
208
+ if ctx.needs_input_grad[0]:
209
+ grad_sum = torch.gather(cumsum_by_group, dim, resp_mem_idx)
210
+ grad_x = grad_pair - probs * grad_sum
211
+ assert not ctx.needs_input_grad[1]
212
+ assert not ctx.needs_input_grad[2]
213
+ assert not ctx.needs_input_grad[3]
214
+
215
+ return grad_x, grad_dim, grad_mem_cnt, grad_resp_mem_idx
216
+
217
+ def landmark_grouped_softmax(x, dim, is_mem, last_section_mask):
218
+
219
+ last_and_rest_mask = last_section_mask # | mask
220
+
221
+ full_access_mask = is_mem | last_and_rest_mask
222
+
223
+ max_mem_cnt = 16
224
+ mem_group_idx = torch.cumsum(is_mem, dim=dim)
225
+ mem_bucket_id = max_mem_cnt - 1
226
+ resp_mem_idx = torch.where(last_and_rest_mask,
227
+ max_mem_cnt - 1,
228
+ torch.where(is_mem, mem_bucket_id, mem_group_idx))
229
+ probs = LandmarkGroupedSoftmaxFunction.apply(x, dim, max_mem_cnt, resp_mem_idx)
230
+
231
+ new_shape = list(x.shape)
232
+ new_shape[dim] = max_mem_cnt
233
+ group_prob = probs.new_zeros((*new_shape, ))
234
+ group_prob.scatter_(dim, torch.where(is_mem, mem_group_idx - 1, max_mem_cnt - 1), probs)
235
+ probs = probs.mul(torch.where(full_access_mask, last_section_mask, torch.gather(group_prob, dim, resp_mem_idx)))
236
+
237
+
238
+ return probs
239
+
240
+ class LlamaAttention(nn.Module):
241
+ """Multi-headed attention from 'Attention Is All You Need' paper"""
242
+
243
+ def __init__(self, config: LlamaConfig):
244
+ super().__init__()
245
+ self.config = config
246
+ self.hidden_size = config.hidden_size
247
+ self.num_heads = config.num_attention_heads
248
+ self.head_dim = self.hidden_size // self.num_heads
249
+ self.max_position_embeddings = config.max_position_embeddings
250
+
251
+ if (self.head_dim * self.num_heads) != self.hidden_size:
252
+ raise ValueError(
253
+ f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
254
+ f" and `num_heads`: {self.num_heads})."
255
+ )
256
+ self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
257
+ self.k_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
258
+ self.v_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=False)
259
+ self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=False)
260
+ self.rotary_emb = LlamaRotaryEmbedding(self.head_dim, max_position_embeddings=self.max_position_embeddings)
261
+
262
+ self.mem_freq = None
263
+ self.top_k = None
264
+ self.max_cache_size = None
265
+
266
+ def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
267
+ return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
268
+
269
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
270
+ self.mem_freq = mem_freq
271
+ self.top_k = top_k
272
+ self.max_cache_size = max_cache_size
273
+
274
+ def forward(
275
+ self,
276
+ hidden_states: torch.Tensor,
277
+ attention_mask: Optional[torch.Tensor] = None,
278
+ position_ids: Optional[torch.LongTensor] = None,
279
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
280
+ output_attentions: bool = False,
281
+ use_cache: bool = False,
282
+ is_mem: Optional[torch.Tensor] = None,
283
+ last_section_mask: Optional[torch.Tensor] = None,
284
+ offload_cache_to_cpu: bool = False,
285
+ ) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
286
+ bsz, q_len, _ = hidden_states.size()
287
+
288
+ query_states = self.q_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
289
+ key_states = self.k_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
290
+ value_states = self.v_proj(hidden_states).view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
291
+
292
+ kv_seq_len = key_states.shape[-2]
293
+ if past_key_value is not None:
294
+ kv_seq_len += past_key_value[0].shape[-2]
295
+ if len(past_key_value) > 2:
296
+ kv_seq_len += past_key_value[3].shape[2] * past_key_value[3].shape[3]
297
+ cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
298
+ key_states_before_pos = key_states
299
+ query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
300
+ # [bsz, nh, t, hd]
301
+
302
+ attn_prefix = None
303
+ if past_key_value is not None:
304
+ # reuse k, v, self_attention
305
+ if self.mem_freq is None:
306
+ cache_len = past_key_value[0].shape[2]
307
+ if self.max_cache_size is not None:
308
+ cache_len = min(cache_len, self.max_cache_size)
309
+ if is_mem is not None:
310
+ is_mem = torch.cat((is_mem.new_zeros((1, 1, q_len, cache_len)), is_mem), dim=-1)
311
+ last_section_mask = torch.cat((last_section_mask.new_ones((1, 1, q_len, cache_len)), last_section_mask), dim=-1)
312
+
313
+ past_key_states = torch.cat([past_key_value[0], key_states], dim=2)
314
+ past_value_states = torch.cat([past_key_value[1], value_states], dim=2)
315
+ key_states = past_key_states[:, :, -(q_len + cache_len):]
316
+ value_states = past_value_states[:, :, -(q_len + cache_len):]
317
+ expected_att_size = (bsz, self.num_heads, q_len, cache_len + q_len)
318
+ else:
319
+ orig_value_states = value_states
320
+
321
+ incomplete_len = past_key_value[0].shape[2] % (self.mem_freq + 1)
322
+ full_len = past_key_value[0].shape[2] - incomplete_len
323
+ past_key_mem, past_key_incomplete = torch.split(past_key_value[0], (full_len, incomplete_len), dim=2)
324
+ past_value_mem, past_value_incomplete = torch.split(past_key_value[1], (full_len, incomplete_len), dim=2)
325
+
326
+ if offload_cache_to_cpu:
327
+ past_key_value = (past_key_incomplete, past_value_incomplete, *past_key_value[2:])
328
+
329
+ if incomplete_len > 0:
330
+ assert q_len + incomplete_len <= (self.mem_freq + 1)
331
+ is_mem = torch.cat((is_mem.new_zeros((1, 1, q_len, incomplete_len)), is_mem), dim=-1)
332
+ last_section_mask = torch.cat((last_section_mask.new_ones((1, 1, q_len, incomplete_len)), last_section_mask), dim=-1)
333
+
334
+ if len(past_key_value) > 2:
335
+ full_len += past_key_value[3].shape[2] * past_key_value[3].shape[3]
336
+ past_key_incomplete_pos = torch.arange(full_len, full_len + incomplete_len, dtype=torch.long, device=position_ids.device).unsqueeze(0)
337
+ _, past_key_incomplete = apply_rotary_pos_emb(None, past_key_incomplete, cos, sin, past_key_incomplete_pos)
338
+ key_states = torch.cat((past_key_incomplete, key_states), dim=2)
339
+ value_states = torch.cat((past_value_incomplete, value_states), dim=2)
340
+
341
+ past_key_mem = past_key_mem.view(bsz, self.num_heads, -1, self.mem_freq + 1, self.head_dim)
342
+ past_value_mem = past_value_mem.view(bsz, self.num_heads, -1, self.mem_freq + 1, self.head_dim)
343
+
344
+ if len(past_key_value) > 2:
345
+ mem_key_nopos = torch.cat((
346
+ past_key_value[2],
347
+ past_key_mem.select(dim=3, index=self.mem_freq)), dim=2)
348
+ past_key_mem_offload = past_key_value[3]
349
+ past_key_mem = torch.cat((
350
+ past_key_mem_offload,
351
+ past_key_mem.to(past_key_mem_offload.device)), dim=2)
352
+ past_value_mem = torch.cat((past_key_value[4], past_value_mem.to(past_key_mem_offload.device)), dim=2)
353
+ else:
354
+ mem_key_nopos = past_key_mem.select(dim=3, index=self.mem_freq)
355
+
356
+ num_mems = past_key_mem.shape[2]
357
+ top_k = min(self.top_k, num_mems)
358
+ prefix_len = full_len - (top_k + 1) * (self.mem_freq + 1)
359
+ mem_indices = torch.cat(
360
+ (position_ids.new_zeros((max(0, num_mems - top_k), )),
361
+ torch.arange(1, top_k + 1, device=query_states.device, dtype=position_ids.dtype)), dim=0)
362
+ mem_pos = (mem_indices * (self.mem_freq + 1) + self.mem_freq).unsqueeze(0).expand(bsz, -1) + prefix_len
363
+ _, mem_key = apply_rotary_pos_emb(None, mem_key_nopos, cos, sin, mem_pos)
364
+ mem_attn_weights = torch.matmul(query_states, mem_key.transpose(2, 3)) / math.sqrt(self.head_dim)
365
+
366
+ if offload_cache_to_cpu:
367
+ aggregate = "max_over_tokens"
368
+ else:
369
+ aggregate = None
370
+ if aggregate == "max_over_tokens":
371
+ token_retrievers = 1
372
+ head_retrievers = self.num_heads
373
+ mem_attn_weights = torch.nn.functional.softmax(mem_attn_weights, dim=-1)
374
+ mem_attn_weights = mem_attn_weights.amax(dim=2, keepdim=True)
375
+ elif aggregate is None:
376
+ token_retrievers = q_len
377
+ head_retrievers = self.num_heads
378
+ else:
379
+ raise NotImplementedError()
380
+
381
+ mem_selected_idx = mem_attn_weights.topk(dim=-1,k=top_k)[1].sort(dim=-1)[0].view(bsz, head_retrievers, token_retrievers, top_k)
382
+
383
+ selected_indices = torch.arange(0, top_k * (self.mem_freq + 1), device=query_states.device, dtype=position_ids.dtype)
384
+ selected_indices = torch.where(mem_selected_idx >= num_mems - top_k, self.mem_freq + 1, 0).unsqueeze(-1) + selected_indices.view(1, 1, 1, top_k, self.mem_freq + 1)
385
+ selected_indices = selected_indices.view(bsz, head_retrievers, token_retrievers, -1).expand(bsz, self.num_heads, q_len, -1) + prefix_len
386
+
387
+
388
+
389
+
390
+ mem_selected_idx = mem_selected_idx.to(past_key_mem.device)
391
+
392
+ mem_selected_idx = mem_selected_idx.view(bsz, self.num_heads, token_retrievers, top_k, 1, 1).expand(bsz, self.num_heads, token_retrievers, top_k, self.mem_freq + 1, self.head_dim)
393
+ selected_keys = past_key_mem.unsqueeze(2).expand(bsz, self.num_heads, token_retrievers, -1, self.mem_freq + 1, self.head_dim)
394
+ selected_keys = selected_keys.take_along_dim(mem_selected_idx, dim=3).to(query_states.device)
395
+ selected_values = past_value_mem.unsqueeze(2).expand(bsz, self.num_heads, token_retrievers, -1, self.mem_freq + 1, self.head_dim).take_along_dim(mem_selected_idx, dim=3).to(query_states.device)
396
+
397
+ selected_keys = selected_keys.view(bsz, self.num_heads, token_retrievers, -1, self.head_dim).expand(bsz, self.num_heads, q_len, -1, self.head_dim)
398
+ selected_keys = apply_rotary_pos_emb(None, selected_keys.unsqueeze(1), cos, sin, selected_indices)[1].squeeze(1)
399
+ selected_values = selected_values.view(bsz, self.num_heads, token_retrievers, -1, self.head_dim).expand(bsz, self.num_heads, q_len, -1, self.head_dim)
400
+ attn_prefix = torch.matmul(query_states.unsqueeze(3), selected_keys.transpose(3, 4)).squeeze(3) / math.sqrt(self.head_dim)
401
+ is_mem_prefix = torch.cat((is_mem.new_zeros((self.mem_freq, )), is_mem.new_ones((1, )))).unsqueeze(0).repeat((top_k, 1))
402
+ is_mem_prefix = is_mem_prefix.view(1, 1, 1, -1).expand(1, 1, q_len, -1)
403
+ is_mem = torch.cat((is_mem_prefix, is_mem), dim=-1)
404
+ last_section_mask = torch.cat((last_section_mask.new_zeros((1, 1, q_len, top_k * (self.mem_freq + 1))), last_section_mask), dim=-1)
405
+ expected_att_size = (bsz, self.num_heads, q_len, q_len + incomplete_len)
406
+
407
+ past_key_states = torch.cat([past_key_value[0], key_states_before_pos], dim=2)
408
+ past_value_states = torch.cat([past_key_value[1], orig_value_states], dim=2)
409
+
410
+ if offload_cache_to_cpu:
411
+ past_key_value = (past_key_states, past_value_states, mem_key_nopos, past_key_mem.to("cpu"), past_value_mem.to("cpu"), *past_key_value[5:]) if use_cache else None
412
+ else:
413
+ past_key_value = (past_key_states, past_value_states) if use_cache else None
414
+
415
+ else:
416
+ if self.mem_freq is None:
417
+ past_key_states = key_states
418
+ else:
419
+ past_key_states = key_states_before_pos
420
+ past_value_states = value_states
421
+ expected_att_size = (bsz, self.num_heads, q_len, kv_seq_len)
422
+ past_key_value = (past_key_states, past_value_states) if use_cache else None
423
+
424
+ attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
425
+ if attn_weights.size() != expected_att_size:
426
+ raise ValueError(
427
+ f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
428
+ f" {attn_weights.size()}"
429
+ )
430
+
431
+ if attention_mask is not None:
432
+ if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
433
+ raise ValueError(
434
+ f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
435
+ )
436
+ attn_weights = attn_weights + attention_mask[...,-attn_weights.shape[-1]:]
437
+ attn_weights = torch.max(attn_weights, torch.tensor(torch.finfo(attn_weights.dtype).min))
438
+ if attn_prefix is not None:
439
+ attn_weights = torch.cat((attn_prefix, attn_weights), dim=-1)
440
+ # upcast attention to fp32
441
+ if is_mem is None:
442
+ raise ValueError("Don't use this without landmarks")
443
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
444
+ else:
445
+ attn_weights = landmark_grouped_softmax(attn_weights, dim=-1, is_mem=is_mem.expand(-1, self.num_heads, -1, -1), last_section_mask=last_section_mask).to(query_states.dtype)
446
+ if attn_prefix is not None:
447
+ attn_prefix, attn_weights = torch.split(attn_weights, (attn_prefix.shape[-1], attn_weights.shape[-1] - attn_prefix.shape[-1]), dim=-1)
448
+ attn_output = torch.matmul(attn_weights, value_states)
449
+ if attn_prefix is not None:
450
+ attn_output += torch.matmul(attn_prefix.unsqueeze(3), selected_values).squeeze(3)
451
+
452
+ if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
453
+ raise ValueError(
454
+ f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
455
+ f" {attn_output.size()}"
456
+ )
457
+
458
+ attn_output = attn_output.transpose(1, 2)
459
+ attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
460
+
461
+ attn_output = self.o_proj(attn_output)
462
+
463
+ if not output_attentions:
464
+ attn_weights = None
465
+
466
+ return attn_output, attn_weights, past_key_value
467
+
468
+
469
+ class LlamaDecoderLayer(nn.Module):
470
+ def __init__(self, config: LlamaConfig):
471
+ super().__init__()
472
+ self.hidden_size = config.hidden_size
473
+ self.self_attn = LlamaAttention(config=config)
474
+ self.mlp = LlamaMLP(
475
+ hidden_size=self.hidden_size,
476
+ intermediate_size=config.intermediate_size,
477
+ hidden_act=config.hidden_act,
478
+ )
479
+ self.input_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
480
+ self.post_attention_layernorm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
481
+
482
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
483
+ self.self_attn.set_mem_cache_args(mem_freq, top_k, max_cache_size)
484
+
485
+ def forward(
486
+ self,
487
+ hidden_states: torch.Tensor,
488
+ attention_mask: Optional[torch.Tensor] = None,
489
+ position_ids: Optional[torch.LongTensor] = None,
490
+ past_key_value: Optional[Tuple[torch.Tensor]] = None,
491
+ output_attentions: Optional[bool] = False,
492
+ use_cache: Optional[bool] = False,
493
+ is_mem: Optional[torch.Tensor] = None,
494
+ last_section_mask: Optional[torch.Tensor] = None,
495
+ offload_cache_to_cpu: bool = False
496
+ ) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
497
+ """
498
+ Args:
499
+ hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
500
+ attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
501
+ `(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
502
+ output_attentions (`bool`, *optional*):
503
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under
504
+ returned tensors for more detail.
505
+ use_cache (`bool`, *optional*):
506
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
507
+ (see `past_key_values`).
508
+ past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
509
+ """
510
+
511
+ residual = hidden_states
512
+
513
+ hidden_states = self.input_layernorm(hidden_states)
514
+
515
+ # Self Attention
516
+ hidden_states, self_attn_weights, present_key_value = self.self_attn(
517
+ hidden_states=hidden_states,
518
+ attention_mask=attention_mask,
519
+ position_ids=position_ids,
520
+ past_key_value=past_key_value,
521
+ output_attentions=output_attentions,
522
+ use_cache=use_cache,
523
+ is_mem=is_mem,
524
+ last_section_mask=last_section_mask,
525
+ offload_cache_to_cpu=offload_cache_to_cpu
526
+ )
527
+ hidden_states = residual + hidden_states
528
+
529
+ # Fully Connected
530
+ residual = hidden_states
531
+ hidden_states = self.post_attention_layernorm(hidden_states)
532
+ hidden_states = self.mlp(hidden_states)
533
+ hidden_states = residual + hidden_states
534
+
535
+ outputs = (hidden_states,)
536
+
537
+ if output_attentions:
538
+ outputs += (self_attn_weights,)
539
+
540
+ if use_cache:
541
+ outputs += (present_key_value,)
542
+
543
+ return outputs
544
+
545
+
546
+ LLAMA_START_DOCSTRING = r"""
547
+ This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
548
+ library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
549
+ etc.)
550
+
551
+ This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
552
+ Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
553
+ and behavior.
554
+
555
+ Parameters:
556
+ config ([`LlamaConfig`]):
557
+ Model configuration class with all the parameters of the model. Initializing with a config file does not
558
+ load the weights associated with the model, only the configuration. Check out the
559
+ [`~PreTrainedModel.from_pretrained`] method to load the model weights.
560
+ """
561
+
562
+
563
+ @add_start_docstrings(
564
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
565
+ LLAMA_START_DOCSTRING,
566
+ )
567
+ class LlamaPreTrainedModel(PreTrainedModel):
568
+ config_class = LlamaConfig
569
+ base_model_prefix = "model"
570
+ supports_gradient_checkpointing = True
571
+ _no_split_modules = ["LlamaDecoderLayer"]
572
+ _keys_to_ignore_on_load_unexpected = [r"decoder\.version"]
573
+
574
+ def _init_weights(self, module):
575
+ std = self.config.initializer_range
576
+ if isinstance(module, nn.Linear):
577
+ module.weight.data.normal_(mean=0.0, std=std)
578
+ if module.bias is not None:
579
+ module.bias.data.zero_()
580
+ elif isinstance(module, nn.Embedding):
581
+ module.weight.data.normal_(mean=0.0, std=std)
582
+ if module.padding_idx is not None:
583
+ module.weight.data[module.padding_idx].zero_()
584
+
585
+ def _set_gradient_checkpointing(self, module, value=False):
586
+ if isinstance(module, LlamaModel):
587
+ module.gradient_checkpointing = value
588
+
589
+
590
+ LLAMA_INPUTS_DOCSTRING = r"""
591
+ Args:
592
+ input_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`):
593
+ Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide
594
+ it.
595
+
596
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
597
+ [`PreTrainedTokenizer.__call__`] for details.
598
+
599
+ [What are input IDs?](../glossary#input-ids)
600
+ attention_mask (`torch.Tensor` of shape `(batch_size, sequence_length)`, *optional*):
601
+ Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
602
+
603
+ - 1 for tokens that are **not masked**,
604
+ - 0 for tokens that are **masked**.
605
+
606
+ [What are attention masks?](../glossary#attention-mask)
607
+
608
+ Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
609
+ [`PreTrainedTokenizer.__call__`] for details.
610
+
611
+ If `past_key_values` is used, optionally only the last `decoder_input_ids` have to be input (see
612
+ `past_key_values`).
613
+
614
+ If you want to change padding behavior, you should read [`modeling_opt._prepare_decoder_attention_mask`]
615
+ and modify to your needs. See diagram 1 in [the paper](https://arxiv.org/abs/1910.13461) for more
616
+ information on the default strategy.
617
+
618
+ - 1 indicates the head is **not masked**,
619
+ - 0 indicates the head is **masked**.
620
+ position_ids (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
621
+ Indices of positions of each input sequence tokens in the position embeddings. Selected in the range `[0,
622
+ config.n_positions - 1]`.
623
+
624
+ [What are position IDs?](../glossary#position-ids)
625
+ past_key_values (`tuple(tuple(torch.FloatTensor))`, *optional*, returned when `use_cache=True` is passed or when `config.use_cache=True`):
626
+ Tuple of `tuple(torch.FloatTensor)` of length `config.n_layers`, with each tuple having 2 tensors of shape
627
+ `(batch_size, num_heads, sequence_length, embed_size_per_head)`) and 2 additional tensors of shape
628
+ `(batch_size, num_heads, encoder_sequence_length, embed_size_per_head)`.
629
+
630
+ Contains pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention
631
+ blocks) that can be used (see `past_key_values` input) to speed up sequential decoding.
632
+
633
+ If `past_key_values` are used, the user can optionally input only the last `decoder_input_ids` (those that
634
+ don't have their past key value states given to this model) of shape `(batch_size, 1)` instead of all
635
+ `decoder_input_ids` of shape `(batch_size, sequence_length)`.
636
+ inputs_embeds (`torch.FloatTensor` of shape `(batch_size, sequence_length, hidden_size)`, *optional*):
637
+ Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
638
+ is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
639
+ model's internal embedding lookup matrix.
640
+ use_cache (`bool`, *optional*):
641
+ If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding (see
642
+ `past_key_values`).
643
+ output_attentions (`bool`, *optional*):
644
+ Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
645
+ tensors for more detail.
646
+ output_hidden_states (`bool`, *optional*):
647
+ Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
648
+ more detail.
649
+ return_dict (`bool`, *optional*):
650
+ Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
651
+ """
652
+
653
+
654
+ @add_start_docstrings(
655
+ "The bare LLaMA Model outputting raw hidden-states without any specific head on top.",
656
+ LLAMA_START_DOCSTRING,
657
+ )
658
+ class LlamaModel(LlamaPreTrainedModel):
659
+ """
660
+ Transformer decoder consisting of *config.num_hidden_layers* layers. Each layer is a [`LlamaDecoderLayer`]
661
+
662
+ Args:
663
+ config: LlamaConfig
664
+ """
665
+
666
+ def __init__(self, config: LlamaConfig):
667
+ super().__init__(config)
668
+ self.padding_idx = config.pad_token_id
669
+ self.vocab_size = config.vocab_size
670
+
671
+ self.embed_tokens = nn.Embedding(config.vocab_size, config.hidden_size, self.padding_idx)
672
+ self.layers = nn.ModuleList([LlamaDecoderLayer(config) for _ in range(config.num_hidden_layers)])
673
+ self.norm = LlamaRMSNorm(config.hidden_size, eps=config.rms_norm_eps)
674
+
675
+ self.mem_id = None
676
+
677
+ self.gradient_checkpointing = False
678
+ # Initialize weights and apply final processing
679
+ self.post_init()
680
+
681
+ def get_input_embeddings(self):
682
+ return self.embed_tokens
683
+
684
+ def set_input_embeddings(self, value):
685
+ self.embed_tokens = value
686
+
687
+ def set_mem_id(self, mem_id):
688
+ self.mem_id = mem_id
689
+
690
+ def set_mem_cache_args(self, mem_freq, top_k, max_cache_size):
691
+ for l in self.layers:
692
+ l.set_mem_cache_args(mem_freq, top_k, max_cache_size)
693
+
694
+ # Copied from transformers.models.bart.modeling_bart.BartDecoder._prepare_decoder_attention_mask
695
+ def _prepare_decoder_attention_mask(self, attention_mask, input_shape, inputs_embeds, past_key_values_length):
696
+ # create causal mask
697
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
698
+ combined_attention_mask = None
699
+ if input_shape[-1] > 1:
700
+ combined_attention_mask = _make_causal_mask(
701
+ input_shape,
702
+ inputs_embeds.dtype,
703
+ device=inputs_embeds.device,
704
+ past_key_values_length=past_key_values_length,
705
+ )
706
+
707
+ if attention_mask is not None:
708
+ # [bsz, seq_len] -> [bsz, 1, tgt_seq_len, src_seq_len]
709
+ expanded_attn_mask = _expand_mask(attention_mask, inputs_embeds.dtype, tgt_len=input_shape[-1]).to(
710
+ inputs_embeds.device
711
+ )
712
+ combined_attention_mask = (
713
+ expanded_attn_mask if combined_attention_mask is None else expanded_attn_mask + combined_attention_mask
714
+ )
715
+
716
+ return combined_attention_mask
717
+
718
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
719
+ def forward(
720
+ self,
721
+ input_ids: torch.LongTensor = None,
722
+ attention_mask: Optional[torch.Tensor] = None,
723
+ position_ids: Optional[torch.LongTensor] = None,
724
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
725
+ inputs_embeds: Optional[torch.FloatTensor] = None,
726
+ use_cache: Optional[bool] = None,
727
+ output_attentions: Optional[bool] = None,
728
+ output_hidden_states: Optional[bool] = None,
729
+ return_dict: Optional[bool] = None,
730
+ offload_cache_to_cpu: Optional[bool] = None,
731
+ ) -> Union[Tuple, BaseModelOutputWithPast]:
732
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
733
+ output_hidden_states = (
734
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
735
+ )
736
+ use_cache = use_cache if use_cache is not None else self.config.use_cache
737
+
738
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
739
+
740
+ # retrieve input_ids and inputs_embeds
741
+ is_mem = None
742
+ if input_ids is not None and inputs_embeds is not None:
743
+ raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
744
+ elif input_ids is not None:
745
+ batch_size, seq_length = input_ids.shape
746
+ if self.mem_id is not None:
747
+ with torch.no_grad():
748
+ is_mem = input_ids == self.mem_id
749
+ elif inputs_embeds is not None:
750
+ batch_size, seq_length, _ = inputs_embeds.shape
751
+ if self.mem_id is not None:
752
+ raise NotImplementedError
753
+ else:
754
+ raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
755
+
756
+ seq_length_with_past = seq_length
757
+ past_key_values_length = 0
758
+
759
+ if past_key_values is not None:
760
+ if is_mem is not None:
761
+ pass
762
+ #raise NotImplementedError
763
+ past_key_values_length = past_key_values[0][0].shape[2]
764
+ if len(past_key_values[0]) > 2:
765
+ past_key_values_length += past_key_values[0][3].shape[2] * past_key_values[0][3].shape[3]
766
+ seq_length_with_past = seq_length_with_past + past_key_values_length
767
+
768
+ if position_ids is None:
769
+ device = input_ids.device if input_ids is not None else inputs_embeds.device
770
+ position_ids = torch.arange(
771
+ past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
772
+ )
773
+ position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
774
+ else:
775
+ position_ids = position_ids.view(-1, seq_length).long()
776
+
777
+ if inputs_embeds is None:
778
+ inputs_embeds = self.embed_tokens(input_ids)
779
+ # embed positions
780
+ if attention_mask is None:
781
+ attention_mask = torch.ones(
782
+ (batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
783
+ )
784
+ attention_mask = self._prepare_decoder_attention_mask(
785
+ attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
786
+ )
787
+
788
+ last_section_mask = None
789
+ if is_mem is not None:
790
+ is_mem = is_mem.unsqueeze(1).unsqueeze(2)
791
+ current_len = input_ids.shape[1]
792
+ mem_ids = torch.where(attention_mask[..., -current_len:] < -1, 0, torch.cumsum(is_mem, -1) - is_mem.int())
793
+ last_section_mask = torch.amax(mem_ids, -1, keepdim=True) == mem_ids
794
+ attention_mask[..., -current_len:].masked_fill_(last_section_mask & is_mem, torch.tensor(torch.finfo(inputs_embeds.dtype).min, device=inputs_embeds.device))
795
+ last_section_mask.logical_and_(attention_mask[..., -current_len:] > -1)
796
+ is_mem = is_mem.logical_and(attention_mask[..., -current_len:] > -1)
797
+
798
+
799
+ hidden_states = inputs_embeds
800
+
801
+ if self.gradient_checkpointing and self.training:
802
+ if use_cache:
803
+ logger.warning_once(
804
+ "`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
805
+ )
806
+ use_cache = False
807
+
808
+ # decoder layers
809
+ all_hidden_states = () if output_hidden_states else None
810
+ all_self_attns = () if output_attentions else None
811
+ next_decoder_cache = () if use_cache else None
812
+
813
+ for idx, decoder_layer in enumerate(self.layers):
814
+ if output_hidden_states:
815
+ all_hidden_states += (hidden_states,)
816
+
817
+ past_key_value = past_key_values[idx] if past_key_values is not None else None
818
+
819
+ if self.gradient_checkpointing and self.training:
820
+
821
+ def create_custom_forward(module):
822
+ def custom_forward(*inputs):
823
+ # None for past_key_value
824
+ return module(*inputs, output_attentions, None)
825
+
826
+ return custom_forward
827
+
828
+ layer_outputs = torch.utils.checkpoint.checkpoint(
829
+ create_custom_forward(decoder_layer),
830
+ hidden_states,
831
+ attention_mask,
832
+ position_ids,
833
+ None,
834
+ is_mem,
835
+ last_section_mask
836
+ )
837
+ else:
838
+ layer_outputs = decoder_layer(
839
+ hidden_states,
840
+ attention_mask=attention_mask,
841
+ position_ids=position_ids,
842
+ past_key_value=past_key_value,
843
+ output_attentions=output_attentions,
844
+ use_cache=use_cache,
845
+ is_mem=is_mem,
846
+ last_section_mask=last_section_mask,
847
+ offload_cache_to_cpu=offload_cache_to_cpu
848
+ )
849
+
850
+ hidden_states = layer_outputs[0]
851
+
852
+ if use_cache:
853
+ next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
854
+
855
+ if output_attentions:
856
+ all_self_attns += (layer_outputs[1],)
857
+
858
+ hidden_states = self.norm(hidden_states)
859
+
860
+ # add hidden states from the last decoder layer
861
+ if output_hidden_states:
862
+ all_hidden_states += (hidden_states,)
863
+
864
+ next_cache = next_decoder_cache if use_cache else None
865
+ if not return_dict:
866
+ return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
867
+ return BaseModelOutputWithPast(
868
+ last_hidden_state=hidden_states,
869
+ past_key_values=next_cache,
870
+ hidden_states=all_hidden_states,
871
+ attentions=all_self_attns,
872
+ )
873
+
874
+
875
+ class LlamaForCausalLM(LlamaPreTrainedModel):
876
+ def __init__(self, config):
877
+ super().__init__(config)
878
+ self.model = LlamaModel(config)
879
+
880
+ self.lm_head = nn.Linear(config.hidden_size, config.vocab_size, bias=False)
881
+
882
+ self.set_mem_id(config.mem_id)
883
+ self.set_mem_cache_args(config.mem_max_seq_len, config.mem_freq, config.mem_top_k, config.mem_max_cache_size)
884
+
885
+ # Initialize weights and apply final processing
886
+ self.post_init()
887
+
888
+ def get_input_embeddings(self):
889
+ return self.model.embed_tokens
890
+
891
+ def set_input_embeddings(self, value):
892
+ self.model.embed_tokens = value
893
+
894
+ def get_output_embeddings(self):
895
+ return self.lm_head
896
+
897
+ def set_output_embeddings(self, new_embeddings):
898
+ self.lm_head = new_embeddings
899
+
900
+ def set_decoder(self, decoder):
901
+ self.model = decoder
902
+
903
+ def get_decoder(self):
904
+ return self.model
905
+
906
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
907
+ @replace_return_docstrings(output_type=CausalLMOutputWithPast, config_class=_CONFIG_FOR_DOC)
908
+ def forward(
909
+ self,
910
+ input_ids: torch.LongTensor = None,
911
+ attention_mask: Optional[torch.Tensor] = None,
912
+ position_ids: Optional[torch.LongTensor] = None,
913
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
914
+ inputs_embeds: Optional[torch.FloatTensor] = None,
915
+ labels: Optional[torch.LongTensor] = None,
916
+ use_cache: Optional[bool] = None,
917
+ output_attentions: Optional[bool] = None,
918
+ output_hidden_states: Optional[bool] = None,
919
+ return_dict: Optional[bool] = None,
920
+ offload_cache_to_cpu: Optional[bool] = None,
921
+ ) -> Union[Tuple, CausalLMOutputWithPast]:
922
+ r"""
923
+ Args:
924
+ labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
925
+ Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
926
+ config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
927
+ (masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
928
+
929
+ Returns:
930
+
931
+ Example:
932
+
933
+ ```python
934
+ >>> from transformers import AutoTokenizer, LlamaForCausalLM
935
+
936
+ >>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
937
+ >>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
938
+
939
+ >>> prompt = "Hey, are you consciours? Can you talk to me?"
940
+ >>> inputs = tokenizer(prompt, return_tensors="pt")
941
+
942
+ >>> # Generate
943
+ >>> generate_ids = model.generate(inputs.input_ids, max_length=30)
944
+ >>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
945
+ "Hey, are you consciours? Can you talk to me?\nI'm not consciours, but I can talk to you."
946
+ ```"""
947
+
948
+ output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
949
+ output_hidden_states = (
950
+ output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
951
+ )
952
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
953
+
954
+ # decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
955
+ window_len = self.max_seq_len or input_ids.shape[1]
956
+ last_logits = None
957
+ for step, idx in enumerate(range(0, input_ids.shape[1], window_len)):
958
+ if idx >= 1:
959
+ if output_attentions or output_hidden_states:
960
+ raise NotImplementedError
961
+ if not use_cache:
962
+ raise NotImplementedError
963
+ outputs = self.model(
964
+ input_ids=input_ids[:, idx:idx + window_len],
965
+ attention_mask=attention_mask[:, :idx + window_len + attention_mask.shape[1] - input_ids.shape[1]] if attention_mask is not None else None,
966
+ position_ids=position_ids[:, idx:idx + window_len] if position_ids is not None else None,
967
+ past_key_values=past_key_values,
968
+ inputs_embeds=inputs_embeds[:, idx:idx + window_len] if inputs_embeds is not None else None,
969
+ use_cache=use_cache,
970
+ output_attentions=output_attentions,
971
+ output_hidden_states=output_hidden_states,
972
+ return_dict=return_dict,
973
+ offload_cache_to_cpu=offload_cache_to_cpu,
974
+ )
975
+ past_key_values = outputs[1]
976
+ if last_logits is not None:
977
+ last_logits = torch.cat((last_logits, outputs[0]), dim=-2)
978
+ last_logits = outputs[0]
979
+
980
+ hidden_states = last_logits
981
+ logits = self.lm_head(hidden_states)
982
+
983
+ loss = None
984
+ if labels is not None:
985
+ # Shift so that tokens < n predict n
986
+ shift_logits = logits[..., :-1, :].contiguous()
987
+ shift_labels = labels[..., 1:].contiguous()
988
+ # Flatten the tokens
989
+ loss_fct = CrossEntropyLoss()
990
+ shift_logits = shift_logits.view(-1, self.config.vocab_size)
991
+ shift_labels = shift_labels.view(-1)
992
+ # Enable model parallelism
993
+ shift_labels = shift_labels.to(shift_logits.device)
994
+ loss = loss_fct(shift_logits, shift_labels)
995
+
996
+ if not return_dict:
997
+ output = (logits,) + outputs[1:]
998
+ return (loss,) + output if loss is not None else output
999
+
1000
+ return CausalLMOutputWithPast(
1001
+ loss=loss,
1002
+ logits=logits,
1003
+ past_key_values=outputs.past_key_values,
1004
+ hidden_states=outputs.hidden_states,
1005
+ attentions=outputs.attentions,
1006
+ )
1007
+
1008
+ def set_mem_id(self, mem_id):
1009
+ self.mem_id = mem_id
1010
+ self.model.set_mem_id(mem_id)
1011
+
1012
+ def set_mem_cache_args(self, max_seq_len, mem_freq, top_k, max_cache_size):
1013
+ self.mem_freq = mem_freq
1014
+ self.top_k = top_k
1015
+ self.max_seq_len = max_seq_len
1016
+ if self.max_seq_len is not None:
1017
+ assert self.max_seq_len % (self.mem_freq + 1) == 0
1018
+ self.model.set_mem_cache_args(mem_freq, top_k, max_cache_size)
1019
+
1020
+ def prepare_inputs_for_generation(
1021
+ self, input_ids, past_key_values=None, attention_mask=None, inputs_embeds=None, **kwargs
1022
+ ):
1023
+ total_len = input_ids.shape[1]
1024
+ if past_key_values:
1025
+ prev_len = input_ids.shape[1] - 1
1026
+ else:
1027
+ prev_len = 0
1028
+
1029
+ position_ids = kwargs.get("position_ids", None)
1030
+
1031
+ if self.mem_freq is not None:
1032
+ if position_ids is not None:
1033
+ raise NotImplementedError
1034
+ T = input_ids.shape[1]
1035
+
1036
+ prev_incomplete_len = prev_len % self.mem_freq
1037
+ prev_complete_len = prev_len - prev_incomplete_len
1038
+ incomplete_len = total_len % self.mem_freq
1039
+ new_full_len = total_len - prev_complete_len - incomplete_len
1040
+
1041
+ prev_input, input_ids_with_mem, input_ids_without_mem = torch.split(input_ids, (prev_complete_len, new_full_len, incomplete_len), dim=-1)
1042
+
1043
+ bsz, q_len = input_ids.size()
1044
+ input_ids_with_mem = input_ids_with_mem.view(bsz, -1, self.mem_freq)
1045
+ input_ids_with_mem = torch.cat(
1046
+ (
1047
+ input_ids_with_mem,
1048
+ input_ids_with_mem.new_full((bsz, input_ids_with_mem.shape[1], 1), self.mem_id)
1049
+ ),
1050
+ dim=-1
1051
+ ).view(bsz, -1)
1052
+ input_ids = torch.cat((prev_input, input_ids_with_mem, input_ids_without_mem), dim=-1)
1053
+ if attention_mask is not None:
1054
+ attention_mask_with_mem, attention_mask_without_mem = torch.split(attention_mask, (prev_complete_len + new_full_len, incomplete_len), dim=-1)
1055
+ attention_mask_with_mem = attention_mask_with_mem.view(bsz, -1, self.mem_freq)
1056
+ attention_mask_with_mem = torch.cat(
1057
+ (
1058
+ attention_mask_with_mem,
1059
+ attention_mask_with_mem.new_ones((bsz, attention_mask_with_mem.shape[1], 1))
1060
+ ),
1061
+ dim=-1
1062
+ ).view(bsz, -1)
1063
+ attention_mask = torch.cat((attention_mask_with_mem, attention_mask_without_mem), dim=-1)
1064
+
1065
+
1066
+ input_ids = input_ids[:, prev_len:]
1067
+ if attention_mask is not None and position_ids is None:
1068
+ # create position_ids on the fly for batch generation
1069
+ position_ids = attention_mask.long().cumsum(-1) - 1
1070
+ position_ids.masked_fill_(attention_mask == 0, 1)
1071
+ position_ids = position_ids[:, -input_ids.shape[1]:].unsqueeze(-1)
1072
+
1073
+ # if `inputs_embeds` are passed, we only want to use them in the 1st generation step
1074
+ if inputs_embeds is not None and past_key_values is None and self.mem_freq is None:
1075
+ model_inputs = {"inputs_embeds": inputs_embeds}
1076
+ else:
1077
+ model_inputs = {"input_ids": input_ids}
1078
+
1079
+ model_inputs.update(
1080
+ {
1081
+ "position_ids": position_ids,
1082
+ "past_key_values": past_key_values,
1083
+ "use_cache": kwargs.get("use_cache"),
1084
+ "attention_mask": attention_mask,
1085
+ "offload_cache_to_cpu": kwargs.get("offload_cache_to_cpu")
1086
+ }
1087
+ )
1088
+ return model_inputs
1089
+
1090
+ @staticmethod
1091
+ def _reorder_cache(past_key_values, beam_idx):
1092
+ reordered_past = ()
1093
+ for layer_past in past_key_values:
1094
+ reordered_past += (tuple(past_state.index_select(0, beam_idx) for past_state in layer_past),)
1095
+ return reordered_past
1096
+
1097
+
1098
+ @add_start_docstrings(
1099
+ """
1100
+ The LLaMa Model transformer with a sequence classification head on top (linear layer).
1101
+
1102
+ [`LlamaForSequenceClassification`] uses the last token in order to do the classification, as other causal models
1103
+ (e.g. GPT-2) do.
1104
+
1105
+ Since it does classification on the last token, it requires to know the position of the last token. If a
1106
+ `pad_token_id` is defined in the configuration, it finds the last token that is not a padding token in each row. If
1107
+ no `pad_token_id` is defined, it simply takes the last value in each row of the batch. Since it cannot guess the
1108
+ padding tokens when `inputs_embeds` are passed instead of `input_ids`, it does the same (take the last value in
1109
+ each row of the batch).
1110
+ """,
1111
+ LLAMA_START_DOCSTRING,
1112
+ )
1113
+ class LlamaForSequenceClassification(LlamaPreTrainedModel):
1114
+ _keys_to_ignore_on_load_missing = [r"lm_head.weight"]
1115
+
1116
+ def __init__(self, config):
1117
+ super().__init__(config)
1118
+ self.num_labels = config.num_labels
1119
+ self.model = LlamaModel(config)
1120
+ self.score = nn.Linear(config.hidden_size, self.num_labels, bias=False)
1121
+
1122
+ # Initialize weights and apply final processing
1123
+ self.post_init()
1124
+
1125
+ def get_input_embeddings(self):
1126
+ return self.model.embed_tokens
1127
+
1128
+ def set_input_embeddings(self, value):
1129
+ self.model.embed_tokens = value
1130
+
1131
+ @add_start_docstrings_to_model_forward(LLAMA_INPUTS_DOCSTRING)
1132
+ def forward(
1133
+ self,
1134
+ input_ids: torch.LongTensor = None,
1135
+ attention_mask: Optional[torch.Tensor] = None,
1136
+ position_ids: Optional[torch.LongTensor] = None,
1137
+ past_key_values: Optional[List[torch.FloatTensor]] = None,
1138
+ inputs_embeds: Optional[torch.FloatTensor] = None,
1139
+ labels: Optional[torch.LongTensor] = None,
1140
+ use_cache: Optional[bool] = None,
1141
+ output_attentions: Optional[bool] = None,
1142
+ output_hidden_states: Optional[bool] = None,
1143
+ return_dict: Optional[bool] = None,
1144
+ ) -> Union[Tuple, SequenceClassifierOutputWithPast]:
1145
+ r"""
1146
+ labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
1147
+ Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
1148
+ config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
1149
+ `config.num_labels > 1` a classification loss is computed (Cross-Entropy).
1150
+ """
1151
+ return_dict = return_dict if return_dict is not None else self.config.use_return_dict
1152
+
1153
+ transformer_outputs = self.model(
1154
+ input_ids,
1155
+ attention_mask=attention_mask,
1156
+ position_ids=position_ids,
1157
+ past_key_values=past_key_values,
1158
+ inputs_embeds=inputs_embeds,
1159
+ use_cache=use_cache,
1160
+ output_attentions=output_attentions,
1161
+ output_hidden_states=output_hidden_states,
1162
+ return_dict=return_dict,
1163
+ )
1164
+ hidden_states = transformer_outputs[0]
1165
+ logits = self.score(hidden_states)
1166
+
1167
+ if input_ids is not None:
1168
+ batch_size = input_ids.shape[0]
1169
+ else:
1170
+ batch_size = inputs_embeds.shape[0]
1171
+
1172
+ if self.config.pad_token_id is None and batch_size != 1:
1173
+ raise ValueError("Cannot handle batch sizes > 1 if no padding token is defined.")
1174
+ if self.config.pad_token_id is None:
1175
+ sequence_lengths = -1
1176
+ else:
1177
+ if input_ids is not None:
1178
+ sequence_lengths = (torch.ne(input_ids, self.config.pad_token_id).sum(-1) - 1).to(logits.device)
1179
+ else:
1180
+ sequence_lengths = -1
1181
+
1182
+ pooled_logits = logits[torch.arange(batch_size, device=logits.device), sequence_lengths]
1183
+
1184
+ loss = None
1185
+ if labels is not None:
1186
+ labels = labels.to(logits.device)
1187
+ if self.config.problem_type is None:
1188
+ if self.num_labels == 1:
1189
+ self.config.problem_type = "regression"
1190
+ elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
1191
+ self.config.problem_type = "single_label_classification"
1192
+ else:
1193
+ self.config.problem_type = "multi_label_classification"
1194
+
1195
+ if self.config.problem_type == "regression":
1196
+ loss_fct = MSELoss()
1197
+ if self.num_labels == 1:
1198
+ loss = loss_fct(pooled_logits.squeeze(), labels.squeeze())
1199
+ else:
1200
+ loss = loss_fct(pooled_logits, labels)
1201
+ elif self.config.problem_type == "single_label_classification":
1202
+ loss_fct = CrossEntropyLoss()
1203
+ loss = loss_fct(pooled_logits.view(-1, self.num_labels), labels.view(-1))
1204
+ elif self.config.problem_type == "multi_label_classification":
1205
+ loss_fct = BCEWithLogitsLoss()
1206
+ loss = loss_fct(pooled_logits, labels)
1207
+ if not return_dict:
1208
+ output = (pooled_logits,) + transformer_outputs[1:]
1209
+ return ((loss,) + output) if loss is not None else output
1210
+
1211
+ return SequenceClassifierOutputWithPast(
1212
+ loss=loss,
1213
+ logits=pooled_logits,
1214
+ past_key_values=transformer_outputs.past_key_values,
1215
+ hidden_states=transformer_outputs.hidden_states,
1216
+ attentions=transformer_outputs.attentions,
1217
+ )