comdoleger commited on
Commit
9b41769
·
verified ·
1 Parent(s): 0f2e275

Upload extensions_built_in/diffusion_models/chroma/src/radiance.py with huggingface_hub

Browse files
extensions_built_in/diffusion_models/chroma/src/radiance.py ADDED
@@ -0,0 +1,380 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+
3
+ import torch
4
+ from torch import Tensor, nn
5
+ import torch.utils.checkpoint as ckpt
6
+
7
+ from .layers import (
8
+ DoubleStreamBlock,
9
+ EmbedND,
10
+ LastLayer,
11
+ SingleStreamBlock,
12
+ timestep_embedding,
13
+ Approximator,
14
+ distribute_modulations,
15
+ NerfEmbedder,
16
+ NerfFinalLayer,
17
+ NerfFinalLayerConv,
18
+ NerfGLUBlock
19
+ )
20
+
21
+
22
+ @dataclass
23
+ class ChromaParams:
24
+ in_channels: int
25
+ context_in_dim: int
26
+ hidden_size: int
27
+ mlp_ratio: float
28
+ num_heads: int
29
+ depth: int
30
+ depth_single_blocks: int
31
+ axes_dim: list[int]
32
+ theta: int
33
+ qkv_bias: bool
34
+ guidance_embed: bool
35
+ approximator_in_dim: int
36
+ approximator_depth: int
37
+ approximator_hidden_size: int
38
+ patch_size: int
39
+ nerf_hidden_size: int
40
+ nerf_mlp_ratio: int
41
+ nerf_depth: int
42
+ nerf_max_freqs: int
43
+ _use_compiled: bool
44
+
45
+
46
+ chroma_params = ChromaParams(
47
+ in_channels=3,
48
+ context_in_dim=4096,
49
+ hidden_size=3072,
50
+ mlp_ratio=4.0,
51
+ num_heads=24,
52
+ depth=19,
53
+ depth_single_blocks=38,
54
+ axes_dim=[16, 56, 56],
55
+ theta=10_000,
56
+ qkv_bias=True,
57
+ guidance_embed=True,
58
+ approximator_in_dim=64,
59
+ approximator_depth=5,
60
+ approximator_hidden_size=5120,
61
+ patch_size=16,
62
+ nerf_hidden_size=64,
63
+ nerf_mlp_ratio=4,
64
+ nerf_depth=4,
65
+ nerf_max_freqs=8,
66
+ _use_compiled=False,
67
+ )
68
+
69
+
70
+ def modify_mask_to_attend_padding(mask, max_seq_length, num_extra_padding=8):
71
+ """
72
+ Modifies attention mask to allow attention to a few extra padding tokens.
73
+
74
+ Args:
75
+ mask: Original attention mask (1 for tokens to attend to, 0 for masked tokens)
76
+ max_seq_length: Maximum sequence length of the model
77
+ num_extra_padding: Number of padding tokens to unmask
78
+
79
+ Returns:
80
+ Modified mask
81
+ """
82
+ # Get the actual sequence length from the mask
83
+ seq_length = mask.sum(dim=-1)
84
+ batch_size = mask.shape[0]
85
+
86
+ modified_mask = mask.clone()
87
+
88
+ for i in range(batch_size):
89
+ current_seq_len = int(seq_length[i].item())
90
+
91
+ # Only add extra padding tokens if there's room
92
+ if current_seq_len < max_seq_length:
93
+ # Calculate how many padding tokens we can unmask
94
+ available_padding = max_seq_length - current_seq_len
95
+ tokens_to_unmask = min(num_extra_padding, available_padding)
96
+
97
+ # Unmask the specified number of padding tokens right after the sequence
98
+ modified_mask[i, current_seq_len : current_seq_len + tokens_to_unmask] = 1
99
+
100
+ return modified_mask
101
+
102
+
103
+ class Chroma(nn.Module):
104
+ """
105
+ Transformer model for flow matching on sequences.
106
+ """
107
+
108
+ def __init__(self, params: ChromaParams):
109
+ super().__init__()
110
+ self.params = params
111
+ self.in_channels = params.in_channels
112
+ self.out_channels = self.in_channels
113
+ self.gradient_checkpointing = False
114
+ if params.hidden_size % params.num_heads != 0:
115
+ raise ValueError(
116
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
117
+ )
118
+ pe_dim = params.hidden_size // params.num_heads
119
+ if sum(params.axes_dim) != pe_dim:
120
+ raise ValueError(
121
+ f"Got {params.axes_dim} but expected positional dim {pe_dim}"
122
+ )
123
+ self.hidden_size = params.hidden_size
124
+ self.num_heads = params.num_heads
125
+ self.pe_embedder = EmbedND(
126
+ dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim
127
+ )
128
+ # self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
129
+ # patchify ops
130
+ self.img_in_patch = nn.Conv2d(
131
+ params.in_channels,
132
+ params.hidden_size,
133
+ kernel_size=params.patch_size,
134
+ stride=params.patch_size,
135
+ bias=True
136
+ )
137
+ nn.init.zeros_(self.img_in_patch.weight)
138
+ nn.init.zeros_(self.img_in_patch.bias)
139
+ # TODO: need proper mapping for this approximator output!
140
+ # currently the mapping is hardcoded in distribute_modulations function
141
+ self.distilled_guidance_layer = Approximator(
142
+ params.approximator_in_dim,
143
+ self.hidden_size,
144
+ params.approximator_hidden_size,
145
+ params.approximator_depth,
146
+ )
147
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
148
+
149
+ self.double_blocks = nn.ModuleList(
150
+ [
151
+ DoubleStreamBlock(
152
+ self.hidden_size,
153
+ self.num_heads,
154
+ mlp_ratio=params.mlp_ratio,
155
+ qkv_bias=params.qkv_bias,
156
+ use_compiled=params._use_compiled,
157
+ )
158
+ for _ in range(params.depth)
159
+ ]
160
+ )
161
+
162
+ self.single_blocks = nn.ModuleList(
163
+ [
164
+ SingleStreamBlock(
165
+ self.hidden_size,
166
+ self.num_heads,
167
+ mlp_ratio=params.mlp_ratio,
168
+ use_compiled=params._use_compiled,
169
+ )
170
+ for _ in range(params.depth_single_blocks)
171
+ ]
172
+ )
173
+
174
+ # self.final_layer = LastLayer(
175
+ # self.hidden_size,
176
+ # 1,
177
+ # self.out_channels,
178
+ # use_compiled=params._use_compiled,
179
+ # )
180
+
181
+ # pixel channel concat with DCT
182
+ self.nerf_image_embedder = NerfEmbedder(
183
+ in_channels=params.in_channels,
184
+ hidden_size_input=params.nerf_hidden_size,
185
+ max_freqs=params.nerf_max_freqs
186
+ )
187
+
188
+ self.nerf_blocks = nn.ModuleList([
189
+ NerfGLUBlock(
190
+ hidden_size_s=params.hidden_size,
191
+ hidden_size_x=params.nerf_hidden_size,
192
+ mlp_ratio=params.nerf_mlp_ratio,
193
+ use_compiled=params._use_compiled
194
+ ) for _ in range(params.nerf_depth)
195
+ ])
196
+ # self.nerf_final_layer = NerfFinalLayer(
197
+ # params.nerf_hidden_size,
198
+ # out_channels=params.in_channels,
199
+ # use_compiled=params._use_compiled
200
+ # )
201
+ self.nerf_final_layer_conv = NerfFinalLayerConv(
202
+ params.nerf_hidden_size,
203
+ out_channels=params.in_channels,
204
+ use_compiled=params._use_compiled
205
+ )
206
+ # TODO: move this hardcoded value to config
207
+ # single layer has 3 modulation vectors
208
+ # double layer has 6 modulation vectors for each expert
209
+ # final layer has 2 modulation vectors
210
+ self.mod_index_length = 3 * params.depth_single_blocks + 2 * 6 * params.depth + 2
211
+ self.depth_single_blocks = params.depth_single_blocks
212
+ self.depth_double_blocks = params.depth
213
+ # self.mod_index = torch.tensor(list(range(self.mod_index_length)), device=0)
214
+ self.register_buffer(
215
+ "mod_index",
216
+ torch.tensor(list(range(self.mod_index_length)), device="cpu"),
217
+ persistent=False,
218
+ )
219
+ self.approximator_in_dim = params.approximator_in_dim
220
+
221
+ @property
222
+ def device(self):
223
+ # Get the device of the module (assumes all parameters are on the same device)
224
+ return next(self.parameters()).device
225
+
226
+ def enable_gradient_checkpointing(self, enable: bool = True):
227
+ self.gradient_checkpointing = enable
228
+
229
+ def forward(
230
+ self,
231
+ img: Tensor,
232
+ img_ids: Tensor,
233
+ txt: Tensor,
234
+ txt_ids: Tensor,
235
+ txt_mask: Tensor,
236
+ timesteps: Tensor,
237
+ guidance: Tensor,
238
+ attn_padding: int = 1,
239
+ ) -> Tensor:
240
+ if img.ndim != 4:
241
+ raise ValueError("Input img tensor must be in [B, C, H, W] format.")
242
+ if txt.ndim != 3:
243
+ raise ValueError("Input txt tensors must have 3 dimensions.")
244
+ B, C, H, W = img.shape
245
+
246
+ # gemini gogogo idk how to unfold and pack the patch properly :P
247
+ # Store the raw pixel values of each patch for the NeRF head later.
248
+ # unfold creates patches: [B, C * P * P, NumPatches]
249
+ nerf_pixels = nn.functional.unfold(img, kernel_size=self.params.patch_size, stride=self.params.patch_size)
250
+ nerf_pixels = nerf_pixels.transpose(1, 2) # -> [B, NumPatches, C * P * P]
251
+
252
+ # partchify ops
253
+ img = self.img_in_patch(img) # -> [B, Hidden, H/P, W/P]
254
+ num_patches = img.shape[2] * img.shape[3]
255
+ # flatten into a sequence for the transformer.
256
+ img = img.flatten(2).transpose(1, 2) # -> [B, NumPatches, Hidden]
257
+
258
+ txt = self.txt_in(txt)
259
+
260
+ # TODO:
261
+ # need to fix grad accumulation issue here for now it's in no grad mode
262
+ # besides, i don't want to wash out the PFP that's trained on this model weights anyway
263
+ # the fan out operation here is deleting the backward graph
264
+ # alternatively doing forward pass for every block manually is doable but slow
265
+ # custom backward probably be better
266
+ with torch.no_grad():
267
+ distill_timestep = timestep_embedding(timesteps, self.approximator_in_dim//4)
268
+ # TODO: need to add toggle to omit this from schnell but that's not a priority
269
+ distil_guidance = timestep_embedding(guidance, self.approximator_in_dim//4)
270
+ # get all modulation index
271
+ modulation_index = timestep_embedding(self.mod_index, self.approximator_in_dim//2)
272
+ # we need to broadcast the modulation index here so each batch has all of the index
273
+ modulation_index = modulation_index.unsqueeze(0).repeat(img.shape[0], 1, 1)
274
+ # and we need to broadcast timestep and guidance along too
275
+ timestep_guidance = (
276
+ torch.cat([distill_timestep, distil_guidance], dim=1)
277
+ .unsqueeze(1)
278
+ .repeat(1, self.mod_index_length, 1)
279
+ )
280
+ # then and only then we could concatenate it together
281
+ input_vec = torch.cat([timestep_guidance, modulation_index], dim=-1)
282
+ mod_vectors = self.distilled_guidance_layer(input_vec.requires_grad_(True))
283
+ mod_vectors_dict = distribute_modulations(mod_vectors, self.depth_single_blocks, self.depth_double_blocks)
284
+
285
+ ids = torch.cat((txt_ids, img_ids), dim=1)
286
+ pe = self.pe_embedder(ids)
287
+
288
+ # compute mask
289
+ # assume max seq length from the batched input
290
+
291
+ max_len = txt.shape[1]
292
+
293
+ # mask
294
+ with torch.no_grad():
295
+ txt_mask_w_padding = modify_mask_to_attend_padding(
296
+ txt_mask, max_len, attn_padding
297
+ )
298
+ txt_img_mask = torch.cat(
299
+ [
300
+ txt_mask_w_padding,
301
+ torch.ones([img.shape[0], img.shape[1]], device=txt_mask.device),
302
+ ],
303
+ dim=1,
304
+ )
305
+ txt_img_mask = txt_img_mask.float().T @ txt_img_mask.float()
306
+ txt_img_mask = (
307
+ txt_img_mask[None, None, ...]
308
+ .repeat(txt.shape[0], self.num_heads, 1, 1)
309
+ .int()
310
+ .bool()
311
+ )
312
+ # txt_mask_w_padding[txt_mask_w_padding==False] = True
313
+
314
+ for i, block in enumerate(self.double_blocks):
315
+ # the guidance replaced by FFN output
316
+ img_mod = mod_vectors_dict[f"double_blocks.{i}.img_mod.lin"]
317
+ txt_mod = mod_vectors_dict[f"double_blocks.{i}.txt_mod.lin"]
318
+ double_mod = [img_mod, txt_mod]
319
+
320
+ # just in case in different GPU for simple pipeline parallel
321
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
322
+ img.requires_grad_(True)
323
+ img, txt = ckpt.checkpoint(
324
+ block, img, txt, pe, double_mod, txt_img_mask
325
+ )
326
+ else:
327
+ img, txt = block(
328
+ img=img, txt=txt, pe=pe, distill_vec=double_mod, mask=txt_img_mask
329
+ )
330
+
331
+ img = torch.cat((txt, img), 1)
332
+ for i, block in enumerate(self.single_blocks):
333
+ single_mod = mod_vectors_dict[f"single_blocks.{i}.modulation.lin"]
334
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
335
+ img.requires_grad_(True)
336
+ img = ckpt.checkpoint(block, img, pe, single_mod, txt_img_mask)
337
+ else:
338
+ img = block(img, pe=pe, distill_vec=single_mod, mask=txt_img_mask)
339
+ img = img[:, txt.shape[1] :, ...]
340
+
341
+ # final_mod = mod_vectors_dict["final_layer.adaLN_modulation.1"]
342
+ # img = self.final_layer(
343
+ # img, distill_vec=final_mod
344
+ # ) # (N, T, patch_size ** 2 * out_channels)
345
+
346
+ # aliasing
347
+ nerf_hidden = img
348
+ # reshape for per-patch processing
349
+ nerf_hidden = nerf_hidden.reshape(B * num_patches, self.params.hidden_size)
350
+ nerf_pixels = nerf_pixels.reshape(B * num_patches, C, self.params.patch_size**2).transpose(1, 2)
351
+
352
+ # get DCT-encoded pixel embeddings [pixel-dct]
353
+ img_dct = self.nerf_image_embedder(nerf_pixels)
354
+
355
+ # pass through the dynamic MLP blocks (the NeRF)
356
+ for i, block in enumerate(self.nerf_blocks):
357
+ if self.training:
358
+ img_dct = ckpt.checkpoint(block, img_dct, nerf_hidden)
359
+ else:
360
+ img_dct = block(img_dct, nerf_hidden)
361
+
362
+ # final projection to get the output pixel values
363
+ # img_dct = self.nerf_final_layer(img_dct) # -> [B*NumPatches, P*P, C]
364
+ img_dct = self.nerf_final_layer_conv.norm(img_dct)
365
+
366
+ # gemini gogogo idk how to fold this properly :P
367
+ # Reassemble the patches into the final image.
368
+ img_dct = img_dct.transpose(1, 2) # -> [B*NumPatches, C, P*P]
369
+ # Reshape to combine with batch dimension for fold
370
+ img_dct = img_dct.reshape(B, num_patches, -1) # -> [B, NumPatches, C*P*P]
371
+ img_dct = img_dct.transpose(1, 2) # -> [B, C*P*P, NumPatches]
372
+ img_dct = nn.functional.fold(
373
+ img_dct,
374
+ output_size=(H, W),
375
+ kernel_size=self.params.patch_size,
376
+ stride=self.params.patch_size
377
+ ) # [B, Hidden, H, W]
378
+ img_dct = self.nerf_final_layer_conv.conv(img_dct)
379
+
380
+ return img_dct