zibojia commited on
Commit
889e416
·
verified ·
1 Parent(s): 46974e7

Delete transformer_minimax_remover.py

Browse files
Files changed (1) hide show
  1. transformer_minimax_remover.py +0 -281
transformer_minimax_remover.py DELETED
@@ -1,281 +0,0 @@
1
- import math
2
- from typing import Dict, Optional, Tuple, Union
3
-
4
- import torch
5
- import torch.nn as nn
6
- import torch.nn.functional as F
7
-
8
- from diffusers.configuration_utils import ConfigMixin, register_to_config
9
- from diffusers.utils import logging
10
- from diffusers.models.attention import FeedForward
11
- from diffusers.models.attention_processor import Attention
12
- from diffusers.models.embeddings import PixArtAlphaTextProjection, TimestepEmbedding, Timesteps, get_1d_rotary_pos_embed
13
- from diffusers.models.modeling_outputs import Transformer2DModelOutput
14
- from diffusers.models.modeling_utils import ModelMixin
15
- from diffusers.models.normalization import FP32LayerNorm
16
-
17
- class AttnProcessor2_0:
18
- def __init__(self):
19
- if not hasattr(F, "scaled_dot_product_attention"):
20
- raise ImportError("AttnProcessor2_0 requires PyTorch 2.0. To use it, please upgrade PyTorch to 2.0.")
21
-
22
- def __call__(
23
- self,
24
- attn: Attention,
25
- hidden_states: torch.Tensor,
26
- rotary_emb: Optional[torch.Tensor] = None,
27
- attention_mask: Optional[torch.Tensor] = None,
28
- encoder_hidden_states: Optional[torch.Tensor] = None
29
- ) -> torch.Tensor:
30
-
31
- encoder_hidden_states = hidden_states
32
- query = attn.to_q(hidden_states)
33
- key = attn.to_k(encoder_hidden_states)
34
- value = attn.to_v(encoder_hidden_states)
35
-
36
- if attn.norm_q is not None:
37
- query = attn.norm_q(query)
38
- if attn.norm_k is not None:
39
- key = attn.norm_k(key)
40
-
41
- query = query.unflatten(2, (attn.heads, -1)).transpose(1, 2)
42
- key = key.unflatten(2, (attn.heads, -1)).transpose(1, 2)
43
- value = value.unflatten(2, (attn.heads, -1)).transpose(1, 2)
44
-
45
- if rotary_emb is not None:
46
-
47
- def apply_rotary_emb(hidden_states: torch.Tensor, freqs: torch.Tensor):
48
- x_rotated = torch.view_as_complex(hidden_states.to(torch.float64).unflatten(3, (-1, 2)))
49
- x_out = torch.view_as_real(x_rotated * freqs).flatten(3, 4)
50
- return x_out.type_as(hidden_states)
51
-
52
- query = apply_rotary_emb(query, rotary_emb)
53
- key = apply_rotary_emb(key, rotary_emb)
54
-
55
- hidden_states = F.scaled_dot_product_attention(
56
- query, key, value, attn_mask=None, dropout_p=0.0, is_causal=False
57
- )
58
- hidden_states = hidden_states.transpose(1, 2).flatten(2, 3)
59
- hidden_states = hidden_states.type_as(query)
60
-
61
- hidden_states = attn.to_out[0](hidden_states)
62
- hidden_states = attn.to_out[1](hidden_states)
63
- return hidden_states
64
-
65
- class TimeEmbedding(nn.Module):
66
- def __init__(
67
- self,
68
- dim: int,
69
- time_freq_dim: int,
70
- time_proj_dim: int
71
- ):
72
- super().__init__()
73
-
74
- self.timesteps_proj = Timesteps(num_channels=time_freq_dim, flip_sin_to_cos=True, downscale_freq_shift=0)
75
- self.time_embedder = TimestepEmbedding(in_channels=time_freq_dim, time_embed_dim=dim)
76
-
77
- self.act_fn = nn.SiLU()
78
- self.time_proj = nn.Linear(dim, time_proj_dim)
79
-
80
- def forward(
81
- self,
82
- timestep: torch.Tensor,
83
- ):
84
- timestep = self.timesteps_proj(timestep)
85
-
86
- time_embedder_dtype = next(iter(self.time_embedder.parameters())).dtype
87
- if timestep.dtype != time_embedder_dtype and time_embedder_dtype != torch.int8:
88
- timestep = timestep.to(time_embedder_dtype)
89
- temb = self.time_embedder(timestep).type_as(self.time_proj.weight.data)
90
- timestep_proj = self.time_proj(self.act_fn(temb))
91
-
92
- return temb, timestep_proj
93
-
94
-
95
- class RotaryPosEmbed(nn.Module):
96
- def __init__(
97
- self, attention_head_dim: int, patch_size: Tuple[int, int, int], max_seq_len: int, theta: float = 10000.0
98
- ):
99
- super().__init__()
100
-
101
- self.attention_head_dim = attention_head_dim
102
- self.patch_size = patch_size
103
- self.max_seq_len = max_seq_len
104
-
105
- h_dim = w_dim = 2 * (attention_head_dim // 6)
106
- t_dim = attention_head_dim - h_dim - w_dim
107
-
108
- freqs = []
109
- for dim in [t_dim, h_dim, w_dim]:
110
- freq = get_1d_rotary_pos_embed(
111
- dim, max_seq_len, theta, use_real=False, repeat_interleave_real=False, freqs_dtype=torch.float64
112
- )
113
- freqs.append(freq)
114
- self.freqs = torch.cat(freqs, dim=1)
115
-
116
- def forward(self, hidden_states: torch.Tensor) -> torch.Tensor:
117
- batch_size, num_channels, num_frames, height, width = hidden_states.shape
118
- p_t, p_h, p_w = self.patch_size
119
- ppf, pph, ppw = num_frames // p_t, height // p_h, width // p_w
120
-
121
- self.freqs = self.freqs.to(hidden_states.device)
122
- freqs = self.freqs.split_with_sizes(
123
- [
124
- self.attention_head_dim // 2 - 2 * (self.attention_head_dim // 6),
125
- self.attention_head_dim // 6,
126
- self.attention_head_dim // 6,
127
- ],
128
- dim=1,
129
- )
130
-
131
- freqs_f = freqs[0][:ppf].view(ppf, 1, 1, -1).expand(ppf, pph, ppw, -1)
132
- freqs_h = freqs[1][:pph].view(1, pph, 1, -1).expand(ppf, pph, ppw, -1)
133
- freqs_w = freqs[2][:ppw].view(1, 1, ppw, -1).expand(ppf, pph, ppw, -1)
134
- freqs = torch.cat([freqs_f, freqs_h, freqs_w], dim=-1).reshape(1, 1, ppf * pph * ppw, -1)
135
- return freqs
136
-
137
-
138
- class TransformerBlock(nn.Module):
139
- def __init__(
140
- self,
141
- dim: int,
142
- ffn_dim: int,
143
- num_heads: int,
144
- qk_norm: str = "rms_norm_across_heads",
145
- cross_attn_norm: bool = False,
146
- eps: float = 1e-6,
147
- added_kv_proj_dim: Optional[int] = None,
148
- ):
149
- super().__init__()
150
-
151
- self.norm1 = FP32LayerNorm(dim, eps, elementwise_affine=False)
152
- self.attn1 = Attention(
153
- query_dim=dim,
154
- heads=num_heads,
155
- kv_heads=num_heads,
156
- dim_head=dim // num_heads,
157
- qk_norm=qk_norm,
158
- eps=eps,
159
- bias=True,
160
- cross_attention_dim=None,
161
- out_bias=True,
162
- processor=AttnProcessor2_0(),
163
- )
164
-
165
- self.ffn = FeedForward(dim, inner_dim=ffn_dim, activation_fn="gelu-approximate")
166
- self.norm2 = FP32LayerNorm(dim, eps, elementwise_affine=False)
167
-
168
- self.scale_shift_table = nn.Parameter(torch.randn(1, 6, dim) / dim**0.5)
169
-
170
- def forward(
171
- self,
172
- hidden_states: torch.Tensor,
173
- temb: torch.Tensor,
174
- rotary_emb: torch.Tensor,
175
- ) -> torch.Tensor:
176
- shift_msa, scale_msa, gate_msa, c_shift_msa, c_scale_msa, c_gate_msa = (
177
- self.scale_shift_table + temb.float()
178
- ).chunk(6, dim=1)
179
-
180
- norm_hidden_states = (self.norm1(hidden_states.float()) * (1 + scale_msa) + shift_msa).type_as(hidden_states)
181
- attn_output = self.attn1(hidden_states=norm_hidden_states, rotary_emb=rotary_emb)
182
- hidden_states = (hidden_states.float() + attn_output * gate_msa).type_as(hidden_states)
183
-
184
- norm_hidden_states = (self.norm2(hidden_states.float()) * (1 + c_scale_msa) + c_shift_msa).type_as(
185
- hidden_states
186
- )
187
- ff_output = self.ffn(norm_hidden_states)
188
- hidden_states = (hidden_states.float() + ff_output.float() * c_gate_msa).type_as(hidden_states)
189
-
190
- return hidden_states
191
-
192
-
193
- class Transformer3DModel(ModelMixin, ConfigMixin):
194
-
195
- _skip_layerwise_casting_patterns = ["patch_embedding", "condition_embedder", "norm"]
196
- _no_split_modules = ["TransformerBlock"]
197
- _keep_in_fp32_modules = ["time_embedder", "scale_shift_table", "norm1", "norm2"]
198
-
199
- @register_to_config
200
- def __init__(
201
- self,
202
- patch_size: Tuple[int] = (1, 2, 2),
203
- num_attention_heads: int = 40,
204
- attention_head_dim: int = 128,
205
- in_channels: int = 16,
206
- out_channels: int = 16,
207
- freq_dim: int = 256,
208
- ffn_dim: int = 13824,
209
- num_layers: int = 40,
210
- cross_attn_norm: bool = True,
211
- qk_norm: Optional[str] = "rms_norm_across_heads",
212
- eps: float = 1e-6,
213
- added_kv_proj_dim: Optional[int] = None,
214
- rope_max_seq_len: int = 1024
215
- ) -> None:
216
- super().__init__()
217
-
218
- inner_dim = num_attention_heads * attention_head_dim
219
- out_channels = out_channels or in_channels
220
-
221
- # 1. Patch & position embedding
222
- self.rope = RotaryPosEmbed(attention_head_dim, patch_size, rope_max_seq_len)
223
- self.patch_embedding = nn.Conv3d(in_channels, inner_dim, kernel_size=patch_size, stride=patch_size)
224
-
225
- # 2. Condition embeddings
226
- self.condition_embedder = TimeEmbedding(
227
- dim=inner_dim,
228
- time_freq_dim=freq_dim,
229
- time_proj_dim=inner_dim * 6,
230
- )
231
-
232
- # 3. Transformer blocks
233
- self.blocks = nn.ModuleList(
234
- [
235
- TransformerBlock(
236
- inner_dim, ffn_dim, num_attention_heads, qk_norm, cross_attn_norm, eps, added_kv_proj_dim
237
- )
238
- for _ in range(num_layers)
239
- ]
240
- )
241
-
242
- # 4. Output norm & projection
243
- self.norm_out = FP32LayerNorm(inner_dim, eps, elementwise_affine=False)
244
- self.proj_out = nn.Linear(inner_dim, out_channels * math.prod(patch_size))
245
- self.scale_shift_table = nn.Parameter(torch.randn(1, 2, inner_dim) / inner_dim**0.5)
246
-
247
- def forward(
248
- self,
249
- hidden_states: torch.Tensor,
250
- timestep: torch.LongTensor
251
- ) -> Union[torch.Tensor, Dict[str, torch.Tensor]]:
252
- batch_size, num_channels, num_frames, height, width = hidden_states.shape
253
- p_t, p_h, p_w = self.config.patch_size
254
- post_patch_num_frames = num_frames // p_t
255
- post_patch_height = height // p_h
256
- post_patch_width = width // p_w
257
-
258
- rotary_emb = self.rope(hidden_states)
259
-
260
- hidden_states = self.patch_embedding(hidden_states)
261
- hidden_states = hidden_states.flatten(2).transpose(1, 2)
262
-
263
- temb, timestep_proj = self.condition_embedder(
264
- timestep
265
- )
266
- timestep_proj = timestep_proj.unflatten(1, (6, -1))
267
-
268
- for block in self.blocks:
269
- hidden_states = block(hidden_states, timestep_proj, rotary_emb)
270
-
271
- shift, scale = (self.scale_shift_table + temb.unsqueeze(1)).chunk(2, dim=1)
272
- hidden_states = (self.norm_out(hidden_states.float()) * (1 + scale) + shift).type_as(hidden_states)
273
- hidden_states = self.proj_out(hidden_states)
274
-
275
- hidden_states = hidden_states.reshape(
276
- batch_size, post_patch_num_frames, post_patch_height, post_patch_width, p_t, p_h, p_w, -1
277
- )
278
- hidden_states = hidden_states.permute(0, 7, 1, 4, 2, 5, 3, 6)
279
- output = hidden_states.flatten(6, 7).flatten(4, 5).flatten(2, 3)
280
-
281
- return Transformer2DModelOutput(sample=output)