unet_2d_blocks.py 139 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
# Copyright 2023 The HuggingFace Team. All rights reserved.
Patrick von Platen's avatar
Patrick von Platen committed
2
3
4
5
6
7
8
9
10
11
12
13
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
14
from typing import Any, Dict, Optional, Tuple, Union
15

16
import numpy as np
17
import torch
18
import torch.nn.functional as F
Patrick von Platen's avatar
Patrick von Platen committed
19
20
from torch import nn

21
from ..utils import is_torch_version, logging
22
from ..utils.torch_utils import apply_freeu
23
from .activations import get_activation
24
from .attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0
25
from .dual_transformer_2d import DualTransformer2DModel
26
from .normalization import AdaGroupNorm
27
28
29
30
31
32
33
34
35
36
from .resnet import (
    Downsample2D,
    FirDownsample2D,
    FirUpsample2D,
    KDownsample2D,
    KUpsample2D,
    ResnetBlock2D,
    ResnetBlockCondNorm2D,
    Upsample2D,
)
37
from .transformer_2d import Transformer2DModel
Patrick von Platen's avatar
Patrick von Platen committed
38
39


40
41
42
logger = logging.get_logger(__name__)  # pylint: disable=invalid-name


43
def get_down_block(
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
    down_block_type: str,
    num_layers: int,
    in_channels: int,
    out_channels: int,
    temb_channels: int,
    add_downsample: bool,
    resnet_eps: float,
    resnet_act_fn: str,
    transformer_layers_per_block: int = 1,
    num_attention_heads: Optional[int] = None,
    resnet_groups: Optional[int] = None,
    cross_attention_dim: Optional[int] = None,
    downsample_padding: Optional[int] = None,
    dual_cross_attention: bool = False,
    use_linear_projection: bool = False,
    only_cross_attention: bool = False,
    upcast_attention: bool = False,
    resnet_time_scale_shift: str = "default",
    attention_type: str = "default",
    resnet_skip_time_act: bool = False,
    resnet_out_scale_factor: float = 1.0,
    cross_attention_norm: Optional[str] = None,
    attention_head_dim: Optional[int] = None,
    downsample_type: Optional[str] = None,
    dropout: float = 0.0,
69
):
70
71
72
73
74
75
76
    # If attn head dim is not defined, we default it to the number of heads
    if attention_head_dim is None:
        logger.warn(
            f"It is recommended to provide `attention_head_dim` when calling `get_down_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
        )
        attention_head_dim = num_attention_heads

Patrick von Platen's avatar
Patrick von Platen committed
77
78
79
    down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
    if down_block_type == "DownBlock2D":
        return DownBlock2D(
80
81
82
83
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
84
            dropout=dropout,
85
86
87
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
88
            resnet_groups=resnet_groups,
Patrick von Platen's avatar
Patrick von Platen committed
89
            downsample_padding=downsample_padding,
Will Berman's avatar
Will Berman committed
90
91
92
93
94
95
96
97
            resnet_time_scale_shift=resnet_time_scale_shift,
        )
    elif down_block_type == "ResnetDownsampleBlock2D":
        return ResnetDownsampleBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
98
            dropout=dropout,
Will Berman's avatar
Will Berman committed
99
100
101
102
103
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            resnet_time_scale_shift=resnet_time_scale_shift,
104
105
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
106
        )
Patrick von Platen's avatar
Patrick von Platen committed
107
    elif down_block_type == "AttnDownBlock2D":
108
109
110
111
        if add_downsample is False:
            downsample_type = None
        else:
            downsample_type = downsample_type or "conv"  # default to 'conv'
Patrick von Platen's avatar
Patrick von Platen committed
112
        return AttnDownBlock2D(
113
114
115
116
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
117
            dropout=dropout,
118
119
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
120
            resnet_groups=resnet_groups,
121
            downsample_padding=downsample_padding,
122
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
123
            resnet_time_scale_shift=resnet_time_scale_shift,
124
            downsample_type=downsample_type,
125
        )
Patrick von Platen's avatar
Patrick von Platen committed
126
    elif down_block_type == "CrossAttnDownBlock2D":
127
        if cross_attention_dim is None:
128
            raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D")
Patrick von Platen's avatar
Patrick von Platen committed
129
        return CrossAttnDownBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
130
            num_layers=num_layers,
131
            transformer_layers_per_block=transformer_layers_per_block,
Patrick von Platen's avatar
Patrick von Platen committed
132
133
134
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
135
            dropout=dropout,
Patrick von Platen's avatar
Patrick von Platen committed
136
137
138
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
139
            resnet_groups=resnet_groups,
Patrick von Platen's avatar
Patrick von Platen committed
140
            downsample_padding=downsample_padding,
141
            cross_attention_dim=cross_attention_dim,
142
            num_attention_heads=num_attention_heads,
143
            dual_cross_attention=dual_cross_attention,
Suraj Patil's avatar
Suraj Patil committed
144
            use_linear_projection=use_linear_projection,
145
            only_cross_attention=only_cross_attention,
146
            upcast_attention=upcast_attention,
Will Berman's avatar
Will Berman committed
147
            resnet_time_scale_shift=resnet_time_scale_shift,
148
            attention_type=attention_type,
Will Berman's avatar
Will Berman committed
149
150
151
152
153
154
155
156
157
        )
    elif down_block_type == "SimpleCrossAttnDownBlock2D":
        if cross_attention_dim is None:
            raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnDownBlock2D")
        return SimpleCrossAttnDownBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
158
            dropout=dropout,
Will Berman's avatar
Will Berman committed
159
160
161
162
163
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            cross_attention_dim=cross_attention_dim,
164
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
165
            resnet_time_scale_shift=resnet_time_scale_shift,
166
167
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
168
            only_cross_attention=only_cross_attention,
169
            cross_attention_norm=cross_attention_norm,
Patrick von Platen's avatar
Patrick von Platen committed
170
        )
Patrick von Platen's avatar
Patrick von Platen committed
171
172
    elif down_block_type == "SkipDownBlock2D":
        return SkipDownBlock2D(
173
174
175
176
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
177
            dropout=dropout,
178
179
180
181
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            downsample_padding=downsample_padding,
Will Berman's avatar
Will Berman committed
182
            resnet_time_scale_shift=resnet_time_scale_shift,
183
        )
Patrick von Platen's avatar
Patrick von Platen committed
184
185
    elif down_block_type == "AttnSkipDownBlock2D":
        return AttnSkipDownBlock2D(
186
187
188
189
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
190
            dropout=dropout,
191
192
193
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
194
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
195
            resnet_time_scale_shift=resnet_time_scale_shift,
196
        )
197
198
199
200
201
    elif down_block_type == "DownEncoderBlock2D":
        return DownEncoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
202
            dropout=dropout,
203
204
205
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
206
            resnet_groups=resnet_groups,
207
            downsample_padding=downsample_padding,
Will Berman's avatar
Will Berman committed
208
            resnet_time_scale_shift=resnet_time_scale_shift,
209
        )
Will Berman's avatar
Will Berman committed
210
211
212
213
214
    elif down_block_type == "AttnDownEncoderBlock2D":
        return AttnDownEncoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
215
            dropout=dropout,
Will Berman's avatar
Will Berman committed
216
217
218
219
220
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            downsample_padding=downsample_padding,
221
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
222
            resnet_time_scale_shift=resnet_time_scale_shift,
Will Berman's avatar
Will Berman committed
223
        )
224
225
226
227
228
229
    elif down_block_type == "KDownBlock2D":
        return KDownBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
230
            dropout=dropout,
231
232
233
234
235
236
237
238
239
240
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
        )
    elif down_block_type == "KCrossAttnDownBlock2D":
        return KCrossAttnDownBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
241
            dropout=dropout,
242
243
244
245
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            cross_attention_dim=cross_attention_dim,
246
            attention_head_dim=attention_head_dim,
247
248
            add_self_attention=True if not add_downsample else False,
        )
Will Berman's avatar
Will Berman committed
249
    raise ValueError(f"{down_block_type} does not exist.")
250
251


252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
def get_mid_block(
    mid_block_type: str,
    temb_channels: int,
    in_channels: int,
    resnet_eps: float,
    resnet_act_fn: str,
    resnet_groups: int,
    output_scale_factor: float = 1.0,
    transformer_layers_per_block: int = 1,
    num_attention_heads: Optional[int] = None,
    cross_attention_dim: Optional[int] = None,
    dual_cross_attention: bool = False,
    use_linear_projection: bool = False,
    mid_block_only_cross_attention: bool = False,
    upcast_attention: bool = False,
    resnet_time_scale_shift: str = "default",
    attention_type: str = "default",
    resnet_skip_time_act: bool = False,
    cross_attention_norm: Optional[str] = None,
    attention_head_dim: Optional[int] = 1,
    dropout: float = 0.0,
):
    if mid_block_type == "UNetMidBlock2DCrossAttn":
        return UNetMidBlock2DCrossAttn(
            transformer_layers_per_block=transformer_layers_per_block,
            in_channels=in_channels,
            temb_channels=temb_channels,
            dropout=dropout,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            output_scale_factor=output_scale_factor,
            resnet_time_scale_shift=resnet_time_scale_shift,
            cross_attention_dim=cross_attention_dim,
            num_attention_heads=num_attention_heads,
            resnet_groups=resnet_groups,
            dual_cross_attention=dual_cross_attention,
            use_linear_projection=use_linear_projection,
            upcast_attention=upcast_attention,
            attention_type=attention_type,
        )
    elif mid_block_type == "UNetMidBlock2DSimpleCrossAttn":
        return UNetMidBlock2DSimpleCrossAttn(
            in_channels=in_channels,
            temb_channels=temb_channels,
            dropout=dropout,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            output_scale_factor=output_scale_factor,
            cross_attention_dim=cross_attention_dim,
            attention_head_dim=attention_head_dim,
            resnet_groups=resnet_groups,
            resnet_time_scale_shift=resnet_time_scale_shift,
            skip_time_act=resnet_skip_time_act,
            only_cross_attention=mid_block_only_cross_attention,
            cross_attention_norm=cross_attention_norm,
        )
    elif mid_block_type == "UNetMidBlock2D":
        return UNetMidBlock2D(
            in_channels=in_channels,
            temb_channels=temb_channels,
            dropout=dropout,
            num_layers=0,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            output_scale_factor=output_scale_factor,
            resnet_groups=resnet_groups,
            resnet_time_scale_shift=resnet_time_scale_shift,
            add_attention=False,
        )
    elif mid_block_type is None:
        return None
    else:
        raise ValueError(f"unknown mid_block_type : {mid_block_type}")


