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


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

452
    raise ValueError(f"{up_block_type} does not exist.")
453
454


455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
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
477
478
479
480
481
class UNetMidBlock2D(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
482
        dropout: float = 0.0,
483
        num_layers: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
484
        resnet_eps: float = 1e-6,
YiYi Xu's avatar
YiYi Xu committed
485
        resnet_time_scale_shift: str = "default",  # default, spatial
Patrick von Platen's avatar
Patrick von Platen committed
486
487
        resnet_act_fn: str = "swish",
        resnet_groups: int = 32,
488
        attn_groups: Optional[int] = None,
489
        resnet_pre_norm: bool = True,
Will Berman's avatar
Will Berman committed
490
        add_attention: bool = True,
491
        attention_head_dim=1,
Patrick von Platen's avatar
Patrick von Platen committed
492
493
494
        output_scale_factor=1.0,
    ):
        super().__init__()
495
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)
Will Berman's avatar
Will Berman committed
496
        self.add_attention = add_attention
Patrick von Platen's avatar
Patrick von Platen committed
497

498
499
500
        if attn_groups is None:
            attn_groups = resnet_groups if resnet_time_scale_shift == "default" else None

501
502
        # there is always at least one resnet
        resnets = [
503
            ResnetBlock2D(
504
505
506
                in_channels=in_channels,
                out_channels=in_channels,
                temb_channels=temb_channels,
507
                eps=resnet_eps,
508
509
510
511
512
513
                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
514
            )
515
516
        ]
        attentions = []
Patrick von Platen's avatar
Patrick von Platen committed
517

518
519
520
521
522
523
        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

524
        for _ in range(num_layers):
Will Berman's avatar
Will Berman committed
525
526
            if self.add_attention:
                attentions.append(
527
                    Attention(
Will Berman's avatar
Will Berman committed
528
                        in_channels,
529
530
                        heads=in_channels // attention_head_dim,
                        dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
531
532
                        rescale_output_factor=output_scale_factor,
                        eps=resnet_eps,
533
                        norm_num_groups=attn_groups,
YiYi Xu's avatar
YiYi Xu committed
534
                        spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
535
536
537
538
                        residual_connection=True,
                        bias=True,
                        upcast_softmax=True,
                        _from_deprecated_attn_block=True,
Will Berman's avatar
Will Berman committed
539
                    )
540
                )
Will Berman's avatar
Will Berman committed
541
542
543
            else:
                attentions.append(None)

544
            resnets.append(
545
                ResnetBlock2D(
546
547
548
                    in_channels=in_channels,
                    out_channels=in_channels,
                    temb_channels=temb_channels,
549
                    eps=resnet_eps,
550
551
552
553
554
555
556
                    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
557
558
            )

559
560
561
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

Will Berman's avatar
Will Berman committed
562
    def forward(self, hidden_states, temb=None):
Patrick von Platen's avatar
Patrick von Platen committed
563
        hidden_states = self.resnets[0](hidden_states, temb)
564
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
Will Berman's avatar
Will Berman committed
565
            if attn is not None:
YiYi Xu's avatar
YiYi Xu committed
566
                hidden_states = attn(hidden_states, temb=temb)
Patrick von Platen's avatar
Patrick von Platen committed
567
            hidden_states = resnet(hidden_states, temb)
Patrick von Platen's avatar
Patrick von Platen committed
568

569
        return hidden_states
Patrick von Platen's avatar
Patrick von Platen committed
570

571

Patrick von Platen's avatar
Patrick von Platen committed
572
573
574
575
576
577
578
class UNetMidBlock2DCrossAttn(nn.Module):
    def __init__(
        self,
        in_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
579
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
580
581
582
583
584
        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,
585
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
586
587
        output_scale_factor=1.0,
        cross_attention_dim=1280,
588
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
589
        use_linear_projection=False,
590
        upcast_attention=False,
591
        attention_type="default",
Patrick von Platen's avatar
Patrick von Platen committed
592
593
594
    ):
        super().__init__()

595
        self.has_cross_attention = True
596
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
597
598
599
600
        resnet_groups = resnet_groups if resnet_groups is not None else min(in_channels // 4, 32)

        # there is always at least one resnet
        resnets = [
601
            ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
                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):
617
618
619
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
620
621
                        num_attention_heads,
                        in_channels // num_attention_heads,
622
                        in_channels=in_channels,
623
                        num_layers=transformer_layers_per_block,
624
625
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
626
                        use_linear_projection=use_linear_projection,
627
                        upcast_attention=upcast_attention,
628
                        attention_type=attention_type,
629
630
631
632
633
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
634
635
                        num_attention_heads,
                        in_channels // num_attention_heads,
636
637
638
639
640
                        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
641
642
                )
            resnets.append(
643
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
                    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)

660
661
        self.gradient_checkpointing = False

662
    def forward(
663
664
665
666
667
668
669
670
        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:
671
672
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
        hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
673
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
674
675
676
677
678
679
680
681
682
683
684
685
            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
686
                hidden_states = attn(
687
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
688
689
690
691
692
                    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,
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
                )[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]
709
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725

        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,
726
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
727
728
        output_scale_factor=1.0,
        cross_attention_dim=1280,
729
        skip_time_act=False,
730
        only_cross_attention=False,
731
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
732
733
734
735
736
    ):
        super().__init__()

        self.has_cross_attention = True

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

740
        self.num_heads = in_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
741
742
743
744
745
746
747
748
749
750
751
752
753
754

        # 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,
755
                skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
756
757
758
759
760
            )
        ]
        attentions = []

        for _ in range(num_layers):
