unet_ldm.py 39.3 KB
Newer Older
patil-suraj's avatar
patil-suraj committed
1
import math
Patrick von Platen's avatar
Patrick von Platen committed
2
3
from abc import abstractmethod
from inspect import isfunction
patil-suraj's avatar
patil-suraj committed
4
5
6
7
8

import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
Patrick von Platen's avatar
Patrick von Platen committed
9

patil-suraj's avatar
patil-suraj committed
10
11
from ..configuration_utils import ConfigMixin
from ..modeling_utils import ModelMixin
Patrick von Platen's avatar
Patrick von Platen committed
12
from .attention import AttentionBlock
13
from .embeddings import get_timestep_embedding
Patrick von Platen's avatar
Patrick von Platen committed
14
from .resnet import Downsample, ResBlock, TimestepBlock, Upsample
patil-suraj's avatar
patil-suraj committed
15

Patrick von Platen's avatar
Patrick von Platen committed
16

patil-suraj's avatar
patil-suraj committed
17
18
19
20
21
def exists(val):
    return val is not None


def uniq(arr):
Patrick von Platen's avatar
Patrick von Platen committed
22
    return {el: True for el in arr}.keys()
patil-suraj's avatar
patil-suraj committed
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53


def default(val, d):
    if exists(val):
        return val
    return d() if isfunction(d) else d


def max_neg_value(t):
    return -torch.finfo(t.dtype).max


def init_(tensor):
    dim = tensor.shape[-1]
    std = 1 / math.sqrt(dim)
    tensor.uniform_(-std, std)
    return tensor


# feedforward
class GEGLU(nn.Module):
    def __init__(self, dim_in, dim_out):
        super().__init__()
        self.proj = nn.Linear(dim_in, dim_out * 2)

    def forward(self, x):
        x, gate = self.proj(x).chunk(2, dim=-1)
        return x * F.gelu(gate)


