unet_2d_blocks.py 119 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
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 .activations import get_activation
23
from .attention import AdaGroupNorm
24
from .attention_processor import Attention, AttnAddedKVProcessor, AttnAddedKVProcessor2_0
25
from .dual_transformer_2d import DualTransformer2DModel
26
from .resnet import Downsample2D, FirDownsample2D, FirUpsample2D, KDownsample2D, KUpsample2D, ResnetBlock2D, Upsample2D
27
from .transformer_2d import Transformer2DModel
Patrick von Platen's avatar
Patrick von Platen committed
28
29


30
31
32
logger = logging.get_logger(__name__)  # pylint: disable=invalid-name


33
34
35
36
37
38
39
40
41
def get_down_block(
    down_block_type,
    num_layers,
    in_channels,
    out_channels,
    temb_channels,
    add_downsample,
    resnet_eps,
    resnet_act_fn,
42
    transformer_layers_per_block=1,
43
    num_attention_heads=None,
44
    resnet_groups=None,
45
    cross_attention_dim=None,
Patrick von Platen's avatar
Patrick von Platen committed
46
    downsample_padding=None,
47
    dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
48
    use_linear_projection=False,
49
    only_cross_attention=False,
50
    upcast_attention=False,
Will Berman's avatar
Will Berman committed
51
    resnet_time_scale_shift="default",
52
53
    resnet_skip_time_act=False,
    resnet_out_scale_factor=1.0,
54
    cross_attention_norm=None,
55
    attention_head_dim=None,
56
    downsample_type=None,
57
):
58
59
60
61
62
63
64
    # 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
65
66
67
    down_block_type = down_block_type[7:] if down_block_type.startswith("UNetRes") else down_block_type
    if down_block_type == "DownBlock2D":
        return DownBlock2D(
68
69
70
71
72
73
74
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
75
            resnet_groups=resnet_groups,
Patrick von Platen's avatar
Patrick von Platen committed
76
            downsample_padding=downsample_padding,
Will Berman's avatar
Will Berman committed
77
78
79
80
81
82
83
84
85
86
87
88
89
            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,
            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,
90
91
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
92
        )
Patrick von Platen's avatar
Patrick von Platen committed
93
    elif down_block_type == "AttnDownBlock2D":
94
95
96
97
        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
98
        return AttnDownBlock2D(
99
100
101
102
103
104
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
105
            resnet_groups=resnet_groups,
106
            downsample_padding=downsample_padding,
107
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
108
            resnet_time_scale_shift=resnet_time_scale_shift,
109
            downsample_type=downsample_type,
110
        )
Patrick von Platen's avatar
Patrick von Platen committed
111
    elif down_block_type == "CrossAttnDownBlock2D":
112
        if cross_attention_dim is None:
113
            raise ValueError("cross_attention_dim must be specified for CrossAttnDownBlock2D")
Patrick von Platen's avatar
Patrick von Platen committed
114
        return CrossAttnDownBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
115
            num_layers=num_layers,
116
            transformer_layers_per_block=transformer_layers_per_block,
Patrick von Platen's avatar
Patrick von Platen committed
117
118
119
120
121
122
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
123
            resnet_groups=resnet_groups,
Patrick von Platen's avatar
Patrick von Platen committed
124
            downsample_padding=downsample_padding,
125
            cross_attention_dim=cross_attention_dim,
126
            num_attention_heads=num_attention_heads,
127
            dual_cross_attention=dual_cross_attention,
Suraj Patil's avatar
Suraj Patil committed
128
            use_linear_projection=use_linear_projection,
129
            only_cross_attention=only_cross_attention,
130
            upcast_attention=upcast_attention,
Will Berman's avatar
Will Berman committed
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
            resnet_time_scale_shift=resnet_time_scale_shift,
        )
    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,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            cross_attention_dim=cross_attention_dim,
146
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
147
            resnet_time_scale_shift=resnet_time_scale_shift,
148
149
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
150
            only_cross_attention=only_cross_attention,
151
            cross_attention_norm=cross_attention_norm,
Patrick von Platen's avatar
Patrick von Platen committed
152
        )
Patrick von Platen's avatar
Patrick von Platen committed
153
154
    elif down_block_type == "SkipDownBlock2D":
        return SkipDownBlock2D(
155
156
157
158
159
160
161
162
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            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
163
            resnet_time_scale_shift=resnet_time_scale_shift,
164
        )
Patrick von Platen's avatar
Patrick von Platen committed
165
166
    elif down_block_type == "AttnSkipDownBlock2D":
        return AttnSkipDownBlock2D(
167
168
169
170
171
172
173
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
174
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
175
            resnet_time_scale_shift=resnet_time_scale_shift,
176
        )
177
178
179
180
181
182
183
184
    elif down_block_type == "DownEncoderBlock2D":
        return DownEncoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
185
            resnet_groups=resnet_groups,
186
            downsample_padding=downsample_padding,
Will Berman's avatar
Will Berman committed
187
            resnet_time_scale_shift=resnet_time_scale_shift,
188
        )
Will Berman's avatar
Will Berman committed
189
190
191
192
193
194
195
196
197
198
    elif down_block_type == "AttnDownEncoderBlock2D":
        return AttnDownEncoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            downsample_padding=downsample_padding,
199
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
200
            resnet_time_scale_shift=resnet_time_scale_shift,
Will Berman's avatar
Will Berman committed
201
        )
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
    elif down_block_type == "KDownBlock2D":
        return KDownBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            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,
            add_downsample=add_downsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            cross_attention_dim=cross_attention_dim,
222
            attention_head_dim=attention_head_dim,
223
224
            add_self_attention=True if not add_downsample else False,
        )