327
def get_up_block(
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
    up_block_type: str,
    num_layers: int,
    in_channels: int,
    out_channels: int,
    prev_output_channel: int,
    temb_channels: int,
    add_upsample: bool,
    resnet_eps: float,
    resnet_act_fn: str,
    resolution_idx: Optional[int] = None,
    transformer_layers_per_block: int = 1,
    num_attention_heads: Optional[int] = None,
    resnet_groups: Optional[int] = None,
    cross_attention_dim: Optional[int] = None,
    dual_cross_attention: bool = False,
    use_linear_projection: bool = False,
    only_cross_attention: bool = False,
    upcast_attention: bool = False,
    resnet_time_scale_shift: str = "default",
    attention_type: str = "default",
    resnet_skip_time_act: bool = False,
    resnet_out_scale_factor: float = 1.0,
    cross_attention_norm: Optional[str] = None,
    attention_head_dim: Optional[int] = None,
    upsample_type: Optional[str] = None,
    dropout: float = 0.0,
) -> nn.Module:
355
356
357
358
359
360
361
    # If attn head dim is not defined, we default it to the number of heads
    if attention_head_dim is None:
        logger.warn(
            f"It is recommended to provide `attention_head_dim` when calling `get_up_block`. Defaulting `attention_head_dim` to {num_attention_heads}."
        )
        attention_head_dim = num_attention_heads

Patrick von Platen's avatar
Patrick von Platen committed
362
363
364
    up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
    if up_block_type == "UpBlock2D":
        return UpBlock2D(
365
366
            num_layers=num_layers,
            in_channels=in_channels,
Patrick von Platen's avatar
Patrick von Platen committed
367
368
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
369
            temb_channels=temb_channels,
370
            resolution_idx=resolution_idx,
371
            dropout=dropout,
372
373
374
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
375
            resnet_groups=resnet_groups,
Will Berman's avatar
Will Berman committed
376
377
378
379
380
381
382
383
384
            resnet_time_scale_shift=resnet_time_scale_shift,
        )
    elif up_block_type == "ResnetUpsampleBlock2D":
        return ResnetUpsampleBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
385
            resolution_idx=resolution_idx,
386
            dropout=dropout,
Will Berman's avatar
Will Berman committed
387
388
389
390
391
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            resnet_time_scale_shift=resnet_time_scale_shift,
392
393
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
394
        )
Patrick von Platen's avatar
Patrick von Platen committed
395
    elif up_block_type == "CrossAttnUpBlock2D":
396
397
        if cross_attention_dim is None:
            raise ValueError("cross_attention_dim must be specified for CrossAttnUpBlock2D")
Patrick von Platen's avatar
Patrick von Platen committed
398
        return CrossAttnUpBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
399
            num_layers=num_layers,
400
            transformer_layers_per_block=transformer_layers_per_block,
Patrick von Platen's avatar
Patrick von Platen committed
401
402
403
404
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
405
            resolution_idx=resolution_idx,
406
            dropout=dropout,
Patrick von Platen's avatar
Patrick von Platen committed
407
408
409
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
410
            resnet_groups=resnet_groups,
411
            cross_attention_dim=cross_attention_dim,
412
            num_attention_heads=num_attention_heads,
413
            dual_cross_attention=dual_cross_attention,
Suraj Patil's avatar
Suraj Patil committed
414
            use_linear_projection=use_linear_projection,
415
            only_cross_attention=only_cross_attention,
416
            upcast_attention=upcast_attention,
Will Berman's avatar
Will Berman committed
417
            resnet_time_scale_shift=resnet_time_scale_shift,
418
            attention_type=attention_type,
Will Berman's avatar
Will Berman committed
419
420
421
422
423
424
425
426
427
428
        )
    elif up_block_type == "SimpleCrossAttnUpBlock2D":
        if cross_attention_dim is None:
            raise ValueError("cross_attention_dim must be specified for SimpleCrossAttnUpBlock2D")
        return SimpleCrossAttnUpBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
429
            resolution_idx=resolution_idx,
430
            dropout=dropout,
Will Berman's avatar
Will Berman committed
431
432
433
434
435
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            cross_attention_dim=cross_attention_dim,
436
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
437
            resnet_time_scale_shift=resnet_time_scale_shift,
438
439
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
440
            only_cross_attention=only_cross_attention,
441
            cross_attention_norm=cross_attention_norm,
Patrick von Platen's avatar
Patrick von Platen committed
442
        )
Patrick von Platen's avatar
Patrick von Platen committed
443
    elif up_block_type == "AttnUpBlock2D":
444
445
446
447
448
        if add_upsample is False:
            upsample_type = None
        else:
            upsample_type = upsample_type or "conv"  # default to 'conv'

Patrick von Platen's avatar
Patrick von Platen committed
449
        return AttnUpBlock2D(
450
451
            num_layers=num_layers,
            in_channels=in_channels,
Patrick von Platen's avatar
Patrick von Platen committed
452
453
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
454
            temb_channels=temb_channels,
455
            resolution_idx=resolution_idx,
456
            dropout=dropout,
457
458
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
459
            resnet_groups=resnet_groups,
460
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
461
            resnet_time_scale_shift=resnet_time_scale_shift,
462
            upsample_type=upsample_type,
463
        )
Patrick von Platen's avatar
Patrick von Platen committed
464
465
    elif up_block_type == "SkipUpBlock2D":
        return SkipUpBlock2D(
466
467
468
469
470
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
471
            resolution_idx=resolution_idx,
472
            dropout=dropout,
473
474
475
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
Will Berman's avatar
Will Berman committed
476
            resnet_time_scale_shift=resnet_time_scale_shift,
477
        )
Patrick von Platen's avatar
Patrick von Platen committed
478
479
    elif up_block_type == "AttnSkipUpBlock2D":
        return AttnSkipUpBlock2D(
480
481
482
483
484
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
485
            resolution_idx=resolution_idx,
486
            dropout=dropout,
487
488
489
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
490
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
491
            resnet_time_scale_shift=resnet_time_scale_shift,
492
        )
493
494
495
496
497
    elif up_block_type == "UpDecoderBlock2D":
        return UpDecoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
498
            resolution_idx=resolution_idx,
499
            dropout=dropout,
500
501
502
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
503
            resnet_groups=resnet_groups,
Will Berman's avatar
Will Berman committed
504
            resnet_time_scale_shift=resnet_time_scale_shift,
YiYi Xu's avatar
YiYi Xu committed
505
            temb_channels=temb_channels,
506
        )
Will Berman's avatar
Will Berman committed
507
508
509
510
511
    elif up_block_type == "AttnUpDecoderBlock2D":
        return AttnUpDecoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
512
            resolution_idx=resolution_idx,
513
            dropout=dropout,
Will Berman's avatar
Will Berman committed
514
515
516
517
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
518
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
519
            resnet_time_scale_shift=resnet_time_scale_shift,
YiYi Xu's avatar
YiYi Xu committed
520
            temb_channels=temb_channels,
Will Berman's avatar
Will Berman committed
521
        )
522
523
524
525
526
527
    elif up_block_type == "KUpBlock2D":
        return KUpBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
528
            resolution_idx=resolution_idx,
529
            dropout=dropout,
530
531
532
533
534
535
536
537
538
539
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
        )
    elif up_block_type == "KCrossAttnUpBlock2D":
        return KCrossAttnUpBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
540
            resolution_idx=resolution_idx,
541
            dropout=dropout,
542
543
544
545
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            cross_attention_dim=cross_attention_dim,
546
            attention_head_dim=attention_head_dim,
547
548
        )

549
    raise ValueError(f"{up_block_type} does not exist.")
550
551


552
class AutoencoderTinyBlock(nn.Module):
553
    """
Patrick von Platen's avatar
Patrick von Platen committed
554
555
    Tiny Autoencoder block used in [`AutoencoderTiny`]. It is a mini residual module consisting of plain conv + ReLU
    blocks.
556
557
558
559

    Args:
        in_channels (`int`): The number of input channels.
        out_channels (`int`): The number of output channels.
Patrick von Platen's avatar
Patrick von Platen committed
560
561
        act_fn (`str`):
            ` The activation function to use. Supported values are `"swish"`, `"mish"`, `"gelu"`, and `"relu"`.
562
563

    Returns:
Patrick von Platen's avatar
Patrick von Platen committed
564
565
        `torch.FloatTensor`: A tensor with the same shape as the input tensor, but with the number of channels equal to
        `out_channels`.
566
567
    """

568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
    def __init__(self, in_channels: int, out_channels: int, act_fn: str):
        super().__init__()
        act_fn = get_activation(act_fn)
        self.conv = nn.Sequential(
            nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1),
            act_fn,
            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
            act_fn,
            nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1),
        )
        self.skip = (
            nn.Conv2d(in_channels, out_channels, kernel_size=1, bias=False)
            if in_channels != out_channels
            else nn.Identity()
        )
        self.fuse = nn.ReLU()

585
    def forward(self, x: torch.FloatTensor) -> torch.FloatTensor:
586
587
588
        return self.fuse(self.conv(x) + self.skip(x))


Patrick von Platen's avatar
Patrick von Platen committed
589
class UNetMidBlock2D(nn.Module):
590
591
592
593
594
595
596
597
598
    """
    A 2D UNet mid-block [`UNetMidBlock2D`] with multiple residual blocks and optional attention blocks.

    Args:
        in_channels (`int`): The number of input channels.
        temb_channels (`int`): The number of temporal embedding channels.
        dropout (`float`, *optional*, defaults to 0.0): The dropout rate.
        num_layers (`int`, *optional*, defaults to 1): The number of residual blocks.
        resnet_eps (`float`, *optional*, 1e-6 ): The epsilon value for the resnet blocks.
Patrick von Platen's avatar
Patrick von Platen committed
599
600
601
        resnet_time_scale_shift (`str`, *optional*, defaults to `default`):
            The type of normalization to apply to the time embeddings. This can help to improve the performance of the
            model on tasks with long-range temporal dependencies.
602
        resnet_act_fn (`str`, *optional*, defaults to `swish`): The activation function for the resnet blocks.
Patrick von Platen's avatar
Patrick von Platen committed
603
604
        resnet_groups (`int`, *optional*, defaults to 32):
            The number of groups to use in the group normalization layers of the resnet blocks.
605
        attn_groups (`Optional[int]`, *optional*, defaults to None): The number of groups for the attention blocks.
Patrick von Platen's avatar
Patrick von Platen committed
606
607
        resnet_pre_norm (`bool`, *optional*, defaults to `True`):
            Whether to use pre-normalization for the resnet blocks.
608
        add_attention (`bool`, *optional*, defaults to `True`): Whether to add attention blocks.
Patrick von Platen's avatar
Patrick von Platen committed
609
610
611
        attention_head_dim (`int`, *optional*, defaults to 1):
            Dimension of a single attention head. The number of attention heads is determined based on this value and
            the number of input channels.
612
613
614
        output_scale_factor (`float`, *optional*, defaults to 1.0): The output scale factor.

    Returns:
Patrick von Platen's avatar
Patrick von Platen committed
615
616
        `torch.FloatTensor`: The output of the last residual block, which is a tensor of shape `(batch_size,
        in_channels, height, width)`.
617
618
619

    """

