comdoleger commited on
Commit
a7870a5
·
verified ·
1 Parent(s): c977967

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

Browse files
extensions_built_in/diffusion_models/chroma/src/model.py ADDED
@@ -0,0 +1,282 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
+ )
16
+
17
+
18
+ @dataclass
19
+ class ChromaParams:
20
+ in_channels: int
21
+ context_in_dim: int
22
+ hidden_size: int
23
+ mlp_ratio: float
24
+ num_heads: int
25
+ depth: int
26
+ depth_single_blocks: int
27
+ axes_dim: list[int]
28
+ theta: int
29
+ qkv_bias: bool
30
+ guidance_embed: bool
31
+ approximator_in_dim: int
32
+ approximator_depth: int
33
+ approximator_hidden_size: int
34
+ _use_compiled: bool
35
+
36
+
37
+ chroma_params = ChromaParams(
38
+ in_channels=64,
39
+ context_in_dim=4096,
40
+ hidden_size=3072,
41
+ mlp_ratio=4.0,
42
+ num_heads=24,
43
+ depth=19,
44
+ depth_single_blocks=38,
45
+ axes_dim=[16, 56, 56],
46
+ theta=10_000,
47
+ qkv_bias=True,
48
+ guidance_embed=True,
49
+ approximator_in_dim=64,
50
+ approximator_depth=5,
51
+ approximator_hidden_size=5120,
52
+ _use_compiled=False,
53
+ )
54
+
55
+
56
+ def modify_mask_to_attend_padding(mask, max_seq_length, num_extra_padding=8):
57
+ """
58
+ Modifies attention mask to allow attention to a few extra padding tokens.
59
+
60
+ Args:
61
+ mask: Original attention mask (1 for tokens to attend to, 0 for masked tokens)
62
+ max_seq_length: Maximum sequence length of the model
63
+ num_extra_padding: Number of padding tokens to unmask
64
+
65
+ Returns:
66
+ Modified mask
67
+ """
68
+ # Get the actual sequence length from the mask
69
+ seq_length = mask.sum(dim=-1)
70
+ batch_size = mask.shape[0]
71
+
72
+ modified_mask = mask.clone()
73
+
74
+ for i in range(batch_size):
75
+ current_seq_len = int(seq_length[i].item())
76
+
77
+ # Only add extra padding tokens if there's room
78
+ if current_seq_len < max_seq_length:
79
+ # Calculate how many padding tokens we can unmask
80
+ available_padding = max_seq_length - current_seq_len
81
+ tokens_to_unmask = min(num_extra_padding, available_padding)
82
+
83
+ # Unmask the specified number of padding tokens right after the sequence
84
+ modified_mask[i, current_seq_len : current_seq_len + tokens_to_unmask] = 1
85
+
86
+ return modified_mask
87
+
88
+
89
+ class Chroma(nn.Module):
90
+ """
91
+ Transformer model for flow matching on sequences.
92
+ """
93
+
94
+ def __init__(self, params: ChromaParams):
95
+ super().__init__()
96
+ self.params = params
97
+ self.in_channels = params.in_channels
98
+ self.out_channels = self.in_channels
99
+ self.gradient_checkpointing = False
100
+ if params.hidden_size % params.num_heads != 0:
101
+ raise ValueError(
102
+ f"Hidden size {params.hidden_size} must be divisible by num_heads {params.num_heads}"
103
+ )
104
+ pe_dim = params.hidden_size // params.num_heads
105
+ if sum(params.axes_dim) != pe_dim:
106
+ raise ValueError(
107
+ f"Got {params.axes_dim} but expected positional dim {pe_dim}"
108
+ )
109
+ self.hidden_size = params.hidden_size
110
+ self.num_heads = params.num_heads
111
+ self.pe_embedder = EmbedND(
112
+ dim=pe_dim, theta=params.theta, axes_dim=params.axes_dim
113
+ )
114
+ self.img_in = nn.Linear(self.in_channels, self.hidden_size, bias=True)
115
+
116
+ # TODO: need proper mapping for this approximator output!
117
+ # currently the mapping is hardcoded in distribute_modulations function
118
+ self.distilled_guidance_layer = Approximator(
119
+ params.approximator_in_dim,
120
+ self.hidden_size,
121
+ params.approximator_hidden_size,
122
+ params.approximator_depth,
123
+ )
124
+ self.txt_in = nn.Linear(params.context_in_dim, self.hidden_size)
125
+
126
+ self.double_blocks = nn.ModuleList(
127
+ [
128
+ DoubleStreamBlock(
129
+ self.hidden_size,
130
+ self.num_heads,
131
+ mlp_ratio=params.mlp_ratio,
132
+ qkv_bias=params.qkv_bias,
133
+ use_compiled=params._use_compiled,
134
+ )
135
+ for _ in range(params.depth)
136
+ ]
137
+ )
138
+
139
+ self.single_blocks = nn.ModuleList(
140
+ [
141
+ SingleStreamBlock(
142
+ self.hidden_size,
143
+ self.num_heads,
144
+ mlp_ratio=params.mlp_ratio,
145
+ use_compiled=params._use_compiled,
146
+ )
147
+ for _ in range(params.depth_single_blocks)
148
+ ]
149
+ )
150
+
151
+ self.final_layer = LastLayer(
152
+ self.hidden_size,
153
+ 1,
154
+ self.out_channels,
155
+ use_compiled=params._use_compiled,
156
+ )
157
+
158
+ # TODO: move this hardcoded value to config
159
+ # single layer has 3 modulation vectors
160
+ # double layer has 6 modulation vectors for each expert
161
+ # final layer has 2 modulation vectors
162
+ self.mod_index_length = 3 * params.depth_single_blocks + 2 * 6 * params.depth + 2
163
+ self.depth_single_blocks = params.depth_single_blocks
164
+ self.depth_double_blocks = params.depth
165
+ # self.mod_index = torch.tensor(list(range(self.mod_index_length)), device=0)
166
+ self.register_buffer(
167
+ "mod_index",
168
+ torch.tensor(list(range(self.mod_index_length)), device="cpu"),
169
+ persistent=False,
170
+ )
171
+ self.approximator_in_dim = params.approximator_in_dim
172
+
173
+ @property
174
+ def device(self):
175
+ # Get the device of the module (assumes all parameters are on the same device)
176
+ return next(self.parameters()).device
177
+
178
+ def enable_gradient_checkpointing(self, enable: bool = True):
179
+ self.gradient_checkpointing = enable
180
+
181
+ def forward(
182
+ self,
183
+ img: Tensor,
184
+ img_ids: Tensor,
185
+ txt: Tensor,
186
+ txt_ids: Tensor,
187
+ txt_mask: Tensor,
188
+ timesteps: Tensor,
189
+ guidance: Tensor,
190
+ attn_padding: int = 1,
191
+ ) -> Tensor:
192
+ if img.ndim != 3 or txt.ndim != 3:
193
+ raise ValueError("Input img and txt tensors must have 3 dimensions.")
194
+
195
+ # running on sequences img
196
+ img = self.img_in(img)
197
+ txt = self.txt_in(txt)
198
+
199
+ # TODO:
200
+ # need to fix grad accumulation issue here for now it's in no grad mode
201
+ # besides, i don't want to wash out the PFP that's trained on this model weights anyway
202
+ # the fan out operation here is deleting the backward graph
203
+ # alternatively doing forward pass for every block manually is doable but slow
204
+ # custom backward probably be better
205
+ with torch.no_grad():
206
+ distill_timestep = timestep_embedding(timesteps, 16)
207
+ # TODO: need to add toggle to omit this from schnell but that's not a priority
208
+ distil_guidance = timestep_embedding(guidance, 16)
209
+ # get all modulation index
210
+ modulation_index = timestep_embedding(self.mod_index, 32)
211
+ # we need to broadcast the modulation index here so each batch has all of the index
212
+ modulation_index = modulation_index.unsqueeze(0).repeat(img.shape[0], 1, 1)
213
+ # and we need to broadcast timestep and guidance along too
214
+ timestep_guidance = (
215
+ torch.cat([distill_timestep, distil_guidance], dim=1)
216
+ .unsqueeze(1)
217
+ .repeat(1, self.mod_index_length, 1)
218
+ )
219
+ # then and only then we could concatenate it together
220
+ input_vec = torch.cat([timestep_guidance, modulation_index], dim=-1)
221
+ mod_vectors = self.distilled_guidance_layer(input_vec.requires_grad_(True))
222
+ mod_vectors_dict = distribute_modulations(mod_vectors, self.depth_single_blocks, self.depth_double_blocks)
223
+
224
+ ids = torch.cat((txt_ids, img_ids), dim=1)
225
+ pe = self.pe_embedder(ids)
226
+
227
+ # compute mask
228
+ # assume max seq length from the batched input
229
+
230
+ max_len = txt.shape[1]
231
+
232
+ # mask
233
+ with torch.no_grad():
234
+ txt_mask_w_padding = modify_mask_to_attend_padding(
235
+ txt_mask, max_len, attn_padding
236
+ )
237
+ txt_img_mask = torch.cat(
238
+ [
239
+ txt_mask_w_padding,
240
+ torch.ones([img.shape[0], img.shape[1]], device=txt_mask.device),
241
+ ],
242
+ dim=1,
243
+ )
244
+ txt_img_mask = txt_img_mask.float().T @ txt_img_mask.float()
245
+ txt_img_mask = (
246
+ txt_img_mask[None, None, ...]
247
+ .repeat(txt.shape[0], self.num_heads, 1, 1)
248
+ .int()
249
+ .bool()
250
+ )
251
+ # txt_mask_w_padding[txt_mask_w_padding==False] = True
252
+
253
+ for i, block in enumerate(self.double_blocks):
254
+ # the guidance replaced by FFN output
255
+ img_mod = mod_vectors_dict[f"double_blocks.{i}.img_mod.lin"]
256
+ txt_mod = mod_vectors_dict[f"double_blocks.{i}.txt_mod.lin"]
257
+ double_mod = [img_mod, txt_mod]
258
+
259
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
260
+ img.requires_grad_(True)
261
+ img, txt = ckpt.checkpoint(
262
+ block, img, txt, pe, double_mod, txt_img_mask
263
+ )
264
+ else:
265
+ img, txt = block(
266
+ img=img, txt=txt, pe=pe, distill_vec=double_mod, mask=txt_img_mask
267
+ )
268
+
269
+ img = torch.cat((txt, img), 1)
270
+ for i, block in enumerate(self.single_blocks):
271
+ single_mod = mod_vectors_dict[f"single_blocks.{i}.modulation.lin"]
272
+ if torch.is_grad_enabled() and self.gradient_checkpointing:
273
+ img.requires_grad_(True)
274
+ img = ckpt.checkpoint(block, img, pe, single_mod, txt_img_mask)
275
+ else:
276
+ img = block(img, pe=pe, distill_vec=single_mod, mask=txt_img_mask)
277
+ img = img[:, txt.shape[1] :, ...]
278
+ final_mod = mod_vectors_dict["final_layer.adaLN_modulation.1"]
279
+ img = self.final_layer(
280
+ img, distill_vec=final_mod
281
+ ) # (N, T, patch_size ** 2 * out_channels)
282
+ return img