761
762
763
764
            processor = (
                AttnAddedKVProcessor2_0() if hasattr(F, "scaled_dot_product_attention") else AttnAddedKVProcessor()
            )

Will Berman's avatar
Will Berman committed
765
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
766
                Attention(
Will Berman's avatar
Will Berman committed
767
768
769
                    query_dim=in_channels,
                    cross_attention_dim=in_channels,
                    heads=self.num_heads,
770
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
771
772
773
774
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
775
                    only_cross_attention=only_cross_attention,
776
                    cross_attention_norm=cross_attention_norm,
777
                    processor=processor,
Will Berman's avatar
Will Berman committed
778
779
780
781
782
783
784
785
786
787
788
789
790
791
                )
            )
            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,
792
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
793
794
795
796
797
798
                )
            )

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

799
    def forward(
800
801
802
803
804
805
806
        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,
807
808
    ):
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
809
        lora_scale = cross_attention_kwargs.get("scale", 1.0)
810
811
812
813
814
815
816
817
818
819
820
821

        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

822
        hidden_states = self.resnets[0](hidden_states, temb, scale=lora_scale)
Will Berman's avatar
Will Berman committed
823
824
825
826
        for attn, resnet in zip(self.attentions, self.resnets[1:]):
            # attn
            hidden_states = attn(
                hidden_states,
827
                encoder_hidden_states=encoder_hidden_states,
828
                attention_mask=mask,
829
                **cross_attention_kwargs,
Will Berman's avatar
Will Berman committed
830
831
832
            )

            # resnet
833
            hidden_states = resnet(hidden_states, temb, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
834
835
836
837

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
838
class AttnDownBlock2D(nn.Module):
839
840
841
842
843
844
845
846
847
848
849
850
    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,
851
        attention_head_dim=1,
852
        output_scale_factor=1.0,
853
        downsample_padding=1,
854
        downsample_type="conv",
855
856
857
858
    ):
        super().__init__()
        resnets = []
        attentions = []
859
        self.downsample_type = downsample_type
860

861
862
863
864
865
866
        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

867
868
869
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
870
                ResnetBlock2D(
871
872
873
874
875
876
877
878
879
880
881
882
883
                    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(
884
                Attention(
885
                    out_channels,
886
887
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
888
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
889
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
890
                    norm_num_groups=resnet_groups,
891
892
893
894
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
895
896
897
898
899
900
                )
            )

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

901
        if downsample_type == "conv":
902
            self.downsamplers = nn.ModuleList(
903
904
                [
                    Downsample2D(
905
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
906
907
                    )
                ]
908
            )
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
        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,
                    )
                ]
            )
927
928
929
        else:
            self.downsamplers = None

930
931
932
933
934
    def forward(self, hidden_states, temb=None, upsample_size=None, cross_attention_kwargs=None):
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}

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

935
936
937
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
938
939
940
            cross_attention_kwargs.update({"scale": lora_scale})
            hidden_states = resnet(hidden_states, temb, scale=lora_scale)
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
941
            output_states = output_states + (hidden_states,)
942
943
944

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
945
                if self.downsample_type == "resnet":
946
                    hidden_states = downsampler(hidden_states, temb=temb, scale=lora_scale)
947
                else:
948
                    hidden_states = downsampler(hidden_states, scale=lora_scale)
949
950
951
952
953
954

            output_states += (hidden_states,)

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
955
class CrossAttnDownBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
956
957
958
959
960
961
962
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
963
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
964
965
966
967
968
        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,
969
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
970
971
972
973
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        downsample_padding=1,
        add_downsample=True,
974
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
975
        use_linear_projection=False,
976
        only_cross_attention=False,
977
        upcast_attention=False,
978
        attention_type="default",
Patrick von Platen's avatar
Patrick von Platen committed
979
980
981
982
983
    ):
        super().__init__()
        resnets = []
        attentions = []

984
        self.has_cross_attention = True
985
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
986
987
988
989

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
990
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
991
992
993
994
995
996
997
998
999
1000
1001
1002
                    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,
                )
            )
1003
1004
1005
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
1006
1007
                        num_attention_heads,
                        out_channels // num_attention_heads,
1008
                        in_channels=out_channels,
1009
                        num_layers=transformer_layers_per_block,
1010
1011
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
1012
                        use_linear_projection=use_linear_projection,
1013
                        only_cross_attention=only_cross_attention,