Will Berman's avatar
Will Berman committed
225
    raise ValueError(f"{down_block_type} does not exist.")
226
227
228
229
230
231


def get_up_block(
    up_block_type,
    num_layers,
    in_channels,
Patrick von Platen's avatar
Patrick von Platen committed
232
233
    out_channels,
    prev_output_channel,
234
235
236
237
    temb_channels,
    add_upsample,
    resnet_eps,
    resnet_act_fn,
238
    transformer_layers_per_block=1,
239
    num_attention_heads=None,
240
    resnet_groups=None,
241
    cross_attention_dim=None,
242
    dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
243
    use_linear_projection=False,
244
    only_cross_attention=False,
245
    upcast_attention=False,
Will Berman's avatar
Will Berman committed
246
    resnet_time_scale_shift="default",
247
248
    resnet_skip_time_act=False,
    resnet_out_scale_factor=1.0,
249
    cross_attention_norm=None,
250
    attention_head_dim=None,
251
    upsample_type=None,
252
):
253
254
255
256
257
258
259
    # 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
260
261
262
    up_block_type = up_block_type[7:] if up_block_type.startswith("UNetRes") else up_block_type
    if up_block_type == "UpBlock2D":
        return UpBlock2D(
263
264
            num_layers=num_layers,
            in_channels=in_channels,
Patrick von Platen's avatar
Patrick von Platen committed
265
266
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
267
268
269
270
            temb_channels=temb_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
271
            resnet_groups=resnet_groups,
Will Berman's avatar
Will Berman committed
272
273
274
275
276
277
278
279
280
281
282
283
284
285
            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,
            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,
286
287
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
288
        )
Patrick von Platen's avatar
Patrick von Platen committed
289
    elif up_block_type == "CrossAttnUpBlock2D":
290
291
        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
292
        return CrossAttnUpBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
293
            num_layers=num_layers,
294
            transformer_layers_per_block=transformer_layers_per_block,
Patrick von Platen's avatar
Patrick von Platen committed
295
296
297
298
299
300
301
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
302
            resnet_groups=resnet_groups,
303
            cross_attention_dim=cross_attention_dim,
304
            num_attention_heads=num_attention_heads,
305
            dual_cross_attention=dual_cross_attention,
Suraj Patil's avatar
Suraj Patil committed
306
            use_linear_projection=use_linear_projection,
307
            only_cross_attention=only_cross_attention,
308
            upcast_attention=upcast_attention,
Will Berman's avatar
Will Berman committed
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
            resnet_time_scale_shift=resnet_time_scale_shift,
        )
    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,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
            cross_attention_dim=cross_attention_dim,
325
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
326
            resnet_time_scale_shift=resnet_time_scale_shift,
327
328
            skip_time_act=resnet_skip_time_act,
            output_scale_factor=resnet_out_scale_factor,
329
            only_cross_attention=only_cross_attention,
330
            cross_attention_norm=cross_attention_norm,
Patrick von Platen's avatar
Patrick von Platen committed
331
        )
Patrick von Platen's avatar
Patrick von Platen committed
332
    elif up_block_type == "AttnUpBlock2D":
333
334
335
336
337
        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
338
        return AttnUpBlock2D(
339
340
            num_layers=num_layers,
            in_channels=in_channels,
Patrick von Platen's avatar
Patrick von Platen committed
341
342
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
343
344
345
            temb_channels=temb_channels,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
346
            resnet_groups=resnet_groups,
347
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
348
            resnet_time_scale_shift=resnet_time_scale_shift,
349
            upsample_type=upsample_type,
350
        )
Patrick von Platen's avatar
Patrick von Platen committed
351
352
    elif up_block_type == "SkipUpBlock2D":
        return SkipUpBlock2D(
353
354
355
356
357
358
359
360
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
Will Berman's avatar
Will Berman committed
361
            resnet_time_scale_shift=resnet_time_scale_shift,
362
        )
Patrick von Platen's avatar
Patrick von Platen committed
363
364
    elif up_block_type == "AttnSkipUpBlock2D":
        return AttnSkipUpBlock2D(
365
366
367
368
369
370
371
372
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            prev_output_channel=prev_output_channel,
            temb_channels=temb_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
373
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
374
            resnet_time_scale_shift=resnet_time_scale_shift,
375
        )
376
377
378
379
380
381
382
383
    elif up_block_type == "UpDecoderBlock2D":
        return UpDecoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
384
            resnet_groups=resnet_groups,
Will Berman's avatar
Will Berman committed
385
            resnet_time_scale_shift=resnet_time_scale_shift,
YiYi Xu's avatar
YiYi Xu committed
386
            temb_channels=temb_channels,
387
        )
Will Berman's avatar
Will Berman committed
388
389
390
391
392
393
394
395
396
    elif up_block_type == "AttnUpDecoderBlock2D":
        return AttnUpDecoderBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            resnet_groups=resnet_groups,
397
            attention_head_dim=attention_head_dim,
Will Berman's avatar
Will Berman committed
398
            resnet_time_scale_shift=resnet_time_scale_shift,
YiYi Xu's avatar
YiYi Xu committed
399
            temb_channels=temb_channels,
Will Berman's avatar
Will Berman committed
400
        )
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
    elif up_block_type == "KUpBlock2D":
        return KUpBlock2D(
            num_layers=num_layers,
            in_channels=in_channels,
            out_channels=out_channels,
            temb_channels=temb_channels,
            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,
            add_upsample=add_upsample,
            resnet_eps=resnet_eps,
            resnet_act_fn=resnet_act_fn,
            cross_attention_dim=cross_attention_dim,
421
            attention_head_dim=attention_head_dim,
422
423
        )

424
    raise ValueError(f"{up_block_type} does not exist.")