class FeedForward(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
54
    def __init__(self, dim, dim_out=None, mult=4, glu=False, dropout=0.0):
patil-suraj's avatar
patil-suraj committed
55
56
57
        super().__init__()
        inner_dim = int(dim * mult)
        dim_out = default(dim_out, dim)
Patrick von Platen's avatar
Patrick von Platen committed
58
59
60
        project_in = nn.Sequential(nn.Linear(dim, inner_dim), nn.GELU()) if not glu else GEGLU(dim, inner_dim)

        self.net = nn.Sequential(project_in, nn.Dropout(dropout), nn.Linear(inner_dim, dim_out))
patil-suraj's avatar
patil-suraj committed
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78

    def forward(self, x):
        return self.net(x)


def zero_module(module):
    """
    Zero out the parameters of a module and return it.
    """
    for p in module.parameters():
        p.detach().zero_()
    return module


def Normalize(in_channels):
    return torch.nn.GroupNorm(num_groups=32, num_channels=in_channels, eps=1e-6, affine=True)


patil-suraj's avatar
cleanup  
patil-suraj committed
79
# class LinearAttention(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#    def __init__(self, dim, heads=4, dim_head=32):
#        super().__init__()
#        self.heads = heads
#        hidden_dim = dim_head * heads
#        self.to_qkv = nn.Conv2d(dim, hidden_dim * 3, 1, bias=False)
#        self.to_out = nn.Conv2d(hidden_dim, dim, 1)
#
#    def forward(self, x):
#        b, c, h, w = x.shape
#        qkv = self.to_qkv(x)
#        q, k, v = rearrange(qkv, "b (qkv heads c) h w -> qkv b heads c (h w)", heads=self.heads, qkv=3)
#        import ipdb; ipdb.set_trace()
#        k = k.softmax(dim=-1)
#        context = torch.einsum("bhdn,bhen->bhde", k, v)
#        out = torch.einsum("bhde,bhdn->bhen", context, q)
#        out = rearrange(out, "b heads c (h w) -> b (heads c) h w", heads=self.heads, h=h, w=w)
#        return self.to_out(out)
#

patil-suraj's avatar
cleanup  
patil-suraj committed
99
# class SpatialSelfAttention(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
#    def __init__(self, in_channels):
#        super().__init__()
#        self.in_channels = in_channels
#
#        self.norm = Normalize(in_channels)
#        self.q = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
#        self.k = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
#        self.v = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
#        self.proj_out = torch.nn.Conv2d(in_channels, in_channels, kernel_size=1, stride=1, padding=0)
#
#    def forward(self, x):
#        h_ = x
#        h_ = self.norm(h_)
#        q = self.q(h_)
#        k = self.k(h_)
#        v = self.v(h_)
#
patil-suraj's avatar
cleanup  
patil-suraj committed
117
# compute attention
Patrick von Platen's avatar
Patrick von Platen committed
118
119
120
121
122
123
124
125
#        b, c, h, w = q.shape
#        q = rearrange(q, "b c h w -> b (h w) c")
#        k = rearrange(k, "b c h w -> b c (h w)")
#        w_ = torch.einsum("bij,bjk->bik", q, k)
#
#        w_ = w_ * (int(c) ** (-0.5))
#        w_ = torch.nn.functional.softmax(w_, dim=2)
#
patil-suraj's avatar
cleanup  
patil-suraj committed
126
# attend to values
Patrick von Platen's avatar
Patrick von Platen committed
127
128
129
130
131
132
133
134
#        v = rearrange(v, "b c h w -> b c (h w)")
#        w_ = rearrange(w_, "b i j -> b j i")
#        h_ = torch.einsum("bij,bjk->bik", v, w_)
#        h_ = rearrange(h_, "b c (h w) -> b c h w", h=h)
#        h_ = self.proj_out(h_)
#
#        return x + h_
#
patil-suraj's avatar
patil-suraj committed
135

patil-suraj's avatar
cleanup  
patil-suraj committed
136

patil-suraj's avatar
patil-suraj committed
137
class CrossAttention(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
138
    def __init__(self, query_dim, context_dim=None, heads=8, dim_head=64, dropout=0.0):
patil-suraj's avatar
patil-suraj committed
139
140
141
142
        super().__init__()
        inner_dim = dim_head * heads
        context_dim = default(context_dim, query_dim)

Patrick von Platen's avatar
Patrick von Platen committed
143
        self.scale = dim_head**-0.5
patil-suraj's avatar
patil-suraj committed
144
145
146
147
148
149
        self.heads = heads

        self.to_q = nn.Linear(query_dim, inner_dim, bias=False)
        self.to_k = nn.Linear(context_dim, inner_dim, bias=False)
        self.to_v = nn.Linear(context_dim, inner_dim, bias=False)

Patrick von Platen's avatar
Patrick von Platen committed
150
        self.to_out = nn.Sequential(nn.Linear(inner_dim, query_dim), nn.Dropout(dropout))
patil-suraj's avatar
patil-suraj committed
151

152
153
154
155
156
157
158
159
160
161
162
163
164
165
    def reshape_heads_to_batch_dim(self, tensor):
        batch_size, seq_len, dim = tensor.shape
        head_size = self.heads
        tensor = tensor.reshape(batch_size, seq_len, head_size, dim // head_size)
        tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size * head_size, seq_len, dim // head_size)
        return tensor

    def reshape_batch_dim_to_heads(self, tensor):
        batch_size, seq_len, dim = tensor.shape
        head_size = self.heads
        tensor = tensor.reshape(batch_size // head_size, head_size, seq_len, dim)
        tensor = tensor.permute(0, 2, 1, 3).reshape(batch_size // head_size, seq_len, dim * head_size)
        return tensor

patil-suraj's avatar
patil-suraj committed
166
    def forward(self, x, context=None, mask=None):
167
168
        batch_size, sequence_length, dim = x.shape

patil-suraj's avatar
patil-suraj committed
169
170
171
172
173
174
175
        h = self.heads

        q = self.to_q(x)
        context = default(context, x)
        k = self.to_k(context)
        v = self.to_v(context)

176
177
178
        q = self.reshape_heads_to_batch_dim(q)
        k = self.reshape_heads_to_batch_dim(k)
        v = self.reshape_heads_to_batch_dim(v)
patil-suraj's avatar
patil-suraj committed
179

Patrick von Platen's avatar
Patrick von Platen committed
180
        sim = torch.einsum("b i d, b j d -> b i j", q, k) * self.scale
patil-suraj's avatar
patil-suraj committed
181
182

        if exists(mask):
183
            mask = mask.reshape(batch_size, -1)
patil-suraj's avatar
patil-suraj committed
184
            max_neg_value = -torch.finfo(sim.dtype).max
185
            mask = mask[:, None, :].repeat(h, 1, 1)
patil-suraj's avatar
patil-suraj committed
186
187
188
189
190
            sim.masked_fill_(~mask, max_neg_value)

        # attention, what we cannot get enough of
        attn = sim.softmax(dim=-1)

Patrick von Platen's avatar
Patrick von Platen committed
191
        out = torch.einsum("b i j, b j d -> b i d", attn, v)
192
        out = self.reshape_batch_dim_to_heads(out)
patil-suraj's avatar
patil-suraj committed
193
194
195
196
        return self.to_out(out)


class BasicTransformerBlock(nn.Module):
Patrick von Platen's avatar
Patrick von Platen committed
197
    def __init__(self, dim, n_heads, d_head, dropout=0.0, context_dim=None, gated_ff=True, checkpoint=True):
patil-suraj's avatar
patil-suraj committed
198
        super().__init__()
Patrick von Platen's avatar
Patrick von Platen committed
199
200
201
        self.attn1 = CrossAttention(
            query_dim=dim, heads=n_heads, dim_head=d_head, dropout=dropout
        )  # is a self-attention
patil-suraj's avatar
patil-suraj committed
202
        self.ff = FeedForward(dim, dropout=dropout, glu=gated_ff)
Patrick von Platen's avatar
Patrick von Platen committed
203
204
205
        self.attn2 = CrossAttention(
            query_dim=dim, context_dim=context_dim, heads=n_heads, dim_head=d_head, dropout=dropout
        )  # is self-attn if context is none
patil-suraj's avatar
patil-suraj committed
206
207
208
209
210
211
212
213
214
215
216
217
218
219
        self.norm1 = nn.LayerNorm(dim)
        self.norm2 = nn.LayerNorm(dim)
        self.norm3 = nn.LayerNorm(dim)
        self.checkpoint = checkpoint

    def forward(self, x, context=None):
        x = self.attn1(self.norm1(x)) + x
        x = self.attn2(self.norm2(x), context=context) + x
        x = self.ff(self.norm3(x)) + x
        return x


class SpatialTransformer(nn.Module):
    """
Patrick von Platen's avatar
Patrick von Platen committed
220
221
    Transformer block for image-like data. First, project the input (aka embedding) and reshape to b, t, d. Then apply
    standard transformer action. Finally, reshape to image
patil-suraj's avatar
patil-suraj committed
222
    """
Patrick von Platen's avatar
Patrick von Platen committed
223
224

    def __init__(self, in_channels, n_heads, d_head, depth=1, dropout=0.0, context_dim=None):
patil-suraj's avatar
patil-suraj committed
225
226
227
228
229
        super().__init__()
        self.in_channels = in_channels
        inner_dim = n_heads * d_head
        self.norm = Normalize(in_channels)

Patrick von Platen's avatar
Patrick von Platen committed
230
        self.proj_in = nn.Conv2d(in_channels, inner_dim, kernel_size=1, stride=1, padding=0)
patil-suraj's avatar
patil-suraj committed
231
232

        self.transformer_blocks = nn.ModuleList(
Patrick von Platen's avatar
Patrick von Platen committed
233
234
235
236
            [
                BasicTransformerBlock(inner_dim, n_heads, d_head, dropout=dropout, context_dim=context_dim)
                for d in range(depth)
            ]
patil-suraj's avatar
patil-suraj committed
237
238
        )

Patrick von Platen's avatar
Patrick von Platen committed
239
        self.proj_out = zero_module(nn.Conv2d(inner_dim, in_channels, kernel_size=1, stride=1, padding=0))
patil-suraj's avatar
patil-suraj committed
240
241
242
243
244
245
246

    def forward(self, x, context=None):
        # note: if no context is given, cross-attention defaults to self-attention
        b, c, h, w = x.shape
        x_in = x
        x = self.norm(x)
        x = self.proj_in(x)
247
        x = x.permute(0, 2, 3, 1).reshape(b, h * w, c)
patil-suraj's avatar
patil-suraj committed
248
249
        for block in self.transformer_blocks:
            x = block(x, context=context)
250
        x = x.reshape(b, h, w, c).permute(0, 3, 1, 2)
patil-suraj's avatar
patil-suraj committed
251
252
253
        x = self.proj_out(x)
        return x + x_in

Patrick von Platen's avatar
Patrick von Platen committed
254

patil-suraj's avatar
patil-suraj committed
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
def convert_module_to_f16(l):
    """
    Convert primitive modules to float16.
    """
    if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
        l.weight.data = l.weight.data.half()
        if l.bias is not None:
            l.bias.data = l.bias.data.half()


def convert_module_to_f32(l):
    """
    Convert primitive modules to float32, undoing convert_module_to_f16().
    """
    if isinstance(l, (nn.Conv1d, nn.Conv2d, nn.Conv3d)):
        l.weight.data = l.weight.data.float()
        if l.bias is not None:
            l.bias.data = l.bias.data.float()


def avg_pool_nd(dims, *args, **kwargs):
    """
    Create a 1D, 2D, or 3D average pooling module.
    """
    if dims == 1:
        return nn.AvgPool1d(*args, **kwargs)
    elif dims == 2:
        return nn.AvgPool2d(*args, **kwargs)
    elif dims == 3:
        return nn.AvgPool3d(*args, **kwargs)
    raise ValueError(f"unsupported dimensions: {dims}")


def conv_nd(dims, *args, **kwargs):
    """
    Create a 1D, 2D, or 3D convolution module.
    """
    if dims == 1:
        return nn.Conv1d(*args, **kwargs)
    elif dims == 2:
        return nn.Conv2d(*args, **kwargs)
    elif dims == 3:
        return nn.Conv3d(*args, **kwargs)
    raise ValueError(f"unsupported dimensions: {dims}")


def linear(*args, **kwargs):
    """
    Create a linear module.
    """
    return nn.Linear(*args, **kwargs)


class GroupNorm32(nn.GroupNorm):
    def __init__(self, num_groups, num_channels, swish, eps=1e-5):
        super().__init__(num_groups=num_groups, num_channels=num_channels, eps=eps)
        self.swish = swish

    def forward(self, x):
        y = super().forward(x.float()).to(x.dtype)
        if self.swish == 1.0:
            y = F.silu(y)
        elif self.swish:
            y = y * F.sigmoid(y * float(self.swish))
        return y


def normalization(channels, swish=0.0):
    """
    Make a standard normalization layer, with an optional swish activation.

Patrick von Platen's avatar
Patrick von Platen committed
326
    :param channels: number of input channels. :return: an nn.Module for normalization.
patil-suraj's avatar
patil-suraj committed
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
    """
    return GroupNorm32(num_channels=channels, num_groups=32, swish=swish)


## go
class AttentionPool2d(nn.Module):
    """
    Adapted from CLIP: https://github.com/openai/CLIP/blob/main/clip/model.py
    """

    def __init__(
        self,
        spacial_dim: int,
        embed_dim: int,
        num_heads_channels: int,
        output_dim: int = None,
    ):
        super().__init__()
Patrick von Platen's avatar
Patrick von Platen committed
345
        self.positional_embedding = nn.Parameter(torch.randn(embed_dim, spacial_dim**2 + 1) / embed_dim**0.5)
patil-suraj's avatar
patil-suraj committed
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
        self.qkv_proj = conv_nd(1, embed_dim, 3 * embed_dim, 1)
        self.c_proj = conv_nd(1, embed_dim, output_dim or embed_dim, 1)
        self.num_heads = embed_dim // num_heads_channels
        self.attention = QKVAttention(self.num_heads)

    def forward(self, x):
        b, c, *_spatial = x.shape
        x = x.reshape(b, c, -1)  # NC(HW)
        x = torch.cat([x.mean(dim=-1, keepdim=True), x], dim=-1)  # NC(HW+1)
        x = x + self.positional_embedding[None, :, :].to(x.dtype)  # NC(HW+1)
        x = self.qkv_proj(x)
        x = self.attention(x)
        x = self.c_proj(x)
        return x[:, :, 0]


Patrick von Platen's avatar
Patrick von Platen committed
362
363
364
365
366
367
368
369
# class TimestepBlock(nn.Module):
#    """
# Any module where forward() takes timestep embeddings as a second argument. #"""
#
#    @abstractmethod
#    def forward(self, x, emb):
#        """
# Apply the module to `x` given `emb` timestep embeddings. #"""
patil-suraj's avatar
patil-suraj committed
370
371
372
373


class TimestepEmbedSequential(nn.Sequential, TimestepBlock):
    """
Patrick von Platen's avatar
Patrick von Platen committed
374
    A sequential module that passes timestep embeddings to the children that support it as an extra input.
patil-suraj's avatar
patil-suraj committed
375
376
377
378
379
380
381
382
383
384
385
386
387
    """

    def forward(self, x, emb, context=None):
        for layer in self:
            if isinstance(layer, TimestepBlock):
                x = layer(x, emb)
            elif isinstance(layer, SpatialTransformer):
                x = layer(x, context)
            else:
                x = layer(x)
        return x


Patrick von Platen's avatar
Patrick von Platen committed
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
# class A_ResBlock(TimestepBlock):
#    """
# A residual block that can optionally change the number of channels. :param channels: the number of input channels. #
:param emb_channels: the number of timestep embedding channels. :param dropout: the rate of dropout. :param #
out_channels: if specified, the number of out channels. :param use_conv: if True and out_channels is specified, use # a
spatial # convolution instead of a smaller 1x1 convolution to change the channels in the skip connection. # :param
dims: determines if the signal is 1D, 2D, or 3D. :param use_checkpoint: if True, use gradient checkpointing # on this
module. :param up: if True, use this block for upsampling. :param down: if True, use this block for # downsampling. #"""
#
#    def __init__(
#        self,
#        channels,
#        emb_channels,
#        dropout,
#        out_channels=None,
#        use_conv=False,
#        use_scale_shift_norm=False,
#        dims=2,
#        use_checkpoint=False,
#        up=False,
#        down=False,
#    ):
#        super().__init__()
#        self.channels = channels
#        self.emb_channels = emb_channels
#        self.dropout = dropout
#        self.out_channels = out_channels or channels
#        self.use_conv = use_conv
#        self.use_checkpoint = use_checkpoint
#        self.use_scale_shift_norm = use_scale_shift_norm
#
#        self.in_layers = nn.Sequential(
#            normalization(channels),
#            nn.SiLU(),
#            conv_nd(dims, channels, self.out_channels, 3, padding=1),
#        )
#
#        self.updown = up or down
#
#        if up:
#            self.h_upd = Upsample(channels, use_conv=False, dims=dims)
#            self.x_upd = Upsample(channels, use_conv=False, dims=dims)
#        elif down:
#            self.h_upd = Downsample(channels, use_conv=False, dims=dims, padding=1, name="op")
#            self.x_upd = Downsample(channels, use_conv=False, dims=dims, padding=1, name="op")
#        else:
#            self.h_upd = self.x_upd = nn.Identity()
#
#        self.emb_layers = nn.Sequential(
#            nn.SiLU(),
#            linear(
#                emb_channels,
#                2 * self.out_channels if use_scale_shift_norm else self.out_channels,
#            ),
#        )
#        self.out_layers = nn.Sequential(
#            normalization(self.out_channels),
#            nn.SiLU(),
#            nn.Dropout(p=dropout),
#            zero_module(conv_nd(dims, self.out_channels, self.out_channels, 3, padding=1)),
#        )
#
#        if self.out_channels == channels:
#            self.skip_connection = nn.Identity()
#        elif use_conv:
#            self.skip_connection = conv_nd(dims, channels, self.out_channels, 3, padding=1)
#        else:
#            self.skip_connection = conv_nd(dims, channels, self.out_channels, 1)
#
#    def forward(self, x, emb):
#        if self.updown:
#            in_rest, in_conv = self.in_layers[:-1], self.in_layers[-1]
#            h = in_rest(x)
#            h = self.h_upd(h)
#            x = self.x_upd(x)
#            h = in_conv(h)
#        else:
#            h = self.in_layers(x)
#        emb_out = self.emb_layers(emb).type(h.dtype)
#        while len(emb_out.shape) < len(h.shape):
#            emb_out = emb_out[..., None]
#        if self.use_scale_shift_norm:
#            out_norm, out_rest = self.out_layers[0], self.out_layers[1:]
#            scale, shift = torch.chunk(emb_out, 2, dim=1)
#            h = out_norm(h) * (1 + scale) + shift
#            h = out_rest(h)
#        else:
#            h = h + emb_out
#            h = self.out_layers(h)
#        return self.skip_connection(x) + h
#
patil-suraj's avatar
patil-suraj committed
479
480
481
482
483
484
485
486
487
488
489
490
491


class QKVAttention(nn.Module):
    """
    A module which performs QKV attention and splits in a different order.
    """

    def __init__(self, n_heads):
        super().__init__()
        self.n_heads = n_heads

    def forward(self, qkv):
        """
Patrick von Platen's avatar
Patrick von Platen committed
492
493
        Apply QKV attention. :param qkv: an [N x (3 * H * C) x T] tensor of Qs, Ks, and Vs. :return: an [N x (H * C) x
        T] tensor after attention.
patil-suraj's avatar
patil-suraj committed
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
        """
        bs, width, length = qkv.shape
        assert width % (3 * self.n_heads) == 0
        ch = width // (3 * self.n_heads)
        q, k, v = qkv.chunk(3, dim=1)
        scale = 1 / math.sqrt(math.sqrt(ch))
        weight = torch.einsum(
            "bct,bcs->bts",
            (q * scale).view(bs * self.n_heads, ch, length),
            (k * scale).view(bs * self.n_heads, ch, length),
        )  # More stable with f16 than dividing afterwards
        weight = torch.softmax(weight.float(), dim=-1).type(weight.dtype)
        a = torch.einsum("bts,bcs->bct", weight, v.reshape(bs * self.n_heads, ch, length))
        return a.reshape(bs, -1, length)

    @staticmethod
    def count_flops(model, _x, y):
        return count_flops_attn(model, _x, y)


def count_flops_attn(model, _x, y):
    """
Patrick von Platen's avatar
Patrick von Platen committed
516
    A counter for the `thop` package to count the operations in an attention operation. Meant to be used like:
patil-suraj's avatar
patil-suraj committed
517
        macs, params = thop.profile(
Patrick von Platen's avatar
Patrick von Platen committed
518
            model, inputs=(inputs, timestamps), custom_ops={QKVAttention: QKVAttention.count_flops},
patil-suraj's avatar
patil-suraj committed
519
520
521
522
523
524
525
        )
    """
    b, c, *spatial = y[0].shape
    num_spatial = int(np.prod(spatial))
    # We perform two matmuls with the same number of ops.
    # The first computes the weight matrix, the second computes
    # the combination of the value vectors.
Patrick von Platen's avatar
Patrick von Platen committed
526
    matmul_ops = 2 * b * (num_spatial**2) * c
patil-suraj's avatar
patil-suraj committed
527
528
529
    model.total_ops += torch.DoubleTensor([matmul_ops])


patil-suraj's avatar
patil-suraj committed
530
class UNetLDMModel(ModelMixin, ConfigMixin):
patil-suraj's avatar
patil-suraj committed
531
    """
Patrick von Platen's avatar
Patrick von Platen committed
532
533
534
535
536
537
538
539
    The full UNet model with attention and timestep embedding. :param in_channels: channels in the input Tensor. :param
    model_channels: base channel count for the model. :param out_channels: channels in the output Tensor. :param
    num_res_blocks: number of residual blocks per downsample. :param attention_resolutions: a collection of downsample
    rates at which
        attention will take place. May be a set, list, or tuple. For example, if this contains 4, then at 4x
        downsampling, attention will be used.
    :param dropout: the dropout probability. :param channel_mult: channel multiplier for each level of the UNet. :param
    conv_resample: if True, use learned convolutions for upsampling and
patil-suraj's avatar
patil-suraj committed
540
        downsampling.
Patrick von Platen's avatar
Patrick von Platen committed
541
542
    :param dims: determines if the signal is 1D, 2D, or 3D. :param num_classes: if specified (as an int), then this
    model will be
patil-suraj's avatar
patil-suraj committed
543
        class-conditional with `num_classes` classes.
Patrick von Platen's avatar
Patrick von Platen committed
544
545
    :param use_checkpoint: use gradient checkpointing to reduce memory usage. :param num_heads: the number of attention
    heads in each attention layer. :param num_heads_channels: if specified, ignore num_heads and instead use
patil-suraj's avatar
patil-suraj committed
546
547
548
                               a fixed channel width per attention head.
    :param num_heads_upsample: works with num_heads to set a different number
                               of heads for upsampling. Deprecated.
Patrick von Platen's avatar
Patrick von Platen committed
549
550
    :param use_scale_shift_norm: use a FiLM-like conditioning mechanism. :param resblock_updown: use residual blocks
    for up/downsampling. :param use_new_attention_order: use a different attention pattern for potentially
patil-suraj's avatar
patil-suraj committed
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
                                    increased efficiency.
    """

    def __init__(
        self,
        image_size,
        in_channels,
        model_channels,
        out_channels,
        num_res_blocks,
        attention_resolutions,
        dropout=0,
        channel_mult=(1, 2, 4, 8),
        conv_resample=True,
        dims=2,
        num_classes=None,
        use_checkpoint=False,
        use_fp16=False,
        num_heads=-1,
        num_head_channels=-1,
        num_heads_upsample=-1,
        use_scale_shift_norm=False,
        resblock_updown=False,
        use_new_attention_order=False,
Patrick von Platen's avatar
Patrick von Platen committed
575
576
577
578
        use_spatial_transformer=False,  # custom transformer support
        transformer_depth=1,  # custom transformer support
        context_dim=None,  # custom transformer support
        n_embed=None,  # custom support for prediction of discrete ids into codebook of first stage vq model
patil-suraj's avatar
patil-suraj committed
579
580
581
        legacy=True,
    ):
        super().__init__()
Patrick von Platen's avatar
Patrick von Platen committed
582

patil-suraj's avatar
patil-suraj committed
583
        # register all __init__ params with self.register
584
        self.register_to_config(
patil-suraj's avatar
patil-suraj committed
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
            image_size=image_size,
            in_channels=in_channels,
            model_channels=model_channels,
            out_channels=out_channels,
            num_res_blocks=num_res_blocks,
            attention_resolutions=attention_resolutions,
            dropout=dropout,
            channel_mult=channel_mult,
            conv_resample=conv_resample,
            dims=dims,
            num_classes=num_classes,
            use_checkpoint=use_checkpoint,
            use_fp16=use_fp16,
            num_heads=num_heads,
            num_head_channels=num_head_channels,
            num_heads_upsample=num_heads_upsample,
            use_scale_shift_norm=use_scale_shift_norm,
            resblock_updown=resblock_updown,
            use_new_attention_order=use_new_attention_order,
            use_spatial_transformer=use_spatial_transformer,
            transformer_depth=transformer_depth,
            context_dim=context_dim,
            n_embed=n_embed,
            legacy=legacy,
        )

        if use_spatial_transformer:
Patrick von Platen's avatar
Patrick von Platen committed
612
613
614
            assert (
                context_dim is not None
            ), "Fool!! You forgot to include the dimension of your cross-attention conditioning..."
patil-suraj's avatar
patil-suraj committed
615
616

        if context_dim is not None:
Patrick von Platen's avatar
Patrick von Platen committed
617
618
619
            assert (
                use_spatial_transformer
            ), "Fool!! You forgot to use the spatial transformer for your cross-attention conditioning..."
patil-suraj's avatar
patil-suraj committed
620
621
622
623
624

        if num_heads_upsample == -1:
            num_heads_upsample = num_heads

        if num_heads == -1:
Patrick von Platen's avatar
Patrick von Platen committed
625
            assert num_head_channels != -1, "Either num_heads or num_head_channels has to be set"
patil-suraj's avatar
patil-suraj committed
626
627

        if num_head_channels == -1:
Patrick von Platen's avatar
Patrick von Platen committed
628
            assert num_heads != -1, "Either num_heads or num_head_channels has to be set"
patil-suraj's avatar
patil-suraj committed
629
630
631
632
633
634
635
636
637
638
639
640

        self.image_size = image_size
        self.in_channels = in_channels
        self.model_channels = model_channels
        self.out_channels = out_channels
        self.num_res_blocks = num_res_blocks
        self.attention_resolutions = attention_resolutions
        self.dropout = dropout
        self.channel_mult = channel_mult
        self.conv_resample = conv_resample
        self.num_classes = num_classes
        self.use_checkpoint = use_checkpoint
patil-suraj's avatar
patil-suraj committed
641
        self.dtype_ = torch.float16 if use_fp16 else torch.float32
patil-suraj's avatar
patil-suraj committed
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
        self.num_heads = num_heads
        self.num_head_channels = num_head_channels
        self.num_heads_upsample = num_heads_upsample
        self.predict_codebook_ids = n_embed is not None

        time_embed_dim = model_channels * 4
        self.time_embed = nn.Sequential(
            linear(model_channels, time_embed_dim),
            nn.SiLU(),
            linear(time_embed_dim, time_embed_dim),
        )

        if self.num_classes is not None:
            self.label_emb = nn.Embedding(num_classes, time_embed_dim)

        self.input_blocks = nn.ModuleList(
Patrick von Platen's avatar
Patrick von Platen committed
658
            [TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))]
patil-suraj's avatar
patil-suraj committed
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
        )
        self._feature_size = model_channels
        input_block_chans = [model_channels]
        ch = model_channels
        ds = 1
        for level, mult in enumerate(channel_mult):
            for _ in range(num_res_blocks):
                layers = [
                    ResBlock(
                        ch,
                        time_embed_dim,
                        dropout,
                        out_channels=mult * model_channels,
                        dims=dims,
                        use_checkpoint=use_checkpoint,
                        use_scale_shift_norm=use_scale_shift_norm,
                    )
                ]
                ch = mult * model_channels
                if ds in attention_resolutions:
                    if num_head_channels == -1:
                        dim_head = ch // num_heads
                    else:
                        num_heads = ch // num_head_channels
                        dim_head = num_head_channels
                    if legacy:
Patrick von Platen's avatar
Patrick von Platen committed
685
                        # num_heads = 1
patil-suraj's avatar
patil-suraj committed
686
687
688
689
690
691
692
693
                        dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
                    layers.append(
                        AttentionBlock(
                            ch,
                            use_checkpoint=use_checkpoint,
                            num_heads=num_heads,
                            num_head_channels=dim_head,
                            use_new_attention_order=use_new_attention_order,
Patrick von Platen's avatar
Patrick von Platen committed
694
695
696
                        )
                        if not use_spatial_transformer
                        else SpatialTransformer(
patil-suraj's avatar
patil-suraj committed
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
                            ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
                        )
                    )
                self.input_blocks.append(TimestepEmbedSequential(*layers))
                self._feature_size += ch
                input_block_chans.append(ch)
            if level != len(channel_mult) - 1:
                out_ch = ch
                self.input_blocks.append(
                    TimestepEmbedSequential(
                        ResBlock(
                            ch,
                            time_embed_dim,
                            dropout,
                            out_channels=out_ch,
                            dims=dims,
                            use_checkpoint=use_checkpoint,
                            use_scale_shift_norm=use_scale_shift_norm,
                            down=True,
                        )
                        if resblock_updown
patil-suraj's avatar
patil-suraj committed
718
719
720
                        else Downsample(
                            ch, use_conv=conv_resample, dims=dims, out_channels=out_ch, padding=1, name="op"
                        )
patil-suraj's avatar
patil-suraj committed
721
722
723
724
725
726
727
728
729
730
731
732
733
                    )
                )
                ch = out_ch
                input_block_chans.append(ch)
                ds *= 2
                self._feature_size += ch

        if num_head_channels == -1:
            dim_head = ch // num_heads
        else:
            num_heads = ch // num_head_channels
            dim_head = num_head_channels
        if legacy:
Patrick von Platen's avatar
Patrick von Platen committed
734
            # num_heads = 1
patil-suraj's avatar
patil-suraj committed
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
            dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
        self.middle_block = TimestepEmbedSequential(
            ResBlock(
                ch,
                time_embed_dim,
                dropout,
                dims=dims,
                use_checkpoint=use_checkpoint,
                use_scale_shift_norm=use_scale_shift_norm,
            ),
            AttentionBlock(
                ch,
                use_checkpoint=use_checkpoint,
                num_heads=num_heads,
                num_head_channels=dim_head,
                use_new_attention_order=use_new_attention_order,
Patrick von Platen's avatar
Patrick von Platen committed
751
752
753
            )
            if not use_spatial_transformer
            else SpatialTransformer(ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim),
patil-suraj's avatar
patil-suraj committed
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
            ResBlock(
                ch,
                time_embed_dim,
                dropout,
                dims=dims,
                use_checkpoint=use_checkpoint,
                use_scale_shift_norm=use_scale_shift_norm,
            ),
        )
        self._feature_size += ch

        self.output_blocks = nn.ModuleList([])
        for level, mult in list(enumerate(channel_mult))[::-1]:
            for i in range(num_res_blocks + 1):
                ich = input_block_chans.pop()
                layers = [
                    ResBlock(
                        ch + ich,
                        time_embed_dim,
                        dropout,
                        out_channels=model_channels * mult,
                        dims=dims,
                        use_checkpoint=use_checkpoint,
                        use_scale_shift_norm=use_scale_shift_norm,
                    )
                ]
                ch = model_channels * mult
                if ds in attention_resolutions:
                    if num_head_channels == -1:
                        dim_head = ch // num_heads
                    else:
                        num_heads = ch // num_head_channels
                        dim_head = num_head_channels
                    if legacy:
Patrick von Platen's avatar
Patrick von Platen committed
788
                        # num_heads = 1
patil-suraj's avatar
patil-suraj committed
789
790
791
792
793
794
795
796
                        dim_head = ch // num_heads if use_spatial_transformer else num_head_channels
                    layers.append(
                        AttentionBlock(
                            ch,
                            use_checkpoint=use_checkpoint,
                            num_heads=num_heads_upsample,
                            num_head_channels=dim_head,
                            use_new_attention_order=use_new_attention_order,
Patrick von Platen's avatar
Patrick von Platen committed
797
798
799
                        )
                        if not use_spatial_transformer
                        else SpatialTransformer(
patil-suraj's avatar
patil-suraj committed
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
                            ch, num_heads, dim_head, depth=transformer_depth, context_dim=context_dim
                        )
                    )
                if level and i == num_res_blocks:
                    out_ch = ch
                    layers.append(
                        ResBlock(
                            ch,
                            time_embed_dim,
                            dropout,
                            out_channels=out_ch,
                            dims=dims,
                            use_checkpoint=use_checkpoint,
                            use_scale_shift_norm=use_scale_shift_norm,
                            up=True,
                        )
                        if resblock_updown
patil-suraj's avatar
patil-suraj committed
817
                        else Upsample(ch, use_conv=conv_resample, dims=dims, out_channels=out_ch)
patil-suraj's avatar
patil-suraj committed
818
819
820
821
822
823
824
825
826
827
828
829
                    )
                    ds //= 2
                self.output_blocks.append(TimestepEmbedSequential(*layers))
                self._feature_size += ch

        self.out = nn.Sequential(
            normalization(ch),
            nn.SiLU(),
            zero_module(conv_nd(dims, model_channels, out_channels, 3, padding=1)),
        )
        if self.predict_codebook_ids:
            self.id_predictor = nn.Sequential(
Patrick von Platen's avatar
Patrick von Platen committed
830
831
832
833
                normalization(ch),
                conv_nd(dims, model_channels, n_embed, 1),
                # nn.LogSoftmax(dim=1)  # change to cross_entropy and produce non-normalized logits
            )
patil-suraj's avatar
patil-suraj committed
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850

    def convert_to_fp16(self):
        """
        Convert the torso of the model to float16.
        """
        self.input_blocks.apply(convert_module_to_f16)
        self.middle_block.apply(convert_module_to_f16)
        self.output_blocks.apply(convert_module_to_f16)

    def convert_to_fp32(self):
        """
        Convert the torso of the model to float32.
        """
        self.input_blocks.apply(convert_module_to_f32)
        self.middle_block.apply(convert_module_to_f32)
        self.output_blocks.apply(convert_module_to_f32)

Patrick von Platen's avatar
Patrick von Platen committed
851
    def forward(self, x, timesteps=None, context=None, y=None, **kwargs):
patil-suraj's avatar
patil-suraj committed
852
        """
Patrick von Platen's avatar
Patrick von Platen committed
853
854
855
        Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch
        of timesteps. :param context: conditioning plugged in via crossattn :param y: an [N] Tensor of labels, if
        class-conditional. :return: an [N x C x ...] Tensor of outputs.
patil-suraj's avatar
patil-suraj committed
856
857
858
859
860
        """
        assert (y is not None) == (
            self.num_classes is not None
        ), "must specify y if and only if the model is class-conditional"
        hs = []
patil-suraj's avatar
patil-suraj committed
861
862
        if not torch.is_tensor(timesteps):
            timesteps = torch.tensor([timesteps], dtype=torch.long, device=x.device)
863
        t_emb = get_timestep_embedding(timesteps, self.model_channels, flip_sin_to_cos=True, downscale_freq_shift=0)
patil-suraj's avatar
patil-suraj committed
864
865
866
867
868
869
        emb = self.time_embed(t_emb)

        if self.num_classes is not None:
            assert y.shape == (x.shape[0],)
            emb = emb + self.label_emb(y)

patil-suraj's avatar
patil-suraj committed
870
        h = x.type(self.dtype_)
patil-suraj's avatar
patil-suraj committed
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
        for module in self.input_blocks:
            h = module(h, emb, context)
            hs.append(h)
        h = self.middle_block(h, emb, context)
        for module in self.output_blocks:
            h = torch.cat([h, hs.pop()], dim=1)
            h = module(h, emb, context)
        h = h.type(x.dtype)
        if self.predict_codebook_ids:
            return self.id_predictor(h)
        else:
            return self.out(h)


class EncoderUNetModel(nn.Module):
    """
Patrick von Platen's avatar
Patrick von Platen committed
887
    The half UNet model with attention and timestep embedding. For usage, see UNet.
patil-suraj's avatar
patil-suraj committed
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
    """

    def __init__(
        self,
        image_size,
        in_channels,
        model_channels,
        out_channels,
        num_res_blocks,
        attention_resolutions,
        dropout=0,
        channel_mult=(1, 2, 4, 8),
        conv_resample=True,
        dims=2,
        use_checkpoint=False,
        use_fp16=False,
        num_heads=1,
        num_head_channels=-1,
        num_heads_upsample=-1,
        use_scale_shift_norm=False,
        resblock_updown=False,
        use_new_attention_order=False,
        pool="adaptive",
        *args,
Patrick von Platen's avatar
Patrick von Platen committed
912
        **kwargs,
patil-suraj's avatar
patil-suraj committed
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
    ):
        super().__init__()

        if num_heads_upsample == -1:
            num_heads_upsample = num_heads

        self.in_channels = in_channels
        self.model_channels = model_channels
        self.out_channels = out_channels
        self.num_res_blocks = num_res_blocks
        self.attention_resolutions = attention_resolutions
        self.dropout = dropout
        self.channel_mult = channel_mult
        self.conv_resample = conv_resample
        self.use_checkpoint = use_checkpoint
        self.dtype = torch.float16 if use_fp16 else torch.float32
        self.num_heads = num_heads
        self.num_head_channels = num_head_channels
        self.num_heads_upsample = num_heads_upsample

        time_embed_dim = model_channels * 4
        self.time_embed = nn.Sequential(
            linear(model_channels, time_embed_dim),
            nn.SiLU(),
            linear(time_embed_dim, time_embed_dim),
        )

        self.input_blocks = nn.ModuleList(
Patrick von Platen's avatar
Patrick von Platen committed
941
            [TimestepEmbedSequential(conv_nd(dims, in_channels, model_channels, 3, padding=1))]
patil-suraj's avatar
patil-suraj committed
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
        )
        self._feature_size = model_channels
        input_block_chans = [model_channels]
        ch = model_channels
        ds = 1
        for level, mult in enumerate(channel_mult):
            for _ in range(num_res_blocks):
                layers = [
                    ResBlock(
                        ch,
                        time_embed_dim,
                        dropout,
                        out_channels=mult * model_channels,
                        dims=dims,
                        use_checkpoint=use_checkpoint,
                        use_scale_shift_norm=use_scale_shift_norm,
                    )
                ]
                ch = mult * model_channels
                if ds in attention_resolutions:
                    layers.append(
                        AttentionBlock(
                            ch,
                            use_checkpoint=use_checkpoint,
                            num_heads=num_heads,
                            num_head_channels=num_head_channels,
                            use_new_attention_order=use_new_attention_order,
                        )
                    )
                self.input_blocks.append(TimestepEmbedSequential(*layers))
                self._feature_size += ch
                input_block_chans.append(ch)
            if level != len(channel_mult) - 1:
                out_ch = ch
                self.input_blocks.append(
                    TimestepEmbedSequential(
                        ResBlock(
                            ch,
                            time_embed_dim,
                            dropout,
                            out_channels=out_ch,
                            dims=dims,
                            use_checkpoint=use_checkpoint,
                            use_scale_shift_norm=use_scale_shift_norm,
                            down=True,
                        )
                        if resblock_updown
patil-suraj's avatar
patil-suraj committed
989
990
991
                        else Downsample(
                            ch, use_conv=conv_resample, dims=dims, out_channels=out_ch, padding=1, name="op"
                        )
patil-suraj's avatar
patil-suraj committed
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
                    )
                )
                ch = out_ch
                input_block_chans.append(ch)
                ds *= 2
                self._feature_size += ch

        self.middle_block = TimestepEmbedSequential(
            ResBlock(
                ch,
                time_embed_dim,
                dropout,
                dims=dims,
                use_checkpoint=use_checkpoint,
                use_scale_shift_norm=use_scale_shift_norm,
            ),
            AttentionBlock(
                ch,
                use_checkpoint=use_checkpoint,
                num_heads=num_heads,
                num_head_channels=num_head_channels,
                use_new_attention_order=use_new_attention_order,
            ),
            ResBlock(
                ch,
                time_embed_dim,
                dropout,
                dims=dims,
                use_checkpoint=use_checkpoint,
                use_scale_shift_norm=use_scale_shift_norm,
            ),
        )
        self._feature_size += ch
        self.pool = pool
        if pool == "adaptive":
            self.out = nn.Sequential(
                normalization(ch),
                nn.SiLU(),
                nn.AdaptiveAvgPool2d((1, 1)),
                zero_module(conv_nd(dims, ch, out_channels, 1)),
                nn.Flatten(),
            )
        elif pool == "attention":
            assert num_head_channels != -1
            self.out = nn.Sequential(
                normalization(ch),
                nn.SiLU(),
Patrick von Platen's avatar
Patrick von Platen committed
1039
                AttentionPool2d((image_size // ds), ch, num_head_channels, out_channels),
patil-suraj's avatar
patil-suraj committed
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
            )
        elif pool == "spatial":
            self.out = nn.Sequential(
                nn.Linear(self._feature_size, 2048),
                nn.ReLU(),
                nn.Linear(2048, self.out_channels),
            )
        elif pool == "spatial_v2":
            self.out = nn.Sequential(
                nn.Linear(self._feature_size, 2048),
                normalization(2048),
                nn.SiLU(),
                nn.Linear(2048, self.out_channels),
            )
        else:
            raise NotImplementedError(f"Unexpected {pool} pooling")

    def convert_to_fp16(self):
        """
        Convert the torso of the model to float16.
        """
        self.input_blocks.apply(convert_module_to_f16)
        self.middle_block.apply(convert_module_to_f16)

    def convert_to_fp32(self):
        """
        Convert the torso of the model to float32.
        """
        self.input_blocks.apply(convert_module_to_f32)
        self.middle_block.apply(convert_module_to_f32)

    def forward(self, x, timesteps):
        """
Patrick von Platen's avatar
Patrick von Platen committed
1073
1074
        Apply the model to an input batch. :param x: an [N x C x ...] Tensor of inputs. :param timesteps: a 1-D batch
        of timesteps. :return: an [N x K] Tensor of outputs.
patil-suraj's avatar
patil-suraj committed
1075
        """
1076
1077
1078
        emb = self.time_embed(
            get_timestep_embedding(timesteps, self.model_channels, flip_sin_to_cos=True, downscale_freq_shift=0)
        )
patil-suraj's avatar
patil-suraj committed
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093

        results = []
        h = x.type(self.dtype)
        for module in self.input_blocks:
            h = module(h, emb)
            if self.pool.startswith("spatial"):
                results.append(h.type(x.dtype).mean(dim=(2, 3)))
        h = self.middle_block(h, emb)
        if self.pool.startswith("spatial"):
            results.append(h.type(x.dtype).mean(dim=(2, 3)))
            h = torch.cat(results, axis=-1)
            return self.out(h)
        else:
            h = h.type(x.dtype)
            return self.out(h)