1014
                        upcast_attention=upcast_attention,
1015
                        attention_type=attention_type,
1016
1017
1018
1019
1020
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
1021
1022
                        num_attention_heads,
                        out_channels // num_attention_heads,
1023
1024
1025
1026
1027
                        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
1028
1029
1030
1031
1032
1033
1034
1035
                )
        self.attentions = nn.ModuleList(attentions)
        self.resnets = nn.ModuleList(resnets)

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1036
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
1037
1038
1039
1040
1041
1042
                    )
                ]
            )
        else:
            self.downsamplers = None

1043
1044
        self.gradient_checkpointing = False

1045
    def forward(
1046
1047
1048
1049
1050
1051
1052
        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
1053
        additional_residuals=None,
1054
    ):
Patrick von Platen's avatar
Patrick von Platen committed
1055
1056
        output_states = ()

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

Will Berman's avatar
Will Berman committed
1059
1060
1061
        blocks = list(zip(self.resnets, self.attentions))

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

Will Berman's avatar
Will Berman committed
1064
                def create_custom_forward(module, return_dict=None):
1065
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
1066
1067
1068
1069
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
1070
1071
1072

                    return custom_forward

1073
1074
1075
1076
1077
1078
1079
                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
1080
                hidden_states = attn(
1081
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1082
1083
1084
1085
1086
                    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,
1087
                )[0]
1088
            else:
1089
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
1090
1091
1092
1093
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
1094
1095
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
1096
1097
                    return_dict=False,
                )[0]
1098

Will Berman's avatar
Will Berman committed
1099
1100
1101
1102
            # 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

1103
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1104
1105
1106

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

1109
            output_states = output_states + (hidden_states,)
Patrick von Platen's avatar
Patrick von Platen committed
1110
1111
1112
1113

        return hidden_states, output_states


Patrick von Platen's avatar
Patrick von Platen committed
1114
class DownBlock2D(nn.Module):
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
    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
1129
        downsample_padding=1,
1130
1131
1132
1133
1134
1135
1136
    ):
        super().__init__()
        resnets = []

        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1137
                ResnetBlock2D(
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
                    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
1155
1156
                [
                    Downsample2D(
1157
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
Patrick von Platen's avatar
Patrick von Platen committed
1158
1159
                    )
                ]
1160
1161
1162
1163
            )
        else:
            self.downsamplers = None

1164
1165
        self.gradient_checkpointing = False

1166
    def forward(self, hidden_states, temb=None, scale: float = 1.0):
1167
1168
1169
        output_states = ()

        for resnet in self.resnets:
1170
1171
1172
1173
1174
1175
1176
1177
            if self.training and self.gradient_checkpointing:

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

                    return custom_forward

1178
1179
1180
1181
1182
1183
1184
1185
                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
                    )
1186
            else:
1187
                hidden_states = resnet(hidden_states, temb, scale=scale)
1188

1189
            output_states = output_states + (hidden_states,)
1190
1191
1192

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

1195
            output_states = output_states + (hidden_states,)
1196
1197
1198
1199

        return hidden_states, output_states


1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
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(
1222
                ResnetBlock2D(
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
                    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(
1242
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1243
1244
1245
1246
1247
1248
                    )
                ]
            )
        else:
            self.downsamplers = None

1249
    def forward(self, hidden_states, scale: float = 1.0):
1250
        for resnet in self.resnets:
1251
            hidden_states = resnet(hidden_states, temb=None, scale=scale)
1252
1253
1254

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1255
                hidden_states = downsampler(hidden_states, scale)
1256
1257
1258
1259

        return hidden_states


1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
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,
1272
        attention_head_dim=1,
1273
1274
1275
1276
1277
1278
1279
1280
        output_scale_factor=1.0,
        add_downsample=True,
        downsample_padding=1,
    ):
        super().__init__()
        resnets = []
        attentions = []

1281
1282
1283
1284
1285
1286
        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

