svg/models/cog/utils.py SHA256 d6d742d6ae297fb1a1c340cdcbf8e97dbc3467e8a344ce3fbda09bdeb8045360
1: import math
2: import os
3: import random
4: from functools import lru_cache
5: from math import floor
6: 
7: import numpy as np
8: import torch
9: from torch.nn.attention.flex_attention import (
10:     create_block_mask,
11: )
12: 
13: 
14: def seed_everything(seed):
15:     random.seed(seed)
16:     os.environ["PYTHONHASHSEED"] = str(seed)
17:     np.random.seed(seed)
18:     torch.manual_seed(seed)
19:     torch.cuda.manual_seed(seed)
20:     torch.backends.cudnn.deterministic = True
21:     torch.backends.cudnn.benchmark = False
22: 
23: 
24: @lru_cache
25: def create_block_mask_cached(score_mod, B, H, M, N, device="cuda", _compile=False):
26:     block_mask = create_block_mask(score_mod, B, H, M, N, device=device, _compile=_compile)
27:     return block_mask
28: 
29: 
30: def generate_temporal_head_mask_mod(prompt_length: int = 226, num_frames: int = 13, token_per_frame: int = 1350, mul: int = 2, attn_sink: bool = False):
31: 
32:     def round_to_multiple(idx):
33:         return floor(idx / 128) * 128
34: 
35:     def temporal_mask_mod(b, h, q_idx, kv_idx):
36:         first_row_mask = q_idx < prompt_length
37:         if attn_sink:
38:             first_column_mask = kv_idx < (prompt_length + token_per_frame)
39:         else:
40:             first_column_mask = kv_idx < prompt_length
41: 
42:         two_frame = round_to_multiple(mul * token_per_frame)
43:         temporal_head_mask = torch.abs(q_idx - kv_idx) < two_frame
44:         return first_column_mask | first_row_mask | temporal_head_mask
45: 
46:     return temporal_mask_mod
47: 
48: 
49: def sparsity_to_width(sparsity, context_length, num_frame, frame_size):
50:     seq_len = context_length + num_frame * frame_size
51:     total_elements = seq_len**2
52: 
53:     sparsity = (sparsity * total_elements - 2 * seq_len * context_length) / total_elements
54: 
55:     width = seq_len * (1 - math.sqrt(1 - sparsity))
56:     width_frame = width / frame_size
57: 
58:     return width_frame
59: 
60: 
61: def get_attention_mask(mask_name, context_length, num_frame, frame_size):
62:     # TODO: Replace with real implementation
63: 
64:     attention_mask = torch.zeros((context_length + num_frame * frame_size, context_length + num_frame * frame_size)).cuda()
65:     if mask_name == "spatial":
66:         attention_mask[:context_length, :] = 1
67:         attention_mask[:, :context_length] = 1
68:         block_size, block_thres = 128, frame_size * 1.5
69:         num_block = math.ceil(num_frame * frame_size / block_size)
70:         for i in range(num_block):
71:             for j in range(num_block):
72:                 if abs(i - j) < block_thres // block_size:
73:                     attention_mask[i * block_size : (i + 1) * block_size, j * block_size : (j + 1) * block_size] = 1
74:         # attention_mask = torch.load("/data/home/xihaocheng/andy_develop/I2VSparse/sparseattn/v1.5/mask_tensor/mask_spatial.pt", map_location="cuda")
75:     elif mask_name == "temporal":
76:         pixel_attn_mask = torch.zeros_like(attention_mask[context_length:, context_length:])
77: 
78:         block_size, block_thres = 128, frame_size * 1.5
79:         num_block = math.ceil(num_frame * frame_size / block_size)
80:         for i in range(num_block):
81:             for j in range(num_block):
82:                 if abs(i - j) < block_thres // block_size:
83:                     pixel_attn_mask[i * block_size : (i + 1) * block_size, j * block_size : (j + 1) * block_size] = 1
84: 
85:         pixel_attn_mask = pixel_attn_mask.reshape(frame_size, num_frame, frame_size, num_frame).permute(1, 0, 3, 2).reshape(frame_size * num_frame, frame_size * num_frame)
86:         attention_mask[context_length:, context_length:] = pixel_attn_mask
87:         # attention_mask = torch.load("/data/home/xihaocheng/andy_develop/I2VSparse/sparseattn/v1.5/mask_tensor/mask_temporal.pt", map_location="cuda")
88:     return attention_mask
svg/models/cog/attention.py SHA256 454cb293c4aed41a912b4b9ce5fbf4155bbcb16458773fa233f190c5b5196679
120:     def sample_mse(self, query, key, value):
121: 
122:         assert len(self.attention_masks) == 2
123: 
124:         cfg, num_heads, seq_len, dim = query.size()
125:         num_sampled_rows = min(self.num_sampled_rows, seq_len)
126:         sampled_rows = torch.randint(low=0, high=seq_len, size=(num_sampled_rows,))
127:         sampled_q = query[:, :, sampled_rows, :]
128:         sampled_qk_scores = torch.matmul(sampled_q, key.transpose(-2, -1)) / (dim**0.5)
129: 
130:         sampled_attn_weights = F.softmax(sampled_qk_scores, dim=-1)
131:         sampled_golden_hidden_states = torch.matmul(sampled_attn_weights, value)  # (1, seq_len, dim)
132: 
133:         sampled_mses = torch.zeros(len(self.attention_masks), cfg, num_heads, device=query.device, dtype=query.dtype)
134: 
135:         # Only have Tri-diagonal and Striped
136: 
137:         for mask_idx, attn_mask in enumerate(self.attention_masks):
138:             sampled_attention_mask = attn_mask[sampled_rows, :]
139:             sampled_attention_scores = sampled_qk_scores.masked_fill(sampled_attention_mask == 0, float("-inf"))
140:             sampled_attn_weights = F.softmax(sampled_attention_scores, dim=-1)
141:             sampled_hidden_states = torch.matmul(sampled_attn_weights, value)
142:             mse = torch.mean((sampled_hidden_states - sampled_golden_hidden_states) ** 2, dim=(2, 3))
143:             sampled_mses[mask_idx] = mse
144: 
145:         return sampled_mses
svg/models/cog/placement.py SHA256 9dcd09cb3b243ace59098381ca80f189a8010f885bd83224f794c4cd8c82d4e9
6: def token_reorder_to_token_major(tensor, fix_len, reorder_len, reorder_num_frame, frame_size):
7:     """Reorder it from frame major to token major!"""
8:     assert reorder_len == reorder_num_frame * frame_size
9:     assert tensor.shape[2] == fix_len + reorder_len
10: 
11:     tensor[:, :, fix_len:, :] = (
12:         tensor[:, :, fix_len:, :]
13:         .reshape(tensor.shape[0], tensor.shape[1], reorder_num_frame, frame_size, tensor.shape[3])
14:         .transpose(2, 3)
15:         .reshape(tensor.shape[0], tensor.shape[1], reorder_len, tensor.shape[3])
16:     )
17:     return tensor
18: 
19: 
20: def token_reorder_to_frame_major(tensor, fix_len, reorder_len, reorder_num_frame, frame_size):
21:     """Reorder it from token major to frame major!"""
22:     assert reorder_len == reorder_num_frame * frame_size
23:     assert tensor.shape[2] == fix_len + reorder_len
24: 
25:     tensor[:, :, fix_len:, :] = (
26:         tensor[:, :, fix_len:, :]
27:         .reshape(tensor.shape[0], tensor.shape[1], frame_size, reorder_num_frame, tensor.shape[3])
28:         .transpose(2, 3)
29:         .reshape(tensor.shape[0], tensor.shape[1], reorder_len, tensor.shape[3])
30:     )
31:     return tensor
73:     if is_temporal:
74:         # if offset_token < context_length:
75:         #   offset_store_token = offset_token
76:         # else:
77:         #   frame_id = (offset_token - context_length) // frame_size
78:         #   patch_id = (offset_token - context_length) - frame_id * frame_size
79:         #   offset_store_token = context_length + patch_id * num_frame + frame_id
80:         frame_id = (offset_token - context_length) // frame_size
81:         patch_id = (offset_token - context_length) - frame_id * frame_size
82:         offset_store_token = tl.where(offset_token < context_length, offset_token, context_length + patch_id * num_frame + frame_id)
83: 
84:         offset_load = (cfg * query_stride_b + head * query_stride_h + offset_token[:, None] * query_stride_s) + offset_d[None, :] * query_stride_d
85:         offset_query = query_ptr + offset_load
86:         offset_key = key_ptr + offset_load
87:         offset_value = value_ptr + offset_load
88: 
89:         offset_store = (cfg * query_stride_b + head * query_stride_h + offset_store_token[:, None] * query_stride_s) + offset_d[None, :] * query_stride_d
90:         offset_query_out = query_out_ptr + offset_store
91:         offset_key_out = key_out_ptr + offset_store
92:         offset_value_out = value_out_ptr + offset_store
93: 
94:         # Maybe tune the pipeline here
95:         query = tl.load(offset_query, mask=offset_mask[:, None])
96:         tl.store(offset_query_out, query, mask=offset_mask[:, None])
97:         key = tl.load(offset_key, mask=offset_mask[:, None])
98:         tl.store(offset_key_out, key, mask=offset_mask[:, None])
99:         value = tl.load(offset_value, mask=offset_mask[:, None])
100:         tl.store(offset_value_out, value, mask=offset_mask[:, None])
294:     if is_temporal:
295:         # if offset_token < context_length:
296:         #   offset_store_token = offset_token
297:         # else:
298:         #   patch_id = (offset_token - context_length) // num_frame
299:         #   frame_id = (offset_token - context_length) - patch_id * num_frame
300:         #   offset_store_token = context_length + frame_id * frame_size + patch_id
301:         patch_id = (offset_token - context_length) // num_frame
302:         frame_id = (offset_token - context_length) - patch_id * num_frame
303:         offset_store_token = tl.where(offset_token < context_length, offset_token, context_length + frame_id * frame_size + patch_id)