Update modeling_dots_vision.py (#19)
Browse files- Update modeling_dots_vision.py (a455edb59a10ff47d298fd2ab6b3fcf53417b42a)
Co-authored-by: chen.jian <[email protected]>
- modeling_dots_vision.py +133 -26
modeling_dots_vision.py
CHANGED
@@ -4,16 +4,29 @@ import torch
|
|
4 |
import torch.nn as nn
|
5 |
import torch.nn.functional as F
|
6 |
import torch.utils.checkpoint
|
7 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
8 |
from torch.nn import LayerNorm
|
9 |
from transformers.modeling_utils import PreTrainedModel
|
10 |
from .configuration_dots import DotsVisionConfig
|
11 |
|
|
|
|
|
|
|
|
|
|
|
12 |
|
13 |
def rotate_half(x):
|
14 |
"""Rotates half the hidden dims of the input."""
|
15 |
x1 = x[..., : x.shape[-1] // 2]
|
16 |
-
x2 = x[..., x.shape[-1] // 2
|
17 |
return torch.cat((-x2, x1), dim=-1)
|
18 |
|
19 |
|
@@ -48,15 +61,15 @@ class VisionRotaryEmbedding(nn.Module):
|
|
48 |
|
49 |
class PatchMerger(nn.Module):
|
50 |
def __init__(
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
|
56 |
-
|
57 |
) -> None:
|
58 |
super().__init__()
|
59 |
-
self.hidden_size = context_dim * (spatial_merge_size**2)
|
60 |
self.pre_norm = pre_norm
|
61 |
if self.pre_norm == "layernorm":
|
62 |
self.ln_q = LayerNorm(context_dim, eps=1e-6)
|
@@ -94,10 +107,10 @@ class VisionAttention(nn.Module):
|
|
94 |
self.proj = nn.Linear(dim, dim, bias=bias)
|
95 |
|
96 |
def forward(
|
97 |
-
|
98 |
-
|
99 |
-
|
100 |
-
|
101 |
) -> torch.Tensor:
|
102 |
seq_length = hidden_states.shape[0]
|
103 |
|
@@ -109,7 +122,7 @@ class VisionAttention(nn.Module):
|
|
109 |
[1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
|
110 |
)
|
111 |
for i in range(1, len(cu_seqlens)):
|
112 |
-
attention_mask[..., cu_seqlens[i - 1]
|
113 |
|
114 |
q = q.transpose(0, 1)
|
115 |
k = k.transpose(0, 1)
|
@@ -134,10 +147,10 @@ class VisionFlashAttention2(nn.Module):
|
|
134 |
self.is_causal = config.is_causal
|
135 |
|
136 |
def forward(
|
137 |
-
|
138 |
-
|
139 |
-
|
140 |
-
|
141 |
) -> torch.Tensor:
|
142 |
seq_length = hidden_states.shape[0]
|
143 |
q, k, v = (
|
@@ -154,6 +167,89 @@ class VisionFlashAttention2(nn.Module):
|
|
154 |
return attn_output
|
155 |
|
156 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
157 |
class VisionSdpaAttention(nn.Module):
|
158 |
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
159 |
super().__init__()
|
@@ -163,10 +259,10 @@ class VisionSdpaAttention(nn.Module):
|
|
163 |
self.config = config
|
164 |
|
165 |
def forward(
|
166 |
-
|
167 |
-
|
168 |
-
|
169 |
-
|
170 |
) -> torch.Tensor:
|
171 |
seq_length = hidden_states.shape[0]
|
172 |
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
@@ -176,7 +272,7 @@ class VisionSdpaAttention(nn.Module):
|
|
176 |
|
177 |
attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
178 |
for i in range(1, len(cu_seqlens)):
|
179 |
-
attention_mask[..., cu_seqlens[i - 1]
|
180 |
|
181 |
q = q.transpose(0, 1)
|
182 |
k = k.transpose(0, 1)
|
@@ -192,8 +288,10 @@ class VisionSdpaAttention(nn.Module):
|
|
192 |
|
193 |
DOTS_VISION_ATTENTION_CLASSES = {
|
194 |
"eager": VisionAttention,
|
|
|
195 |
"flash_attention_2": VisionFlashAttention2,
|
196 |
"sdpa": VisionSdpaAttention,
|
|
|
197 |
}
|
198 |
|
199 |
|
@@ -231,7 +329,6 @@ class DotsSwiGLUFFN(nn.Module):
|
|
231 |
return x
|
232 |
|
233 |
|
234 |
-
|
235 |
class DotsPatchEmbed(nn.Module):
|
236 |
def __init__(self, config):
|
237 |
super().__init__()
|
@@ -249,7 +346,7 @@ class DotsPatchEmbed(nn.Module):
|
|
249 |
self.norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
250 |
|
251 |
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor:
|
252 |
-
x = x.view(-1, self.num_channels, self.temporal_patch_size, self.patch_size, self.patch_size)[:, :, 0]
|
253 |
x = self.proj(x).view(-1, self.embed_dim)
|
254 |
x = self.norm(x)
|
255 |
return x
|
@@ -272,6 +369,16 @@ class DotsViTPreprocessor(nn.Module):
|
|
272 |
class DotsVisionBlock(nn.Module):
|
273 |
def __init__(self, config, attn_implementation: str = "flash_attention_2"):
|
274 |
super().__init__()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
275 |
self.attn = DOTS_VISION_ATTENTION_CLASSES[attn_implementation](
|
276 |
config, config.embed_dim, num_heads=config.num_attention_heads, bias=config.use_bias
|
277 |
)
|
@@ -401,4 +508,4 @@ class DotsVisionTransformer(PreTrainedModel):
|
|
401 |
hidden_states = self.post_trunk_norm(hidden_states)
|
402 |
|
403 |
hidden_states = self.merger(hidden_states)
|
404 |
-
return hidden_states
|
|
|
4 |
import torch.nn as nn
|
5 |
import torch.nn.functional as F
|
6 |
import torch.utils.checkpoint
|
7 |
+
|
8 |
+
flash_attn_available = True
|
9 |
+
npu_available = True
|
10 |
+
|
11 |
+
try:
|
12 |
+
from flash_attn import flash_attn_varlen_func
|
13 |
+
except ImportError:
|
14 |
+
flash_attn_available = False
|
15 |
+
|
16 |
from torch.nn import LayerNorm
|
17 |
from transformers.modeling_utils import PreTrainedModel
|
18 |
from .configuration_dots import DotsVisionConfig
|
19 |
|
20 |
+
try:
|
21 |
+
import torch_npu
|
22 |
+
except ImportError:
|
23 |
+
npu_available = False
|
24 |
+
|
25 |
|
26 |
def rotate_half(x):
|
27 |
"""Rotates half the hidden dims of the input."""
|
28 |
x1 = x[..., : x.shape[-1] // 2]
|
29 |
+
x2 = x[..., x.shape[-1] // 2:]
|
30 |
return torch.cat((-x2, x1), dim=-1)
|
31 |
|
32 |
|
|
|
61 |
|
62 |
class PatchMerger(nn.Module):
|
63 |
def __init__(
|
64 |
+
self,
|
65 |
+
dim: int,
|
66 |
+
context_dim: int,
|
67 |
+
spatial_merge_size: int = 2,
|
68 |
+
pre_norm="layernorm",
|
69 |
+
init_merger_std=None,
|
70 |
) -> None:
|
71 |
super().__init__()
|
72 |
+
self.hidden_size = context_dim * (spatial_merge_size ** 2)
|
73 |
self.pre_norm = pre_norm
|
74 |
if self.pre_norm == "layernorm":
|
75 |
self.ln_q = LayerNorm(context_dim, eps=1e-6)
|
|
|
107 |
self.proj = nn.Linear(dim, dim, bias=bias)
|
108 |
|
109 |
def forward(
|
110 |
+
self,
|
111 |
+
hidden_states: torch.Tensor,
|
112 |
+
cu_seqlens: torch.Tensor,
|
113 |
+
rotary_pos_emb: torch.Tensor = None,
|
114 |
) -> torch.Tensor:
|
115 |
seq_length = hidden_states.shape[0]
|
116 |
|
|
|
122 |
[1, seq_length, seq_length], torch.finfo(q.dtype).min, device=q.device, dtype=q.dtype
|
123 |
)
|
124 |
for i in range(1, len(cu_seqlens)):
|
125 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = 0
|
126 |
|
127 |
q = q.transpose(0, 1)
|
128 |
k = k.transpose(0, 1)
|
|
|
147 |
self.is_causal = config.is_causal
|
148 |
|
149 |
def forward(
|
150 |
+
self,
|
151 |
+
hidden_states: torch.Tensor,
|
152 |
+
cu_seqlens: torch.Tensor,
|
153 |
+
rotary_pos_emb: torch.Tensor = None,
|
154 |
) -> torch.Tensor:
|
155 |
seq_length = hidden_states.shape[0]
|
156 |
q, k, v = (
|
|
|
167 |
return attn_output
|
168 |
|
169 |
|
170 |
+
class VisionAttentionV2(nn.Module):
|
171 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
172 |
+
super().__init__()
|
173 |
+
self.num_heads = num_heads
|
174 |
+
self.head_dim = dim // num_heads
|
175 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
176 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
177 |
+
|
178 |
+
def forward(
|
179 |
+
self,
|
180 |
+
hidden_states: torch.Tensor,
|
181 |
+
cu_seqlens: torch.Tensor,
|
182 |
+
rotary_pos_emb: torch.Tensor = None,
|
183 |
+
) -> torch.Tensor:
|
184 |
+
seq_length = hidden_states.shape[0]
|
185 |
+
|
186 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
187 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
188 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
189 |
+
|
190 |
+
seqlens = torch.diff(cu_seqlens).tolist()
|
191 |
+
|
192 |
+
q_list = torch.split(q, seqlens, 0)
|
193 |
+
k_list = torch.split(k, seqlens, 0)
|
194 |
+
v_list = torch.split(v, seqlens, 0)
|
195 |
+
# eager attention 空间复杂度为 O(n^2) , n 为 b*s(batch_size * seq_len), 序列太长容易OOM, 这个实现 更具batch 切分 seq
|
196 |
+
# 减少内存需求, 计算相对 continus batching 较慢。
|
197 |
+
outputs = []
|
198 |
+
for q_i, k_i, v_i in zip(q_list, k_list, v_list):
|
199 |
+
q_i = q_i.transpose(0, 1)
|
200 |
+
k_i = k_i.transpose(0, 1)
|
201 |
+
v_i = v_i.transpose(0, 1)
|
202 |
+
out = torch.matmul(q_i, k_i.transpose(1, 2)) / math.sqrt(self.head_dim)
|
203 |
+
out = nn.functional.softmax(out, dim=-1, dtype=torch.float32).to(q.dtype)
|
204 |
+
out = torch.matmul(out, v_i)
|
205 |
+
out = out.transpose(0, 1)
|
206 |
+
outputs.append(out)
|
207 |
+
|
208 |
+
attn_output = torch.concat(outputs, dim=0)
|
209 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
210 |
+
attn_output = self.proj(attn_output)
|
211 |
+
return attn_output
|
212 |
+
|
213 |
+
|
214 |
+
class VisionAscendAttention(nn.Module):
|
215 |
+
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
216 |
+
super().__init__()
|
217 |
+
self.num_heads = num_heads
|
218 |
+
self.head_dim = dim // num_heads
|
219 |
+
self.qkv = nn.Linear(dim, dim * 3, bias=bias)
|
220 |
+
self.proj = nn.Linear(dim, dim, bias=bias)
|
221 |
+
self.config = config
|
222 |
+
|
223 |
+
def forward(
|
224 |
+
self,
|
225 |
+
hidden_states: torch.Tensor,
|
226 |
+
cu_seqlens: torch.Tensor,
|
227 |
+
rotary_pos_emb: torch.Tensor = None,
|
228 |
+
) -> torch.Tensor:
|
229 |
+
seq_length = hidden_states.shape[0]
|
230 |
+
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
231 |
+
|
232 |
+
q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
233 |
+
k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
|
234 |
+
|
235 |
+
attention_mask = torch.ones([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
236 |
+
for i in range(1, len(cu_seqlens)):
|
237 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = False
|
238 |
+
|
239 |
+
q = q.transpose(0, 1).unsqueeze(0)
|
240 |
+
k = k.transpose(0, 1).unsqueeze(0)
|
241 |
+
v = v.transpose(0, 1).unsqueeze(0)
|
242 |
+
|
243 |
+
attn_output = torch_npu.npu_prompt_flash_attention(q, k, v,
|
244 |
+
atten_mask=attention_mask,
|
245 |
+
num_heads=self.num_heads, input_layout="BNSD",
|
246 |
+
scale_value=self.head_dim ** -0.5)
|
247 |
+
attn_output = attn_output.squeeze(0).transpose(0, 1)
|
248 |
+
attn_output = attn_output.reshape(seq_length, -1)
|
249 |
+
attn_output = self.proj(attn_output)
|
250 |
+
return attn_output
|
251 |
+
|
252 |
+
|
253 |
class VisionSdpaAttention(nn.Module):
|
254 |
def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
|
255 |
super().__init__()
|
|
|
259 |
self.config = config
|
260 |
|
261 |
def forward(
|
262 |
+
self,
|
263 |
+
hidden_states: torch.Tensor,
|
264 |
+
cu_seqlens: torch.Tensor,
|
265 |
+
rotary_pos_emb: torch.Tensor = None,
|
266 |
) -> torch.Tensor:
|
267 |
seq_length = hidden_states.shape[0]
|
268 |
q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
|
|
|
272 |
|
273 |
attention_mask = torch.zeros([1, seq_length, seq_length], device=q.device, dtype=torch.bool)
|
274 |
for i in range(1, len(cu_seqlens)):
|
275 |
+
attention_mask[..., cu_seqlens[i - 1]: cu_seqlens[i], cu_seqlens[i - 1]: cu_seqlens[i]] = True
|
276 |
|
277 |
q = q.transpose(0, 1)
|
278 |
k = k.transpose(0, 1)
|
|
|
288 |
|
289 |
DOTS_VISION_ATTENTION_CLASSES = {
|
290 |
"eager": VisionAttention,
|
291 |
+
"eager_v2": VisionAttentionV2, # 内存更少
|
292 |
"flash_attention_2": VisionFlashAttention2,
|
293 |
"sdpa": VisionSdpaAttention,
|
294 |
+
"ascend_fa": VisionAscendAttention, # ascend, 长序列精度下降严重。
|
295 |
}
|
296 |
|
297 |
|
|
|
329 |
return x
|
330 |
|
331 |
|
|
|
332 |
class DotsPatchEmbed(nn.Module):
|
333 |
def __init__(self, config):
|
334 |
super().__init__()
|
|
|
346 |
self.norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
|
347 |
|
348 |
def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor:
|
349 |
+
x = x.view(-1, self.num_channels, self.temporal_patch_size, self.patch_size, self.patch_size)[:, :, 0]
|
350 |
x = self.proj(x).view(-1, self.embed_dim)
|
351 |
x = self.norm(x)
|
352 |
return x
|
|
|
369 |
class DotsVisionBlock(nn.Module):
|
370 |
def __init__(self, config, attn_implementation: str = "flash_attention_2"):
|
371 |
super().__init__()
|
372 |
+
|
373 |
+
if attn_implementation == "flash_attention_2" and not flash_attn_available:
|
374 |
+
# fallback to eager
|
375 |
+
attn_implementation = "eager"
|
376 |
+
print("flash attention not available! fallback to eager implementation ")
|
377 |
+
|
378 |
+
if attn_implementation == "ascend_fa" and not npu_available:
|
379 |
+
attn_implementation = "eager"
|
380 |
+
print("flash attention not available! fallback to eager implementation ")
|
381 |
+
|
382 |
self.attn = DOTS_VISION_ATTENTION_CLASSES[attn_implementation](
|
383 |
config, config.embed_dim, num_heads=config.num_attention_heads, bias=config.use_bias
|
384 |
)
|
|
|
508 |
hidden_states = self.post_trunk_norm(hidden_states)
|
509 |
|
510 |
hidden_states = self.merger(hidden_states)
|
511 |
+
return hidden_states
|