1287
1288
1289
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            resnets.append(
1290
                ResnetBlock2D(
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
                    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(
1304
                Attention(
1305
                    out_channels,
1306
1307
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1308
1309
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
1310
                    norm_num_groups=resnet_groups,
1311
1312
1313
1314
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
                )
            )

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

        if add_downsample:
            self.downsamplers = nn.ModuleList(
                [
                    Downsample2D(
1325
                        out_channels, use_conv=True, out_channels=out_channels, padding=downsample_padding, name="op"
1326
1327
1328
1329
1330
1331
                    )
                ]
            )
        else:
            self.downsamplers = None

1332
    def forward(self, hidden_states, scale: float = 1.0):
1333
        for resnet, attn in zip(self.resnets, self.attentions):
1334
1335
1336
            hidden_states = resnet(hidden_states, temb=None, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
1337
1338
1339

        if self.downsamplers is not None:
            for downsampler in self.downsamplers:
1340
                hidden_states = downsampler(hidden_states, scale)
1341
1342
1343
1344

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
1345
class AttnSkipDownBlock2D(nn.Module):
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
    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,
1357
        attention_head_dim=1,
1358
1359
1360
1361
1362
1363
1364
        output_scale_factor=np.sqrt(2.0),
        add_downsample=True,
    ):
        super().__init__()
        self.attentions = nn.ModuleList([])
        self.resnets = nn.ModuleList([])

1365
1366
1367
1368
1369
1370
        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

1371
1372
1373
        for i in range(num_layers):
            in_channels = in_channels if i == 0 else out_channels
            self.resnets.append(
1374
                ResnetBlock2D(
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
                    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(
1389
                Attention(
1390
                    out_channels,
1391
1392
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
1393
1394
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
1395
1396
1397
1398
1399
                    norm_num_groups=32,
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
1400
1401
1402
1403
                )
            )

        if add_downsample:
1404
            self.resnet_down = ResnetBlock2D(
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
                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,
1415
                use_in_shortcut=True,
1416
1417
1418
                down=True,
                kernel="fir",
            )
1419
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1420
1421
1422
1423
1424
1425
            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

1426
    def forward(self, hidden_states, temb=None, skip_sample=None, scale: float = 1.0):
1427
1428
1429
        output_states = ()

        for resnet, attn in zip(self.resnets, self.attentions):
1430
1431
1432
            hidden_states = resnet(hidden_states, temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
1433
1434
1435
            output_states += (hidden_states,)

        if self.downsamplers is not None:
1436
            hidden_states = self.resnet_down(hidden_states, temb, scale=scale)
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
            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
1447
class SkipDownBlock2D(nn.Module):
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
    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(
1469
                ResnetBlock2D(
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
                    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:
1485
            self.resnet_down = ResnetBlock2D(
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
                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,
1496
                use_in_shortcut=True,
1497
1498
1499
                down=True,
                kernel="fir",
            )
1500
            self.downsamplers = nn.ModuleList([FirDownsample2D(out_channels, out_channels=out_channels)])
1501
1502
1503
1504
1505
1506
            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

1507
    def forward(self, hidden_states, temb=None, skip_sample=None, scale: float = 1.0):
1508
1509
1510
        output_states = ()

        for resnet in self.resnets:
1511
            hidden_states = resnet(hidden_states, temb, scale)
1512
1513
1514
            output_states += (hidden_states,)

        if self.downsamplers is not None:
1515
            hidden_states = self.resnet_down(hidden_states, temb, scale)
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
            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
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
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,
1541
        skip_time_act=False,
Will Berman's avatar
Will Berman committed
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
    ):
        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,
1560
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
                )
            )

        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,
1580
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1581
1582
1583
1584
1585
1586
1587
1588
1589
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

1590
    def forward(self, hidden_states, temb=None, scale: float = 1.0):
Will Berman's avatar
Will Berman committed
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
        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

1602
1603
1604
1605
1606
1607
1608
1609
                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
1610
            else:
1611
                hidden_states = resnet(hidden_states, temb, scale)
Will Berman's avatar
Will Berman committed
1612

1613
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1614
1615
1616

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

1619
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636

        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,
1637
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
1638
1639
1640
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_downsample=True,
1641
        skip_time_act=False,
1642
        only_cross_attention=False,
1643
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
1644
1645
1646
1647
1648
1649
1650
1651
    ):
        super().__init__()

        self.has_cross_attention = True

        resnets = []
        attentions = []

1652
1653
        self.attention_head_dim = attention_head_dim
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668

        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,
1669
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1670
1671
                )
            )
1672
1673
1674
1675
1676

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

Will Berman's avatar
Will Berman committed
1677
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
1678
                Attention(
Will Berman's avatar
Will Berman committed
1679
1680
1681
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
1682
                    dim_head=attention_head_dim,
Will Berman's avatar
Will Berman committed
1683
1684
1685
1686
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
1687
                    only_cross_attention=only_cross_attention,
1688
                    cross_attention_norm=cross_attention_norm,
1689
                    processor=processor,
Will Berman's avatar
Will Berman committed
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
                )
            )
        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,
1709
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
1710
1711
1712
1713
1714
1715
1716
1717
1718
                        down=True,
                    )
                ]
            )
        else:
            self.downsamplers = None

        self.gradient_checkpointing = False

1719
    def forward(
1720
1721
1722
1723
1724
1725
1726
        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,
1727
    ):
Will Berman's avatar
Will Berman committed
1728
        output_states = ()
1729
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
Will Berman's avatar
Will Berman committed
1730

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

1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
        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
1744
        for resnet, attn in zip(self.resnets, self.attentions):
1745
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
1746

1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
                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
1757
                hidden_states = attn(
1758
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1759
1760
1761
1762
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
1763
            else:
1764
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
1765
1766
1767
1768

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
1769
                    attention_mask=mask,
1770
1771
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
1772

1773
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1774
1775
1776

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

1779
            output_states = output_states + (hidden_states,)
Will Berman's avatar
Will Berman committed
1780
1781
1782
1783

        return hidden_states, output_states


1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
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

1830
    def forward(self, hidden_states, temb=None, scale: float = 1.0):
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
        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

1842
1843
1844
1845
1846
1847
1848
1849
                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
                    )
