ACCC1380 commited on
Commit
b1d9e54
1 Parent(s): 71ae55a

Upload lora-scripts/sd-scripts/library/sdxl_original_unet.py with huggingface_hub

Browse files
lora-scripts/sd-scripts/library/sdxl_original_unet.py ADDED
@@ -0,0 +1,1286 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Diffusersのコードをベースとした sd_xl_baseのU-Net
2
+ # state dictの形式をSDXLに合わせてある
3
+
4
+ """
5
+ target: sgm.modules.diffusionmodules.openaimodel.UNetModel
6
+ params:
7
+ adm_in_channels: 2816
8
+ num_classes: sequential
9
+ use_checkpoint: True
10
+ in_channels: 4
11
+ out_channels: 4
12
+ model_channels: 320
13
+ attention_resolutions: [4, 2]
14
+ num_res_blocks: 2
15
+ channel_mult: [1, 2, 4]
16
+ num_head_channels: 64
17
+ use_spatial_transformer: True
18
+ use_linear_in_transformer: True
19
+ transformer_depth: [1, 2, 10] # note: the first is unused (due to attn_res starting at 2) 32, 16, 8 --> 64, 32, 16
20
+ context_dim: 2048
21
+ spatial_transformer_attn_type: softmax-xformers
22
+ legacy: False
23
+ """
24
+
25
+ import math
26
+ from types import SimpleNamespace
27
+ from typing import Any, Optional
28
+ import torch
29
+ import torch.utils.checkpoint
30
+ from torch import nn
31
+ from torch.nn import functional as F
32
+ from einops import rearrange
33
+ from .utils import setup_logging
34
+
35
+ setup_logging()
36
+ import logging
37
+
38
+ logger = logging.getLogger(__name__)
39
+
40
+ IN_CHANNELS: int = 4
41
+ OUT_CHANNELS: int = 4
42
+ ADM_IN_CHANNELS: int = 2816
43
+ CONTEXT_DIM: int = 2048
44
+ MODEL_CHANNELS: int = 320
45
+ TIME_EMBED_DIM = 320 * 4
46
+
47
+ USE_REENTRANT = True
48
+
49
+ # region memory efficient attention
50
+
51
+ # FlashAttentionを使うCrossAttention
52
+ # based on https://github.com/lucidrains/memory-efficient-attention-pytorch/blob/main/memory_efficient_attention_pytorch/flash_attention.py
53
+ # LICENSE MIT https://github.com/lucidrains/memory-efficient-attention-pytorch/blob/main/LICENSE
54
+
55
+ # constants
56
+
57
+ EPSILON = 1e-6
58
+
59
+ # helper functions
60
+
61
+
62
+ def exists(val):
63
+ return val is not None
64
+
65
+
66
+ def default(val, d):
67
+ return val if exists(val) else d
68
+
69
+
70
+ # flash attention forwards and backwards
71
+
72
+ # https://arxiv.org/abs/2205.14135
73
+
74
+
75
+ class FlashAttentionFunction(torch.autograd.Function):
76
+ @staticmethod
77
+ @torch.no_grad()
78
+ def forward(ctx, q, k, v, mask, causal, q_bucket_size, k_bucket_size):
79
+ """Algorithm 2 in the paper"""
80
+
81
+ device = q.device
82
+ dtype = q.dtype
83
+ max_neg_value = -torch.finfo(q.dtype).max
84
+ qk_len_diff = max(k.shape[-2] - q.shape[-2], 0)
85
+
86
+ o = torch.zeros_like(q)
87
+ all_row_sums = torch.zeros((*q.shape[:-1], 1), dtype=dtype, device=device)
88
+ all_row_maxes = torch.full((*q.shape[:-1], 1), max_neg_value, dtype=dtype, device=device)
89
+
90
+ scale = q.shape[-1] ** -0.5
91
+
92
+ if not exists(mask):
93
+ mask = (None,) * math.ceil(q.shape[-2] / q_bucket_size)
94
+ else:
95
+ mask = rearrange(mask, "b n -> b 1 1 n")
96
+ mask = mask.split(q_bucket_size, dim=-1)
97
+
98
+ row_splits = zip(
99
+ q.split(q_bucket_size, dim=-2),
100
+ o.split(q_bucket_size, dim=-2),
101
+ mask,
102
+ all_row_sums.split(q_bucket_size, dim=-2),
103
+ all_row_maxes.split(q_bucket_size, dim=-2),
104
+ )
105
+
106
+ for ind, (qc, oc, row_mask, row_sums, row_maxes) in enumerate(row_splits):
107
+ q_start_index = ind * q_bucket_size - qk_len_diff
108
+
109
+ col_splits = zip(
110
+ k.split(k_bucket_size, dim=-2),
111
+ v.split(k_bucket_size, dim=-2),
112
+ )
113
+
114
+ for k_ind, (kc, vc) in enumerate(col_splits):
115
+ k_start_index = k_ind * k_bucket_size
116
+
117
+ attn_weights = torch.einsum("... i d, ... j d -> ... i j", qc, kc) * scale
118
+
119
+ if exists(row_mask):
120
+ attn_weights.masked_fill_(~row_mask, max_neg_value)
121
+
122
+ if causal and q_start_index < (k_start_index + k_bucket_size - 1):
123
+ causal_mask = torch.ones((qc.shape[-2], kc.shape[-2]), dtype=torch.bool, device=device).triu(
124
+ q_start_index - k_start_index + 1
125
+ )
126
+ attn_weights.masked_fill_(causal_mask, max_neg_value)
127
+
128
+ block_row_maxes = attn_weights.amax(dim=-1, keepdims=True)
129
+ attn_weights -= block_row_maxes
130
+ exp_weights = torch.exp(attn_weights)
131
+
132
+ if exists(row_mask):
133
+ exp_weights.masked_fill_(~row_mask, 0.0)
134
+
135
+ block_row_sums = exp_weights.sum(dim=-1, keepdims=True).clamp(min=EPSILON)
136
+
137
+ new_row_maxes = torch.maximum(block_row_maxes, row_maxes)
138
+
139
+ exp_values = torch.einsum("... i j, ... j d -> ... i d", exp_weights, vc)
140
+
141
+ exp_row_max_diff = torch.exp(row_maxes - new_row_maxes)
142
+ exp_block_row_max_diff = torch.exp(block_row_maxes - new_row_maxes)
143
+
144
+ new_row_sums = exp_row_max_diff * row_sums + exp_block_row_max_diff * block_row_sums
145
+
146
+ oc.mul_((row_sums / new_row_sums) * exp_row_max_diff).add_((exp_block_row_max_diff / new_row_sums) * exp_values)
147
+
148
+ row_maxes.copy_(new_row_maxes)
149
+ row_sums.copy_(new_row_sums)
150
+
151
+ ctx.args = (causal, scale, mask, q_bucket_size, k_bucket_size)
152
+ ctx.save_for_backward(q, k, v, o, all_row_sums, all_row_maxes)
153
+
154
+ return o
155
+
156
+ @staticmethod
157
+ @torch.no_grad()
158
+ def backward(ctx, do):
159
+ """Algorithm 4 in the paper"""
160
+
161
+ causal, scale, mask, q_bucket_size, k_bucket_size = ctx.args
162
+ q, k, v, o, l, m = ctx.saved_tensors
163
+
164
+ device = q.device
165
+
166
+ max_neg_value = -torch.finfo(q.dtype).max
167
+ qk_len_diff = max(k.shape[-2] - q.shape[-2], 0)
168
+
169
+ dq = torch.zeros_like(q)
170
+ dk = torch.zeros_like(k)
171
+ dv = torch.zeros_like(v)
172
+
173
+ row_splits = zip(
174
+ q.split(q_bucket_size, dim=-2),
175
+ o.split(q_bucket_size, dim=-2),
176
+ do.split(q_bucket_size, dim=-2),
177
+ mask,
178
+ l.split(q_bucket_size, dim=-2),
179
+ m.split(q_bucket_size, dim=-2),
180
+ dq.split(q_bucket_size, dim=-2),
181
+ )
182
+
183
+ for ind, (qc, oc, doc, row_mask, lc, mc, dqc) in enumerate(row_splits):
184
+ q_start_index = ind * q_bucket_size - qk_len_diff
185
+
186
+ col_splits = zip(
187
+ k.split(k_bucket_size, dim=-2),
188
+ v.split(k_bucket_size, dim=-2),
189
+ dk.split(k_bucket_size, dim=-2),
190
+ dv.split(k_bucket_size, dim=-2),
191
+ )
192
+
193
+ for k_ind, (kc, vc, dkc, dvc) in enumerate(col_splits):
194
+ k_start_index = k_ind * k_bucket_size
195
+
196
+ attn_weights = torch.einsum("... i d, ... j d -> ... i j", qc, kc) * scale
197
+
198
+ if causal and q_start_index < (k_start_index + k_bucket_size - 1):
199
+ causal_mask = torch.ones((qc.shape[-2], kc.shape[-2]), dtype=torch.bool, device=device).triu(
200
+ q_start_index - k_start_index + 1
201
+ )
202
+ attn_weights.masked_fill_(causal_mask, max_neg_value)
203
+
204
+ exp_attn_weights = torch.exp(attn_weights - mc)
205
+
206
+ if exists(row_mask):
207
+ exp_attn_weights.masked_fill_(~row_mask, 0.0)
208
+
209
+ p = exp_attn_weights / lc
210
+
211
+ dv_chunk = torch.einsum("... i j, ... i d -> ... j d", p, doc)
212
+ dp = torch.einsum("... i d, ... j d -> ... i j", doc, vc)
213
+
214
+ D = (doc * oc).sum(dim=-1, keepdims=True)
215
+ ds = p * scale * (dp - D)
216
+
217
+ dq_chunk = torch.einsum("... i j, ... j d -> ... i d", ds, kc)
218
+ dk_chunk = torch.einsum("... i j, ... i d -> ... j d", ds, qc)
219
+
220
+ dqc.add_(dq_chunk)
221
+ dkc.add_(dk_chunk)
222
+ dvc.add_(dv_chunk)
223
+
224
+ return dq, dk, dv, None, None, None, None
225
+
226
+
227
+ # endregion
228
+
229
+
230
+ def get_parameter_dtype(parameter: torch.nn.Module):
231
+ return next(parameter.parameters()).dtype
232
+
233
+
234
+ def get_parameter_device(parameter: torch.nn.Module):
235
+ return next(parameter.parameters()).device
236
+
237
+
238
+ def get_timestep_embedding(
239
+ timesteps: torch.Tensor,
240
+ embedding_dim: int,
241
+ downscale_freq_shift: float = 1,
242
+ scale: float = 1,
243
+ max_period: int = 10000,
244
+ ):
245
+ """
246
+ This matches the implementation in Denoising Diffusion Probabilistic Models: Create sinusoidal timestep embeddings.
247
+
248
+ :param timesteps: a 1-D Tensor of N indices, one per batch element.
249
+ These may be fractional.
250
+ :param embedding_dim: the dimension of the output. :param max_period: controls the minimum frequency of the
251
+ embeddings. :return: an [N x dim] Tensor of positional embeddings.
252
+ """
253
+ assert len(timesteps.shape) == 1, "Timesteps should be a 1d-array"
254
+
255
+ half_dim = embedding_dim // 2
256
+ exponent = -math.log(max_period) * torch.arange(start=0, end=half_dim, dtype=torch.float32, device=timesteps.device)
257
+ exponent = exponent / (half_dim - downscale_freq_shift)
258
+
259
+ emb = torch.exp(exponent)
260
+ emb = timesteps[:, None].float() * emb[None, :]
261
+
262
+ # scale embeddings
263
+ emb = scale * emb
264
+
265
+ # concat sine and cosine embeddings: flipped from Diffusers original ver because always flip_sin_to_cos=True
266
+ emb = torch.cat([torch.cos(emb), torch.sin(emb)], dim=-1)
267
+
268
+ # zero pad
269
+ if embedding_dim % 2 == 1:
270
+ emb = torch.nn.functional.pad(emb, (0, 1, 0, 0))
271
+ return emb
272
+
273
+
274
+ # Deep Shrink: We do not common this function, because minimize dependencies.
275
+ def resize_like(x, target, mode="bicubic", align_corners=False):
276
+ org_dtype = x.dtype
277
+ if org_dtype == torch.bfloat16:
278
+ x = x.to(torch.float32)
279
+
280
+ if x.shape[-2:] != target.shape[-2:]:
281
+ if mode == "nearest":
282
+ x = F.interpolate(x, size=target.shape[-2:], mode=mode)
283
+ else:
284
+ x = F.interpolate(x, size=target.shape[-2:], mode=mode, align_corners=align_corners)
285
+
286
+ if org_dtype == torch.bfloat16:
287
+ x = x.to(org_dtype)
288
+ return x
289
+
290
+
291
+ class GroupNorm32(nn.GroupNorm):
292
+ def forward(self, x):
293
+ if self.weight.dtype != torch.float32:
294
+ return super().forward(x)
295
+ return super().forward(x.float()).type(x.dtype)
296
+
297
+
298
+ class ResnetBlock2D(nn.Module):
299
+ def __init__(
300
+ self,
301
+ in_channels,
302
+ out_channels,
303
+ ):
304
+ super().__init__()
305
+ self.in_channels = in_channels
306
+ self.out_channels = out_channels
307
+
308
+ self.in_layers = nn.Sequential(
309
+ GroupNorm32(32, in_channels),
310
+ nn.SiLU(),
311
+ nn.Conv2d(in_channels, out_channels, kernel_size=3, stride=1, padding=1),
312
+ )
313
+
314
+ self.emb_layers = nn.Sequential(nn.SiLU(), nn.Linear(TIME_EMBED_DIM, out_channels))
315
+
316
+ self.out_layers = nn.Sequential(
317
+ GroupNorm32(32, out_channels),
318
+ nn.SiLU(),
319
+ nn.Identity(), # to make state_dict compatible with original model
320
+ nn.Conv2d(out_channels, out_channels, kernel_size=3, stride=1, padding=1),
321
+ )
322
+
323
+ if in_channels != out_channels:
324
+ self.skip_connection = nn.Conv2d(in_channels, out_channels, kernel_size=1, stride=1, padding=0)
325
+ else:
326
+ self.skip_connection = nn.Identity()
327
+
328
+ self.gradient_checkpointing = False
329
+
330
+ def forward_body(self, x, emb):
331
+ h = self.in_layers(x)
332
+ emb_out = self.emb_layers(emb).type(h.dtype)
333
+ h = h + emb_out[:, :, None, None]
334
+ h = self.out_layers(h)
335
+ x = self.skip_connection(x)
336
+ return x + h
337
+
338
+ def forward(self, x, emb):
339
+ if self.training and self.gradient_checkpointing:
340
+ # logger.info("ResnetBlock2D: gradient_checkpointing")
341
+
342
+ def create_custom_forward(func):
343
+ def custom_forward(*inputs):
344
+ return func(*inputs)
345
+
346
+ return custom_forward
347
+
348
+ x = torch.utils.checkpoint.checkpoint(create_custom_forward(self.forward_body), x, emb, use_reentrant=USE_REENTRANT)
349
+ else:
350
+ x = self.forward_body(x, emb)
351
+
352
+ return x
353
+
354
+
355
+ class Downsample2D(nn.Module):
356
+ def __init__(self, channels, out_channels):
357
+ super().__init__()
358
+
359
+ self.channels = channels
360
+ self.out_channels = out_channels
361
+
362
+ self.op = nn.Conv2d(self.channels, self.out_channels, 3, stride=2, padding=1)
363
+
364
+ self.gradient_checkpointing = False
365
+
366
+ def forward_body(self, hidden_states):
367
+ assert hidden_states.shape[1] == self.channels
368
+ hidden_states = self.op(hidden_states)
369
+
370
+ return hidden_states
371
+
372
+ def forward(self, hidden_states):
373
+ if self.training and self.gradient_checkpointing:
374
+ # logger.info("Downsample2D: gradient_checkpointing")
375
+
376
+ def create_custom_forward(func):
377
+ def custom_forward(*inputs):
378
+ return func(*inputs)
379
+
380
+ return custom_forward
381
+
382
+ hidden_states = torch.utils.checkpoint.checkpoint(
383
+ create_custom_forward(self.forward_body), hidden_states, use_reentrant=USE_REENTRANT
384
+ )
385
+ else:
386
+ hidden_states = self.forward_body(hidden_states)
387
+
388
+ return hidden_states
389
+
390
+
391
+ class CrossAttention(nn.Module):
392
+ def __init__(
393
+ self,
394
+ query_dim: int,
395
+ cross_attention_dim: Optional[int] = None,
396
+ heads: int = 8,
397
+ dim_head: int = 64,
398
+ upcast_attention: bool = False,
399
+ ):
400
+ super().__init__()
401
+ inner_dim = dim_head * heads
402
+ cross_attention_dim = cross_attention_dim if cross_attention_dim is not None else query_dim
403
+ self.upcast_attention = upcast_attention
404
+
405
+ self.scale = dim_head**-0.5
406
+ self.heads = heads
407
+
408
+ self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
409
+ self.to_k = nn.Linear(cross_attention_dim, inner_dim, bias=False)
410
+ self.to_v = nn.Linear(cross_attention_dim, inner_dim, bias=False)
411
+
412
+ self.to_out = nn.ModuleList([])
413
+ self.to_out.append(nn.Linear(inner_dim, query_dim))
414
+ # no dropout here
415
+
416
+ self.use_memory_efficient_attention_xformers = False
417
+ self.use_memory_efficient_attention_mem_eff = False
418
+ self.use_sdpa = False
419
+
420
+ def set_use_memory_efficient_attention(self, xformers, mem_eff):
421
+ self.use_memory_efficient_attention_xformers = xformers
422
+ self.use_memory_efficient_attention_mem_eff = mem_eff
423
+
424
+ def set_use_sdpa(self, sdpa):
425
+ self.use_sdpa = sdpa
426
+
427
+ def reshape_heads_to_batch_dim(self, tensor):
428
+ batch_size, seq_len, dim = tensor.shape
429
+ head_size = self.heads
430
+ tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
431
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size * head_size, seq_len, dim // head_size)
432
+ return tensor
433
+
434
+ def reshape_batch_dim_to_heads(self, tensor):
435
+ batch_size, seq_len, dim = tensor.shape
436
+ head_size = self.heads
437
+ tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
438
+ tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
439
+ return tensor
440
+
441
+ def forward(self, hidden_states, context=None, mask=None):
442
+ if self.use_memory_efficient_attention_xformers:
443
+ return self.forward_memory_efficient_xformers(hidden_states, context, mask)
444
+ if self.use_memory_efficient_attention_mem_eff:
445
+ return self.forward_memory_efficient_mem_eff(hidden_states, context, mask)
446
+ if self.use_sdpa:
447
+ return self.forward_sdpa(hidden_states, context, mask)
448
+
449
+ query = self.to_q(hidden_states)
450
+ context = context if context is not None else hidden_states
451
+ key = self.to_k(context)
452
+ value = self.to_v(context)
453
+
454
+ query = self.reshape_heads_to_batch_dim(query)
455
+ key = self.reshape_heads_to_batch_dim(key)
456
+ value = self.reshape_heads_to_batch_dim(value)
457
+
458
+ hidden_states = self._attention(query, key, value)
459
+
460
+ # linear proj
461
+ hidden_states = self.to_out[0](hidden_states)
462
+ # hidden_states = self.to_out[1](hidden_states) # no dropout
463
+ return hidden_states
464
+
465
+ def _attention(self, query, key, value):
466
+ if self.upcast_attention:
467
+ query = query.float()
468
+ key = key.float()
469
+
470
+ attention_scores = torch.baddbmm(
471
+ torch.empty(query.shape[0], query.shape[1], key.shape[1], dtype=query.dtype, device=query.device),
472
+ query,
473
+ key.transpose(-1, -2),
474
+ beta=0,
475
+ alpha=self.scale,
476
+ )
477
+ attention_probs = attention_scores.softmax(dim=-1)
478
+
479
+ # cast back to the original dtype
480
+ attention_probs = attention_probs.to(value.dtype)
481
+
482
+ # compute attention output
483
+ hidden_states = torch.bmm(attention_probs, value)
484
+
485
+ # reshape hidden_states
486
+ hidden_states = self.reshape_batch_dim_to_heads(hidden_states)
487
+ return hidden_states
488
+
489
+ # TODO support Hypernetworks
490
+ def forward_memory_efficient_xformers(self, x, context=None, mask=None):
491
+ import xformers.ops
492
+
493
+ h = self.heads
494
+ q_in = self.to_q(x)
495
+ context = context if context is not None else x
496
+ context = context.to(x.dtype)
497
+ k_in = self.to_k(context)
498
+ v_in = self.to_v(context)
499
+
500
+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b n h d", h=h), (q_in, k_in, v_in))
501
+ del q_in, k_in, v_in
502
+
503
+ q = q.contiguous()
504
+ k = k.contiguous()
505
+ v = v.contiguous()
506
+ out = xformers.ops.memory_efficient_attention(q, k, v, attn_bias=None) # 最適なのを選んでくれる
507
+ del q, k, v
508
+
509
+ out = rearrange(out, "b n h d -> b n (h d)", h=h)
510
+
511
+ out = self.to_out[0](out)
512
+ return out
513
+
514
+ def forward_memory_efficient_mem_eff(self, x, context=None, mask=None):
515
+ flash_func = FlashAttentionFunction
516
+
517
+ q_bucket_size = 512
518
+ k_bucket_size = 1024
519
+
520
+ h = self.heads
521
+ q = self.to_q(x)
522
+ context = context if context is not None else x
523
+ context = context.to(x.dtype)
524
+ k = self.to_k(context)
525
+ v = self.to_v(context)
526
+ del context, x
527
+
528
+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q, k, v))
529
+
530
+ out = flash_func.apply(q, k, v, mask, False, q_bucket_size, k_bucket_size)
531
+
532
+ out = rearrange(out, "b h n d -> b n (h d)")
533
+
534
+ out = self.to_out[0](out)
535
+ return out
536
+
537
+ def forward_sdpa(self, x, context=None, mask=None):
538
+ h = self.heads
539
+ q_in = self.to_q(x)
540
+ context = context if context is not None else x
541
+ context = context.to(x.dtype)
542
+ k_in = self.to_k(context)
543
+ v_in = self.to_v(context)
544
+
545
+ q, k, v = map(lambda t: rearrange(t, "b n (h d) -> b h n d", h=h), (q_in, k_in, v_in))
546
+ del q_in, k_in, v_in
547
+
548
+ out = F.scaled_dot_product_attention(q, k, v, attn_mask=mask, dropout_p=0.0, is_causal=False)
549
+
550
+ out = rearrange(out, "b h n d -> b n (h d)", h=h)
551
+
552
+ out = self.to_out[0](out)
553
+ return out
554
+
555
+
556
+ # feedforward
557
+ class GEGLU(nn.Module):
558
+ r"""
559
+ A variant of the gated linear unit activation function from https://arxiv.org/abs/2002.05202.
560
+
561
+ Parameters:
562
+ dim_in (`int`): The number of channels in the input.
563
+ dim_out (`int`): The number of channels in the output.
564
+ """
565
+
566
+ def __init__(self, dim_in: int, dim_out: int):
567
+ super().__init__()
568
+ self.proj = nn.Linear(dim_in, dim_out * 2)
569
+
570
+ def gelu(self, gate):
571
+ if gate.device.type != "mps":
572
+ return F.gelu(gate)
573
+ # mps: gelu is not implemented for float16
574
+ return F.gelu(gate.to(dtype=torch.float32)).to(dtype=gate.dtype)
575
+
576
+ def forward(self, hidden_states):
577
+ hidden_states, gate = self.proj(hidden_states).chunk(2, dim=-1)
578
+ return hidden_states * self.gelu(gate)
579
+
580
+
581
+ class FeedForward(nn.Module):
582
+ def __init__(
583
+ self,
584
+ dim: int,
585
+ ):
586
+ super().__init__()
587
+ inner_dim = int(dim * 4) # mult is always 4
588
+
589
+ self.net = nn.ModuleList([])
590
+ # project in
591
+ self.net.append(GEGLU(dim, inner_dim))
592
+ # project dropout
593
+ self.net.append(nn.Identity()) # nn.Dropout(0)) # dummy for dropout with 0
594
+ # project out
595
+ self.net.append(nn.Linear(inner_dim, dim))
596
+
597
+ def forward(self, hidden_states):
598
+ for module in self.net:
599
+ hidden_states = module(hidden_states)
600
+ return hidden_states
601
+
602
+
603
+ class BasicTransformerBlock(nn.Module):
604
+ def __init__(
605
+ self, dim: int, num_attention_heads: int, attention_head_dim: int, cross_attention_dim: int, upcast_attention: bool = False
606
+ ):
607
+ super().__init__()
608
+
609
+ self.gradient_checkpointing = False
610
+
611
+ # 1. Self-Attn
612
+ self.attn1 = CrossAttention(
613
+ query_dim=dim,
614
+ cross_attention_dim=None,
615
+ heads=num_attention_heads,
616
+ dim_head=attention_head_dim,
617
+ upcast_attention=upcast_attention,
618
+ )
619
+ self.ff = FeedForward(dim)
620
+
621
+ # 2. Cross-Attn
622
+ self.attn2 = CrossAttention(
623
+ query_dim=dim,
624
+ cross_attention_dim=cross_attention_dim,
625
+ heads=num_attention_heads,
626
+ dim_head=attention_head_dim,
627
+ upcast_attention=upcast_attention,
628
+ )
629
+
630
+ self.norm1 = nn.LayerNorm(dim)
631
+ self.norm2 = nn.LayerNorm(dim)
632
+
633
+ # 3. Feed-forward
634
+ self.norm3 = nn.LayerNorm(dim)
635
+
636
+ def set_use_memory_efficient_attention(self, xformers: bool, mem_eff: bool):
637
+ self.attn1.set_use_memory_efficient_attention(xformers, mem_eff)
638
+ self.attn2.set_use_memory_efficient_attention(xformers, mem_eff)
639
+
640
+ def set_use_sdpa(self, sdpa: bool):
641
+ self.attn1.set_use_sdpa(sdpa)
642
+ self.attn2.set_use_sdpa(sdpa)
643
+
644
+ def forward_body(self, hidden_states, context=None, timestep=None):
645
+ # 1. Self-Attention
646
+ norm_hidden_states = self.norm1(hidden_states)
647
+
648
+ hidden_states = self.attn1(norm_hidden_states) + hidden_states
649
+
650
+ # 2. Cross-Attention
651
+ norm_hidden_states = self.norm2(hidden_states)
652
+ hidden_states = self.attn2(norm_hidden_states, context=context) + hidden_states
653
+
654
+ # 3. Feed-forward
655
+ hidden_states = self.ff(self.norm3(hidden_states)) + hidden_states
656
+
657
+ return hidden_states
658
+
659
+ def forward(self, hidden_states, context=None, timestep=None):
660
+ if self.training and self.gradient_checkpointing:
661
+ # logger.info("BasicTransformerBlock: checkpointing")
662
+
663
+ def create_custom_forward(func):
664
+ def custom_forward(*inputs):
665
+ return func(*inputs)
666
+
667
+ return custom_forward
668
+
669
+ output = torch.utils.checkpoint.checkpoint(
670
+ create_custom_forward(self.forward_body), hidden_states, context, timestep, use_reentrant=USE_REENTRANT
671
+ )
672
+ else:
673
+ output = self.forward_body(hidden_states, context, timestep)
674
+
675
+ return output
676
+
677
+
678
+ class Transformer2DModel(nn.Module):
679
+ def __init__(
680
+ self,
681
+ num_attention_heads: int = 16,
682
+ attention_head_dim: int = 88,
683
+ in_channels: Optional[int] = None,
684
+ cross_attention_dim: Optional[int] = None,
685
+ use_linear_projection: bool = False,
686
+ upcast_attention: bool = False,
687
+ num_transformer_layers: int = 1,
688
+ ):
689
+ super().__init__()
690
+ self.in_channels = in_channels
691
+ self.num_attention_heads = num_attention_heads
692
+ self.attention_head_dim = attention_head_dim
693
+ inner_dim = num_attention_heads * attention_head_dim
694
+ self.use_linear_projection = use_linear_projection
695
+
696
+ self.norm = torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)
697
+ # self.norm = GroupNorm32(32, in_channels, eps=1e-6, affine=True)
698
+
699
+ if use_linear_projection:
700
+ self.proj_in = nn.Linear(in_channels, inner_dim)
701
+ else:
702
+ self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
703
+
704
+ blocks = []
705
+ for _ in range(num_transformer_layers):
706
+ blocks.append(
707
+ BasicTransformerBlock(
708
+ inner_dim,
709
+ num_attention_heads,
710
+ attention_head_dim,
711
+ cross_attention_dim=cross_attention_dim,
712
+ upcast_attention=upcast_attention,
713
+ )
714
+ )
715
+
716
+ self.transformer_blocks = nn.ModuleList(blocks)
717
+
718
+ if use_linear_projection:
719
+ self.proj_out = nn.Linear(in_channels, inner_dim)
720
+ else:
721
+ self.proj_out = nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0)
722
+
723
+ self.gradient_checkpointing = False
724
+
725
+ def set_use_memory_efficient_attention(self, xformers, mem_eff):
726
+ for transformer in self.transformer_blocks:
727
+ transformer.set_use_memory_efficient_attention(xformers, mem_eff)
728
+
729
+ def set_use_sdpa(self, sdpa):
730
+ for transformer in self.transformer_blocks:
731
+ transformer.set_use_sdpa(sdpa)
732
+
733
+ def forward(self, hidden_states, encoder_hidden_states=None, timestep=None):
734
+ # 1. Input
735
+ batch, _, height, weight = hidden_states.shape
736
+ residual = hidden_states
737
+
738
+ hidden_states = self.norm(hidden_states)
739
+ if not self.use_linear_projection:
740
+ hidden_states = self.proj_in(hidden_states)
741
+ inner_dim = hidden_states.shape[1]
742
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
743
+ else:
744
+ inner_dim = hidden_states.shape[1]
745
+ hidden_states = hidden_states.permute(0, 2, 3, 1).reshape(batch, height * weight, inner_dim)
746
+ hidden_states = self.proj_in(hidden_states)
747
+
748
+ # 2. Blocks
749
+ for block in self.transformer_blocks:
750
+ hidden_states = block(hidden_states, context=encoder_hidden_states, timestep=timestep)
751
+
752
+ # 3. Output
753
+ if not self.use_linear_projection:
754
+ hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
755
+ hidden_states = self.proj_out(hidden_states)
756
+ else:
757
+ hidden_states = self.proj_out(hidden_states)
758
+ hidden_states = hidden_states.reshape(batch, height, weight, inner_dim).permute(0, 3, 1, 2).contiguous()
759
+
760
+ output = hidden_states + residual
761
+
762
+ return output
763
+
764
+
765
+ class Upsample2D(nn.Module):
766
+ def __init__(self, channels, out_channels):
767
+ super().__init__()
768
+ self.channels = channels
769
+ self.out_channels = out_channels
770
+ self.conv = nn.Conv2d(self.channels, self.out_channels, 3, padding=1)
771
+
772
+ self.gradient_checkpointing = False
773
+
774
+ def forward_body(self, hidden_states, output_size=None):
775
+ assert hidden_states.shape[1] == self.channels
776
+
777
+ # Cast to float32 to as 'upsample_nearest2d_out_frame' op does not support bfloat16
778
+ # TODO(Suraj): Remove this cast once the issue is fixed in PyTorch
779
+ # https://github.com/pytorch/pytorch/issues/86679
780
+ dtype = hidden_states.dtype
781
+ if dtype == torch.bfloat16:
782
+ hidden_states = hidden_states.to(torch.float32)
783
+
784
+ # upsample_nearest_nhwc fails with large batch sizes. see https://github.com/huggingface/diffusers/issues/984
785
+ if hidden_states.shape[0] >= 64:
786
+ hidden_states = hidden_states.contiguous()
787
+
788
+ # if `output_size` is passed we force the interpolation output size and do not make use of `scale_factor=2`
789
+ if output_size is None:
790
+ hidden_states = F.interpolate(hidden_states, scale_factor=2.0, mode="nearest")
791
+ else:
792
+ hidden_states = F.interpolate(hidden_states, size=output_size, mode="nearest")
793
+
794
+ # If the input is bfloat16, we cast back to bfloat16
795
+ if dtype == torch.bfloat16:
796
+ hidden_states = hidden_states.to(dtype)
797
+
798
+ hidden_states = self.conv(hidden_states)
799
+
800
+ return hidden_states
801
+
802
+ def forward(self, hidden_states, output_size=None):
803
+ if self.training and self.gradient_checkpointing:
804
+ # logger.info("Upsample2D: gradient_checkpointing")
805
+
806
+ def create_custom_forward(func):
807
+ def custom_forward(*inputs):
808
+ return func(*inputs)
809
+
810
+ return custom_forward
811
+
812
+ hidden_states = torch.utils.checkpoint.checkpoint(
813
+ create_custom_forward(self.forward_body), hidden_states, output_size, use_reentrant=USE_REENTRANT
814
+ )
815
+ else:
816
+ hidden_states = self.forward_body(hidden_states, output_size)
817
+
818
+ return hidden_states
819
+
820
+
821
+ class SdxlUNet2DConditionModel(nn.Module):
822
+ _supports_gradient_checkpointing = True
823
+
824
+ def __init__(
825
+ self,
826
+ **kwargs,
827
+ ):
828
+ super().__init__()
829
+
830
+ self.in_channels = IN_CHANNELS
831
+ self.out_channels = OUT_CHANNELS
832
+ self.model_channels = MODEL_CHANNELS
833
+ self.time_embed_dim = TIME_EMBED_DIM
834
+ self.adm_in_channels = ADM_IN_CHANNELS
835
+
836
+ self.gradient_checkpointing = False
837
+ # self.sample_size = sample_size
838
+
839
+ # time embedding
840
+ self.time_embed = nn.Sequential(
841
+ nn.Linear(self.model_channels, self.time_embed_dim),
842
+ nn.SiLU(),
843
+ nn.Linear(self.time_embed_dim, self.time_embed_dim),
844
+ )
845
+
846
+ # label embedding
847
+ self.label_emb = nn.Sequential(
848
+ nn.Sequential(
849
+ nn.Linear(self.adm_in_channels, self.time_embed_dim),
850
+ nn.SiLU(),
851
+ nn.Linear(self.time_embed_dim, self.time_embed_dim),
852
+ )
853
+ )
854
+
855
+ # input
856
+ self.input_blocks = nn.ModuleList(
857
+ [
858
+ nn.Sequential(
859
+ nn.Conv2d(self.in_channels, self.model_channels, kernel_size=3, padding=(1, 1)),
860
+ )
861
+ ]
862
+ )
863
+
864
+ # level 0
865
+ for i in range(2):
866
+ layers = [
867
+ ResnetBlock2D(
868
+ in_channels=1 * self.model_channels,
869
+ out_channels=1 * self.model_channels,
870
+ ),
871
+ ]
872
+ self.input_blocks.append(nn.ModuleList(layers))
873
+
874
+ self.input_blocks.append(
875
+ nn.Sequential(
876
+ Downsample2D(
877
+ channels=1 * self.model_channels,
878
+ out_channels=1 * self.model_channels,
879
+ ),
880
+ )
881
+ )
882
+
883
+ # level 1
884
+ for i in range(2):
885
+ layers = [
886
+ ResnetBlock2D(
887
+ in_channels=(1 if i == 0 else 2) * self.model_channels,
888
+ out_channels=2 * self.model_channels,
889
+ ),
890
+ Transformer2DModel(
891
+ num_attention_heads=2 * self.model_channels // 64,
892
+ attention_head_dim=64,
893
+ in_channels=2 * self.model_channels,
894
+ num_transformer_layers=2,
895
+ use_linear_projection=True,
896
+ cross_attention_dim=2048,
897
+ ),
898
+ ]
899
+ self.input_blocks.append(nn.ModuleList(layers))
900
+
901
+ self.input_blocks.append(
902
+ nn.Sequential(
903
+ Downsample2D(
904
+ channels=2 * self.model_channels,
905
+ out_channels=2 * self.model_channels,
906
+ ),
907
+ )
908
+ )
909
+
910
+ # level 2
911
+ for i in range(2):
912
+ layers = [
913
+ ResnetBlock2D(
914
+ in_channels=(2 if i == 0 else 4) * self.model_channels,
915
+ out_channels=4 * self.model_channels,
916
+ ),
917
+ Transformer2DModel(
918
+ num_attention_heads=4 * self.model_channels // 64,
919
+ attention_head_dim=64,
920
+ in_channels=4 * self.model_channels,
921
+ num_transformer_layers=10,
922
+ use_linear_projection=True,
923
+ cross_attention_dim=2048,
924
+ ),
925
+ ]
926
+ self.input_blocks.append(nn.ModuleList(layers))
927
+
928
+ # mid
929
+ self.middle_block = nn.ModuleList(
930
+ [
931
+ ResnetBlock2D(
932
+ in_channels=4 * self.model_channels,
933
+ out_channels=4 * self.model_channels,
934
+ ),
935
+ Transformer2DModel(
936
+ num_attention_heads=4 * self.model_channels // 64,
937
+ attention_head_dim=64,
938
+ in_channels=4 * self.model_channels,
939
+ num_transformer_layers=10,
940
+ use_linear_projection=True,
941
+ cross_attention_dim=2048,
942
+ ),
943
+ ResnetBlock2D(
944
+ in_channels=4 * self.model_channels,
945
+ out_channels=4 * self.model_channels,
946
+ ),
947
+ ]
948
+ )
949
+
950
+ # output
951
+ self.output_blocks = nn.ModuleList([])
952
+
953
+ # level 2
954
+ for i in range(3):
955
+ layers = [
956
+ ResnetBlock2D(
957
+ in_channels=4 * self.model_channels + (4 if i <= 1 else 2) * self.model_channels,
958
+ out_channels=4 * self.model_channels,
959
+ ),
960
+ Transformer2DModel(
961
+ num_attention_heads=4 * self.model_channels // 64,
962
+ attention_head_dim=64,
963
+ in_channels=4 * self.model_channels,
964
+ num_transformer_layers=10,
965
+ use_linear_projection=True,
966
+ cross_attention_dim=2048,
967
+ ),
968
+ ]
969
+ if i == 2:
970
+ layers.append(
971
+ Upsample2D(
972
+ channels=4 * self.model_channels,
973
+ out_channels=4 * self.model_channels,
974
+ )
975
+ )
976
+
977
+ self.output_blocks.append(nn.ModuleList(layers))
978
+
979
+ # level 1
980
+ for i in range(3):
981
+ layers = [
982
+ ResnetBlock2D(
983
+ in_channels=2 * self.model_channels + (4 if i == 0 else (2 if i == 1 else 1)) * self.model_channels,
984
+ out_channels=2 * self.model_channels,
985
+ ),
986
+ Transformer2DModel(
987
+ num_attention_heads=2 * self.model_channels // 64,
988
+ attention_head_dim=64,
989
+ in_channels=2 * self.model_channels,
990
+ num_transformer_layers=2,
991
+ use_linear_projection=True,
992
+ cross_attention_dim=2048,
993
+ ),
994
+ ]
995
+ if i == 2:
996
+ layers.append(
997
+ Upsample2D(
998
+ channels=2 * self.model_channels,
999
+ out_channels=2 * self.model_channels,
1000
+ )
1001
+ )
1002
+
1003
+ self.output_blocks.append(nn.ModuleList(layers))
1004
+
1005
+ # level 0
1006
+ for i in range(3):
1007
+ layers = [
1008
+ ResnetBlock2D(
1009
+ in_channels=1 * self.model_channels + (2 if i == 0 else 1) * self.model_channels,
1010
+ out_channels=1 * self.model_channels,
1011
+ ),
1012
+ ]
1013
+
1014
+ self.output_blocks.append(nn.ModuleList(layers))
1015
+
1016
+ # output
1017
+ self.out = nn.ModuleList(
1018
+ [GroupNorm32(32, self.model_channels), nn.SiLU(), nn.Conv2d(self.model_channels, self.out_channels, 3, padding=1)]
1019
+ )
1020
+
1021
+ # region diffusers compatibility
1022
+ def prepare_config(self):
1023
+ self.config = SimpleNamespace()
1024
+
1025
+ @property
1026
+ def dtype(self) -> torch.dtype:
1027
+ # `torch.dtype`: The dtype of the module (assuming that all the module parameters have the same dtype).
1028
+ return get_parameter_dtype(self)
1029
+
1030
+ @property
1031
+ def device(self) -> torch.device:
1032
+ # `torch.device`: The device on which the module is (assuming that all the module parameters are on the same device).
1033
+ return get_parameter_device(self)
1034
+
1035
+ def set_attention_slice(self, slice_size):
1036
+ raise NotImplementedError("Attention slicing is not supported for this model.")
1037
+
1038
+ def is_gradient_checkpointing(self) -> bool:
1039
+ return any(hasattr(m, "gradient_checkpointing") and m.gradient_checkpointing for m in self.modules())
1040
+
1041
+ def enable_gradient_checkpointing(self):
1042
+ self.gradient_checkpointing = True
1043
+ self.set_gradient_checkpointing(value=True)
1044
+
1045
+ def disable_gradient_checkpointing(self):
1046
+ self.gradient_checkpointing = False
1047
+ self.set_gradient_checkpointing(value=False)
1048
+
1049
+ def set_use_memory_efficient_attention(self, xformers: bool, mem_eff: bool) -> None:
1050
+ blocks = self.input_blocks + [self.middle_block] + self.output_blocks
1051
+ for block in blocks:
1052
+ for module in block:
1053
+ if hasattr(module, "set_use_memory_efficient_attention"):
1054
+ # logger.info(module.__class__.__name__)
1055
+ module.set_use_memory_efficient_attention(xformers, mem_eff)
1056
+
1057
+ def set_use_sdpa(self, sdpa: bool) -> None:
1058
+ blocks = self.input_blocks + [self.middle_block] + self.output_blocks
1059
+ for block in blocks:
1060
+ for module in block:
1061
+ if hasattr(module, "set_use_sdpa"):
1062
+ module.set_use_sdpa(sdpa)
1063
+
1064
+ def set_gradient_checkpointing(self, value=False):
1065
+ blocks = self.input_blocks + [self.middle_block] + self.output_blocks
1066
+ for block in blocks:
1067
+ for module in block.modules():
1068
+ if hasattr(module, "gradient_checkpointing"):
1069
+ # logger.info(f{module.__class__.__name__} {module.gradient_checkpointing} -> {value}")
1070
+ module.gradient_checkpointing = value
1071
+
1072
+ # endregion
1073
+
1074
+ def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
1075
+ # broadcast timesteps to batch dimension
1076
+ timesteps = timesteps.expand(x.shape[0])
1077
+
1078
+ hs = []
1079
+ t_emb = get_timestep_embedding(timesteps, self.model_channels, downscale_freq_shift=0) # , repeat_only=False)
1080
+ t_emb = t_emb.to(x.dtype)
1081
+ emb = self.time_embed(t_emb)
1082
+
1083
+ assert x.shape[0] == y.shape[0], f"batch size mismatch: {x.shape[0]} != {y.shape[0]}"
1084
+ assert x.dtype == y.dtype, f"dtype mismatch: {x.dtype} != {y.dtype}"
1085
+ # assert x.dtype == self.dtype
1086
+ emb = emb + self.label_emb(y)
1087
+
1088
+ def call_module(module, h, emb, context):
1089
+ x = h
1090
+ for layer in module:
1091
+ # logger.info(layer.__class__.__name__, x.dtype, emb.dtype, context.dtype if context is not None else None)
1092
+ if isinstance(layer, ResnetBlock2D):
1093
+ x = layer(x, emb)
1094
+ elif isinstance(layer, Transformer2DModel):
1095
+ x = layer(x, context)
1096
+ else:
1097
+ x = layer(x)
1098
+ return x
1099
+
1100
+ # h = x.type(self.dtype)
1101
+ h = x
1102
+
1103
+ for module in self.input_blocks:
1104
+ h = call_module(module, h, emb, context)
1105
+ hs.append(h)
1106
+
1107
+ h = call_module(self.middle_block, h, emb, context)
1108
+
1109
+ for module in self.output_blocks:
1110
+ h = torch.cat([h, hs.pop()], dim=1)
1111
+ h = call_module(module, h, emb, context)
1112
+
1113
+ h = h.type(x.dtype)
1114
+ h = call_module(self.out, h, emb, context)
1115
+
1116
+ return h
1117
+
1118
+
1119
+ class InferSdxlUNet2DConditionModel:
1120
+ def __init__(self, original_unet: SdxlUNet2DConditionModel, **kwargs):
1121
+ self.delegate = original_unet
1122
+
1123
+ # override original model's forward method: because forward is not called by `__call__`
1124
+ # overriding `__call__` is not enough, because nn.Module.forward has a special handling
1125
+ self.delegate.forward = self.forward
1126
+
1127
+ # Deep Shrink
1128
+ self.ds_depth_1 = None
1129
+ self.ds_depth_2 = None
1130
+ self.ds_timesteps_1 = None
1131
+ self.ds_timesteps_2 = None
1132
+ self.ds_ratio = None
1133
+
1134
+ # call original model's methods
1135
+ def __getattr__(self, name):
1136
+ return getattr(self.delegate, name)
1137
+
1138
+ def __call__(self, *args, **kwargs):
1139
+ return self.delegate(*args, **kwargs)
1140
+
1141
+ def set_deep_shrink(self, ds_depth_1, ds_timesteps_1=650, ds_depth_2=None, ds_timesteps_2=None, ds_ratio=0.5):
1142
+ if ds_depth_1 is None:
1143
+ logger.info("Deep Shrink is disabled.")
1144
+ self.ds_depth_1 = None
1145
+ self.ds_timesteps_1 = None
1146
+ self.ds_depth_2 = None
1147
+ self.ds_timesteps_2 = None
1148
+ self.ds_ratio = None
1149
+ else:
1150
+ logger.info(
1151
+ f"Deep Shrink is enabled: [depth={ds_depth_1}/{ds_depth_2}, timesteps={ds_timesteps_1}/{ds_timesteps_2}, ratio={ds_ratio}]"
1152
+ )
1153
+ self.ds_depth_1 = ds_depth_1
1154
+ self.ds_timesteps_1 = ds_timesteps_1
1155
+ self.ds_depth_2 = ds_depth_2 if ds_depth_2 is not None else -1
1156
+ self.ds_timesteps_2 = ds_timesteps_2 if ds_timesteps_2 is not None else 1000
1157
+ self.ds_ratio = ds_ratio
1158
+
1159
+ def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
1160
+ r"""
1161
+ current implementation is a copy of `SdxlUNet2DConditionModel.forward()` with Deep Shrink.
1162
+ """
1163
+ _self = self.delegate
1164
+
1165
+ # broadcast timesteps to batch dimension
1166
+ timesteps = timesteps.expand(x.shape[0])
1167
+
1168
+ hs = []
1169
+ t_emb = get_timestep_embedding(timesteps, _self.model_channels, downscale_freq_shift=0) # , repeat_only=False)
1170
+ t_emb = t_emb.to(x.dtype)
1171
+ emb = _self.time_embed(t_emb)
1172
+
1173
+ assert x.shape[0] == y.shape[0], f"batch size mismatch: {x.shape[0]} != {y.shape[0]}"
1174
+ assert x.dtype == y.dtype, f"dtype mismatch: {x.dtype} != {y.dtype}"
1175
+ # assert x.dtype == _self.dtype
1176
+ emb = emb + _self.label_emb(y)
1177
+
1178
+ def call_module(module, h, emb, context):
1179
+ x = h
1180
+ for layer in module:
1181
+ # print(layer.__class__.__name__, x.dtype, emb.dtype, context.dtype if context is not None else None)
1182
+ if isinstance(layer, ResnetBlock2D):
1183
+ x = layer(x, emb)
1184
+ elif isinstance(layer, Transformer2DModel):
1185
+ x = layer(x, context)
1186
+ else:
1187
+ x = layer(x)
1188
+ return x
1189
+
1190
+ # h = x.type(self.dtype)
1191
+ h = x
1192
+
1193
+ for depth, module in enumerate(_self.input_blocks):
1194
+ # Deep Shrink
1195
+ if self.ds_depth_1 is not None:
1196
+ if (depth == self.ds_depth_1 and timesteps[0] >= self.ds_timesteps_1) or (
1197
+ self.ds_depth_2 is not None
1198
+ and depth == self.ds_depth_2
1199
+ and timesteps[0] < self.ds_timesteps_1
1200
+ and timesteps[0] >= self.ds_timesteps_2
1201
+ ):
1202
+ # print("downsample", h.shape, self.ds_ratio)
1203
+ org_dtype = h.dtype
1204
+ if org_dtype == torch.bfloat16:
1205
+ h = h.to(torch.float32)
1206
+ h = F.interpolate(h, scale_factor=self.ds_ratio, mode="bicubic", align_corners=False).to(org_dtype)
1207
+
1208
+ h = call_module(module, h, emb, context)
1209
+ hs.append(h)
1210
+
1211
+ h = call_module(_self.middle_block, h, emb, context)
1212
+
1213
+ for module in _self.output_blocks:
1214
+ # Deep Shrink
1215
+ if self.ds_depth_1 is not None:
1216
+ if hs[-1].shape[-2:] != h.shape[-2:]:
1217
+ # print("upsample", h.shape, hs[-1].shape)
1218
+ h = resize_like(h, hs[-1])
1219
+
1220
+ h = torch.cat([h, hs.pop()], dim=1)
1221
+ h = call_module(module, h, emb, context)
1222
+
1223
+ # Deep Shrink: in case of depth 0
1224
+ if self.ds_depth_1 == 0 and h.shape[-2:] != x.shape[-2:]:
1225
+ # print("upsample", h.shape, x.shape)
1226
+ h = resize_like(h, x)
1227
+
1228
+ h = h.type(x.dtype)
1229
+ h = call_module(_self.out, h, emb, context)
1230
+
1231
+ return h
1232
+
1233
+
1234
+ if __name__ == "__main__":
1235
+ import time
1236
+
1237
+ logger.info("create unet")
1238
+ unet = SdxlUNet2DConditionModel()
1239
+
1240
+ unet.to("cuda")
1241
+ unet.set_use_memory_efficient_attention(True, False)
1242
+ unet.set_gradient_checkpointing(True)
1243
+ unet.train()
1244
+
1245
+ # 使用メモリ量確認用の疑似学習ループ
1246
+ logger.info("preparing optimizer")
1247
+
1248
+ # optimizer = torch.optim.SGD(unet.parameters(), lr=1e-3, nesterov=True, momentum=0.9) # not working
1249
+
1250
+ # import bitsandbytes
1251
+ # optimizer = bitsandbytes.adam.Adam8bit(unet.parameters(), lr=1e-3) # not working
1252
+ # optimizer = bitsandbytes.optim.RMSprop8bit(unet.parameters(), lr=1e-3) # working at 23.5 GB with torch2
1253
+ # optimizer=bitsandbytes.optim.Adagrad8bit(unet.parameters(), lr=1e-3) # working at 23.5 GB with torch2
1254
+
1255
+ import transformers
1256
+
1257
+ optimizer = transformers.optimization.Adafactor(unet.parameters(), relative_step=True) # working at 22.2GB with torch2
1258
+
1259
+ scaler = torch.cuda.amp.GradScaler(enabled=True)
1260
+
1261
+ logger.info("start training")
1262
+ steps = 10
1263
+ batch_size = 1
1264
+
1265
+ for step in range(steps):
1266
+ logger.info(f"step {step}")
1267
+ if step == 1:
1268
+ time_start = time.perf_counter()
1269
+
1270
+ x = torch.randn(batch_size, 4, 128, 128).cuda() # 1024x1024
1271
+ t = torch.randint(low=0, high=10, size=(batch_size,), device="cuda")
1272
+ ctx = torch.randn(batch_size, 77, 2048).cuda()
1273
+ y = torch.randn(batch_size, ADM_IN_CHANNELS).cuda()
1274
+
1275
+ with torch.cuda.amp.autocast(enabled=True):
1276
+ output = unet(x, t, ctx, y)
1277
+ target = torch.randn_like(output)
1278
+ loss = torch.nn.functional.mse_loss(output, target)
1279
+
1280
+ scaler.scale(loss).backward()
1281
+ scaler.step(optimizer)
1282
+ scaler.update()
1283
+ optimizer.zero_grad(set_to_none=True)
1284
+
1285
+ time_end = time.perf_counter()
1286
+ logger.info(f"elapsed time: {time_end - time_start} [sec] for last {steps - 1} steps")