Patrick von Platen's avatar
Patrick von Platen committed
620
621
622
623
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
624
        dropout: float = 0.0,
625
        num_layers: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
626
        resnet_eps: float = 1e-6,
YiYi Xu's avatar
YiYi Xu committed
627
        resnet_time_scale_shift: str = "default",  # default, spatial
Patrick von Platen's avatar
Patrick von Platen committed
628
629
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
630
        attn_groups: Optional[int] = None,
631
        resnet_pre_norm: bool = True,
Will Berman's avatar
Will Berman committed
632
        add_attention: bool = True,
633
634
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
Patrick von Platen's avatar
Patrick von Platen committed
635
636
    ):
        super().__init__()
637
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
Will Berman's avatar
Will Berman committed
638
        self.add_attention = add_attention
Patrick von Platen's avatar
Patrick von Platen committed
639

640
641
642
        if attn_groups is None:
            attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None

643
        # there is always at least one resnet
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
        if resnet_time_scale_shift == "spatial":
            resnets = [
                ResnetBlockCondNorm2D(
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm="spatial",
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                )
            ]
        else:
            resnets = [
                ResnetBlock2D(
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            ]
673
        attentions = []
Patrick von Platen's avatar
Patrick von Platen committed
674

675
676
677
678
679
680
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {in_channels}."
            )
            attention_head_dim = in_channels

681
        for _ in range(num_layers):
Will Berman's avatar
Will Berman committed
682
683
            if self.add_attention:
                attentions.append(
684
                    Attention(
Will Berman's avatar
Will Berman committed
685
                        in_channels,
686
687
                        heads=in_channels // attention_head_dim,
                        dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
688
689
                        rescale_output_factor=output_scale_factor,
                        eps=resnet_eps,
690
                        norm_num_groups=attn_groups,
YiYi Xu's avatar
YiYi Xu committed
691
                        spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
692
693
694
695
                        residual_connection=True,
                        bias=True,
                        upcast_softmax=True,
                        _from_deprecated_attn_block=True,
Will Berman's avatar
Will Berman committed
696
                    )
697
                )
Will Berman's avatar
Will Berman committed
698
699
700
            else:
                attentions.append(None)

701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
            if resnet_time_scale_shift == "spatial":
                resnets.append(
                    ResnetBlockCondNorm2D(
                        in_channels=in_channels,
                        out_channels=in_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm="spatial",
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                    )
                )
            else:
                resnets.append(
                    ResnetBlock2D(
                        in_channels=in_channels,
                        out_channels=in_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                    )
729
                )
Patrick von Platen's avatar
Patrick von Platen committed
730

731
732
733
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

734
    def forward(self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None) -> torch.FloatTensor:
Patrick von Platen's avatar
Patrick von Platen committed
735
        hidden_states = self.resnets[0](hidden_states, temb)
736
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
Will Berman's avatar
Will Berman committed
737
            if attn is not None:
YiYi Xu's avatar
YiYi Xu committed
738
                hidden_states = attn(hidden_states, temb=temb)
Patrick von Platen's avatar
Patrick von Platen committed
739
            hidden_states = resnet(hidden_states, temb)
Patrick von Platen's avatar
Patrick von Platen committed
740

741
        return hidden_states
Patrick von Platen's avatar
Patrick von Platen committed
742

743

Patrick von Platen's avatar
Patrick von Platen committed
744
745
746
747
748
749
750
class UNetMidBlock2DCrossAttn(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
751
        transformer_layers_per_block: Union[int, Tuple[int]] = 1,
Patrick von Platen's avatar
Patrick von Platen committed
752
753
754
755
756
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
757
758
759
760
761
762
763
        num_attention_heads: int = 1,
        output_scale_factor: float = 1.0,
        cross_attention_dim: int = 1280,
        dual_cross_attention: bool = False,
        use_linear_projection: bool = False,
        upcast_attention: bool = False,
        attention_type: str = "default",
Patrick von Platen's avatar
Patrick von Platen committed
764
765
766
    ):
        super().__init__()

767
        self.has_cross_attention = True
768
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
769
770
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)

771
772
773
774
        # support for variable transformer layers per block
        if isinstance(transformer_layers_per_block, int):
            transformer_layers_per_block = [transformer_layers_per_block] * num_layers

Patrick von Platen's avatar
Patrick von Platen committed
775
776
        # there is always at least one resnet
        resnets = [
777
            ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
                in_channels=in_channels,
                out_channels=in_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=resnet_groups,
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
            )
        ]
        attentions = []

792
        for i in range(num_layers):
793
794
795
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
796
797
                        num_attention_heads,
                        in_channels // num_attention_heads,
798
                        in_channels=in_channels,
799
                        num_layers=transformer_layers_per_block[i],
800
801
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
802
                        use_linear_projection=use_linear_projection,
803
                        upcast_attention=upcast_attention,
804
                        attention_type=attention_type,
805
806
807
808
809
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
810
811
                        num_attention_heads,
                        in_channels // num_attention_heads,
812
813
814
815
816
                        in_channels=in_channels,
                        num_layers=1,
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
                    )
Patrick von Platen's avatar
Patrick von Platen committed
817
818
                )
            resnets.append(
819
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

836
837
        self.gradient_checkpointing = False

838
    def forward(
839
840
841
842
843
844
845
846
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
    ) -> torch.FloatTensor:
847
848
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
        hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
849
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
850
851
852
853
854
855
856
857
858
859
860
861
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module, return_dict=None):
                    def custom_forward(*inputs):
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)

                    return custom_forward

                ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
ethansmith2000's avatar
ethansmith2000 committed
862
                hidden_states = attn(
863
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
864
865
866
867
868
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
                    return_dict=False,
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
                )[0]
                hidden_states = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(resnet),
                    hidden_states,
                    temb,
                    **ckpt_kwargs,
                )
            else:
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
                    return_dict=False,
                )[0]
885
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901

        return hidden_states


class UNetMidBlock2DSimpleCrossAttn(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
902
903
904
905
906
907
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
        cross_attention_dim: int = 1280,
        skip_time_act: bool = False,
        only_cross_attention: bool = False,
        cross_attention_norm: Optional[str] = None,
Will Berman's avatar
Will Berman committed
908
909
910
911
912
    ):
        super().__init__()

        self.has_cross_attention = True

913
        self.attention_head_dim = attention_head_dim
Will Berman's avatar
Will Berman committed
914
915
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)

916
        self.num_heads = in_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
917
918
919
920
921
922
923
924
925
926
927
928
929
930

        # there is always at least one resnet
        resnets = [
            ResnetBlock2D(
                in_channels=in_channels,
                out_channels=in_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=resnet_groups,
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
931
                skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
932
933
934
935
936
            )
        ]
        attentions = []

        for _ in range(num_layers):
937
938
939
940
            processor = (
                AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
            )

Will Berman's avatar
Will Berman committed
941
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
942
                Attention(
Will Berman's avatar
Will Berman committed
943
944
945
                    query_dim=in_channels,
                    cross_attention_dim=in_channels,
                    heads=self.num_heads,
946
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
947
948
949
950
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
951
                    only_cross_attention=only_cross_attention,
952
                    cross_attention_norm=cross_attention_norm,
953
                    processor=processor,
Will Berman's avatar
Will Berman committed
954
955
956
957
958
959
960
961
962
963
964
965
966
967
                )
            )
            resnets.append(
                ResnetBlock2D(
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
968
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
969
970
971
972
973
974
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

975
    def forward(
976
977
978
979
980
981
982
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
983
    ) -> torch.FloatTensor:
984
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
985
        lora_scale = cross_attention_kwargs.get("scale", 1.0)
986
987
988
989
990
991
992
993
994
995
996
997

        if attention_mask is None:
            # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask.
            mask = None if encoder_hidden_states is None else encoder_attention_mask
        else:
            # when attention_mask is defined: we don't even check for encoder_attention_mask.
            # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks.
            # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask.
            #       then we can simplify this whole if/else block to:
            #         mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask
            mask = attention_mask

998
        hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
999
1000
1001
1002
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
            # attn
            hidden_states = attn(
                hidden_states,
1003
                encoder_hidden_states=encoder_hidden_states,
1004
                attention_mask=mask,
1005
                **cross_attention_kwargs,
Will Berman's avatar
Will Berman committed
1006
1007
1008
            )

            # resnet
1009
            hidden_states = resnet(hidden_states, temb, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
1010
1011
1012
1013

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
1014
class AttnDownBlock2D(nn.Module):
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1027
1028
1029
1030
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
        downsample_padding: int = 1,
        downsample_type: str = "conv",
1031
1032
1033
1034
    ):
        super().__init__()
        resnets = []
        attentions = []
1035
        self.downsample_type = downsample_type
1036

1037
1038
1039
1040
1041
1042
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

1043
1044
1045
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1046
                ResnetBlock2D(
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )
            attentions.append(
1060
                Attention(
1061
                    out_channels,
1062
1063
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1064
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
1065
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
1066
                    norm_num_groups=resnet_groups,
1067
1068
1069
1070
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1071
1072
1073
1074
1075
1076
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

1077
        if downsample_type == "conv":
1078
            self.downsamplers = nn.ModuleList(
1079
1080
                [
                    Downsample2D(
1081
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1082
1083
                    )
                ]
1084
            )
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
        elif downsample_type == "resnet":
            self.downsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                        down=True,
                    )
                ]
            )
1103
1104
1105
        else:
            self.downsamplers = None

1106
1107
1108
1109
1110
1111
1112
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
1113
1114
1115
1116
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}

        lora_scale = cross_attention_kwargs.get("scale", 1.0)

1117
1118
1119
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
1120
1121
1122
            cross_attention_kwargs.update({"scale": lora_scale})
            hidden_states = resnet(hidden_states, temb, scale=lora_scale)
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
1123
            output_states = output_states + (hidden_states,)