425
426


427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
class AutoencoderTinyBlock(nn.Module):
    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()

    def forward(self, x):
        return self.fuse(self.conv(x) + self.skip(x))


Patrick von Platen's avatar
Patrick von Platen committed
449
450
451
452
453
class UNetMidBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
454
        dropout: float = 0.0,
455
        num_layers: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
456
        resnet_eps: float = 1e-6,
YiYi Xu's avatar
YiYi Xu committed
457
        resnet_time_scale_shift: str = "default",  # default, spatial
Patrick von Platen's avatar
Patrick von Platen committed
458
459
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
460
        resnet_pre_norm: bool = True,
Will Berman's avatar
Will Berman committed
461
        add_attention: bool = True,
462
        attention_head_dim=1,
Patrick von Platen's avatar
Patrick von Platen committed
463
464
465
        output_scale_factor=1.0,
    ):
        super().__init__()
466
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
Will Berman's avatar
Will Berman committed
467
        self.add_attention = add_attention
Patrick von Platen's avatar
Patrick von Platen committed
468

469
470
        # there is always at least one resnet
        resnets = [
471
            ResnetBlock2D(
472
473
474
                in_channels=in_channels,
                out_channels=in_channels,
                temb_channels=temb_channels,
475
                eps=resnet_eps,
476
477
478
479
480
481
                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,
Patrick von Platen's avatar
Patrick von Platen committed
482
            )
483
484
        ]
        attentions = []
Patrick von Platen's avatar
Patrick von Platen committed
485

486
487
488
489
490
491
        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

492
        for _ in range(num_layers):
Will Berman's avatar
Will Berman committed
493
494
            if self.add_attention:
                attentions.append(
495
                    Attention(
Will Berman's avatar
Will Berman committed
496
                        in_channels,
497
498
                        heads=in_channels // attention_head_dim,
                        dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
499
500
                        rescale_output_factor=output_scale_factor,
                        eps=resnet_eps,
YiYi Xu's avatar
YiYi Xu committed
501
502
                        norm_num_groups=resnet_groups if resnet_time_scale_shift == "default" else None,
                        spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
503
504
505
506
                        residual_connection=True,
                        bias=True,
                        upcast_softmax=True,
                        _from_deprecated_attn_block=True,
Will Berman's avatar
Will Berman committed
507
                    )
508
                )
Will Berman's avatar
Will Berman committed
509
510
511
            else:
                attentions.append(None)

512
            resnets.append(
513
                ResnetBlock2D(
514
515
516
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
517
                    eps=resnet_eps,
518
519
520
521
522
523
524
                    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,
                )
Patrick von Platen's avatar
Patrick von Platen committed
525
526
            )

527
528
529
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

Will Berman's avatar
Will Berman committed
530
    def forward(self, hidden_states, temb=None):
Patrick von Platen's avatar
Patrick von Platen committed
531
        hidden_states = self.resnets[0](hidden_states, temb)
532
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
Will Berman's avatar
Will Berman committed
533
            if attn is not None:
YiYi Xu's avatar
YiYi Xu committed
534
                hidden_states = attn(hidden_states, temb=temb)
Patrick von Platen's avatar
Patrick von Platen committed
535
            hidden_states = resnet(hidden_states, temb)
Patrick von Platen's avatar
Patrick von Platen committed
536

537
        return hidden_states
Patrick von Platen's avatar
Patrick von Platen committed
538

539

Patrick von Platen's avatar
Patrick von Platen committed
540
541
542
543
544
545
546
class UNetMidBlock2DCrossAttn(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
547
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
548
549
550
551
552
        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,
553
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
554
555
        output_scale_factor=1.0,
        cross_attention_dim=1280,
556
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
557
        use_linear_projection=False,
558
        upcast_attention=False,
Patrick von Platen's avatar
Patrick von Platen committed
559
560
561
    ):
        super().__init__()

562
        self.has_cross_attention = True
563
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
564
565
566
567
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)

        # there is always at least one resnet
        resnets = [
568
            ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
                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 = []

        for _ in range(num_layers):
584
585
586
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
587
588
                        num_attention_heads,
                        in_channels // num_attention_heads,
589
                        in_channels=in_channels,
590
                        num_layers=transformer_layers_per_block,
591
592
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
593
                        use_linear_projection=use_linear_projection,
594
                        upcast_attention=upcast_attention,
595
596
597
598
599
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
600
601
                        num_attention_heads,
                        in_channels // num_attention_heads,
602
603
604
605
606
                        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
607
608
                )
            resnets.append(
609
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
                    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)

626
627
        self.gradient_checkpointing = False

628
    def forward(
629
630
631
632
633
634
635
636
        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:
Patrick von Platen's avatar
Patrick von Platen committed
637
638
        hidden_states = self.resnets[0](hidden_states, temb)
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
639
640
641
642
643
644
645
646
647
648
649
650
            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
651
                hidden_states = attn(
652
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
653
654
655
656
657
                    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,
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
                )[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]
                hidden_states = resnet(hidden_states, temb)
Will Berman's avatar
Will Berman committed
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690

        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,
691
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
692
693
        output_scale_factor=1.0,
        cross_attention_dim=1280,
694
        skip_time_act=False,
695
        only_cross_attention=False,
696
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
697
698
699
700
701
    ):
        super().__init__()

        self.has_cross_attention = True

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

705
        self.num_heads = in_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
706
707
708
709
710
711
712
713
714
715
716
717
718
719

        # 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,
720
                skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
721
722
723
724
725
            )
        ]
        attentions = []

        for _ in range(num_layers):
726
727
728
729
            processor = (
                AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
            )

