NirajRajai commited on
Commit
24a413e
·
verified ·
1 Parent(s): 2a4a7a9

Upload modeling_dots_vision.py

Browse files
Files changed (1) hide show
  1. modeling_dots_vision.py +404 -0
modeling_dots_vision.py ADDED
@@ -0,0 +1,404 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+
3
+ import torch
4
+ import torch.nn as nn
5
+ import torch.nn.functional as F
6
+ import torch.utils.checkpoint
7
+ from flash_attn import flash_attn_varlen_func
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
+
20
+ def apply_rotary_pos_emb_vision(tensor: torch.Tensor, freqs: torch.Tensor) -> torch.Tensor:
21
+ orig_dtype = tensor.dtype
22
+ tensor = tensor.float()
23
+
24
+ cos = freqs.cos()
25
+ sin = freqs.sin()
26
+
27
+ cos = cos.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
28
+ sin = sin.unsqueeze(1).repeat(1, 1, 2).unsqueeze(0).float()
29
+
30
+ output = (tensor * cos) + (rotate_half(tensor) * sin)
31
+
32
+ output = output.to(orig_dtype)
33
+
34
+ return output
35
+
36
+
37
+ class VisionRotaryEmbedding(nn.Module):
38
+ def __init__(self, dim: int, theta: float = 10000.0) -> None:
39
+ super().__init__()
40
+ inv_freq = 1.0 / (theta ** (torch.arange(0, dim, 2, dtype=torch.float) / dim))
41
+ self.register_buffer("inv_freq", inv_freq, persistent=False)
42
+
43
+ def forward(self, seqlen: int) -> torch.Tensor:
44
+ seq = torch.arange(seqlen, device=self.inv_freq.device, dtype=self.inv_freq.dtype)
45
+ freqs = torch.outer(seq, self.inv_freq)
46
+ return freqs
47
+
48
+
49
+ class PatchMerger(nn.Module):
50
+ def __init__(
51
+ self,
52
+ dim: int,
53
+ context_dim: int,
54
+ spatial_merge_size: int = 2,
55
+ pre_norm="layernorm",
56
+ init_merger_std=None,
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)
63
+ elif self.pre_norm == "rmsnorm":
64
+ self.ln_q = RMSNorm(context_dim, eps=1e-6)
65
+ else:
66
+ print("no norm in patch merger")
67
+
68
+ self.mlp = nn.Sequential(
69
+ nn.Linear(self.hidden_size, self.hidden_size),
70
+ nn.GELU(),
71
+ nn.Linear(self.hidden_size, dim),
72
+ )
73
+
74
+ if init_merger_std is not None:
75
+ nn.init.normal_(self.mlp[0].weight, mean=0.0, std=init_merger_std)
76
+ nn.init.zeros_(self.mlp[0].bias)
77
+ nn.init.normal_(self.mlp[2].weight, mean=0.0, std=init_merger_std)
78
+ nn.init.zeros_(self.mlp[2].bias)
79
+
80
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
81
+ if self.pre_norm:
82
+ x = self.mlp(self.ln_q(x).view(-1, self.hidden_size))
83
+ else:
84
+ x = self.mlp(x.view(-1, self.hidden_size))
85
+ return x
86
+
87
+
88
+ class VisionAttention(nn.Module):
89
+ def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
90
+ super().__init__()
91
+ self.num_heads = num_heads
92
+ self.head_dim = dim // num_heads
93
+ self.qkv = nn.Linear(dim, dim * 3, bias=bias)
94
+ self.proj = nn.Linear(dim, dim, bias=bias)
95
+
96
+ def forward(
97
+ self,
98
+ hidden_states: torch.Tensor,
99
+ cu_seqlens: torch.Tensor,
100
+ rotary_pos_emb: torch.Tensor = None,
101
+ ) -> torch.Tensor:
102
+ seq_length = hidden_states.shape[0]
103
+
104
+ q, k, v = self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
105
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
106
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
107
+
108
+ attention_mask = torch.full(
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] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = 0
113
+
114
+ q = q.transpose(0, 1)
115
+ k = k.transpose(0, 1)
116
+ v = v.transpose(0, 1)
117
+ attn_weights = torch.matmul(q, k.transpose(1, 2)) / math.sqrt(self.head_dim)
118
+ attn_weights = attn_weights + attention_mask
119
+ attn_weights = nn.functional.softmax(attn_weights, dim=-1, dtype=torch.float32).to(q.dtype)
120
+ attn_output = torch.matmul(attn_weights, v)
121
+ attn_output = attn_output.transpose(0, 1)
122
+ attn_output = attn_output.reshape(seq_length, -1)
123
+ attn_output = self.proj(attn_output)
124
+ return attn_output
125
+
126
+
127
+ class VisionFlashAttention2(nn.Module):
128
+ def __init__(self, config, dim: int, num_heads: int = 16, bias=True) -> None:
129
+ super().__init__()
130
+ self.num_heads = num_heads
131
+ self.qkv = nn.Linear(dim, dim * 3, bias=bias)
132
+ self.proj = nn.Linear(dim, dim, bias=bias)
133
+ self.config = config
134
+ self.is_causal = config.is_causal
135
+
136
+ def forward(
137
+ self,
138
+ hidden_states: torch.Tensor,
139
+ cu_seqlens: torch.Tensor,
140
+ rotary_pos_emb: torch.Tensor = None,
141
+ ) -> torch.Tensor:
142
+ seq_length = hidden_states.shape[0]
143
+ q, k, v = (
144
+ self.qkv(hidden_states).reshape(seq_length, 3, self.num_heads, -1).permute(1, 0, 2, 3).unbind(0)
145
+ ) # 'shd'
146
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
147
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
148
+ max_seqlen = (cu_seqlens[1:] - cu_seqlens[:-1]).max().item()
149
+ attn_output = flash_attn_varlen_func(
150
+ q, k, v, cu_seqlens, cu_seqlens, max_seqlen, max_seqlen, causal=self.is_causal
151
+ ).reshape(seq_length, -1)
152
+ attn_output = self.proj(attn_output)
153
+
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__()
160
+ self.num_heads = num_heads
161
+ self.qkv = nn.Linear(dim, dim * 3, bias=bias)
162
+ self.proj = nn.Linear(dim, dim, bias=bias)
163
+ self.config = config
164
+
165
+ def forward(
166
+ self,
167
+ hidden_states: torch.Tensor,
168
+ cu_seqlens: torch.Tensor,
169
+ rotary_pos_emb: torch.Tensor = None,
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)
173
+
174
+ q = apply_rotary_pos_emb_vision(q.unsqueeze(0), rotary_pos_emb).squeeze(0)
175
+ k = apply_rotary_pos_emb_vision(k.unsqueeze(0), rotary_pos_emb).squeeze(0)
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] : cu_seqlens[i], cu_seqlens[i - 1] : cu_seqlens[i]] = True
180
+
181
+ q = q.transpose(0, 1)
182
+ k = k.transpose(0, 1)
183
+ v = v.transpose(0, 1)
184
+
185
+ attn_output = F.scaled_dot_product_attention(q, k, v, attention_mask, dropout_p=0.0)
186
+ attn_output = attn_output.transpose(0, 1)
187
+ attn_output = attn_output.reshape(seq_length, -1)
188
+
189
+ attn_output = self.proj(attn_output)
190
+ return attn_output
191
+
192
+
193
+ DOTS_VISION_ATTENTION_CLASSES = {
194
+ "eager": VisionAttention,
195
+ "flash_attention_2": VisionFlashAttention2,
196
+ "sdpa": VisionSdpaAttention,
197
+ }
198
+
199
+
200
+ class RMSNorm(nn.Module):
201
+ def __init__(self, dim: int, eps: float = 1e-6):
202
+ super().__init__()
203
+ self.weight = nn.Parameter(torch.ones(dim))
204
+ self.eps = eps
205
+
206
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
207
+ output = self._norm(x.float()).type_as(x)
208
+ return output * self.weight
209
+
210
+ def extra_repr(self) -> str:
211
+ return f"{tuple(self.weight.shape)}, eps={self.eps}"
212
+
213
+ def _norm(self, x: torch.Tensor) -> torch.Tensor:
214
+ return x * torch.rsqrt(x.pow(2).mean(-1, keepdim=True) + self.eps)
215
+
216
+
217
+ class DotsSwiGLUFFN(nn.Module):
218
+ def __init__(self, config):
219
+ super().__init__()
220
+ hidden_features = config.intermediate_size
221
+ in_features = config.embed_dim
222
+ bias = config.use_bias
223
+
224
+ self.fc1 = nn.Linear(in_features, hidden_features, bias=bias)
225
+ self.fc2 = nn.Linear(hidden_features, in_features, bias=bias)
226
+ self.fc3 = nn.Linear(in_features, hidden_features, bias=bias)
227
+
228
+ def forward(self, x: torch.Tensor) -> torch.Tensor:
229
+ x = F.silu(self.fc1(x)) * self.fc3(x)
230
+ x = self.fc2(x)
231
+ return x
232
+
233
+
234
+
235
+ class DotsPatchEmbed(nn.Module):
236
+ def __init__(self, config):
237
+ super().__init__()
238
+ self.num_channels = config.num_channels
239
+ self.patch_size = config.patch_size
240
+ self.temporal_patch_size = config.temporal_patch_size
241
+ self.embed_dim = config.embed_dim
242
+ self.config = config
243
+ self.proj = nn.Conv2d(
244
+ config.num_channels,
245
+ config.embed_dim,
246
+ kernel_size=(config.patch_size, config.patch_size),
247
+ stride=(config.patch_size, config.patch_size),
248
+ )
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
256
+
257
+
258
+ class DotsViTPreprocessor(nn.Module):
259
+ def __init__(self, config):
260
+ super().__init__()
261
+ self.patch_h = config.patch_size
262
+ self.patch_w = config.patch_size
263
+ self.embed_dim = config.embed_dim
264
+ self.config = config
265
+ self.patchifier = DotsPatchEmbed(config)
266
+
267
+ def forward(self, x: torch.Tensor, grid_thw=None) -> torch.Tensor:
268
+ tokens = self.patchifier(x, grid_thw)
269
+ return tokens
270
+
271
+
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
+ )
278
+ self.norm1 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
279
+ self.mlp = DotsSwiGLUFFN(config)
280
+ self.norm2 = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
281
+
282
+ def forward(self, hidden_states, cu_seqlens, rotary_pos_emb) -> torch.Tensor:
283
+ hidden_states = hidden_states + self.attn(
284
+ self.norm1(hidden_states), cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb
285
+ )
286
+ hidden_states = hidden_states + self.mlp(self.norm2(hidden_states))
287
+ return hidden_states
288
+
289
+
290
+ class DotsVisionTransformer(PreTrainedModel):
291
+ def __init__(self, config: DotsVisionConfig) -> None:
292
+ super().__init__(config)
293
+ self.config = config
294
+ self.spatial_merge_size = config.spatial_merge_size
295
+
296
+ self.patch_embed = DotsViTPreprocessor(config)
297
+ self._init_weights(self.patch_embed.patchifier.proj)
298
+
299
+ head_dim = config.embed_dim // config.num_attention_heads
300
+
301
+ self.rotary_pos_emb = VisionRotaryEmbedding(head_dim // 2)
302
+
303
+ _num_hidden_layers = config.num_hidden_layers
304
+ self.blocks = nn.ModuleList(
305
+ [DotsVisionBlock(config, config.attn_implementation) for _ in range(_num_hidden_layers)]
306
+ )
307
+
308
+ if self.config.post_norm:
309
+ self.post_trunk_norm = RMSNorm(config.embed_dim, eps=config.rms_norm_eps)
310
+
311
+ self.merger = PatchMerger(
312
+ dim=config.hidden_size,
313
+ context_dim=config.embed_dim,
314
+ spatial_merge_size=config.spatial_merge_size,
315
+ init_merger_std=self.config.init_merger_std,
316
+ )
317
+
318
+ self.gradient_checkpointing = False
319
+ self._gradient_checkpointing_func = torch.utils.checkpoint.checkpoint
320
+
321
+ def _init_weights(self, module):
322
+ std = self.config.initializer_range
323
+ if isinstance(module, (nn.Linear, nn.Conv3d)):
324
+ module.weight.data.normal_(mean=0.0, std=std)
325
+ if module.bias is not None:
326
+ module.bias.data.zero_()
327
+ elif isinstance(module, nn.Embedding):
328
+ module.weight.data.normal_(mean=0.0, std=std)
329
+ if module.padding_idx is not None:
330
+ module.weight.data[module.padding_idx].zero_()
331
+
332
+ @property
333
+ def dtype(self) -> torch.dtype:
334
+ return self.blocks[0].mlp.fc2.weight.dtype
335
+
336
+ @property
337
+ def device(self) -> torch.device:
338
+ return self.blocks[0].mlp.fc2.weight.device
339
+
340
+ def get_pos_ids_by_grid(self, grid_thw):
341
+ pos_ids = []
342
+ for t, h, w in grid_thw:
343
+ hpos_ids = torch.arange(h).unsqueeze(1).expand(-1, w)
344
+ hpos_ids = hpos_ids.reshape(
345
+ h // self.spatial_merge_size,
346
+ self.spatial_merge_size,
347
+ w // self.spatial_merge_size,
348
+ self.spatial_merge_size,
349
+ )
350
+ hpos_ids = hpos_ids.permute(0, 2, 1, 3)
351
+ hpos_ids = hpos_ids.flatten()
352
+
353
+ wpos_ids = torch.arange(w).unsqueeze(0).expand(h, -1)
354
+ wpos_ids = wpos_ids.reshape(
355
+ h // self.spatial_merge_size,
356
+ self.spatial_merge_size,
357
+ w // self.spatial_merge_size,
358
+ self.spatial_merge_size,
359
+ )
360
+ wpos_ids = wpos_ids.permute(0, 2, 1, 3)
361
+ wpos_ids = wpos_ids.flatten()
362
+ pos_ids.append(
363
+ torch.stack([hpos_ids, wpos_ids], dim=-1).repeat(t, 1)
364
+ )
365
+
366
+ return pos_ids
367
+
368
+ def rot_pos_emb(self, grid_thw):
369
+ pos_ids = self.get_pos_ids_by_grid(grid_thw)
370
+ pos_ids = torch.cat(pos_ids, dim=0)
371
+ max_grid_size = grid_thw[:, 1:].max()
372
+ rotary_pos_emb_full = self.rotary_pos_emb(max_grid_size)
373
+ rotary_pos_emb = rotary_pos_emb_full[pos_ids].flatten(1)
374
+ return rotary_pos_emb
375
+
376
+ def forward(self, hidden_states: torch.Tensor, grid_thw: torch.Tensor, bf16=True) -> torch.Tensor:
377
+ if bf16:
378
+ hidden_states = hidden_states.bfloat16()
379
+ hidden_states = self.patch_embed(hidden_states, grid_thw)
380
+
381
+ rotary_pos_emb = self.rot_pos_emb(grid_thw)
382
+
383
+ cu_seqlens = torch.repeat_interleave(grid_thw[:, 1] * grid_thw[:, 2], grid_thw[:, 0]).cumsum(
384
+ dim=0,
385
+ dtype=grid_thw.dtype if torch.jit.is_tracing() else torch.int32,
386
+ )
387
+ cu_seqlens = F.pad(cu_seqlens, (1, 0), value=0)
388
+
389
+ for blk in self.blocks:
390
+ if self.gradient_checkpointing and self.training:
391
+ hidden_states = self._gradient_checkpointing_func(
392
+ blk.__call__,
393
+ hidden_states,
394
+ cu_seqlens,
395
+ rotary_pos_emb,
396
+ )
397
+ else:
398
+ hidden_states = blk(hidden_states, cu_seqlens=cu_seqlens, rotary_pos_emb=rotary_pos_emb)
399
+
400
+ if self.config.post_norm:
401
+ hidden_states = self.post_trunk_norm(hidden_states)
402
+
403
+ hidden_states = self.merger(hidden_states)
404
+ return hidden_states