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