Will Berman's avatar
Will Berman committed
730
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
731
                Attention(
Will Berman's avatar
Will Berman committed
732
733
734
                    query_dim=in_channels,
                    cross_attention_dim=in_channels,
                    heads=self.num_heads,
735
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
736
737
738
739
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
740
                    only_cross_attention=only_cross_attention,
741
                    cross_attention_norm=cross_attention_norm,
742
                    processor=processor,
Will Berman's avatar
Will Berman committed
743
744
745
746
747
748
749
750
751
752
753
754
755
756
                )
            )
            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,
757
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
758
759
760
761
762
763
                )
            )

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

764
    def forward(
765
766
767
768
769
770
771
        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,
772
773
    ):
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
774
775
776
777
778
779
780
781
782
783
784
785

        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
786
787
788
789
790
        hidden_states = self.resnets[0](hidden_states, temb)
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
            # attn
            hidden_states = attn(
                hidden_states,
791
                encoder_hidden_states=encoder_hidden_states,
792
                attention_mask=mask,
793
                **cross_attention_kwargs,
Will Berman's avatar
Will Berman committed
794
795
796
            )

            # resnet
Patrick von Platen's avatar
Patrick von Platen committed
797
798
799
800
801
            hidden_states = resnet(hidden_states, temb)

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
802
class AttnDownBlock2D(nn.Module):
803
804
805
806
807
808
809
810
811
812
813
814
    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,
815
        attention_head_dim=1,
816
        output_scale_factor=1.0,
817
        downsample_padding=1,
818
        downsample_type="conv",
819
820
821
822
    ):
        super().__init__()
        resnets = []
        attentions = []
823
        self.downsample_type = downsample_type
824

825
826
827
828
829
830
        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

831
832
833
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
834
                ResnetBlock2D(
835
836
837
838
839
840
841
842
843
844
845
846
847
                    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(
848
                Attention(
849
                    out_channels,
850
851
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
852
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
853
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
854
                    norm_num_groups=resnet_groups,
855
856
857
858
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
859
860
861
862
863
864
                )
            )

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

865
        if downsample_type == "conv":
866
            self.downsamplers = nn.ModuleList(
867
868
                [
                    Downsample2D(
869
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
870
871
                    )
                ]
872
            )
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
        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,
                    )
                ]
            )
891
892
893
        else:
            self.downsamplers = None

894
    def forward(self, hidden_states, temb=None, upsample_size=None):
895
896
897
898
899
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
            hidden_states = resnet(hidden_states, temb)
            hidden_states = attn(hidden_states)
900
            output_states = output_states + (hidden_states,)
901
902
903

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
904
905
906
907
                if self.downsample_type == "resnet":
                    hidden_states = downsampler(hidden_states, temb=temb)
                else:
                    hidden_states = downsampler(hidden_states)
908
909
910
911
912
913

            output_states += (hidden_states,)

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
914
class CrossAttnDownBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
915
916
917
918
919
920
921
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
922
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
923
924
925
926
927
        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,
928
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
929
930
931
932
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        downsample_padding=1,
        add_downsample=True,
933
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
934
        use_linear_projection=False,
935
        only_cross_attention=False,
936
        upcast_attention=False,
Patrick von Platen's avatar
Patrick von Platen committed
937
938
939
940
941
    ):
        super().__init__()
        resnets = []
        attentions = []

942
        self.has_cross_attention = True
943
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
944
945
946
947

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
948
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
949
950
951
952
953
954
955
956
957
958
959
960
                    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,
                )
            )
961
962
963
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
964
965
                        num_attention_heads,
                        out_channels // num_attention_heads,
966
                        in_channels=out_channels,
967
                        num_layers=transformer_layers_per_block,
968
969
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
970
                        use_linear_projection=use_linear_projection,
971
                        only_cross_attention=only_cross_attention,
972
                        upcast_attention=upcast_attention,
973
974
975
976
977
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
978
979
                        num_attention_heads,
                        out_channels // num_attention_heads,
980
981
982
983
984
                        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
985
986
987
988
989
990
991
992
                )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
993
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
994
995
996
997
998
999
                    )
                ]
            )
        else:
            self.downsamplers = None

1000
1001
        self.gradient_checkpointing = False

1002
    def forward(
1003
1004
1005
1006
1007
1008
1009
        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,
Will Berman's avatar
Will Berman committed
1010
        additional_residuals=None,
1011
    ):
Patrick von Platen's avatar
Patrick von Platen committed
1012
1013
        output_states = ()

Will Berman's avatar
Will Berman committed
1014
1015
1016
        blocks = list(zip(self.resnets, self.attentions))

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

Will Berman's avatar
Will Berman committed
1019
                def create_custom_forward(module, return_dict=None):
1020
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
1021
1022
1023
1024
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
1025
1026
1027

                    return custom_forward

1028
1029
1030
1031
1032
1033
1034
                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
1035
                hidden_states = attn(
1036
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1037
1038
1039
1040
1041
                    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,
1042
                )[0]
1043
1044
            else:
                hidden_states = resnet(hidden_states, temb)
1045
1046
1047
1048
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
1049
1050
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
1051
1052
                    return_dict=False,
                )[0]
1053

Will Berman's avatar
Will Berman committed
1054
1055
1056
1057
            # 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

1058
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1059
1060
1061
1062
1063

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

1064
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1065
1066
1067
1068

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
1069
class DownBlock2D(nn.Module):
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
    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,
        output_scale_factor=1.0,
        add_downsample=True,
Patrick von Platen's avatar
Patrick von Platen committed
1084
        downsample_padding=1,
1085
1086
1087
1088
1089
1090
1091
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1092
                ResnetBlock2D(
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
                    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
1110
1111
                [
                    Downsample2D(
1112
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
1113
1114
                    )
                ]
1115
1116
1117
1118
            )
        else:
            self.downsamplers = None