1124
1125
1126

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1127
                if self.downsample_type == "resnet":
1128
                    hidden_states = downsampler(hidden_states, temb=temb, scale=lora_scale)
1129
                else:
1130
                    hidden_states = downsampler(hidden_states, scale=lora_scale)
1131
1132
1133
1134
1135
1136

            output_states += (hidden_states,)

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
1137
class CrossAttnDownBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
1138
1139
1140
1141
1142
1143
1144
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
1145
        transformer_layers_per_block: Union[int, Tuple[int]] = 1,
Patrick von Platen's avatar
Patrick von Platen committed
1146
1147
1148
1149
1150
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
        num_attention_heads: int = 1,
        cross_attention_dim: int = 1280,
        output_scale_factor: float = 1.0,
        downsample_padding: int = 1,
        add_downsample: bool = True,
        dual_cross_attention: bool = False,
        use_linear_projection: bool = False,
        only_cross_attention: bool = False,
        upcast_attention: bool = False,
        attention_type: str = "default",
Patrick von Platen's avatar
Patrick von Platen committed
1161
1162
1163
1164
1165
    ):
        super().__init__()
        resnets = []
        attentions = []

1166
        self.has_cross_attention = True
1167
        self.num_attention_heads = num_attention_heads
1168
1169
        if isinstance(transformer_layers_per_block, int):
            transformer_layers_per_block = [transformer_layers_per_block] * num_layers
Patrick von Platen's avatar
Patrick von Platen committed
1170
1171
1172
1173

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1174
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )
1187
1188
1189
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
1190
1191
                        num_attention_heads,
                        out_channels // num_attention_heads,
1192
                        in_channels=out_channels,
1193
                        num_layers=transformer_layers_per_block[i],
1194
1195
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
1196
                        use_linear_projection=use_linear_projection,
1197
                        only_cross_attention=only_cross_attention,
1198
                        upcast_attention=upcast_attention,
1199
                        attention_type=attention_type,
1200
1201
1202
1203
1204
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
1205
1206
                        num_attention_heads,
                        out_channels // num_attention_heads,
1207
1208
1209
1210
1211
                        in_channels=out_channels,
                        num_layers=1,
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
                    )
Patrick von Platen's avatar
Patrick von Platen committed
1212
1213
1214
1215
1216
1217
1218
1219
                )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1220
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
1221
1222
1223
1224
1225
1226
                    )
                ]
            )
        else:
            self.downsamplers = None

1227
1228
        self.gradient_checkpointing = False

1229
    def forward(
1230
1231
1232
1233
1234
1235
1236
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
1237
1238
        additional_residuals: Optional[torch.FloatTensor] = None,
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
Patrick von Platen's avatar
Patrick von Platen committed
1239
1240
        output_states = ()

1241
1242
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0

Will Berman's avatar
Will Berman committed
1243
1244
1245
        blocks = list(zip(self.resnets, self.attentions))

        for i, (resnet, attn) in enumerate(blocks):
1246
1247
            if self.training and self.gradient_checkpointing:

Will Berman's avatar
Will Berman committed
1248
                def create_custom_forward(module, return_dict=None):
1249
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
1250
1251
1252
1253
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
1254
1255
1256

                    return custom_forward

1257
1258
1259
1260
1261
1262
1263
                ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
                hidden_states = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(resnet),
                    hidden_states,
                    temb,
                    **ckpt_kwargs,
                )
ethansmith2000's avatar
ethansmith2000 committed
1264
                hidden_states = attn(
1265
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1266
1267
1268
1269
1270
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
                    return_dict=False,
1271
                )[0]
1272
            else:
1273
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
1274
1275
1276
1277
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
1278
1279
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
1280
1281
                    return_dict=False,
                )[0]
1282

Will Berman's avatar
Will Berman committed
1283
1284
1285
1286
            # apply additional residuals to the output of the last pair of resnet and attention blocks
            if i == len(blocks) - 1 and additional_residuals is not None:
                hidden_states = hidden_states + additional_residuals

1287
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1288
1289
1290

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1291
                hidden_states = downsampler(hidden_states, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
1292

1293
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1294
1295
1296
1297

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
1298
class DownBlock2D(nn.Module):
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1311
1312
1313
        output_scale_factor: float = 1.0,
        add_downsample: bool = True,
        downsample_padding: int = 1,
1314
1315
1316
1317
1318
1319
1320
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1321
                ResnetBlock2D(
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
Patrick von Platen's avatar
Patrick von Platen committed
1339
1340
                [
                    Downsample2D(
1341
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
1342
1343
                    )
                ]
1344
1345
1346
1347
            )
        else:
            self.downsamplers = None

1348
1349
        self.gradient_checkpointing = False

1350
1351
1352
    def forward(
        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
1353
1354
1355
        output_states = ()

        for resnet in self.resnets:
1356
1357
1358
1359
1360
1361
1362
1363
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

1364
1365
1366
1367
1368
1369
1370
1371
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
1372
            else:
1373
                hidden_states = resnet(hidden_states, temb, scale=scale)
1374

1375
            output_states = output_states + (hidden_states,)
1376
1377
1378

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1379
                hidden_states = downsampler(hidden_states, scale=scale)
1380

1381
            output_states = output_states + (hidden_states,)
1382
1383
1384
1385

        return hidden_states, output_states


1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
class DownEncoderBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1398
1399
1400
        output_scale_factor: float = 1.0,
        add_downsample: bool = True,
        downsample_padding: int = 1,
1401
1402
1403
1404
1405
1406
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
            if resnet_time_scale_shift == "spatial":
                resnets.append(
                    ResnetBlockCondNorm2D(
                        in_channels=in_channels,
                        out_channels=out_channels,
                        temb_channels=None,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm="spatial",
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                    )
                )
            else:
                resnets.append(
                    ResnetBlock2D(
                        in_channels=in_channels,
                        out_channels=out_channels,
                        temb_channels=None,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                    )
1435
1436
1437
1438
1439
1440
1441
1442
                )

        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1443
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1444
1445
1446
1447
1448
1449
                    )
                ]
            )
        else:
            self.downsamplers = None

1450
    def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
1451
        for resnet in self.resnets:
1452
            hidden_states = resnet(hidden_states, temb=None, scale=scale)
1453
1454
1455

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1456
                hidden_states = downsampler(hidden_states, scale)
1457
1458
1459
1460

        return hidden_states


1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
class AttnDownEncoderBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1473
1474
1475
1476
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
        add_downsample: bool = True,
        downsample_padding: int = 1,
1477
1478
1479
1480
1481
    ):
        super().__init__()
        resnets = []
        attentions = []

1482
1483
1484
1485
1486
1487
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

1488
1489
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
            if resnet_time_scale_shift == "spatial":
                resnets.append(
                    ResnetBlockCondNorm2D(
                        in_channels=in_channels,
                        out_channels=out_channels,
                        temb_channels=None,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm="spatial",
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                    )
                )
            else:
                resnets.append(
                    ResnetBlock2D(
                        in_channels=in_channels,
                        out_channels=out_channels,
                        temb_channels=None,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                    )
1518
1519
                )
            attentions.append(
1520
                Attention(
1521
                    out_channels,
1522
1523
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1524
1525
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
1526
                    norm_num_groups=resnet_groups,
1527
1528
1529
1530
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1541
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1542
1543
1544
1545
1546
1547
                    )
                ]
            )
        else:
            self.downsamplers = None

1548
    def forward(self, hidden_states: torch.FloatTensor, scale: float = 1.0) -> torch.FloatTensor:
1549
        for resnet, attn in zip(self.resnets, self.attentions):
1550
1551
1552
            hidden_states = resnet(hidden_states, temb=None, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
1553
1554
1555

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1556
                hidden_states = downsampler(hidden_states, scale)
1557
1558
1559
1560

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
1561
class AttnSkipDownBlock2D(nn.Module):
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_pre_norm: bool = True,
1573
1574
1575
        attention_head_dim: int = 1,
        output_scale_factor: float = np.sqrt(2.0),
        add_downsample: bool = True,
1576
1577
1578
1579
1580
    ):
        super().__init__()
        self.attentions = nn.ModuleList([])
        self.resnets = nn.ModuleList([])

1581
1582
1583
1584
1585
1586
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

