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