1119
1120
        self.gradient_checkpointing = False

1121
1122
1123
1124
    def forward(self, hidden_states, temb=None):
        output_states = ()

        for resnet in self.resnets:
1125
1126
1127
1128
1129
1130
1131
1132
            if self.training and self.gradient_checkpointing:

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

                    return custom_forward

1133
1134
1135
1136
1137
1138
1139
1140
                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
                    )
1141
1142
1143
            else:
                hidden_states = resnet(hidden_states, temb)

1144
            output_states = output_states + (hidden_states,)
1145
1146
1147
1148
1149

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

1150
            output_states = output_states + (hidden_states,)
1151
1152
1153
1154

        return hidden_states, output_states


1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
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,
        output_scale_factor=1.0,
        add_downsample=True,
        downsample_padding=1,
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1177
                ResnetBlock2D(
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
                    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,
                )
            )

        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1197
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
                    )
                ]
            )
        else:
            self.downsamplers = None

    def forward(self, hidden_states):
        for resnet in self.resnets:
            hidden_states = resnet(hidden_states, temb=None)

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

        return hidden_states


1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
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,
1227
        attention_head_dim=1,
1228
1229
1230
1231
1232
1233
1234
1235
        output_scale_factor=1.0,
        add_downsample=True,
        downsample_padding=1,
    ):
        super().__init__()
        resnets = []
        attentions = []

1236
1237
1238
1239
1240
1241
        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

1242
1243
1244
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1245
                ResnetBlock2D(
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
                    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,
                )
            )
            attentions.append(
1259
                Attention(
1260
                    out_channels,
1261
1262
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1263
1264
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
1265
                    norm_num_groups=resnet_groups,
1266
1267
1268
1269
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
                )
            )

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

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1280
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
                    )
                ]
            )
        else:
            self.downsamplers = None

    def forward(self, hidden_states):
        for resnet, attn in zip(self.resnets, self.attentions):
            hidden_states = resnet(hidden_states, temb=None)
            hidden_states = attn(hidden_states)

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

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
1299
class AttnSkipDownBlock2D(nn.Module):
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_pre_norm: bool = True,
1311
        attention_head_dim=1,
1312
1313
1314
1315
1316
1317
1318
        output_scale_factor=np.sqrt(2.0),
        add_downsample=True,
    ):
        super().__init__()
        self.attentions = nn.ModuleList([])
        self.resnets = nn.ModuleList([])

1319
1320
1321
1322
1323
1324
        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

1325
1326
1327
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            self.resnets.append(
1328
                ResnetBlock2D(
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
                    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(
1343
                Attention(
1344
                    out_channels,
1345
1346
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1347
1348
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
1349
1350
1351
1352
1353
                    norm_num_groups=32,
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1354
1355
1356
1357
                )
            )

        if add_downsample:
1358
            self.resnet_down = ResnetBlock2D(
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
                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,
1369
                use_in_shortcut=True,
1370
1371
1372
                down=True,
                kernel="fir",
            )
1373
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
            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

    def forward(self, hidden_states, temb=None, skip_sample=None):
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
            hidden_states = resnet(hidden_states, temb)
            hidden_states = attn(hidden_states)
            output_states += (hidden_states,)

        if self.downsamplers is not None:
            hidden_states = self.resnet_down(hidden_states, temb)
            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
1400
class SkipDownBlock2D(nn.Module):
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
    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,
        output_scale_factor=np.sqrt(2.0),
        add_downsample=True,
        downsample_padding=1,
    ):
        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(
1422
                ResnetBlock2D(
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
                    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:
1438
            self.resnet_down = ResnetBlock2D(
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
                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,
1449
                use_in_shortcut=True,
1450
1451
1452
                down=True,
                kernel="fir",
            )
1453
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
            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

    def forward(self, hidden_states, temb=None, skip_sample=None):
        output_states = ()

        for resnet in self.resnets:
            hidden_states = resnet(hidden_states, temb)
            output_states += (hidden_states,)

        if self.downsamplers is not None:
            hidden_states = self.resnet_down(hidden_states, temb)
            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
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
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,
        output_scale_factor=1.0,
        add_downsample=True,
1494
        skip_time_act=False,
Will Berman's avatar
Will Berman committed
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
    ):
        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,
1513
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
                )
            )

        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,
1533
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

    def forward(self, hidden_states, temb=None):
        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

1555
1556
1557
1558
1559
1560
1561
1562
                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
1563
1564
1565
            else:
                hidden_states = resnet(hidden_states, temb)

1566
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1567
1568
1569
1570
1571

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

1572
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589

        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,
1590
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
1591
1592
1593
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_downsample=True,
1594
        skip_time_act=False,
1595
        only_cross_attention=False,
1596
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
1597
1598
1599
1600
1601
1602
1603
1604
    ):
        super().__init__()

        self.has_cross_attention = True

        resnets = []
        attentions = []

1605
1606
        self.attention_head_dim = attention_head_dim
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621

        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,
1622
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1623
1624
                )
            )
1625
1626
1627
1628
1629

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

Will Berman's avatar
Will Berman committed
1630
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
1631
                Attention(
Will Berman's avatar
Will Berman committed
1632
1633
1634
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
1635
                    dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
1636
1637
1638
1639
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
1640
                    only_cross_attention=only_cross_attention,
1641
                    cross_attention_norm=cross_attention_norm,
1642
                    processor=processor,
Will Berman's avatar
Will Berman committed
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
                )
            )
        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,
1662
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1663
1664
1665
1666
1667
1668
1669
1670
1671
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