1587
1588
1589
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            self.resnets.append(
1590
                ResnetBlock2D(
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=min(in_channels // 4, 32),
                    groups_out=min(out_channels // 4, 32),
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )
            self.attentions.append(
1605
                Attention(
1606
                    out_channels,
1607
1608
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1609
1610
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
1611
1612
1613
1614
1615
                    norm_num_groups=32,
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1616
1617
1618
1619
                )
            )

        if add_downsample:
1620
            self.resnet_down = ResnetBlock2D(
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
                in_channels=out_channels,
                out_channels=out_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=min(out_channels // 4, 32),
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
1631
                use_in_shortcut=True,
1632
1633
1634
                down=True,
                kernel="fir",
            )
1635
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1636
1637
1638
1639
1640
1641
            self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1))
        else:
            self.resnet_down = None
            self.downsamplers = None
            self.skip_conv = None

1642
1643
1644
1645
1646
1647
1648
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        skip_sample: Optional[torch.FloatTensor] = None,
        scale: float = 1.0,
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]:
1649
1650
1651
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
1652
1653
1654
            hidden_states = resnet(hidden_states, temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
1655
1656
1657
            output_states += (hidden_states,)

        if self.downsamplers is not None:
1658
            hidden_states = self.resnet_down(hidden_states, temb, scale=scale)
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
            for downsampler in self.downsamplers:
                skip_sample = downsampler(skip_sample)

            hidden_states = self.skip_conv(skip_sample) + hidden_states

            output_states += (hidden_states,)

        return hidden_states, output_states, skip_sample


Patrick von Platen's avatar
Patrick von Platen committed
1669
class SkipDownBlock2D(nn.Module):
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_pre_norm: bool = True,
1681
1682
1683
        output_scale_factor: float = np.sqrt(2.0),
        add_downsample: bool = True,
        downsample_padding: int = 1,
1684
1685
1686
1687
1688
1689
1690
    ):
        super().__init__()
        self.resnets = nn.ModuleList([])

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            self.resnets.append(
1691
                ResnetBlock2D(
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=min(in_channels // 4, 32),
                    groups_out=min(out_channels // 4, 32),
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

        if add_downsample:
1707
            self.resnet_down = ResnetBlock2D(
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
                in_channels=out_channels,
                out_channels=out_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=min(out_channels // 4, 32),
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
1718
                use_in_shortcut=True,
1719
1720
1721
                down=True,
                kernel="fir",
            )
1722
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1723
1724
1725
1726
1727
1728
            self.skip_conv = nn.Conv2d(3, out_channels, kernel_size=(1, 1), stride=(1, 1))
        else:
            self.resnet_down = None
            self.downsamplers = None
            self.skip_conv = None

1729
1730
1731
1732
1733
1734
1735
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        skip_sample: Optional[torch.FloatTensor] = None,
        scale: float = 1.0,
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...], torch.FloatTensor]:
1736
1737
1738
        output_states = ()

        for resnet in self.resnets:
1739
            hidden_states = resnet(hidden_states, temb, scale)
1740
1741
1742
            output_states += (hidden_states,)

        if self.downsamplers is not None:
1743
            hidden_states = self.resnet_down(hidden_states, temb, scale)
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
            for downsampler in self.downsamplers:
                skip_sample = downsampler(skip_sample)

            hidden_states = self.skip_conv(skip_sample) + hidden_states

            output_states += (hidden_states,)

        return hidden_states, output_states, skip_sample


Will Berman's avatar
Will Berman committed
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
class ResnetDownsampleBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1767
1768
1769
        output_scale_factor: float = 1.0,
        add_downsample: bool = True,
        skip_time_act: bool = False,
Will Berman's avatar
Will Berman committed
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
                ResnetBlock2D(
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
1788
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
1808
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1809
1810
1811
1812
1813
1814
1815
1816
1817
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

1818
1819
1820
    def forward(
        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
Will Berman's avatar
Will Berman committed
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
        output_states = ()

        for resnet in self.resnets:
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

1832
1833
1834
1835
1836
1837
1838
1839
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
Will Berman's avatar
Will Berman committed
1840
            else:
1841
                hidden_states = resnet(hidden_states, temb, scale)
Will Berman's avatar
Will Berman committed
1842

1843
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1844
1845
1846

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1847
                hidden_states = downsampler(hidden_states, temb, scale)
Will Berman's avatar
Will Berman committed
1848

1849
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866

        return hidden_states, output_states


class SimpleCrossAttnDownBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
1867
1868
1869
1870
1871
1872
1873
        attention_head_dim: int = 1,
        cross_attention_dim: int = 1280,
        output_scale_factor: float = 1.0,
        add_downsample: bool = True,
        skip_time_act: bool = False,
        only_cross_attention: bool = False,
        cross_attention_norm: Optional[str] = None,
Will Berman's avatar
Will Berman committed
1874
1875
1876
1877
1878
1879
1880
1881
    ):
        super().__init__()

        self.has_cross_attention = True

        resnets = []
        attentions = []

1882
1883
        self.attention_head_dim = attention_head_dim
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
                ResnetBlock2D(
                    in_channels=in_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
1899
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1900
1901
                )
            )
1902
1903
1904
1905
1906

            processor = (
                AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
            )

Will Berman's avatar
Will Berman committed
1907
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
1908
                Attention(
Will Berman's avatar
Will Berman committed
1909
1910
1911
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
1912
                    dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
1913
1914
1915
1916
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
1917
                    only_cross_attention=only_cross_attention,
1918
                    cross_attention_norm=cross_attention_norm,
1919
                    processor=processor,
Will Berman's avatar
Will Berman committed
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
                )
            )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
1939
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1940
1941
1942
1943
1944
1945
1946
1947
1948
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

1949
    def forward(
1950
1951
1952
1953
1954
1955
1956
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
1957
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
Will Berman's avatar
Will Berman committed
1958
        output_states = ()
1959
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
Will Berman's avatar
Will Berman committed
1960

1961
1962
        lora_scale = cross_attention_kwargs.get("scale", 1.0)

1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
        if attention_mask is None:
            # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask.
            mask = None if encoder_hidden_states is None else encoder_attention_mask
        else:
            # when attention_mask is defined: we don't even check for encoder_attention_mask.
            # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks.
            # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask.
            #       then we can simplify this whole if/else block to:
            #         mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask
            mask = attention_mask

Will Berman's avatar
Will Berman committed
1974
        for resnet, attn in zip(self.resnets, self.attentions):
1975
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
1976

1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
                def create_custom_forward(module, return_dict=None):
                    def custom_forward(*inputs):
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)

                    return custom_forward

                hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
ethansmith2000's avatar
ethansmith2000 committed
1987
                hidden_states = attn(
1988
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1989
1990
1991
1992
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
1993
            else:
1994
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
1995
1996
1997
1998

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
1999
                    attention_mask=mask,
2000
2001
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
2002

2003
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
2004
2005
2006

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
2007
                hidden_states = downsampler(hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
2008

2009
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
2010
2011
2012
2013

        return hidden_states, output_states


2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
class KDownBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 4,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
        resnet_group_size: int = 32,
2025
        add_downsample: bool = False,
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            groups = in_channels // resnet_group_size
            groups_out = out_channels // resnet_group_size

            resnets.append(
2036
                ResnetBlockCondNorm2D(
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
                    in_channels=in_channels,
                    out_channels=out_channels,
                    dropout=dropout,
                    temb_channels=temb_channels,
                    groups=groups,
                    groups_out=groups_out,
                    eps=resnet_eps,
                    non_linearity=resnet_act_fn,
                    time_embedding_norm="ada_group",
                    conv_shortcut_bias=False,
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            # YiYi's comments- might be able to use FirDownsample2D, look into details later
            self.downsamplers = nn.ModuleList([KDownsample2D()])
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

2060
2061
2062
    def forward(
        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
        output_states = ()

        for resnet in self.resnets:
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

2074
2075
2076
2077
2078
2079
2080
2081
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
2082
            else:
2083
                hidden_states = resnet(hidden_states, temb, scale)
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103

            output_states += (hidden_states,)

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
                hidden_states = downsampler(hidden_states)

        return hidden_states, output_states


class KCrossAttnDownBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        cross_attention_dim: int,
        dropout: float = 0.0,
        num_layers: int = 4,
        resnet_group_size: int = 32,
2104
        add_downsample: bool = True,
2105
        attention_head_dim: int = 64,
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
        add_self_attention: bool = False,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
    ):
        super().__init__()
        resnets = []
        attentions = []

        self.has_cross_attention = True

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            groups = in_channels // resnet_group_size
            groups_out = out_channels // resnet_group_size

            resnets.append(
2122
                ResnetBlockCondNorm2D(
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
                    in_channels=in_channels,
                    out_channels=out_channels,
                    dropout=dropout,
                    temb_channels=temb_channels,
                    groups=groups,
                    groups_out=groups_out,
                    eps=resnet_eps,
                    non_linearity=resnet_act_fn,
                    time_embedding_norm="ada_group",
                    conv_shortcut_bias=False,
                )
            )
            attentions.append(
                KAttentionBlock(
                    out_channels,
2138
2139
                    out_channels // attention_head_dim,
                    attention_head_dim,
2140
2141
2142
2143
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
2144
                    cross_attention_norm="layer_norm",
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
                    group_size=resnet_group_size,
                )
            )

        self.resnets = nn.ModuleList(resnets)
        self.attentions = nn.ModuleList(attentions)

        if add_downsample:
            self.downsamplers = nn.ModuleList([KDownsample2D()])
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

    def forward(
2160
2161
2162
2163
2164
2165
2166
        self,
        hidden_states: torch.FloatTensor,
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
2167
    ) -> Tuple[torch.FloatTensor, Tuple[torch.FloatTensor, ...]]:
2168
        output_states = ()
2169
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182

        for resnet, attn in zip(self.resnets, self.attentions):
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module, return_dict=None):
                    def custom_forward(*inputs):
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)

                    return custom_forward

2183
2184
2185
2186
2187
2188
2189
                ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
                hidden_states = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(resnet),
                    hidden_states,
                    temb,
                    **ckpt_kwargs,
                )
ethansmith2000's avatar
ethansmith2000 committed
2190
                hidden_states = attn(
2191
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2192
2193
2194
2195
2196
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
2197
                )
2198
            else:
2199
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
2200
2201
2202
2203
2204
2205
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
2206
                    encoder_attention_mask=encoder_attention_mask,
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
                )

            if self.downsamplers is None:
                output_states += (None,)
            else:
                output_states += (hidden_states,)

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
                hidden_states = downsampler(hidden_states)

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
2221
class AttnUpBlock2D(nn.Module):
2222
2223
2224
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
2225
2226
        prev_output_channel: int,
        out_channels: int,
2227
        temb_channels: int,
2228
        resolution_idx: int = None,
2229
2230
2231
2232
2233
2234
2235
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
2236
2237
2238
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
        upsample_type: str = "conv",
2239
2240
2241
2242
2243
    ):
        super().__init__()
        resnets = []
        attentions = []

2244
2245
        self.upsample_type = upsample_type

2246
2247
2248
2249
2250
2251
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `in_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

2252
        for i in range(num_layers):
Patrick von Platen's avatar
Patrick von Platen committed
2253
2254
2255
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

2256
            resnets.append(
2257
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2258
2259
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )
            attentions.append(
2271
                Attention(
Patrick von Platen's avatar
Patrick von Platen committed
2272
                    out_channels,
2273
2274
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
2275
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
2276
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
2277
                    norm_num_groups=resnet_groups,
2278
2279
2280
2281
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
2282
2283
2284
2285
2286
2287
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

2288
        if upsample_type == "conv":
Patrick von Platen's avatar
Patrick von Platen committed
2289
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
        elif upsample_type == "resnet":
            self.upsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                        up=True,
                    )
                ]
            )
2308
2309
2310
        else:
            self.upsamplers = None

2311
2312
        self.resolution_idx = resolution_idx

2313
2314
2315
2316
2317
2318
2319
2320
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        scale: float = 1.0,
    ) -> torch.FloatTensor:
2321
2322
2323
2324
2325
2326
        for resnet, attn in zip(self.resnets, self.attentions):
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

2327
2328
2329
            hidden_states = resnet(hidden_states, temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
2330
2331
2332

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2333
                if self.upsample_type == "resnet":
2334
                    hidden_states = upsampler(hidden_states, temb=temb, scale=scale)
2335
                else:
2336
                    hidden_states = upsampler(hidden_states, scale=scale)
2337
2338
2339
2340

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2341
class CrossAttnUpBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
2342
2343
2344
2345
2346
2347
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        prev_output_channel: int,
        temb_channels: int,
2348
        resolution_idx: Optional[int] = None,
Patrick von Platen's avatar
Patrick von Platen committed
2349
2350
        dropout: float = 0.0,
        num_layers: int = 1,
2351
        transformer_layers_per_block: Union[int, Tuple[int]] = 1,
Patrick von Platen's avatar
Patrick von Platen committed
2352
2353
2354
2355
2356
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
2357
2358
2359
2360
2361
2362
2363
2364
2365
        num_attention_heads: int = 1,
        cross_attention_dim: int = 1280,
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
        dual_cross_attention: bool = False,
        use_linear_projection: bool = False,
        only_cross_attention: bool = False,
        upcast_attention: bool = False,
        attention_type: str = "default",
Patrick von Platen's avatar
Patrick von Platen committed
2366
2367
2368
2369
2370
    ):
        super().__init__()
        resnets = []
        attentions = []

2371
        self.has_cross_attention = True
2372
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
2373

2374
2375
2376
        if isinstance(transformer_layers_per_block, int):
            transformer_layers_per_block = [transformer_layers_per_block] * num_layers

Patrick von Platen's avatar
Patrick von Platen committed
2377
2378
2379
2380
2381
        for i in range(num_layers):
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

            resnets.append(
2382
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )
2395
2396
2397
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
2398
2399
                        num_attention_heads,
                        out_channels // num_attention_heads,
2400
                        in_channels=out_channels,
2401
                        num_layers=transformer_layers_per_block[i],
2402
2403
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
2404
                        use_linear_projection=use_linear_projection,
2405
                        only_cross_attention=only_cross_attention,
2406
                        upcast_attention=upcast_attention,
2407
                        attention_type=attention_type,
2408
2409
2410
2411
2412
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
2413
2414
                        num_attention_heads,
                        out_channels // num_attention_heads,
2415
2416
2417
2418
2419
                        in_channels=out_channels,
                        num_layers=1,
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
                    )
Patrick von Platen's avatar
Patrick von Platen committed
2420
2421
2422
2423
2424
2425
2426
2427
2428
                )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
        else:
            self.upsamplers = None

2429
        self.gradient_checkpointing = False
2430
        self.resolution_idx = resolution_idx
2431
2432
2433

    def forward(
        self,
2434
2435
2436
2437
2438
2439
2440
2441
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        upsample_size: Optional[int] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
2442
    ) -> torch.FloatTensor:
2443
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
2444
2445
2446
2447
2448
2449
        is_freeu_enabled = (
            getattr(self, "s1", None)
            and getattr(self, "s2", None)
            and getattr(self, "b1", None)
            and getattr(self, "b2", None)
        )
2450

Patrick von Platen's avatar
Patrick von Platen committed
2451
2452
2453
2454
        for resnet, attn in zip(self.resnets, self.attentions):
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467

            # FreeU: Only operate on the first two stages
            if is_freeu_enabled:
                hidden_states, res_hidden_states = apply_freeu(
                    self.resolution_idx,
                    hidden_states,
                    res_hidden_states,
                    s1=self.s1,
                    s2=self.s2,
                    b1=self.b1,
                    b2=self.b2,
                )

Patrick von Platen's avatar
Patrick von Platen committed
2468
2469
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

2470
2471
            if self.training and self.gradient_checkpointing:

Will Berman's avatar
Will Berman committed
2472
                def create_custom_forward(module, return_dict=None):
2473
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
2474
2475
2476
2477
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
2478
2479
2480

                    return custom_forward

2481
2482
2483
2484
2485
2486
2487
                ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
                hidden_states = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(resnet),
                    hidden_states,
                    temb,
                    **ckpt_kwargs,
                )
ethansmith2000's avatar
ethansmith2000 committed
2488
                hidden_states = attn(
2489
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2490
2491
2492
2493
2494
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
                    return_dict=False,
2495
                )[0]
2496
            else:
2497
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
2498
2499
2500
2501
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
2502
2503
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
2504
2505
                    return_dict=False,
                )[0]
Patrick von Platen's avatar
Patrick von Platen committed
2506
2507
2508

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2509
                hidden_states = upsampler(hidden_states, upsample_size, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
2510
2511
2512
2513

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2514
class UpBlock2D(nn.Module):
2515
2516
2517
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
2518
2519
        prev_output_channel: int,
        out_channels: int,
2520
        temb_channels: int,
2521
        resolution_idx: Optional[int] = None,
2522
2523
2524
2525
2526
2527
2528
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
2529
2530
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
2531
2532
2533
2534
2535
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
Patrick von Platen's avatar
Patrick von Platen committed
2536
2537
2538
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

2539
            resnets.append(
2540
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2541
2542
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
Patrick von Platen's avatar
Patrick von Platen committed
2557
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2558
2559
2560
        else:
            self.upsamplers = None

2561
        self.gradient_checkpointing = False
2562
        self.resolution_idx = resolution_idx
2563

2564
2565
2566
2567
2568
2569
2570
2571
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        scale: float = 1.0,
    ) -> torch.FloatTensor:
2572
2573
2574
2575
2576
2577
2578
        is_freeu_enabled = (
            getattr(self, "s1", None)
            and getattr(self, "s2", None)
            and getattr(self, "b1", None)
            and getattr(self, "b2", None)
        )

2579
2580
2581
2582
        for resnet in self.resnets:
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595

            # FreeU: Only operate on the first two stages
            if is_freeu_enabled:
                hidden_states, res_hidden_states = apply_freeu(
                    self.resolution_idx,
                    hidden_states,
                    res_hidden_states,
                    s1=self.s1,
                    s2=self.s2,
                    b1=self.b1,
                    b2=self.b2,
                )

2596
2597
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

2598
2599
2600
2601
2602
2603
2604
2605
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

2606
2607
2608
2609
2610
2611
2612
2613
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
2614
            else:
2615
                hidden_states = resnet(hidden_states, temb, scale=scale)
2616
2617
2618

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2619
                hidden_states = upsampler(hidden_states, upsample_size, scale=scale)
2620
2621

        return hidden_states
2622
2623


2624
2625
2626
2627
2628
class UpDecoderBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
2629
        resolution_idx: Optional[int] = None,
2630
2631
2632
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
YiYi Xu's avatar
YiYi Xu committed
2633
        resnet_time_scale_shift: str = "default",  # default, spatial
2634
2635
2636
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
2637
2638
2639
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
        temb_channels: Optional[int] = None,
2640
2641
2642
2643
2644
2645
2646
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            input_channels = in_channels if i == 0 else out_channels

2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
            if resnet_time_scale_shift == "spatial":
                resnets.append(
                    ResnetBlockCondNorm2D(
                        in_channels=input_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm="spatial",
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                    )
                )
            else:
                resnets.append(
                    ResnetBlock2D(
                        in_channels=input_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                    )
2675
2676
2677
2678
2679
2680
2681
2682
2683
                )

        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
        else:
            self.upsamplers = None

2684
2685
        self.resolution_idx = resolution_idx

2686
2687
2688
    def forward(
        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
    ) -> torch.FloatTensor:
2689
        for resnet in self.resnets:
2690
            hidden_states = resnet(hidden_states, temb=temb, scale=scale)
2691
2692
2693
2694
2695
2696
2697
2698

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
                hidden_states = upsampler(hidden_states)

        return hidden_states


2699
2700
2701
2702
2703
class AttnUpDecoderBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
2704
        resolution_idx: Optional[int] = None,
2705
2706
2707
2708
2709
2710
2711
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
2712
2713
2714
2715
        attention_head_dim: int = 1,
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
        temb_channels: Optional[int] = None,
2716
2717
2718
2719
2720
    ):
        super().__init__()
        resnets = []
        attentions = []

2721
2722
2723
2724
2725
2726
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

2727
2728
2729
        for i in range(num_layers):
            input_channels = in_channels if i == 0 else out_channels

2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
            if resnet_time_scale_shift == "spatial":
                resnets.append(
                    ResnetBlockCondNorm2D(
                        in_channels=input_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm="spatial",
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                    )
2743
                )
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
            else:
                resnets.append(
                    ResnetBlock2D(
                        in_channels=input_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
                    )
                )

2760
            attentions.append(
2761
                Attention(
2762
                    out_channels,
2763
2764
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
2765
2766
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
2767
                    norm_num_groups=resnet_groups if resnet_time_scale_shift != "spatial" else None,
YiYi Xu's avatar
YiYi Xu committed
2768
                    spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
2769
2770
2771
2772
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
                )
            )

        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
        else:
            self.upsamplers = None

2784
2785
        self.resolution_idx = resolution_idx

2786
2787
2788
    def forward(
        self, hidden_states: torch.FloatTensor, temb: Optional[torch.FloatTensor] = None, scale: float = 1.0
    ) -> torch.FloatTensor:
2789
        for resnet, attn in zip(self.resnets, self.attentions):
2790
2791
2792
            hidden_states = resnet(hidden_states, temb=temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, temb=temb, **cross_attention_kwargs)
2793
2794
2795

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2796
                hidden_states = upsampler(hidden_states, scale=scale)
2797
2798
2799
2800

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2801
class AttnSkipUpBlock2D(nn.Module):
2802
2803
2804
2805
2806
2807
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: int,
        out_channels: int,
        temb_channels: int,
2808
        resolution_idx: Optional[int] = None,
2809
2810
2811
2812
2813
2814
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_pre_norm: bool = True,
2815
2816
2817
        attention_head_dim: int = 1,
        output_scale_factor: float = np.sqrt(2.0),
        add_upsample: bool = True,
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
    ):
        super().__init__()
        self.attentions = nn.ModuleList([])
        self.resnets = nn.ModuleList([])

        for i in range(num_layers):
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

            self.resnets.append(
2828
                ResnetBlock2D(
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=min(resnet_in_channels + res_skip_channels // 4, 32),
                    groups_out=min(out_channels // 4, 32),
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

2843
2844
2845
2846
2847
2848
        if attention_head_dim is None:
            logger.warn(
                f"It is not recommend to pass `attention_head_dim=None`. Defaulting `attention_head_dim` to `out_channels`: {out_channels}."
            )
            attention_head_dim = out_channels

2849
        self.attentions.append(
2850
            Attention(
2851
                out_channels,
2852
2853
                heads=out_channels // attention_head_dim,
                dim_head=attention_head_dim,
2854
2855
                rescale_output_factor=output_scale_factor,
                eps=resnet_eps,
2856
2857
2858
2859
2860
                norm_num_groups=32,
                residual_connection=True,
                bias=True,
                upcast_softmax=True,
                _from_deprecated_attn_block=True,
2861
2862
2863
2864
2865
            )
        )

        self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels)
        if add_upsample:
2866
            self.resnet_up = ResnetBlock2D(
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
                in_channels=out_channels,
                out_channels=out_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=min(out_channels // 4, 32),
                groups_out=min(out_channels // 4, 32),
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
2878
                use_in_shortcut=True,
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
                up=True,
                kernel="fir",
            )
            self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            self.skip_norm = torch.nn.GroupNorm(
                num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True
            )
            self.act = nn.SiLU()
        else:
            self.resnet_up = None
            self.skip_conv = None
            self.skip_norm = None
            self.act = None

2893
2894
        self.resolution_idx = resolution_idx

2895
2896
2897
2898
2899
2900
2901
2902
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        skip_sample=None,
        scale: float = 1.0,
    ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
2903
2904
2905
2906
2907
2908
        for resnet in self.resnets:
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

2909
            hidden_states = resnet(hidden_states, temb, scale=scale)
2910

2911
2912
        cross_attention_kwargs = {"scale": scale}
        hidden_states = self.attentions[0](hidden_states, **cross_attention_kwargs)
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925

        if skip_sample is not None:
            skip_sample = self.upsampler(skip_sample)
        else:
            skip_sample = 0

        if self.resnet_up is not None:
            skip_sample_states = self.skip_norm(hidden_states)
            skip_sample_states = self.act(skip_sample_states)
            skip_sample_states = self.skip_conv(skip_sample_states)

            skip_sample = skip_sample + skip_sample_states

2926
            hidden_states = self.resnet_up(hidden_states, temb, scale=scale)
2927
2928
2929
2930

        return hidden_states, skip_sample


Patrick von Platen's avatar
Patrick von Platen committed
2931
class SkipUpBlock2D(nn.Module):
2932
2933
2934
2935
2936
2937
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: int,
        out_channels: int,
        temb_channels: int,
2938
        resolution_idx: Optional[int] = None,
2939
2940
2941
2942
2943
2944
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_pre_norm: bool = True,
2945
2946
2947
        output_scale_factor: float = np.sqrt(2.0),
        add_upsample: bool = True,
        upsample_padding: int = 1,
2948
2949
2950
2951
2952
2953
2954
2955
2956
    ):
        super().__init__()
        self.resnets = nn.ModuleList([])

        for i in range(num_layers):
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

            self.resnets.append(
2957
                ResnetBlock2D(
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=min((resnet_in_channels + res_skip_channels) // 4, 32),
                    groups_out=min(out_channels // 4, 32),
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
                )
            )

        self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels)
        if add_upsample:
2974
            self.resnet_up = ResnetBlock2D(
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
                in_channels=out_channels,
                out_channels=out_channels,
                temb_channels=temb_channels,
                eps=resnet_eps,
                groups=min(out_channels // 4, 32),
                groups_out=min(out_channels // 4, 32),
                dropout=dropout,
                time_embedding_norm=resnet_time_scale_shift,
                non_linearity=resnet_act_fn,
                output_scale_factor=output_scale_factor,
                pre_norm=resnet_pre_norm,
2986
                use_in_shortcut=True,
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
                up=True,
                kernel="fir",
            )
            self.skip_conv = nn.Conv2d(out_channels, 3, kernel_size=(3, 3), stride=(1, 1), padding=(1, 1))
            self.skip_norm = torch.nn.GroupNorm(
                num_groups=min(out_channels // 4, 32), num_channels=out_channels, eps=resnet_eps, affine=True
            )
            self.act = nn.SiLU()
        else:
            self.resnet_up = None
            self.skip_conv = None
            self.skip_norm = None
            self.act = None

3001
3002
        self.resolution_idx = resolution_idx

3003
3004
3005
3006
3007
3008
3009
3010
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        skip_sample=None,
        scale: float = 1.0,
    ) -> Tuple[torch.FloatTensor, torch.FloatTensor]:
3011
3012
3013
3014
3015
3016
        for resnet in self.resnets:
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

3017
            hidden_states = resnet(hidden_states, temb, scale=scale)
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030

        if skip_sample is not None:
            skip_sample = self.upsampler(skip_sample)
        else:
            skip_sample = 0

        if self.resnet_up is not None:
            skip_sample_states = self.skip_norm(hidden_states)
            skip_sample_states = self.act(skip_sample_states)
            skip_sample_states = self.skip_conv(skip_sample_states)

            skip_sample = skip_sample + skip_sample_states

3031
            hidden_states = self.resnet_up(hidden_states, temb, scale=scale)
3032
3033

        return hidden_states, skip_sample
Will Berman's avatar
Will Berman committed
3034
3035
3036
3037
3038
3039
3040
3041
3042


class ResnetUpsampleBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: int,
        out_channels: int,
        temb_channels: int,
3043
        resolution_idx: Optional[int] = None,
Will Berman's avatar
Will Berman committed
3044
3045
3046
3047
3048
3049
3050
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
3051
3052
3053
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
        skip_time_act: bool = False,
Will Berman's avatar
Will Berman committed
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

            resnets.append(
                ResnetBlock2D(
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
3074
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
3094
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
3095
3096
3097
3098
3099
3100
3101
3102
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False
3103
        self.resolution_idx = resolution_idx
Will Berman's avatar
Will Berman committed
3104

3105
3106
3107
3108
3109
3110
3111
3112
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        scale: float = 1.0,
    ) -> torch.FloatTensor:
Will Berman's avatar
Will Berman committed
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
        for resnet in self.resnets:
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

3127
3128
3129
3130
3131
3132
3133
3134
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
Will Berman's avatar
Will Berman committed
3135
            else:
3136
                hidden_states = resnet(hidden_states, temb, scale=scale)
Will Berman's avatar
Will Berman committed
3137
3138
3139

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
3140
                hidden_states = upsampler(hidden_states, temb, scale=scale)
Will Berman's avatar
Will Berman committed
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151

        return hidden_states


class SimpleCrossAttnUpBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        prev_output_channel: int,
        temb_channels: int,
3152
        resolution_idx: Optional[int] = None,
Will Berman's avatar
Will Berman committed
3153
3154
3155
3156
3157
3158
3159
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
        resnet_time_scale_shift: str = "default",
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
3160
3161
3162
3163
3164
3165
3166
        attention_head_dim: int = 1,
        cross_attention_dim: int = 1280,
        output_scale_factor: float = 1.0,
        add_upsample: bool = True,
        skip_time_act: bool = False,
        only_cross_attention: bool = False,
        cross_attention_norm: Optional[str] = None,
Will Berman's avatar
Will Berman committed
3167
3168
3169
3170
3171
3172
    ):
        super().__init__()
        resnets = []
        attentions = []

        self.has_cross_attention = True
3173
        self.attention_head_dim = attention_head_dim
Will Berman's avatar
Will Berman committed
3174

3175
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192

        for i in range(num_layers):
            res_skip_channels = in_channels if (i == num_layers - 1) else out_channels
            resnet_in_channels = prev_output_channel if i == 0 else out_channels

            resnets.append(
                ResnetBlock2D(
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=resnet_groups,
                    dropout=dropout,
                    time_embedding_norm=resnet_time_scale_shift,
                    non_linearity=resnet_act_fn,
                    output_scale_factor=output_scale_factor,
                    pre_norm=resnet_pre_norm,
3193
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
3194
3195
                )
            )
3196
3197
3198
3199
3200

            processor = (
                AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
            )

Will Berman's avatar
Will Berman committed
3201
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
3202
                Attention(
Will Berman's avatar
Will Berman committed
3203
3204
3205
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
3206
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
3207
3208
3209
3210
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
3211
                    only_cross_attention=only_cross_attention,
3212
                    cross_attention_norm=cross_attention_norm,
3213
                    processor=processor,
Will Berman's avatar
Will Berman committed
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
                )
            )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList(
                [
                    ResnetBlock2D(
                        in_channels=out_channels,
                        out_channels=out_channels,
                        temb_channels=temb_channels,
                        eps=resnet_eps,
                        groups=resnet_groups,
                        dropout=dropout,
                        time_embedding_norm=resnet_time_scale_shift,
                        non_linearity=resnet_act_fn,
                        output_scale_factor=output_scale_factor,
                        pre_norm=resnet_pre_norm,
3233
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
3234
3235
3236
3237
3238
3239
3240
3241
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False
3242
        self.resolution_idx = resolution_idx
Will Berman's avatar
Will Berman committed
3243
3244
3245

    def forward(
        self,
3246
3247
3248
3249
3250
3251
3252
3253
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
3254
    ) -> torch.FloatTensor:
3255
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
3256

3257
        lora_scale = cross_attention_kwargs.get("scale", 1.0)
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
        if attention_mask is None:
            # if encoder_hidden_states is defined: we are doing cross-attn, so we should use cross-attn mask.
            mask = None if encoder_hidden_states is None else encoder_attention_mask
        else:
            # when attention_mask is defined: we don't even check for encoder_attention_mask.
            # this is to maintain compatibility with UnCLIP, which uses 'attention_mask' param for cross-attn masks.
            # TODO: UnCLIP should express cross-attn mask via encoder_attention_mask param instead of via attention_mask.
            #       then we can simplify this whole if/else block to:
            #         mask = attention_mask if encoder_hidden_states is None else encoder_attention_mask
            mask = attention_mask

Will Berman's avatar
Will Berman committed
3269
3270
3271
3272
3273
3274
3275
        for resnet, attn in zip(self.resnets, self.attentions):
            # resnet
            # pop res hidden states
            res_hidden_states = res_hidden_states_tuple[-1]
            res_hidden_states_tuple = res_hidden_states_tuple[:-1]
            hidden_states = torch.cat([hidden_states, res_hidden_states], dim=1)

3276
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
3277

3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
                def create_custom_forward(module, return_dict=None):
                    def custom_forward(*inputs):
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)

                    return custom_forward

                hidden_states = torch.utils.checkpoint.checkpoint(create_custom_forward(resnet), hidden_states, temb)
ethansmith2000's avatar
ethansmith2000 committed
3288
                hidden_states = attn(
3289
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
3290
3291
3292
3293
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
3294
            else:
3295
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
3296
3297
3298
3299

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
3300
                    attention_mask=mask,
3301
3302
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
3303
3304
3305

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
3306
                hidden_states = upsampler(hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
3307
3308

        return hidden_states
3309
3310
3311
3312
3313
3314
3315
3316


class KUpBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
3317
        resolution_idx: int,
3318
3319
3320
3321
3322
        dropout: float = 0.0,
        num_layers: int = 5,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
        resnet_group_size: Optional[int] = 32,
3323
        add_upsample: bool = True,
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
    ):
        super().__init__()
        resnets = []
        k_in_channels = 2 * out_channels
        k_out_channels = in_channels
        num_layers = num_layers - 1

        for i in range(num_layers):
            in_channels = k_in_channels if i == 0 else out_channels
            groups = in_channels // resnet_group_size
            groups_out = out_channels // resnet_group_size

            resnets.append(
3337
                ResnetBlockCondNorm2D(
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
                    in_channels=in_channels,
                    out_channels=k_out_channels if (i == num_layers - 1) else out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=groups,
                    groups_out=groups_out,
                    dropout=dropout,
                    non_linearity=resnet_act_fn,
                    time_embedding_norm="ada_group",
                    conv_shortcut_bias=False,
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_upsample:
            self.upsamplers = nn.ModuleList([KUpsample2D()])
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False
3359
        self.resolution_idx = resolution_idx
3360

3361
3362
3363
3364
3365
3366
3367
3368
    def forward(
        self,
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        upsample_size: Optional[int] = None,
        scale: float = 1.0,
    ) -> torch.FloatTensor:
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
        res_hidden_states_tuple = res_hidden_states_tuple[-1]
        if res_hidden_states_tuple is not None:
            hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1)

        for resnet in self.resnets:
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module):
                    def custom_forward(*inputs):
                        return module(*inputs)

                    return custom_forward

3382
3383
3384
3385
3386
3387
3388
3389
                if is_torch_version(">=", "1.11.0"):
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb, use_reentrant=False
                    )
                else:
                    hidden_states = torch.utils.checkpoint.checkpoint(
                        create_custom_forward(resnet), hidden_states, temb
                    )
3390
            else:
3391
                hidden_states = resnet(hidden_states, temb, scale=scale)
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
                hidden_states = upsampler(hidden_states)

        return hidden_states


class KCrossAttnUpBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
3406
        resolution_idx: int,
3407
3408
3409
3410
3411
        dropout: float = 0.0,
        num_layers: int = 4,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
        resnet_group_size: int = 32,
3412
        attention_head_dim: int = 1,  # attention dim_head
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
        cross_attention_dim: int = 768,
        add_upsample: bool = True,
        upcast_attention: bool = False,
    ):
        super().__init__()
        resnets = []
        attentions = []

        is_first_block = in_channels == out_channels == temb_channels
        is_middle_block = in_channels != out_channels
        add_self_attention = True if is_first_block else False

        self.has_cross_attention = True
3426
        self.attention_head_dim = attention_head_dim
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444

        # in_channels, and out_channels for the block (k-unet)
        k_in_channels = out_channels if is_first_block else 2 * out_channels
        k_out_channels = in_channels

        num_layers = num_layers - 1

        for i in range(num_layers):
            in_channels = k_in_channels if i == 0 else out_channels
            groups = in_channels // resnet_group_size
            groups_out = out_channels // resnet_group_size

            if is_middle_block and (i == num_layers - 1):
                conv_2d_out_channels = k_out_channels
            else:
                conv_2d_out_channels = None

            resnets.append(
3445
                ResnetBlockCondNorm2D(
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
                    in_channels=in_channels,
                    out_channels=out_channels,
                    conv_2d_out_channels=conv_2d_out_channels,
                    temb_channels=temb_channels,
                    eps=resnet_eps,
                    groups=groups,
                    groups_out=groups_out,
                    dropout=dropout,
                    non_linearity=resnet_act_fn,
                    time_embedding_norm="ada_group",
                    conv_shortcut_bias=False,
                )
            )
            attentions.append(
                KAttentionBlock(
                    k_out_channels if (i == num_layers - 1) else out_channels,
3462
                    k_out_channels // attention_head_dim
3463
                    if (i == num_layers - 1)
3464
3465
                    else out_channels // attention_head_dim,
                    attention_head_dim,
3466
3467
3468
3469
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
3470
                    cross_attention_norm="layer_norm",
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
                    upcast_attention=upcast_attention,
                )
            )

        self.resnets = nn.ModuleList(resnets)
        self.attentions = nn.ModuleList(attentions)

        if add_upsample:
            self.upsamplers = nn.ModuleList([KUpsample2D()])
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False
3484
        self.resolution_idx = resolution_idx
3485
3486
3487

    def forward(
        self,
3488
3489
3490
3491
3492
3493
3494
3495
        hidden_states: torch.FloatTensor,
        res_hidden_states_tuple: Tuple[torch.FloatTensor, ...],
        temb: Optional[torch.FloatTensor] = None,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        upsample_size: Optional[int] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
3496
    ) -> torch.FloatTensor:
3497
3498
3499
3500
        res_hidden_states_tuple = res_hidden_states_tuple[-1]
        if res_hidden_states_tuple is not None:
            hidden_states = torch.cat([hidden_states, res_hidden_states_tuple], dim=1)

3501
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
        for resnet, attn in zip(self.resnets, self.attentions):
            if self.training and self.gradient_checkpointing:

                def create_custom_forward(module, return_dict=None):
                    def custom_forward(*inputs):
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)

                    return custom_forward

3514
3515
3516
3517
3518
3519
3520
                ckpt_kwargs: Dict[str, Any] = {"use_reentrant": False} if is_torch_version(">=", "1.11.0") else {}
                hidden_states = torch.utils.checkpoint.checkpoint(
                    create_custom_forward(resnet),
                    hidden_states,
                    temb,
                    **ckpt_kwargs,
                )
ethansmith2000's avatar
ethansmith2000 committed
3521
                hidden_states = attn(
3522
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
3523
3524
3525
3526
3527
3528
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
                )
3529
            else:
3530
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
3531
3532
3533
3534
3535
3536
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
3537
                    encoder_attention_mask=encoder_attention_mask,
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
                )

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
                hidden_states = upsampler(hidden_states)

        return hidden_states


# can potentially later be renamed to `No-feed-forward` attention
class KAttentionBlock(nn.Module):
    r"""
    A basic Transformer block.

    Parameters:
        dim (`int`): The number of channels in the input and output.
        num_attention_heads (`int`): The number of heads to use for multi-head attention.
        attention_head_dim (`int`): The number of channels in each head.
        dropout (`float`, *optional*, defaults to 0.0): The dropout probability to use.
        cross_attention_dim (`int`, *optional*): The size of the encoder_hidden_states vector for cross attention.
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
        attention_bias (`bool`, *optional*, defaults to `False`):
            Configure if the attention layers should contain a bias parameter.
        upcast_attention (`bool`, *optional*, defaults to `False`):
            Set to `True` to upcast the attention computation to `float32`.
        temb_channels (`int`, *optional*, defaults to 768):
            The number of channels in the token embedding.
        add_self_attention (`bool`, *optional*, defaults to `False`):
            Set to `True` to add self-attention to the block.
        cross_attention_norm (`str`, *optional*, defaults to `None`):
            The type of normalization to use for the cross attention. Can be `None`, `layer_norm`, or `group_norm`.
        group_size (`int`, *optional*, defaults to 32):
            The number of groups to separate the channels into for group normalization.
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
    """

    def __init__(
        self,
        dim: int,
        num_attention_heads: int,
        attention_head_dim: int,
        dropout: float = 0.0,
        cross_attention_dim: Optional[int] = None,
        attention_bias: bool = False,
        upcast_attention: bool = False,
        temb_channels: int = 768,  # for ada_group_norm
        add_self_attention: bool = False,
3583
        cross_attention_norm: Optional[str] = None,
3584
3585
3586
3587
3588
3589
3590
3591
        group_size: int = 32,
    ):
        super().__init__()
        self.add_self_attention = add_self_attention

        # 1. Self-Attn
        if add_self_attention:
            self.norm1 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size))
Patrick von Platen's avatar
Patrick von Platen committed
3592
            self.attn1 = Attention(
3593
3594
3595
3596
3597
3598
                query_dim=dim,
                heads=num_attention_heads,
                dim_head=attention_head_dim,
                dropout=dropout,
                bias=attention_bias,
                cross_attention_dim=None,
3599
                cross_attention_norm=None,
3600
3601
3602
3603
            )

        # 2. Cross-Attn
        self.norm2 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size))
Patrick von Platen's avatar
Patrick von Platen committed
3604
        self.attn2 = Attention(
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
            query_dim=dim,
            cross_attention_dim=cross_attention_dim,
            heads=num_attention_heads,
            dim_head=attention_head_dim,
            dropout=dropout,
            bias=attention_bias,
            upcast_attention=upcast_attention,
            cross_attention_norm=cross_attention_norm,
        )

3615
    def _to_3d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor:
3616
3617
        return hidden_states.permute(0, 2, 3, 1).reshape(hidden_states.shape[0], height * weight, -1)

3618
    def _to_4d(self, hidden_states: torch.FloatTensor, height: int, weight: int) -> torch.FloatTensor:
3619
3620
3621
3622
        return hidden_states.permute(0, 2, 1).reshape(hidden_states.shape[0], -1, height, weight)

    def forward(
        self,
3623
3624
3625
3626
3627
3628
3629
3630
        hidden_states: torch.FloatTensor,
        encoder_hidden_states: Optional[torch.FloatTensor] = None,
        # TODO: mark emb as non-optional (self.norm2 requires it).
        #       requires assessing impact of change to positional param interface.
        emb: Optional[torch.FloatTensor] = None,
        attention_mask: Optional[torch.FloatTensor] = None,
        cross_attention_kwargs: Optional[Dict[str, Any]] = None,
        encoder_attention_mask: Optional[torch.FloatTensor] = None,
3631
    ) -> torch.FloatTensor:
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}

        # 1. Self-Attention
        if self.add_self_attention:
            norm_hidden_states = self.norm1(hidden_states, emb)

            height, weight = norm_hidden_states.shape[2:]
            norm_hidden_states = self._to_3d(norm_hidden_states, height, weight)

            attn_output = self.attn1(
                norm_hidden_states,
                encoder_hidden_states=None,
3644
                attention_mask=attention_mask,
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
                **cross_attention_kwargs,
            )
            attn_output = self._to_4d(attn_output, height, weight)

            hidden_states = attn_output + hidden_states

        # 2. Cross-Attention/None
        norm_hidden_states = self.norm2(hidden_states, emb)

        height, weight = norm_hidden_states.shape[2:]
        norm_hidden_states = self._to_3d(norm_hidden_states, height, weight)
        attn_output = self.attn2(
            norm_hidden_states,
            encoder_hidden_states=encoder_hidden_states,
3659
            attention_mask=attention_mask if encoder_hidden_states is None else encoder_attention_mask,
3660
3661
3662
3663
3664
3665
3666
            **cross_attention_kwargs,
        )
        attn_output = self._to_4d(attn_output, height, weight)

        hidden_states = attn_output + hidden_states

        return hidden_states