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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import math
|
2 |
+
import warnings
|
3 |
+
from functools import partial
|
4 |
+
from typing import List, Optional, Tuple, Union
|
5 |
+
|
6 |
+
import torch
|
7 |
+
import torch.nn.functional as F
|
8 |
+
import torch.utils.checkpoint
|
9 |
+
from torch import nn
|
10 |
+
|
11 |
+
|
12 |
+
import copy
|
13 |
+
import os
|
14 |
+
import sys
|
15 |
+
|
16 |
+
dir_path = os.path.dirname(os.path.realpath(__file__))
|
17 |
+
sys.path.insert(0, dir_path)
|
18 |
+
|
19 |
+
from .modeling_attn_mask_utils import _prepare_4d_causal_attention_mask, _prepare_4d_causal_attention_mask_for_sdpa
|
20 |
+
|
21 |
+
import transformers
|
22 |
+
from transformers.models.llama.modeling_llama import *
|
23 |
+
|
24 |
+
def _get_unpad_data(attention_mask):
|
25 |
+
seqlens_in_batch = attention_mask.sum(dim=-1, dtype=torch.int32)
|
26 |
+
indices = torch.nonzero(attention_mask.flatten(), as_tuple=False).flatten()
|
27 |
+
max_seqlen_in_batch = seqlens_in_batch.max().item()
|
28 |
+
cu_seqlens = F.pad(torch.cumsum(seqlens_in_batch, dim=0, dtype=torch.torch.int32), (1, 0))
|
29 |
+
return (
|
30 |
+
indices,
|
31 |
+
cu_seqlens,
|
32 |
+
max_seqlen_in_batch,
|
33 |
+
)
|
34 |
+
|
35 |
+
|
36 |
+
from transformers.configuration_utils import PretrainedConfig
|
37 |
+
from transformers.utils import logging
|
38 |
+
|
39 |
+
from .modeling_attn_mask_utils import _prepare_4d_causal_attention_mask
|
40 |
+
from .configuration_mplug_owl2 import LlamaConfig
|
41 |
+
|
42 |
+
class MultiwayNetwork(nn.Module):
|
43 |
+
|
44 |
+
def __init__(self, module_provider, num_multiway=2):
|
45 |
+
super(MultiwayNetwork, self).__init__()
|
46 |
+
|
47 |
+
self.multiway = torch.nn.ModuleList([module_provider() for _ in range(num_multiway)])
|
48 |
+
|
49 |
+
def forward(self, hidden_states, multiway_indices):
|
50 |
+
|
51 |
+
if len(self.multiway) == 1:
|
52 |
+
return self.multiway[0](hidden_states)
|
53 |
+
|
54 |
+
output_hidden_states = torch.empty_like(hidden_states)
|
55 |
+
|
56 |
+
for idx, subway in enumerate(self.multiway):
|
57 |
+
local_indices = multiway_indices.eq(idx).nonzero(as_tuple=True)
|
58 |
+
hidden = hidden_states[local_indices].unsqueeze(1).contiguous()
|
59 |
+
if hidden.numel():
|
60 |
+
output = subway(hidden)
|
61 |
+
if isinstance(output, tuple):
|
62 |
+
output = output[0]
|
63 |
+
output = output.squeeze(1)
|
64 |
+
output_hidden_states[local_indices] = output
|
65 |
+
|
66 |
+
return output_hidden_states.contiguous()
|
67 |
+
|
68 |
+
|
69 |
+
class LlamaAttention(nn.Module):
|
70 |
+
"""Multi-headed attention from 'Attention Is All You Need' paper"""
|
71 |
+
|
72 |
+
def __init__(self, config: LlamaConfig, layer_idx: Optional[int] = None):
|
73 |
+
super().__init__()
|
74 |
+
self.config = config
|
75 |
+
self.layer_idx = layer_idx
|
76 |
+
if layer_idx is None:
|
77 |
+
logger.warning_once(
|
78 |
+
f"Instantiating {self.__class__.__name__} without passing `layer_idx` is not recommended and will "
|
79 |
+
"to errors during the forward call, if caching is used. Please make sure to provide a `layer_idx` "
|
80 |
+
"when creating this class."
|
81 |
+
)
|
82 |
+
|
83 |
+
self.attention_dropout = config.attention_dropout
|
84 |
+
self.hidden_size = config.hidden_size
|
85 |
+
self.num_heads = config.num_attention_heads
|
86 |
+
self.head_dim = self.hidden_size // self.num_heads
|
87 |
+
self.num_key_value_heads = config.num_key_value_heads
|
88 |
+
self.num_key_value_groups = self.num_heads // self.num_key_value_heads
|
89 |
+
self.max_position_embeddings = config.max_position_embeddings
|
90 |
+
self.rope_theta = config.rope_theta
|
91 |
+
self.is_causal = True
|
92 |
+
|
93 |
+
if (self.head_dim * self.num_heads) != self.hidden_size:
|
94 |
+
raise ValueError(
|
95 |
+
f"hidden_size must be divisible by num_heads (got `hidden_size`: {self.hidden_size}"
|
96 |
+
f" and `num_heads`: {self.num_heads})."
|
97 |
+
)
|
98 |
+
self.q_proj = nn.Linear(self.hidden_size, self.num_heads * self.head_dim, bias=config.attention_bias)
|
99 |
+
self.k_proj = MultiwayNetwork(module_provider=partial(
|
100 |
+
nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
101 |
+
)
|
102 |
+
self.v_proj = MultiwayNetwork(module_provider=partial(
|
103 |
+
nn.Linear, in_features=self.hidden_size, out_features=self.num_key_value_heads * self.head_dim, bias=config.attention_bias)
|
104 |
+
)
|
105 |
+
self.o_proj = nn.Linear(self.num_heads * self.head_dim, self.hidden_size, bias=config.attention_bias)
|
106 |
+
self._init_rope()
|
107 |
+
|
108 |
+
def _init_rope(self):
|
109 |
+
if self.config.rope_scaling is None:
|
110 |
+
self.rotary_emb = LlamaRotaryEmbedding(
|
111 |
+
self.head_dim,
|
112 |
+
max_position_embeddings=self.max_position_embeddings,
|
113 |
+
base=self.rope_theta,
|
114 |
+
)
|
115 |
+
else:
|
116 |
+
scaling_type = self.config.rope_scaling["type"]
|
117 |
+
scaling_factor = self.config.rope_scaling["factor"]
|
118 |
+
if scaling_type == "linear":
|
119 |
+
self.rotary_emb = LlamaLinearScalingRotaryEmbedding(
|
120 |
+
self.head_dim,
|
121 |
+
max_position_embeddings=self.max_position_embeddings,
|
122 |
+
scaling_factor=scaling_factor,
|
123 |
+
base=self.rope_theta,
|
124 |
+
)
|
125 |
+
elif scaling_type == "dynamic":
|
126 |
+
self.rotary_emb = LlamaDynamicNTKScalingRotaryEmbedding(
|
127 |
+
self.head_dim,
|
128 |
+
max_position_embeddings=self.max_position_embeddings,
|
129 |
+
scaling_factor=scaling_factor,
|
130 |
+
base=self.rope_theta,
|
131 |
+
)
|
132 |
+
else:
|
133 |
+
raise ValueError(f"Unknown RoPE scaling type {scaling_type}")
|
134 |
+
|
135 |
+
def _shape(self, tensor: torch.Tensor, seq_len: int, bsz: int):
|
136 |
+
return tensor.view(bsz, seq_len, self.num_heads, self.head_dim).transpose(1, 2).contiguous()
|
137 |
+
|
138 |
+
def forward(
|
139 |
+
self,
|
140 |
+
hidden_states: torch.Tensor,
|
141 |
+
modality_indicators: torch.Tensor,
|
142 |
+
attention_mask: Optional[torch.Tensor] = None,
|
143 |
+
position_ids: Optional[torch.LongTensor] = None,
|
144 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
145 |
+
output_attentions: bool = False,
|
146 |
+
use_cache: bool = False,
|
147 |
+
padding_mask: Optional[torch.LongTensor] = None,
|
148 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
149 |
+
bsz, q_len, _ = hidden_states.size()
|
150 |
+
|
151 |
+
query_states = self.q_proj(hidden_states, )
|
152 |
+
key_states = self.k_proj(hidden_states, modality_indicators)
|
153 |
+
value_states = self.v_proj(hidden_states, modality_indicators)
|
154 |
+
|
155 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
156 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
157 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
158 |
+
|
159 |
+
kv_seq_len = key_states.shape[-2]
|
160 |
+
if past_key_value is not None:
|
161 |
+
kv_seq_len += past_key_value[0].shape[-2]
|
162 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
163 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
164 |
+
|
165 |
+
if past_key_value is not None:
|
166 |
+
# reuse k, v, self_attention
|
167 |
+
key_states = torch.cat([past_key_value[0], key_states], dim=2)
|
168 |
+
value_states = torch.cat([past_key_value[1], value_states], dim=2)
|
169 |
+
|
170 |
+
past_key_value = (key_states, value_states) if use_cache else None
|
171 |
+
|
172 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
173 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
174 |
+
|
175 |
+
attn_weights = torch.matmul(query_states, key_states.transpose(2, 3)) / math.sqrt(self.head_dim)
|
176 |
+
|
177 |
+
if attn_weights.size() != (bsz, self.num_heads, q_len, kv_seq_len):
|
178 |
+
raise ValueError(
|
179 |
+
f"Attention weights should be of size {(bsz, self.num_heads, q_len, kv_seq_len)}, but is"
|
180 |
+
f" {attn_weights.size()}"
|
181 |
+
)
|
182 |
+
|
183 |
+
if attention_mask is not None:
|
184 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
185 |
+
raise ValueError(
|
186 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
187 |
+
)
|
188 |
+
attn_weights = attn_weights + attention_mask
|
189 |
+
|
190 |
+
# upcast attention to fp32
|
191 |
+
attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(query_states.dtype)
|
192 |
+
attn_output = torch.matmul(attn_weights, value_states)
|
193 |
+
|
194 |
+
if attn_output.size() != (bsz, self.num_heads, q_len, self.head_dim):
|
195 |
+
raise ValueError(
|
196 |
+
f"`attn_output` should be of size {(bsz, self.num_heads, q_len, self.head_dim)}, but is"
|
197 |
+
f" {attn_output.size()}"
|
198 |
+
)
|
199 |
+
|
200 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
201 |
+
|
202 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
203 |
+
|
204 |
+
attn_output = self.o_proj(attn_output)
|
205 |
+
|
206 |
+
if not output_attentions:
|
207 |
+
attn_weights = None
|
208 |
+
|
209 |
+
return attn_output, attn_weights, past_key_value
|
210 |
+
|
211 |
+
|
212 |
+
class LlamaFlashAttention2(LlamaAttention):
|
213 |
+
"""
|
214 |
+
Llama flash attention module. This module inherits from `LlamaAttention` as the weights of the module stays
|
215 |
+
untouched. The only required change would be on the forward pass where it needs to correctly call the public API of
|
216 |
+
flash attention and deal with padding tokens in case the input contains any of them.
|
217 |
+
"""
|
218 |
+
|
219 |
+
def __init__(self, *args, **kwargs):
|
220 |
+
super().__init__(*args, **kwargs)
|
221 |
+
|
222 |
+
# TODO: Should be removed once Flash Attention for RoCm is bumped to 2.1.
|
223 |
+
# flash_attn<2.1 generates top-left aligned causal mask, while what is needed here is bottom-right alignement, that was made default for flash_attn>=2.1. This attribute is used to handle this difference. Reference: https://github.com/Dao-AILab/flash-attention/releases/tag/v2.1.0.
|
224 |
+
# Beware that with flash_attn<2.1, using q_seqlen != k_seqlen (except for the case q_seqlen == 1) produces a wrong mask (top-left).
|
225 |
+
self._flash_attn_uses_top_left_mask = not is_flash_attn_greater_or_equal_2_10()
|
226 |
+
|
227 |
+
def forward(
|
228 |
+
self,
|
229 |
+
hidden_states: torch.Tensor,
|
230 |
+
modality_indicators: torch.Tensor,
|
231 |
+
attention_mask: Optional[torch.LongTensor] = None,
|
232 |
+
position_ids: Optional[torch.LongTensor] = None,
|
233 |
+
past_key_value: Optional[Cache] = None,
|
234 |
+
output_attentions: bool = False,
|
235 |
+
use_cache: bool = False,
|
236 |
+
**kwargs,
|
237 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
238 |
+
# LlamaFlashAttention2 attention does not support output_attentions
|
239 |
+
if "padding_mask" in kwargs:
|
240 |
+
warnings.warn(
|
241 |
+
"Passing `padding_mask` is deprecated and will be removed in v4.37. Please make sure use `attention_mask` instead.`"
|
242 |
+
)
|
243 |
+
|
244 |
+
# overwrite attention_mask with padding_mask
|
245 |
+
attention_mask = kwargs.pop("padding_mask")
|
246 |
+
|
247 |
+
output_attentions = False
|
248 |
+
|
249 |
+
bsz, q_len, _ = hidden_states.size()
|
250 |
+
|
251 |
+
query_states = self.q_proj(hidden_states)
|
252 |
+
key_states = self.k_proj(hidden_states, modality_indicators)
|
253 |
+
value_states = self.v_proj(hidden_states, modality_indicators)
|
254 |
+
|
255 |
+
# Flash attention requires the input to have the shape
|
256 |
+
# batch_size x seq_length x head_dim x hidden_dim
|
257 |
+
# therefore we just need to keep the original shape
|
258 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
259 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
260 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
261 |
+
|
262 |
+
kv_seq_len = key_states.shape[-2]
|
263 |
+
if past_key_value is not None:
|
264 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
265 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
266 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
267 |
+
|
268 |
+
if past_key_value is not None:
|
269 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
270 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
271 |
+
|
272 |
+
# TODO: These transpose are quite inefficient but Flash Attention requires the layout [batch_size, sequence_length, num_heads, head_dim]. We would need to refactor the KV cache
|
273 |
+
# to be able to avoid many of these transpose/reshape/view.
|
274 |
+
query_states = query_states.transpose(1, 2)
|
275 |
+
key_states = key_states.transpose(1, 2)
|
276 |
+
value_states = value_states.transpose(1, 2)
|
277 |
+
|
278 |
+
dropout_rate = self.attention_dropout if self.training else 0.0
|
279 |
+
|
280 |
+
# In PEFT, usually we cast the layer norms in float32 for training stability reasons
|
281 |
+
# therefore the input hidden states gets silently casted in float32. Hence, we need
|
282 |
+
# cast them back in the correct dtype just to be sure everything works as expected.
|
283 |
+
# This might slowdown training & inference so it is recommended to not cast the LayerNorms
|
284 |
+
# in fp32. (LlamaRMSNorm handles it correctly)
|
285 |
+
|
286 |
+
input_dtype = query_states.dtype
|
287 |
+
if input_dtype == torch.float32:
|
288 |
+
if torch.is_autocast_enabled():
|
289 |
+
target_dtype = torch.get_autocast_gpu_dtype()
|
290 |
+
# Handle the case where the model is quantized
|
291 |
+
elif hasattr(self.config, "_pre_quantization_dtype"):
|
292 |
+
target_dtype = self.config._pre_quantization_dtype
|
293 |
+
else:
|
294 |
+
target_dtype = self.q_proj.weight.dtype
|
295 |
+
|
296 |
+
logger.warning_once(
|
297 |
+
f"The input hidden states seems to be silently casted in float32, this might be related to"
|
298 |
+
f" the fact you have upcasted embedding or layer norm layers in float32. We will cast back the input in"
|
299 |
+
f" {target_dtype}."
|
300 |
+
)
|
301 |
+
|
302 |
+
query_states = query_states.to(target_dtype)
|
303 |
+
key_states = key_states.to(target_dtype)
|
304 |
+
value_states = value_states.to(target_dtype)
|
305 |
+
|
306 |
+
attn_output = self._flash_attention_forward(
|
307 |
+
query_states, key_states, value_states, attention_mask, q_len, dropout=dropout_rate
|
308 |
+
)
|
309 |
+
|
310 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size).contiguous()
|
311 |
+
attn_output = self.o_proj(attn_output)
|
312 |
+
|
313 |
+
if not output_attentions:
|
314 |
+
attn_weights = None
|
315 |
+
|
316 |
+
return attn_output, attn_weights, past_key_value
|
317 |
+
|
318 |
+
def _flash_attention_forward(
|
319 |
+
self, query_states, key_states, value_states, attention_mask, query_length, dropout=0.0, softmax_scale=None
|
320 |
+
):
|
321 |
+
"""
|
322 |
+
Calls the forward method of Flash Attention - if the input hidden states contain at least one padding token
|
323 |
+
first unpad the input, then computes the attention scores and pad the final attention scores.
|
324 |
+
|
325 |
+
Args:
|
326 |
+
query_states (`torch.Tensor`):
|
327 |
+
Input query states to be passed to Flash Attention API
|
328 |
+
key_states (`torch.Tensor`):
|
329 |
+
Input key states to be passed to Flash Attention API
|
330 |
+
value_states (`torch.Tensor`):
|
331 |
+
Input value states to be passed to Flash Attention API
|
332 |
+
attention_mask (`torch.Tensor`):
|
333 |
+
The padding mask - corresponds to a tensor of size `(batch_size, seq_len)` where 0 stands for the
|
334 |
+
position of padding tokens and 1 for the position of non-padding tokens.
|
335 |
+
dropout (`int`, *optional*):
|
336 |
+
Attention dropout
|
337 |
+
softmax_scale (`float`, *optional*):
|
338 |
+
The scaling of QK^T before applying softmax. Default to 1 / sqrt(head_dim)
|
339 |
+
"""
|
340 |
+
if not self._flash_attn_uses_top_left_mask:
|
341 |
+
causal = self.is_causal
|
342 |
+
else:
|
343 |
+
# TODO: Remove the `query_length != 1` check once Flash Attention for RoCm is bumped to 2.1. For details, please see the comment in LlamaFlashAttention2 __init__.
|
344 |
+
causal = self.is_causal and query_length != 1
|
345 |
+
|
346 |
+
# Contains at least one padding token in the sequence
|
347 |
+
if attention_mask is not None:
|
348 |
+
batch_size = query_states.shape[0]
|
349 |
+
query_states, key_states, value_states, indices_q, cu_seq_lens, max_seq_lens = self._upad_input(
|
350 |
+
query_states, key_states, value_states, attention_mask, query_length
|
351 |
+
)
|
352 |
+
|
353 |
+
cu_seqlens_q, cu_seqlens_k = cu_seq_lens
|
354 |
+
max_seqlen_in_batch_q, max_seqlen_in_batch_k = max_seq_lens
|
355 |
+
|
356 |
+
attn_output_unpad = flash_attn_varlen_func(
|
357 |
+
query_states,
|
358 |
+
key_states,
|
359 |
+
value_states,
|
360 |
+
cu_seqlens_q=cu_seqlens_q,
|
361 |
+
cu_seqlens_k=cu_seqlens_k,
|
362 |
+
max_seqlen_q=max_seqlen_in_batch_q,
|
363 |
+
max_seqlen_k=max_seqlen_in_batch_k,
|
364 |
+
dropout_p=dropout,
|
365 |
+
softmax_scale=softmax_scale,
|
366 |
+
causal=causal,
|
367 |
+
)
|
368 |
+
|
369 |
+
attn_output = pad_input(attn_output_unpad, indices_q, batch_size, query_length)
|
370 |
+
else:
|
371 |
+
attn_output = flash_attn_func(
|
372 |
+
query_states, key_states, value_states, dropout, softmax_scale=softmax_scale, causal=causal
|
373 |
+
)
|
374 |
+
|
375 |
+
return attn_output
|
376 |
+
|
377 |
+
def _upad_input(self, query_layer, key_layer, value_layer, attention_mask, query_length):
|
378 |
+
indices_k, cu_seqlens_k, max_seqlen_in_batch_k = _get_unpad_data(attention_mask)
|
379 |
+
batch_size, kv_seq_len, num_key_value_heads, head_dim = key_layer.shape
|
380 |
+
|
381 |
+
key_layer = index_first_axis(
|
382 |
+
key_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
383 |
+
)
|
384 |
+
value_layer = index_first_axis(
|
385 |
+
value_layer.reshape(batch_size * kv_seq_len, num_key_value_heads, head_dim), indices_k
|
386 |
+
)
|
387 |
+
if query_length == kv_seq_len:
|
388 |
+
query_layer = index_first_axis(
|
389 |
+
query_layer.reshape(batch_size * kv_seq_len, self.num_heads, head_dim), indices_k
|
390 |
+
)
|
391 |
+
cu_seqlens_q = cu_seqlens_k
|
392 |
+
max_seqlen_in_batch_q = max_seqlen_in_batch_k
|
393 |
+
indices_q = indices_k
|
394 |
+
elif query_length == 1:
|
395 |
+
max_seqlen_in_batch_q = 1
|
396 |
+
cu_seqlens_q = torch.arange(
|
397 |
+
batch_size + 1, dtype=torch.int32, device=query_layer.device
|
398 |
+
) # There is a memcpy here, that is very bad.
|
399 |
+
indices_q = cu_seqlens_q[:-1]
|
400 |
+
query_layer = query_layer.squeeze(1)
|
401 |
+
else:
|
402 |
+
# The -q_len: slice assumes left padding.
|
403 |
+
attention_mask = attention_mask[:, -query_length:]
|
404 |
+
query_layer, indices_q, cu_seqlens_q, max_seqlen_in_batch_q = unpad_input(query_layer, attention_mask)
|
405 |
+
|
406 |
+
return (
|
407 |
+
query_layer,
|
408 |
+
key_layer,
|
409 |
+
value_layer,
|
410 |
+
indices_q,
|
411 |
+
(cu_seqlens_q, cu_seqlens_k),
|
412 |
+
(max_seqlen_in_batch_q, max_seqlen_in_batch_k),
|
413 |
+
)
|
414 |
+
|
415 |
+
|
416 |
+
class LlamaSdpaAttention(LlamaAttention):
|
417 |
+
"""
|
418 |
+
Llama attention module using torch.nn.functional.scaled_dot_product_attention. This module inherits from
|
419 |
+
`LlamaAttention` as the weights of the module stays untouched. The only changes are on the forward pass to adapt to
|
420 |
+
SDPA API.
|
421 |
+
"""
|
422 |
+
|
423 |
+
# Adapted from LlamaAttention.forward
|
424 |
+
def forward(
|
425 |
+
self,
|
426 |
+
hidden_states: torch.Tensor,
|
427 |
+
modality_indicators: torch.Tensor,
|
428 |
+
attention_mask: Optional[torch.Tensor] = None,
|
429 |
+
position_ids: Optional[torch.LongTensor] = None,
|
430 |
+
past_key_value: Optional[Cache] = None,
|
431 |
+
output_attentions: bool = False,
|
432 |
+
use_cache: bool = False,
|
433 |
+
) -> Tuple[torch.Tensor, Optional[torch.Tensor], Optional[Tuple[torch.Tensor]]]:
|
434 |
+
if output_attentions:
|
435 |
+
# TODO: Improve this warning with e.g. `model.config.attn_implementation = "manual"` once this is implemented.
|
436 |
+
logger.warning_once(
|
437 |
+
"LlamaModel is using LlamaSdpaAttention, but `torch.nn.functional.scaled_dot_product_attention` does not support `output_attentions=True`. Falling back to the manual attention implementation, "
|
438 |
+
'but specifying the manual implementation will be required from Transformers version v5.0.0 onwards. This warning can be removed using the argument `attn_implementation="eager"` when loading the model.'
|
439 |
+
)
|
440 |
+
return super().forward(
|
441 |
+
hidden_states=hidden_states,
|
442 |
+
modality_indicators=modality_indicators,
|
443 |
+
attention_mask=attention_mask,
|
444 |
+
position_ids=position_ids,
|
445 |
+
past_key_value=past_key_value,
|
446 |
+
output_attentions=output_attentions,
|
447 |
+
use_cache=use_cache,
|
448 |
+
)
|
449 |
+
|
450 |
+
bsz, q_len, _ = hidden_states.size()
|
451 |
+
|
452 |
+
query_states = self.q_proj(hidden_states)
|
453 |
+
key_states = self.k_proj(hidden_states, modality_indicators)
|
454 |
+
value_states = self.v_proj(hidden_states, modality_indicators)
|
455 |
+
|
456 |
+
query_states = query_states.view(bsz, q_len, self.num_heads, self.head_dim).transpose(1, 2)
|
457 |
+
key_states = key_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
458 |
+
value_states = value_states.view(bsz, q_len, self.num_key_value_heads, self.head_dim).transpose(1, 2)
|
459 |
+
|
460 |
+
kv_seq_len = key_states.shape[-2]
|
461 |
+
if past_key_value is not None:
|
462 |
+
kv_seq_len += past_key_value.get_usable_length(kv_seq_len, self.layer_idx)
|
463 |
+
cos, sin = self.rotary_emb(value_states, seq_len=kv_seq_len)
|
464 |
+
|
465 |
+
query_states, key_states = apply_rotary_pos_emb(query_states, key_states, cos, sin, position_ids)
|
466 |
+
|
467 |
+
if past_key_value is not None:
|
468 |
+
cache_kwargs = {"sin": sin, "cos": cos} # Specific to RoPE models
|
469 |
+
key_states, value_states = past_key_value.update(key_states, value_states, self.layer_idx, cache_kwargs)
|
470 |
+
|
471 |
+
key_states = repeat_kv(key_states, self.num_key_value_groups)
|
472 |
+
value_states = repeat_kv(value_states, self.num_key_value_groups)
|
473 |
+
|
474 |
+
if attention_mask is not None:
|
475 |
+
if attention_mask.size() != (bsz, 1, q_len, kv_seq_len):
|
476 |
+
raise ValueError(
|
477 |
+
f"Attention mask should be of size {(bsz, 1, q_len, kv_seq_len)}, but is {attention_mask.size()}"
|
478 |
+
)
|
479 |
+
|
480 |
+
# SDPA with memory-efficient backend is currently (torch==2.1.2) bugged with non-contiguous inputs with custom attn_mask,
|
481 |
+
# Reference: https://github.com/pytorch/pytorch/issues/112577.
|
482 |
+
if query_states.device.type == "cuda" and attention_mask is not None:
|
483 |
+
query_states = query_states.contiguous()
|
484 |
+
key_states = key_states.contiguous()
|
485 |
+
value_states = value_states.contiguous()
|
486 |
+
|
487 |
+
attn_output = torch.nn.functional.scaled_dot_product_attention(
|
488 |
+
query_states,
|
489 |
+
key_states,
|
490 |
+
value_states,
|
491 |
+
attn_mask=attention_mask,
|
492 |
+
dropout_p=self.attention_dropout if self.training else 0.0,
|
493 |
+
# The q_len > 1 is necessary to match with AttentionMaskConverter.to_causal_4d that does not create a causal mask in case q_len == 1.
|
494 |
+
is_causal=self.is_causal and attention_mask is None and q_len > 1,
|
495 |
+
)
|
496 |
+
|
497 |
+
attn_output = attn_output.transpose(1, 2).contiguous()
|
498 |
+
attn_output = attn_output.reshape(bsz, q_len, self.hidden_size)
|
499 |
+
|
500 |
+
attn_output = self.o_proj(attn_output)
|
501 |
+
|
502 |
+
return attn_output, None, past_key_value
|
503 |
+
|
504 |
+
|
505 |
+
|
506 |
+
LLAMA_ATTENTION_CLASSES = {
|
507 |
+
"eager": LlamaAttention,
|
508 |
+
"flash_attention_2": LlamaFlashAttention2,
|
509 |
+
"sdpa": LlamaSdpaAttention,
|
510 |
+
}
|
511 |
+
|
512 |
+
class LlamaDecoderLayer(nn.Module):
|
513 |
+
def __init__(self, config: LlamaConfig, layer_idx):
|
514 |
+
super().__init__()
|
515 |
+
self.hidden_size = config.hidden_size
|
516 |
+
self.self_attn = LlamaAttention(config=config)
|
517 |
+
self.self_attn = LLAMA_ATTENTION_CLASSES[config._attn_implementation](config=config, layer_idx=layer_idx)
|
518 |
+
self.mlp = LlamaMLP(config)
|
519 |
+
self.input_layernorm = MultiwayNetwork(module_provider=partial(
|
520 |
+
LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps
|
521 |
+
))
|
522 |
+
self.post_attention_layernorm = MultiwayNetwork(module_provider=partial(
|
523 |
+
LlamaRMSNorm, hidden_size=config.hidden_size, eps=config.rms_norm_eps
|
524 |
+
))
|
525 |
+
|
526 |
+
def forward(
|
527 |
+
self,
|
528 |
+
hidden_states: torch.Tensor,
|
529 |
+
modality_indicators: torch.Tensor = None,
|
530 |
+
attention_mask: Optional[torch.Tensor] = None,
|
531 |
+
position_ids: Optional[torch.LongTensor] = None,
|
532 |
+
past_key_value: Optional[Tuple[torch.Tensor]] = None,
|
533 |
+
output_attentions: Optional[bool] = False,
|
534 |
+
use_cache: Optional[bool] = False,
|
535 |
+
) -> Tuple[torch.FloatTensor, Optional[Tuple[torch.FloatTensor, torch.FloatTensor]]]:
|
536 |
+
"""
|
537 |
+
Args:
|
538 |
+
hidden_states (`torch.FloatTensor`): input to the layer of shape `(batch, seq_len, embed_dim)`
|
539 |
+
attention_mask (`torch.FloatTensor`, *optional*): attention mask of size
|
540 |
+
`(batch, 1, tgt_len, src_len)` where padding elements are indicated by very large negative values.
|
541 |
+
output_attentions (`bool`, *optional*):
|
542 |
+
Whether or not to return the attentions tensors of all attention layers. See `attentions` under
|
543 |
+
returned tensors for more detail.
|
544 |
+
use_cache (`bool`, *optional*):
|
545 |
+
If set to `True`, `past_key_values` key value states are returned and can be used to speed up decoding
|
546 |
+
(see `past_key_values`).
|
547 |
+
past_key_value (`Tuple(torch.FloatTensor)`, *optional*): cached past key and value projection states
|
548 |
+
"""
|
549 |
+
|
550 |
+
residual = hidden_states
|
551 |
+
|
552 |
+
hidden_states = self.input_layernorm(hidden_states, modality_indicators)
|
553 |
+
|
554 |
+
# Self Attention
|
555 |
+
hidden_states, self_attn_weights, present_key_value = self.self_attn(
|
556 |
+
hidden_states=hidden_states,
|
557 |
+
modality_indicators=modality_indicators,
|
558 |
+
attention_mask=attention_mask,
|
559 |
+
position_ids=position_ids,
|
560 |
+
past_key_value=past_key_value,
|
561 |
+
output_attentions=output_attentions,
|
562 |
+
use_cache=use_cache,
|
563 |
+
)
|
564 |
+
hidden_states = residual + hidden_states
|
565 |
+
|
566 |
+
# Fully Connected
|
567 |
+
residual = hidden_states
|
568 |
+
hidden_states = self.post_attention_layernorm(hidden_states, modality_indicators)
|
569 |
+
hidden_states = self.mlp(hidden_states)
|
570 |
+
hidden_states = residual + hidden_states
|
571 |
+
|
572 |
+
outputs = (hidden_states,)
|
573 |
+
|
574 |
+
if output_attentions:
|
575 |
+
outputs += (self_attn_weights,)
|
576 |
+
|
577 |
+
if use_cache:
|
578 |
+
outputs += (present_key_value,)
|
579 |
+
|
580 |
+
return outputs
|
581 |
+
|
582 |
+
|
583 |
+
def model_forward(
|
584 |
+
self,
|
585 |
+
input_ids: torch.LongTensor = None,
|
586 |
+
modality_indicators: torch.Tensor = None,
|
587 |
+
attention_mask: Optional[torch.Tensor] = None,
|
588 |
+
position_ids: Optional[torch.LongTensor] = None,
|
589 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
590 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
591 |
+
use_cache: Optional[bool] = None,
|
592 |
+
output_attentions: Optional[bool] = None,
|
593 |
+
output_hidden_states: Optional[bool] = None,
|
594 |
+
return_dict: Optional[bool] = None,
|
595 |
+
) -> Union[Tuple, BaseModelOutputWithPast]:
|
596 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
597 |
+
output_hidden_states = (
|
598 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
599 |
+
)
|
600 |
+
use_cache = use_cache if use_cache is not None else self.config.use_cache
|
601 |
+
|
602 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
603 |
+
|
604 |
+
# retrieve input_ids and inputs_embeds
|
605 |
+
if input_ids is not None and inputs_embeds is not None:
|
606 |
+
raise ValueError("You cannot specify both decoder_input_ids and decoder_inputs_embeds at the same time")
|
607 |
+
elif input_ids is not None:
|
608 |
+
batch_size, seq_length = input_ids.shape
|
609 |
+
elif inputs_embeds is not None:
|
610 |
+
batch_size, seq_length, _ = inputs_embeds.shape
|
611 |
+
else:
|
612 |
+
raise ValueError("You have to specify either decoder_input_ids or decoder_inputs_embeds")
|
613 |
+
|
614 |
+
seq_length_with_past = seq_length
|
615 |
+
past_key_values_length = 0
|
616 |
+
|
617 |
+
if past_key_values is not None:
|
618 |
+
past_key_values_length = past_key_values[0][0].shape[2]
|
619 |
+
seq_length_with_past = seq_length_with_past + past_key_values_length
|
620 |
+
|
621 |
+
if position_ids is None:
|
622 |
+
device = input_ids.device if input_ids is not None else inputs_embeds.device
|
623 |
+
position_ids = torch.arange(
|
624 |
+
past_key_values_length, seq_length + past_key_values_length, dtype=torch.long, device=device
|
625 |
+
)
|
626 |
+
position_ids = position_ids.unsqueeze(0).view(-1, seq_length)
|
627 |
+
else:
|
628 |
+
position_ids = position_ids.view(-1, seq_length).long()
|
629 |
+
|
630 |
+
if inputs_embeds is None:
|
631 |
+
inputs_embeds = self.embed_tokens(input_ids)
|
632 |
+
# embed positions
|
633 |
+
if attention_mask is None:
|
634 |
+
attention_mask = torch.ones(
|
635 |
+
(batch_size, seq_length_with_past), dtype=torch.bool, device=inputs_embeds.device
|
636 |
+
)
|
637 |
+
|
638 |
+
if self._use_flash_attention_2:
|
639 |
+
# 2d mask is passed through the layers
|
640 |
+
attention_mask = attention_mask if (attention_mask is not None and 0 in attention_mask) else None
|
641 |
+
elif self._use_sdpa and not output_attentions:
|
642 |
+
# output_attentions=True can not be supported when using SDPA, and we fall back on
|
643 |
+
# the manual implementation that requires a 4D causal mask in all cases.
|
644 |
+
attention_mask = _prepare_4d_causal_attention_mask_for_sdpa(
|
645 |
+
attention_mask,
|
646 |
+
(batch_size, seq_length),
|
647 |
+
inputs_embeds,
|
648 |
+
past_key_values_length,
|
649 |
+
)
|
650 |
+
else:
|
651 |
+
# 4d mask is passed through the layers
|
652 |
+
attention_mask = _prepare_4d_causal_attention_mask(
|
653 |
+
attention_mask, (batch_size, seq_length), inputs_embeds, past_key_values_length
|
654 |
+
)
|
655 |
+
|
656 |
+
hidden_states = inputs_embeds
|
657 |
+
|
658 |
+
if self.gradient_checkpointing and self.training:
|
659 |
+
if use_cache:
|
660 |
+
logger.warning_once(
|
661 |
+
"`use_cache=True` is incompatible with gradient checkpointing. Setting `use_cache=False`..."
|
662 |
+
)
|
663 |
+
use_cache = False
|
664 |
+
|
665 |
+
# decoder layers
|
666 |
+
all_hidden_states = () if output_hidden_states else None
|
667 |
+
all_self_attns = () if output_attentions else None
|
668 |
+
next_decoder_cache = () if use_cache else None
|
669 |
+
|
670 |
+
for idx, decoder_layer in enumerate(self.layers):
|
671 |
+
if output_hidden_states:
|
672 |
+
all_hidden_states += (hidden_states,)
|
673 |
+
|
674 |
+
past_key_value = past_key_values[idx] if past_key_values is not None else None
|
675 |
+
|
676 |
+
if self.gradient_checkpointing and self.training:
|
677 |
+
|
678 |
+
def create_custom_forward(module):
|
679 |
+
def custom_forward(*inputs):
|
680 |
+
# None for past_key_value
|
681 |
+
return module(*inputs, past_key_value, output_attentions)
|
682 |
+
|
683 |
+
return custom_forward
|
684 |
+
|
685 |
+
layer_outputs = torch.utils.checkpoint.checkpoint(
|
686 |
+
create_custom_forward(decoder_layer),
|
687 |
+
hidden_states,
|
688 |
+
modality_indicators,
|
689 |
+
attention_mask,
|
690 |
+
position_ids,
|
691 |
+
)
|
692 |
+
else:
|
693 |
+
layer_outputs = decoder_layer(
|
694 |
+
hidden_states,
|
695 |
+
modality_indicators=modality_indicators,
|
696 |
+
attention_mask=attention_mask,
|
697 |
+
position_ids=position_ids,
|
698 |
+
past_key_value=past_key_value,
|
699 |
+
output_attentions=output_attentions,
|
700 |
+
use_cache=use_cache,
|
701 |
+
)
|
702 |
+
|
703 |
+
hidden_states = layer_outputs[0]
|
704 |
+
|
705 |
+
if use_cache:
|
706 |
+
next_decoder_cache += (layer_outputs[2 if output_attentions else 1],)
|
707 |
+
|
708 |
+
if output_attentions:
|
709 |
+
all_self_attns += (layer_outputs[1],)
|
710 |
+
|
711 |
+
hidden_states = self.norm(hidden_states)
|
712 |
+
|
713 |
+
# add hidden states from the last decoder layer
|
714 |
+
if output_hidden_states:
|
715 |
+
all_hidden_states += (hidden_states,)
|
716 |
+
|
717 |
+
next_cache = next_decoder_cache if use_cache else None
|
718 |
+
if not return_dict:
|
719 |
+
return tuple(v for v in [hidden_states, next_cache, all_hidden_states, all_self_attns] if v is not None)
|
720 |
+
return BaseModelOutputWithPast(
|
721 |
+
last_hidden_state=hidden_states,
|
722 |
+
past_key_values=next_cache,
|
723 |
+
hidden_states=all_hidden_states,
|
724 |
+
attentions=all_self_attns,
|
725 |
+
)
|
726 |
+
|
727 |
+
|
728 |
+
def causal_model_forward(
|
729 |
+
self,
|
730 |
+
input_ids: torch.LongTensor = None,
|
731 |
+
modality_indicators: torch.Tensor = None,
|
732 |
+
attention_mask: Optional[torch.Tensor] = None,
|
733 |
+
position_ids: Optional[torch.LongTensor] = None,
|
734 |
+
past_key_values: Optional[List[torch.FloatTensor]] = None,
|
735 |
+
inputs_embeds: Optional[torch.FloatTensor] = None,
|
736 |
+
labels: Optional[torch.LongTensor] = None,
|
737 |
+
use_cache: Optional[bool] = None,
|
738 |
+
output_attentions: Optional[bool] = None,
|
739 |
+
output_hidden_states: Optional[bool] = None,
|
740 |
+
return_dict: Optional[bool] = None,
|
741 |
+
) -> Union[Tuple, CausalLMOutputWithPast]:
|
742 |
+
r"""
|
743 |
+
Args:
|
744 |
+
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
|
745 |
+
Labels for computing the masked language modeling loss. Indices should either be in `[0, ...,
|
746 |
+
config.vocab_size]` or -100 (see `input_ids` docstring). Tokens with indices set to `-100` are ignored
|
747 |
+
(masked), the loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
|
748 |
+
|
749 |
+
Returns:
|
750 |
+
|
751 |
+
Example:
|
752 |
+
|
753 |
+
```python
|
754 |
+
>>> from transformers import AutoTokenizer, LlamaForCausalLM
|
755 |
+
|
756 |
+
>>> model = LlamaForCausalLM.from_pretrained(PATH_TO_CONVERTED_WEIGHTS)
|
757 |
+
>>> tokenizer = AutoTokenizer.from_pretrained(PATH_TO_CONVERTED_TOKENIZER)
|
758 |
+
|
759 |
+
>>> prompt = "Hey, are you conscious? Can you talk to me?"
|
760 |
+
>>> inputs = tokenizer(prompt, return_tensors="pt")
|
761 |
+
|
762 |
+
>>> # Generate
|
763 |
+
>>> generate_ids = model.generate(inputs.input_ids, max_length=30)
|
764 |
+
>>> tokenizer.batch_decode(generate_ids, skip_special_tokens=True, clean_up_tokenization_spaces=False)[0]
|
765 |
+
"Hey, are you conscious? Can you talk to me?\nI'm not conscious, but I can talk to you."
|
766 |
+
```"""
|
767 |
+
|
768 |
+
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
|
769 |
+
output_hidden_states = (
|
770 |
+
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
|
771 |
+
)
|
772 |
+
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
|
773 |
+
|
774 |
+
# decoder outputs consists of (dec_features, layer_state, dec_hidden, dec_attn)
|
775 |
+
outputs = self.model(
|
776 |
+
input_ids=input_ids,
|
777 |
+
modality_indicators=modality_indicators,
|
778 |
+
attention_mask=attention_mask,
|
779 |
+
position_ids=position_ids,
|
780 |
+
past_key_values=past_key_values,
|
781 |
+
inputs_embeds=inputs_embeds,
|
782 |
+
use_cache=use_cache,
|
783 |
+
output_attentions=output_attentions,
|
784 |
+
output_hidden_states=output_hidden_states,
|
785 |
+
return_dict=return_dict,
|
786 |
+
)
|
787 |
+
|
788 |
+
hidden_states = outputs[0]
|
789 |
+
if self.config.pretraining_tp > 1:
|
790 |
+
lm_head_slices = self.lm_head.weight.split(self.vocab_size // self.config.pretraining_tp, dim=0)
|
791 |
+
logits = [F.linear(hidden_states, lm_head_slices[i]) for i in range(self.config.pretraining_tp)]
|
792 |
+
logits = torch.cat(logits, dim=-1)
|
793 |
+
else:
|
794 |
+
logits = self.lm_head(hidden_states)
|
795 |
+
logits = logits.float()
|
796 |
+
|
797 |
+
loss = None
|
798 |
+
if labels is not None:
|
799 |
+
# Shift so that tokens < n predict n
|
800 |
+
shift_logits = logits[..., :-1, :].contiguous()
|
801 |
+
shift_labels = labels[..., 1:].contiguous()
|
802 |
+
# Flatten the tokens
|
803 |
+
loss_fct = CrossEntropyLoss()
|
804 |
+
shift_logits = shift_logits.view(-1, self.config.vocab_size)
|
805 |
+
shift_labels = shift_labels.view(-1)
|
806 |
+
# Enable model parallelism
|
807 |
+
shift_labels = shift_labels.to(shift_logits.device)
|
808 |
+
loss = loss_fct(shift_logits, shift_labels)
|
809 |
+
|
810 |
+
if not return_dict:
|
811 |
+
output = (logits,) + outputs[1:]
|
812 |
+
return (loss,) + output if loss is not None else output
|
813 |
+
|
814 |
+
return CausalLMOutputWithPast(
|
815 |
+
loss=loss,
|
816 |
+
logits=logits,
|
817 |
+
past_key_values=outputs.past_key_values,
|
818 |
+
hidden_states=outputs.hidden_states,
|
819 |
+
attentions=outputs.attentions,
|
820 |
+
)
|
821 |
+
|
822 |
+
def replace_llama_modality_adaptive():
|
823 |
+
transformers.models.llama.configuration_llama.LlamaConfig = LlamaConfig
|
824 |
+
transformers.models.llama.modeling_llama.LlamaAttention = LlamaAttention
|
825 |
+
transformers.models.llama.modeling_llama.LlamaFlashAttention2 = LlamaFlashAttention2
|
826 |
+
transformers.models.llama.modeling_llama.LlamaSdpaAttention = LlamaSdpaAttention
|
827 |
+
transformers.models.llama.modeling_llama.LlamaDecoderLayer = LlamaDecoderLayer
|
828 |
+
transformers.models.llama.modeling_llama.LlamaModel.forward = model_forward
|
829 |
+
transformers.models.llama.modeling_llama.LlamaForCausalLM.forward = causal_model_forward
|
830 |
+
|
831 |
+
|
832 |
+
if __name__ == "__main__":
|
833 |
+
replace_llama_modality_adaptive()
|
834 |
+
config = transformers.LlamaConfig.from_pretrained('/cpfs01/shared/public/test/vicuna-7b-v1.5/')
|
835 |
+
model = transformers.LlamaForCausalLM(config)
|
836 |
+
print(model)
|