1850
            else:
1851
                hidden_states = resnet(hidden_states, temb, scale)
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872

            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,
1873
        attention_head_dim: int = 64,
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
        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,
1906
1907
                    out_channels // attention_head_dim,
                    attention_head_dim,
1908
1909
1910
1911
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
1912
                    cross_attention_norm="layer_norm",
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
                    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(
1928
1929
1930
1931
1932
1933
1934
        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,
1935
1936
    ):
        output_states = ()
1937
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950

        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

1951
1952
1953
1954
1955
1956
1957
                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
1958
                hidden_states = attn(
1959
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
1960
1961
1962
1963
1964
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
1965
                )
1966
            else:
1967
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
1968
1969
1970
1971
1972
1973
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
1974
                    encoder_attention_mask=encoder_attention_mask,
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
                )

            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
1989
class AttnUpBlock2D(nn.Module):
1990
1991
1992
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
1993
1994
        prev_output_channel: int,
        out_channels: int,
1995
1996
1997
1998
1999
2000
2001
2002
        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,
2003
        attention_head_dim=1,
2004
        output_scale_factor=1.0,
2005
        upsample_type="conv",
2006
2007
2008
2009
2010
    ):
        super().__init__()
        resnets = []
        attentions = []

2011
2012
        self.upsample_type = upsample_type

2013
2014
2015
2016
2017
2018
        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

2019
        for i in range(num_layers):
Patrick von Platen's avatar
Patrick von Platen committed
2020
2021
2022
            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

2023
            resnets.append(
2024
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2025
2026
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
                    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(
2038
                Attention(
Patrick von Platen's avatar
Patrick von Platen committed
2039
                    out_channels,
2040
2041
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
2042
                    rescale_output_factor=output_scale_factor,
Patrick von Platen's avatar
Patrick von Platen committed
2043
                    eps=resnet_eps,
Will Berman's avatar
Will Berman committed
2044
                    norm_num_groups=resnet_groups,
2045
2046
2047
2048
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
2049
2050
2051
2052
2053
2054
                )
            )

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

2055
        if upsample_type == "conv":
Patrick von Platen's avatar
Patrick von Platen committed
2056
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
        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,
                    )
                ]
            )
2075
2076
2077
        else:
            self.upsamplers = None

2078
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None, scale: float = 1.0):
2079
2080
2081
2082
2083
2084
        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)

2085
2086
2087
            hidden_states = resnet(hidden_states, temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, **cross_attention_kwargs)
2088
2089
2090

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2091
                if self.upsample_type == "resnet":
2092
                    hidden_states = upsampler(hidden_states, temb=temb, scale=scale)
2093
                else:
2094
                    hidden_states = upsampler(hidden_states, scale=scale)
2095
2096
2097
2098

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2099
class CrossAttnUpBlock2D(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
2100
2101
2102
2103
2104
2105
2106
2107
    def __init__(
        self,
        in_channels: int,
        out_channels: int,
        prev_output_channel: int,
        temb_channels: int,
        dropout: float = 0.0,
        num_layers: int = 1,
2108
        transformer_layers_per_block: int = 1,
Patrick von Platen's avatar
Patrick von Platen committed
2109
2110
2111
2112
2113
        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,
2114
        num_attention_heads=1,
Patrick von Platen's avatar
Patrick von Platen committed
2115
2116
2117
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_upsample=True,
2118
        dual_cross_attention=False,
Suraj Patil's avatar
Suraj Patil committed
2119
        use_linear_projection=False,
2120
        only_cross_attention=False,
2121
        upcast_attention=False,
2122
        attention_type="default",
Patrick von Platen's avatar
Patrick von Platen committed
2123
2124
2125
2126
2127
    ):
        super().__init__()
        resnets = []
        attentions = []

2128
        self.has_cross_attention = True
2129
        self.num_attention_heads = num_attention_heads
Patrick von Platen's avatar
Patrick von Platen committed
2130
2131
2132
2133
2134
2135

        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(
2136
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
                    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,
                )
            )
2149
2150
2151
            if not dual_cross_attention:
                attentions.append(
                    Transformer2DModel(
2152
2153
                        num_attention_heads,
                        out_channels // num_attention_heads,
2154
                        in_channels=out_channels,
2155
                        num_layers=transformer_layers_per_block,
2156
2157
                        cross_attention_dim=cross_attention_dim,
                        norm_num_groups=resnet_groups,
Suraj Patil's avatar
Suraj Patil committed
2158
                        use_linear_projection=use_linear_projection,
2159
                        only_cross_attention=only_cross_attention,
2160
                        upcast_attention=upcast_attention,
2161
                        attention_type=attention_type,
2162
2163
2164
2165
2166
                    )
                )
            else:
                attentions.append(
                    DualTransformer2DModel(
2167
2168
                        num_attention_heads,
                        out_channels // num_attention_heads,
2169
2170
2171
2172
2173
                        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
2174
2175
2176
2177
2178
2179
2180
2181
2182
                )
        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

2183
2184
2185
2186
        self.gradient_checkpointing = False

    def forward(
        self,
2187
2188
2189
2190
2191
2192
2193
2194
        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,
2195
    ):
2196
2197
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0

Patrick von Platen's avatar
Patrick von Platen committed
2198
2199
2200
2201
2202
2203
        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)