1672
    def forward(
1673
1674
1675
1676
1677
1678
1679
        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,
1680
    ):
Will Berman's avatar
Will Berman committed
1681
        output_states = ()
1682
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
Will Berman's avatar
Will Berman committed
1683

1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
        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
1695
        for resnet, attn in zip(self.resnets, self.attentions):
1696
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
1697

1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
                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
1708
                hidden_states = attn(
1709
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1710
1711
1712
1713
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
1714
1715
1716
1717
1718
1719
            else:
                hidden_states = resnet(hidden_states, temb)

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
1720
                    attention_mask=mask,
1721
1722
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
1723

1724
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1725
1726
1727
1728
1729

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

1730
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1731
1732
1733
1734

        return hidden_states, output_states


1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
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,
        add_downsample=False,
    ):
        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(
                ResnetBlock2D(
                    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

    def forward(self, hidden_states, temb=None):
        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

1793
1794
1795
1796
1797
1798
1799
1800
                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
                    )
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
            else:
                hidden_states = resnet(hidden_states, temb)

            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,
        add_downsample=True,
1824
        attention_head_dim: int = 64,
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
        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(
                ResnetBlock2D(
                    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,
1857
1858
                    out_channels // attention_head_dim,
                    attention_head_dim,
1859
1860
1861
1862
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
1863
                    cross_attention_norm="layer_norm",
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
                    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(
1879
1880
1881
1882
1883
1884
1885
        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,
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
    ):
        output_states = ()

        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

1901
1902
1903
1904
1905
1906
1907
                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
1908
                hidden_states = attn(
1909
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1910
1911
1912
1913
1914
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
1915
                )
1916
1917
1918
1919
1920
1921
1922
1923
            else:
                hidden_states = resnet(hidden_states, temb)
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
1924
                    encoder_attention_mask=encoder_attention_mask,
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
                )

            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
1939
class AttnUpBlock2D(nn.Module):
1940
1941
1942
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
1943
1944
        prev_output_channel: int,
        out_channels: int,
1945
1946
1947
1948
1949
1950
1951
1952
        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,
1953
        attention_head_dim=1,
1954
        output_scale_factor=1.0,
1955
        upsample_type="conv",
1956
1957
1958
1959
1960
    ):
        super().__init__()
        resnets = []
        attentions = []

1961
1962
        self.upsample_type = upsample_type

1963
1964
1965
1966
1967
1968
        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

1969
        for i in range(num_layers):
Patrick von Platen's avatar
Patrick von Platen committed
1970
1971
1972
            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

1973
            resnets.append(
1974
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
1975
1976
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
                    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(
1988
                Attention(
Patrick von Platen's avatar
Patrick von Platen committed
1989
                    out_channels,
1990
1991
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1992
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
1993
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
1994
                    norm_num_groups=resnet_groups,
1995
1996
1997
1998
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1999
2000
2001
2002
2003
2004
                )
            )

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

2005
        if upsample_type == "conv":
Patrick von Platen's avatar
Patrick von Platen committed
2006
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
        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,
                    )
                ]
            )
2025
2026
2027
        else:
            self.upsamplers = None

2028
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
        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)

            hidden_states = resnet(hidden_states, temb)
            hidden_states = attn(hidden_states)

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2040
2041
2042
2043
                if self.upsample_type == "resnet":
                    hidden_states = upsampler(hidden_states, temb=temb)
                else:
                    hidden_states = upsampler(hidden_states)
2044
2045
2046
2047

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2048
class CrossAttnUpBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
2049
2050
2051
2052
2053
2054
2055
2056
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        prev_output_channel: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
2057
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
2058
2059
2060
2061
2062
        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,
2063
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
2064
2065
2066
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_upsample=True,
2067
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
2068
        use_linear_projection=False,
2069
        only_cross_attention=False,
2070
        upcast_attention=False,
Patrick von Platen's avatar
Patrick von Platen committed
2071
2072
2073
2074
2075
    ):
        super().__init__()
        resnets = []
        attentions = []

2076
        self.has_cross_attention = True
2077
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
2078
2079
2080
2081
2082
2083

        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(
2084
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
                    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,
                )
            )
2097
2098
2099
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
2100
2101
                        num_attention_heads,
                        out_channels // num_attention_heads,
2102
                        in_channels=out_channels,
2103
                        num_layers=transformer_layers_per_block,
2104
2105
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
2106
                        use_linear_projection=use_linear_projection,
2107
                        only_cross_attention=only_cross_attention,
2108
                        upcast_attention=upcast_attention,
2109
2110
2111
2112
2113
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
2114
2115
                        num_attention_heads,
                        out_channels // num_attention_heads,
2116
2117
2118
2119
2120
                        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
2121
2122
2123
2124
2125
2126
2127
2128
2129
                )
        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

2130
2131
2132
2133
        self.gradient_checkpointing = False

    def forward(
        self,
2134
2135
2136
2137
2138
2139
2140
2141
        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,
2142
    ):
Patrick von Platen's avatar
Patrick von Platen committed
2143
2144
2145
2146
2147
2148
        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)

2149
2150
            if self.training and self.gradient_checkpointing:

Will Berman's avatar
Will Berman committed
2151
                def create_custom_forward(module, return_dict=None):
2152
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
2153
2154
2155
2156
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
2157
2158
2159

                    return custom_forward

2160
2161
2162
2163
2164
2165
2166
                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
2167
                hidden_states = attn(
2168
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2169
2170
2171
2172
2173
                    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,
2174
                )[0]
2175
2176
            else:
                hidden_states = resnet(hidden_states, temb)
2177
2178
2179
2180
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
2181
2182
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
2183
2184
                    return_dict=False,
                )[0]