2204
2205
            if self.training and self.gradient_checkpointing:

Will Berman's avatar
Will Berman committed
2206
                def create_custom_forward(module, return_dict=None):
2207
                    def custom_forward(*inputs):
Will Berman's avatar
Will Berman committed
2208
2209
2210
2211
                        if return_dict is not None:
                            return module(*inputs, return_dict=return_dict)
                        else:
                            return module(*inputs)
2212
2213
2214

                    return custom_forward

2215
2216
2217
2218
2219
2220
2221
                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
2222
                hidden_states = attn(
2223
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2224
2225
2226
2227
2228
                    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,
2229
                )[0]
2230
            else:
2231
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
2232
2233
2234
2235
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    cross_attention_kwargs=cross_attention_kwargs,
2236
2237
                    attention_mask=attention_mask,
                    encoder_attention_mask=encoder_attention_mask,
2238
2239
                    return_dict=False,
                )[0]
Patrick von Platen's avatar
Patrick von Platen committed
2240
2241
2242

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2243
                hidden_states = upsampler(hidden_states, upsample_size, scale=lora_scale)
Patrick von Platen's avatar
Patrick von Platen committed
2244
2245
2246
2247

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2248
class UpBlock2D(nn.Module):
2249
2250
2251
    def __init__(
        self,
        in_channels: int,
Patrick von Platen's avatar
Patrick von Platen committed
2252
2253
        prev_output_channel: int,
        out_channels: int,
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
        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
2269
2270
2271
            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

2272
            resnets.append(
2273
                ResnetBlock2D(
Patrick von Platen's avatar
Patrick von Platen committed
2274
2275
                    in_channels=resnet_in_channels + res_skip_channels,
                    out_channels=out_channels,
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
                    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
2290
            self.upsamplers = nn.ModuleList([Upsample2D(out_channels, use_conv=True, out_channels=out_channels)])
2291
2292
2293
        else:
            self.upsamplers = None

2294
2295
        self.gradient_checkpointing = False

2296
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None, scale: float = 1.0):
2297
2298
2299
2300
2301
2302
        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)

2303
2304
2305
2306
2307
2308
2309
2310
            if self.training and self.gradient_checkpointing:

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

                    return custom_forward

2311
2312
2313
2314
2315
2316
2317
2318
                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
                    )
2319
            else:
2320
                hidden_states = resnet(hidden_states, temb, scale=scale)
2321
2322
2323

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2324
                hidden_states = upsampler(hidden_states, upsample_size, scale=scale)
2325
2326

        return hidden_states
2327
2328


2329
2330
2331
2332
2333
2334
2335
2336
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
2337
        resnet_time_scale_shift: str = "default",  # default, spatial
2338
2339
2340
2341
2342
        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
2343
        temb_channels=None,