Patrick von Platen's avatar
Patrick von Platen committed
2185
2186
2187

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2188
                hidden_states = upsampler(hidden_states, upsample_size)
Patrick von Platen's avatar
Patrick von Platen committed
2189
2190
2191
2192

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2193
class UpBlock2D(nn.Module):
2194
2195
2196
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
2197
2198
        prev_output_channel: int,
        out_channels: int,
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
        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,
        output_scale_factor=1.0,
        add_upsample=True,
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
Patrick von Platen's avatar
Patrick von Platen committed
2214
2215
2216
            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

2217
            resnets.append(
2218
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2219
2220
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
                    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
2235
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2236
2237
2238
        else:
            self.upsamplers = None

2239
2240
        self.gradient_checkpointing = False

2241
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
2242
2243
2244
2245
2246
2247
        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)

2248
2249
2250
2251
2252
2253
2254
2255
            if self.training and self.gradient_checkpointing:

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

                    return custom_forward

2256
2257
2258
2259
2260
2261
2262
2263
                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
                    )
2264
2265
            else:
                hidden_states = resnet(hidden_states, temb)
2266
2267
2268

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2269
                hidden_states = upsampler(hidden_states, upsample_size)
2270
2271

        return hidden_states
2272
2273


2274
2275
2276
2277
2278
2279
2280
2281
class UpDecoderBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
        resnet_eps: float = 1e-6,
YiYi Xu's avatar
YiYi Xu committed
2282
        resnet_time_scale_shift: str = "default",  # default, spatial
2283
2284
2285
2286
2287
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
        resnet_pre_norm: bool = True,
        output_scale_factor=1.0,
        add_upsample=True,
YiYi Xu's avatar
YiYi Xu committed
2288
        temb_channels=None,
2289
2290
2291
2292
2293
2294
2295
2296
    ):
        super().__init__()
        resnets = []

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

            resnets.append(
2297
                ResnetBlock2D(
2298
2299
                    in_channels=input_channels,
                    out_channels=out_channels,
YiYi Xu's avatar
YiYi Xu committed
2300
                    temb_channels=temb_channels,
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
                    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:
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
        else:
            self.upsamplers = None

YiYi Xu's avatar
YiYi Xu committed
2318
    def forward(self, hidden_states, temb=None):
2319
        for resnet in self.resnets:
YiYi Xu's avatar
YiYi Xu committed
2320
            hidden_states = resnet(hidden_states, temb=temb)
2321
2322
2323
2324
2325
2326
2327
2328

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

        return hidden_states


2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
class AttnUpDecoderBlock2D(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,
2341
        attention_head_dim=1,
2342
2343
        output_scale_factor=1.0,
        add_upsample=True,
YiYi Xu's avatar
YiYi Xu committed
2344
        temb_channels=None,
2345
2346
2347
2348
2349
    ):
        super().__init__()
        resnets = []
        attentions = []

2350
2351
2352
2353
2354
2355
        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

2356
2357
2358
2359
        for i in range(num_layers):
            input_channels = in_channels if i == 0 else out_channels

            resnets.append(
2360
                ResnetBlock2D(
2361
2362
                    in_channels=input_channels,
                    out_channels=out_channels,
YiYi Xu's avatar
YiYi Xu committed
2363
                    temb_channels=temb_channels,
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
                    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(
2374
                Attention(
2375
                    out_channels,
2376
2377
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
2378
2379
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
2380
                    norm_num_groups=resnet_groups if resnet_time_scale_shift != "spatial" else None,
YiYi Xu's avatar
YiYi Xu committed
2381
                    spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
2382
2383
2384
2385
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
                )
            )

        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

YiYi Xu's avatar
YiYi Xu committed
2397
    def forward(self, hidden_states, temb=None):
2398
        for resnet, attn in zip(self.resnets, self.attentions):
YiYi Xu's avatar
YiYi Xu committed
2399
2400
            hidden_states = resnet(hidden_states, temb=temb)
            hidden_states = attn(hidden_states, temb=temb)
2401
2402
2403
2404
2405
2406
2407
2408

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

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2409
class AttnSkipUpBlock2D(nn.Module):
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: 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,
2422
        attention_head_dim=1,
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
        output_scale_factor=np.sqrt(2.0),
        add_upsample=True,
    ):
        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(
2435
                ResnetBlock2D(
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
                    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,
                )
            )

2450
2451
2452
2453
2454
2455
        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

2456
        self.attentions.append(
2457
            Attention(
2458
                out_channels,
2459
2460
                heads=out_channels // attention_head_dim,
                dim_head=attention_head_dim,
2461
2462
                rescale_output_factor=output_scale_factor,
                eps=resnet_eps,
2463
2464
2465
2466
2467
                norm_num_groups=32,
                residual_connection=True,
                bias=True,
                upcast_softmax=True,
                _from_deprecated_attn_block=True,
2468
2469
2470
2471
2472
            )
        )

        self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels)
        if add_upsample:
2473
            self.resnet_up = ResnetBlock2D(
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
                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,
2485
                use_in_shortcut=True,
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
                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

    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, skip_sample=None):
        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)

            hidden_states = resnet(hidden_states, temb)

        hidden_states = self.attentions[0](hidden_states)

        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

            hidden_states = self.resnet_up(hidden_states, temb)

        return hidden_states, skip_sample


Patrick von Platen's avatar
Patrick von Platen committed
2528
class SkipUpBlock2D(nn.Module):
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: 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,
        output_scale_factor=np.sqrt(2.0),
        add_upsample=True,
        upsample_padding=1,
    ):
        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(
2553
                ResnetBlock2D(
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
                    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:
2570
            self.resnet_up = ResnetBlock2D(
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
                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,
2582
                use_in_shortcut=True,
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
                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

    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, skip_sample=None):
        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)

            hidden_states = resnet(hidden_states, temb)

        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

            hidden_states = self.resnet_up(hidden_states, temb)

        return hidden_states, skip_sample
Will Berman's avatar
Will Berman committed
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638


class ResnetUpsampleBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        prev_output_channel: 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,
        output_scale_factor=1.0,
        add_upsample=True,
2639
        skip_time_act=False,
Will Berman's avatar
Will Berman committed
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
    ):
        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,