2344
2345
2346
2347
2348
2349
2350
2351
    ):
        super().__init__()
        resnets = []

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

            resnets.append(
2352
                ResnetBlock2D(
2353
2354
                    in_channels=input_channels,
                    out_channels=out_channels,
YiYi Xu's avatar
YiYi Xu committed
2355
                    temb_channels=temb_channels,
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
                    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

2373
    def forward(self, hidden_states, temb=None, scale: float = 1.0):
2374
        for resnet in self.resnets:
2375
            hidden_states = resnet(hidden_states, temb=temb, scale=scale)
2376
2377
2378
2379
2380
2381
2382
2383

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

        return hidden_states


2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
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,
2396
        attention_head_dim=1,
2397
2398
        output_scale_factor=1.0,
        add_upsample=True,
YiYi Xu's avatar
YiYi Xu committed
2399
        temb_channels=None,
2400
2401
2402
2403
2404
    ):
        super().__init__()
        resnets = []
        attentions = []

2405
2406
2407
2408
2409
2410
        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

2411
2412
2413
2414
        for i in range(num_layers):
            input_channels = in_channels if i == 0 else out_channels

            resnets.append(
2415
                ResnetBlock2D(
2416
2417
                    in_channels=input_channels,
                    out_channels=out_channels,
YiYi Xu's avatar
YiYi Xu committed
2418
                    temb_channels=temb_channels,
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
                    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(
2429
                Attention(
2430
                    out_channels,
2431
2432
                    heads=out_channels // attention_head_dim,
                    dim_head=attention_head_dim,
2433
2434
                    rescale_output_factor=output_scale_factor,
                    eps=resnet_eps,
2435
                    norm_num_groups=resnet_groups if resnet_time_scale_shift != "spatial" else None,
YiYi Xu's avatar
YiYi Xu committed
2436
                    spatial_norm_dim=temb_channels if resnet_time_scale_shift == "spatial" else None,
2437
2438
2439
2440
                    residual_connection=True,
                    bias=True,
                    upcast_softmax=True,
                    _from_deprecated_attn_block=True,
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
                )
            )

        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

2452
    def forward(self, hidden_states, temb=None, scale: float = 1.0):
2453
        for resnet, attn in zip(self.resnets, self.attentions):
2454
2455
2456
            hidden_states = resnet(hidden_states, temb=temb, scale=scale)
            cross_attention_kwargs = {"scale": scale}
            hidden_states = attn(hidden_states, temb=temb, **cross_attention_kwargs)
2457
2458
2459

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2460
                hidden_states = upsampler(hidden_states, scale=scale)
2461
2462
2463
2464

        return hidden_states


Patrick von Platen's avatar
Patrick von Platen committed
2465
class AttnSkipUpBlock2D(nn.Module):
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
    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,
2478
        attention_head_dim=1,
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
        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(
2491
                ResnetBlock2D(
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
                    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,
                )
            )

2506
2507
2508
2509
2510
2511
        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

2512
        self.attentions.append(
2513
            Attention(
2514
                out_channels,
2515
2516
                heads=out_channels // attention_head_dim,
                dim_head=attention_head_dim,
2517
2518
                rescale_output_factor=output_scale_factor,
                eps=resnet_eps,
2519
2520
2521
2522
2523
                norm_num_groups=32,
                residual_connection=True,
                bias=True,
                upcast_softmax=True,
                _from_deprecated_attn_block=True,
2524
2525
2526
2527
2528
            )
        )

        self.upsampler = FirUpsample2D(in_channels, out_channels=out_channels)
        if add_upsample:
2529
            self.resnet_up = ResnetBlock2D(
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
                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,
2541
                use_in_shortcut=True,
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
                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

2556
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, skip_sample=None, scale: float = 1.0):
2557
2558
2559
2560
2561
2562
        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)

2563
            hidden_states = resnet(hidden_states, temb, scale=scale)
2564

2565
2566
        cross_attention_kwargs = {"scale": scale}
        hidden_states = self.attentions[0](hidden_states, **cross_attention_kwargs)
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579

        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

2580
            hidden_states = self.resnet_up(hidden_states, temb, scale=scale)
2581
2582
2583
2584

        return hidden_states, skip_sample


Patrick von Platen's avatar
Patrick von Platen committed
2585
class SkipUpBlock2D(nn.Module):
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
    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(
2610
                ResnetBlock2D(
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
                    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:
2627
            self.resnet_up = ResnetBlock2D(
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
                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,
2639
                use_in_shortcut=True,
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
                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

2654
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, skip_sample=None, scale: float = 1.0):
2655
2656
2657
2658
2659
2660
        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)

2661
            hidden_states = resnet(hidden_states, temb, scale=scale)
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674

        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

2675
            hidden_states = self.resnet_up(hidden_states, temb, scale=scale)
2676
2677

        return hidden_states, skip_sample
Will Berman's avatar
Will Berman committed
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695


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,
2696
        skip_time_act=False,
Will Berman's avatar
Will Berman committed
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
    ):
        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,
2717
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
                )
            )

        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,
2737
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2738
2739
2740
2741
2742
2743
2744
2745
2746
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False

2747
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None, scale: float = 1.0):
Will Berman's avatar
Will Berman committed
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
        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

2762
2763
2764
2765
2766
2767
2768
2769
                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
2770
            else:
2771
                hidden_states = resnet(hidden_states, temb, scale=scale)
Will Berman's avatar
Will Berman committed
2772
2773
2774

        if self.upsamplers is not None:
            for upsampler in self.upsamplers:
2775
                hidden_states = upsampler(hidden_states, temb, scale=scale)
Will Berman's avatar
Will Berman committed
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793

        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,
2794
        attention_head_dim=1,
Will Berman's avatar
Will Berman committed
2795
2796
2797
        cross_attention_dim=1280,
        output_scale_factor=1.0,
        add_upsample=True,
2798
        skip_time_act=False,
2799
        only_cross_attention=False,
2800
        cross_attention_norm=None,
Will Berman's avatar
Will Berman committed
2801
2802
2803
2804
2805
2806
    ):
        super().__init__()
        resnets = []
        attentions = []

        self.has_cross_attention = True
2807
        self.attention_head_dim = attention_head_dim
Will Berman's avatar
Will Berman committed
2808

2809
        self.num_heads = out_channels // self.attention_head_dim
Will Berman's avatar
Will Berman committed
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826

        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,
2827
                    skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2828
2829
                )
            )
2830
2831
2832
2833
2834

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