2660
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
                )
            )

        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,
2680
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False

    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
        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

2705
2706
2707
2708
2709
2710
2711
2712
                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
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
            else:
                hidden_states = resnet(hidden_states, temb)

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

        return hidden_states


class SimpleCrossAttnUpBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        prev_output_channel: 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,
2737
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
2738
2739
2740
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_upsample=True,
2741
        skip_time_act=False,
2742
        only_cross_attention=False,
2743
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
2744
2745
2746
2747
2748
2749
    ):
        super().__init__()
        resnets = []
        attentions = []

        self.has_cross_attention = True
2750
        self.attention_head_dim = attention_head_dim
Will Berman's avatar
Will Berman committed
2751

2752
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769

        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,
2770
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2771
2772
                )
            )
2773
2774
2775
2776
2777

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

Will Berman's avatar
Will Berman committed
2778
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
2779
                Attention(
Will Berman's avatar
Will Berman committed
2780
2781
2782
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
2783
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
2784
2785
2786
2787
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
2788
                    only_cross_attention=only_cross_attention,
2789
                    cross_attention_norm=cross_attention_norm,
2790
                    processor=processor,
Will Berman's avatar
Will Berman committed
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
                )
            )
        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,
2810
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False

    def forward(
        self,
2822
2823
2824
2825
2826
2827
2828
2829
        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,
Will Berman's avatar
Will Berman committed
2830
    ):
2831
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843

        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
2844
2845
2846
2847
2848
2849
2850
        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)

2851
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
2852

2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
                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
2863
                hidden_states = attn(
2864
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2865
2866
2867
2868
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
2869
2870
2871
2872
2873
2874
            else:
                hidden_states = resnet(hidden_states, temb)

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
2875
                    attention_mask=mask,
2876
2877
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
2878
2879
2880
2881
2882
2883

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

        return hidden_states
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947


class KUpBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 5,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
        resnet_group_size: Optional[int] = 32,
        add_upsample=True,
    ):
        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(
                ResnetBlock2D(
                    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

    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None):
        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

2948
2949
2950
2951
2952
2953
2954
2955
                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
                    )
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
            else:
                hidden_states = resnet(hidden_states, temb)

        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,
        dropout: float = 0.0,
        num_layers: int = 4,
        resnet_eps: float = 1e-5,
        resnet_act_fn: str = "gelu",
        resnet_group_size: int = 32,
2977
        attention_head_dim=1,  # attention dim_head
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
        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
2991
        self.attention_head_dim = attention_head_dim
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026

        # 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(
                ResnetBlock2D(
                    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,
3027
                    k_out_channels // attention_head_dim
3028
                    if (i == num_layers - 1)
3029
3030
                    else out_channels // attention_head_dim,
                    attention_head_dim,
3031
3032
3033
3034
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
3035
                    cross_attention_norm="layer_norm",
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
                    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

    def forward(
        self,
3052
3053
3054
3055
3056
3057
3058
3059
        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,
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
    ):
        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, 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

3077
3078
3079
3080
3081
3082
3083
                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
3084
                hidden_states = attn(
3085
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
3086
3087
3088
3089
3090
3091
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
                )
3092
3093
3094
3095
3096
3097
3098
3099
            else:
                hidden_states = resnet(hidden_states, temb)
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
3100
                    encoder_attention_mask=encoder_attention_mask,
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
                )

        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.
        activation_fn (`str`, *optional*, defaults to `"geglu"`): Activation function to be used in feed-forward.
        num_embeds_ada_norm (:
            obj: `int`, *optional*): The number of diffusion steps used during training. See `Transformer2DModel`.
        attention_bias (:
            obj: `bool`, *optional*, defaults to `False`): Configure if the attentions should contain a bias parameter.
    """

    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,
3139
        cross_attention_norm: Optional[str] = None,
3140
3141
3142
3143
3144
3145
3146
3147
        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
3148
            self.attn1 = Attention(
3149
3150
3151
3152
3153
3154
                query_dim=dim,
                heads=num_attention_heads,
                dim_head=attention_head_dim,
                dropout=dropout,
                bias=attention_bias,
                cross_attention_dim=None,
3155
                cross_attention_norm=None,
3156
3157
3158
3159
            )

        # 2. Cross-Attn
        self.norm2 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size))
Patrick von Platen's avatar
Patrick von Platen committed
3160
        self.attn2 = Attention(
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
            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,
        )

    def _to_3d(self, hidden_states, height, weight):
        return hidden_states.permute(0, 2, 3, 1).reshape(hidden_states.shape[0], height * weight, -1)

    def _to_4d(self, hidden_states, height, weight):
        return hidden_states.permute(0, 2, 1).reshape(hidden_states.shape[0], -1, height, weight)

    def forward(
        self,
3179
3180
3181
3182
3183
3184
3185
3186
        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,
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
    ):
        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,
3200
                attention_mask=attention_mask,
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
                **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,
3215
            attention_mask=attention_mask if encoder_hidden_states is None else encoder_attention_mask,
3216
3217
3218
3219
3220
3221
3222
            **cross_attention_kwargs,
        )
        attn_output = self._to_4d(attn_output, height, weight)

        hidden_states = attn_output + hidden_states

        return hidden_states