Will Berman's avatar
Will Berman committed
2835
            attentions.append(
Patrick von Platen's avatar
Patrick von Platen committed
2836
                Attention(
Will Berman's avatar
Will Berman committed
2837
2838
2839
                    query_dim=out_channels,
                    cross_attention_dim=out_channels,
                    heads=self.num_heads,
2840
                    dim_head=self.attention_head_dim,
Will Berman's avatar
Will Berman committed
2841
2842
2843
2844
                    added_kv_proj_dim=cross_attention_dim,
                    norm_num_groups=resnet_groups,
                    bias=True,
                    upcast_softmax=True,
2845
                    only_cross_attention=only_cross_attention,
2846
                    cross_attention_norm=cross_attention_norm,
2847
                    processor=processor,
Will Berman's avatar
Will Berman committed
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
                )
            )
        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,
2867
                        skip_time_act=skip_time_act,
Will Berman's avatar
Will Berman committed
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
                        up=True,
                    )
                ]
            )
        else:
            self.upsamplers = None

        self.gradient_checkpointing = False

    def forward(
        self,
2879
2880
2881
2882
2883
2884
2885
2886
        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
2887
    ):
2888
        cross_attention_kwargs = cross_attention_kwargs if cross_attention_kwargs is not None else {}
2889

2890
        lora_scale = cross_attention_kwargs.get("scale", 1.0)
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
        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
2902
2903
2904
2905
2906
2907
2908
        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)

2909
            if self.training and self.gradient_checkpointing:
Will Berman's avatar
Will Berman committed
2910

2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
                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
2921
                hidden_states = attn(
2922
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
2923
2924
2925
2926
                    encoder_hidden_states=encoder_hidden_states,
                    attention_mask=mask,
                    **cross_attention_kwargs,
                )
2927
            else:
2928
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
2929
2930
2931
2932

                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
2933
                    attention_mask=mask,
2934
2935
                    **cross_attention_kwargs,
                )
Will Berman's avatar
Will Berman committed
2936
2937
2938

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

        return hidden_states
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991


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

2992
    def forward(self, hidden_states, res_hidden_states_tuple, temb=None, upsample_size=None, scale: float = 1.0):
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
        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

3006
3007
3008
3009
3010
3011
3012
3013
                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
                    )
3014
            else:
3015
                hidden_states = resnet(hidden_states, temb, scale=scale)
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034

        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,
3035
        attention_head_dim=1,  # attention dim_head
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
        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
3049
        self.attention_head_dim = attention_head_dim
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084

        # 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,
3085
                    k_out_channels // attention_head_dim
3086
                    if (i == num_layers - 1)
3087
3088
                    else out_channels // attention_head_dim,
                    attention_head_dim,
3089
3090
3091
3092
                    cross_attention_dim=cross_attention_dim,
                    temb_channels=temb_channels,
                    attention_bias=True,
                    add_self_attention=add_self_attention,
3093
                    cross_attention_norm="layer_norm",
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
                    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,
3110
3111
3112
3113
3114
3115
3116
3117
        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,
3118
3119
3120
3121
3122
    ):
        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)

3123
        lora_scale = cross_attention_kwargs.get("scale", 1.0) if cross_attention_kwargs is not None else 1.0
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
        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

3136
3137
3138
3139
3140
3141
3142
                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
3143
                hidden_states = attn(
3144
                    hidden_states,
ethansmith2000's avatar
ethansmith2000 committed
3145
3146
3147
3148
3149
3150
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
                    encoder_attention_mask=encoder_attention_mask,
                )
3151
            else:
3152
                hidden_states = resnet(hidden_states, temb, scale=lora_scale)
3153
3154
3155
3156
3157
3158
                hidden_states = attn(
                    hidden_states,
                    encoder_hidden_states=encoder_hidden_states,
                    emb=temb,
                    attention_mask=attention_mask,
                    cross_attention_kwargs=cross_attention_kwargs,
3159
                    encoder_attention_mask=encoder_attention_mask,
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
                )

        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,
3198
        cross_attention_norm: Optional[str] = None,
3199
3200
3201
3202
3203
3204
3205
3206
        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
3207
            self.attn1 = Attention(
3208
3209
3210
3211
3212
3213
                query_dim=dim,
                heads=num_attention_heads,
                dim_head=attention_head_dim,
                dropout=dropout,
                bias=attention_bias,
                cross_attention_dim=None,
3214
                cross_attention_norm=None,
3215
3216
3217
3218
            )

        # 2. Cross-Attn
        self.norm2 = AdaGroupNorm(temb_channels, dim, max(1, dim // group_size))
Patrick von Platen's avatar
Patrick von Platen committed
3219
        self.attn2 = Attention(
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
            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,
3238
3239
3240
3241
3242
3243
3244
3245
        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,
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
    ):
        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,
3259
                attention_mask=attention_mask,
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
                **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,
3274
            attention_mask=attention_mask if encoder_hidden_states is None else encoder_attention_mask,
3275
3276
3277
3278
3279
3280
3281
            **cross_attention_kwargs,
        )
        attn_output = self._to_4d(attn_output, height, weight)

        hidden_states = attn_output + hidden_states

        return hidden_states