test_layers_utils.py 22.2 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
# coding=utf-8
2
# Copyright 2025 HuggingFace Inc.
Patrick von Platen's avatar
Patrick von Platen committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#
# 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.


import unittest

import numpy as np
import torch
Will Berman's avatar
Will Berman committed
21
from torch import nn
Patrick von Platen's avatar
Patrick von Platen committed
22

23
from diffusers.models.attention import GEGLU, AdaLayerNorm, ApproximateGELU
24
from diffusers.models.embeddings import get_timestep_embedding
Erin's avatar
Erin committed
25
from diffusers.models.resnet import Downsample2D, ResnetBlock2D, Upsample2D
26
from diffusers.models.transformers.transformer_2d import Transformer2DModel
27
28

from ..testing_utils import (
Arsalan's avatar
Arsalan committed
29
30
    backend_manual_seed,
    require_torch_accelerator_with_fp64,
31
    require_torch_version_greater_equal,
Arsalan's avatar
Arsalan committed
32
33
    torch_device,
)
Patrick von Platen's avatar
Patrick von Platen committed
34
35


36
37
class EmbeddingsTests(unittest.TestCase):
    def test_timestep_embeddings(self):
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
        embedding_dim = 256
        timesteps = torch.arange(16)

        t1 = get_timestep_embedding(timesteps, embedding_dim)

        # first vector should always be composed only of 0's and 1's
        assert (t1[0, : embedding_dim // 2] - 0).abs().sum() < 1e-5
        assert (t1[0, embedding_dim // 2 :] - 1).abs().sum() < 1e-5

        # last element of each vector should be one
        assert (t1[:, -1] - 1).abs().sum() < 1e-5

        # For large embeddings (e.g. 128) the frequency of every vector is higher
        # than the previous one which means that the gradients of later vectors are
        # ALWAYS higher than the previous ones
        grad_mean = np.abs(np.gradient(t1, axis=-1)).mean(axis=1)

        prev_grad = 0.0
        for grad in grad_mean:
            assert grad > prev_grad
            prev_grad = grad

    def test_timestep_flip_sin_cos(self):
        embedding_dim = 16
        timesteps = torch.arange(10)

        t1 = get_timestep_embedding(timesteps, embedding_dim, flip_sin_to_cos=True)
        t1 = torch.cat([t1[:, embedding_dim // 2 :], t1[:, : embedding_dim // 2]], dim=-1)

        t2 = get_timestep_embedding(timesteps, embedding_dim, flip_sin_to_cos=False)

        assert torch.allclose(t1.cpu(), t2.cpu(), 1e-3)

    def test_timestep_downscale_freq_shift(self):
        embedding_dim = 16
        timesteps = torch.arange(10)

        t1 = get_timestep_embedding(timesteps, embedding_dim, downscale_freq_shift=0)
        t2 = get_timestep_embedding(timesteps, embedding_dim, downscale_freq_shift=1)

        # get cosine half (vectors that are wrapped into cosine)
        cosine_half = (t1 - t2)[:, embedding_dim // 2 :]

        # cosine needs to be negative
        assert (np.abs((cosine_half <= 0).numpy()) - 1).sum() < 1e-5
Patrick von Platen's avatar
Patrick von Platen committed
83

84
85
86
    def test_sinoid_embeddings_hardcoded(self):
        embedding_dim = 64
        timesteps = torch.arange(128)
Patrick von Platen's avatar
Patrick von Platen committed
87

88
89
90
91
92
93
        # standard unet, score_vde
        t1 = get_timestep_embedding(timesteps, embedding_dim, downscale_freq_shift=1, flip_sin_to_cos=False)
        # glide, ldm
        t2 = get_timestep_embedding(timesteps, embedding_dim, downscale_freq_shift=0, flip_sin_to_cos=True)
        # grad-tts
        t3 = get_timestep_embedding(timesteps, embedding_dim, scale=1000)
Patrick von Platen's avatar
Patrick von Platen committed
94

95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
        assert torch.allclose(
            t1[23:26, 47:50].flatten().cpu(),
            torch.tensor([0.9646, 0.9804, 0.9892, 0.9615, 0.9787, 0.9882, 0.9582, 0.9769, 0.9872]),
            1e-3,
        )
        assert torch.allclose(
            t2[23:26, 47:50].flatten().cpu(),
            torch.tensor([0.3019, 0.2280, 0.1716, 0.3146, 0.2377, 0.1790, 0.3272, 0.2474, 0.1864]),
            1e-3,
        )
        assert torch.allclose(
            t3[23:26, 47:50].flatten().cpu(),
            torch.tensor([-0.9801, -0.9464, -0.9349, -0.3952, 0.8887, -0.9709, 0.5299, -0.2853, -0.9927]),
            1e-3,
        )
patil-suraj's avatar
patil-suraj committed
110
111


112
class Upsample2DBlockTests(unittest.TestCase):
patil-suraj's avatar
patil-suraj committed
113
114
115
    def test_upsample_default(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 32, 32)
116
        upsample = Upsample2D(channels=32, use_conv=False)
patil-suraj's avatar
patil-suraj committed
117
118
119
120
121
122
123
124
        with torch.no_grad():
            upsampled = upsample(sample)

        assert upsampled.shape == (1, 32, 64, 64)
        output_slice = upsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([-0.2173, -1.2079, -1.2079, 0.2952, 1.1254, 1.1254, 0.2952, 1.1254, 1.1254])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    @require_torch_version_greater_equal("2.1")
    def test_upsample_bfloat16(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 32, 32).to(torch.bfloat16)
        upsample = Upsample2D(channels=32, use_conv=False)
        with torch.no_grad():
            upsampled = upsample(sample)

        assert upsampled.shape == (1, 32, 64, 64)
        output_slice = upsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [-0.2173, -1.2079, -1.2079, 0.2952, 1.1254, 1.1254, 0.2952, 1.1254, 1.1254], dtype=torch.bfloat16
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

patil-suraj's avatar
patil-suraj committed
140
141
142
    def test_upsample_with_conv(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 32, 32)
143
        upsample = Upsample2D(channels=32, use_conv=True)
patil-suraj's avatar
patil-suraj committed
144
145
146
147
148
149
150
151
152
153
154
        with torch.no_grad():
            upsampled = upsample(sample)

        assert upsampled.shape == (1, 32, 64, 64)
        output_slice = upsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([0.7145, 1.3773, 0.3492, 0.8448, 1.0839, -0.3341, 0.5956, 0.1250, -0.4841])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_upsample_with_conv_out_dim(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 32, 32)
155
        upsample = Upsample2D(channels=32, use_conv=True, out_channels=64)
patil-suraj's avatar
patil-suraj committed
156
157
158
159
160
161
162
163
164
165
166
        with torch.no_grad():
            upsampled = upsample(sample)

        assert upsampled.shape == (1, 64, 64, 64)
        output_slice = upsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([0.2703, 0.1656, -0.2538, -0.0553, -0.2984, 0.1044, 0.1155, 0.2579, 0.7755])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_upsample_with_transpose(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 32, 32)
167
        upsample = Upsample2D(channels=32, use_conv=False, use_conv_transpose=True)
patil-suraj's avatar
patil-suraj committed
168
169
170
171
172
173
174
        with torch.no_grad():
            upsampled = upsample(sample)

        assert upsampled.shape == (1, 32, 64, 64)
        output_slice = upsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([-0.3028, -0.1582, 0.0071, 0.0350, -0.4799, -0.1139, 0.1056, -0.1153, -0.1046])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)
patil-suraj's avatar
patil-suraj committed
175
176


177
class Downsample2DBlockTests(unittest.TestCase):
patil-suraj's avatar
patil-suraj committed
178
179
180
    def test_downsample_default(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64)
181
        downsample = Downsample2D(channels=32, use_conv=False)
patil-suraj's avatar
patil-suraj committed
182
183
184
185
186
187
188
189
190
191
192
193
194
        with torch.no_grad():
            downsampled = downsample(sample)

        assert downsampled.shape == (1, 32, 32, 32)
        output_slice = downsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([-0.0513, -0.3889, 0.0640, 0.0836, -0.5460, -0.0341, -0.0169, -0.6967, 0.1179])
        max_diff = (output_slice.flatten() - expected_slice).abs().sum().item()
        assert max_diff <= 1e-3
        # assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-1)

    def test_downsample_with_conv(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64)
195
        downsample = Downsample2D(channels=32, use_conv=True)
patil-suraj's avatar
patil-suraj committed
196
197
198
199
200
201
202
203
204
205
206
207
208
209
        with torch.no_grad():
            downsampled = downsample(sample)

        assert downsampled.shape == (1, 32, 32, 32)
        output_slice = downsampled[0, -1, -3:, -3:]

        expected_slice = torch.tensor(
            [0.9267, 0.5878, 0.3337, 1.2321, -0.1191, -0.3984, -0.7532, -0.0715, -0.3913],
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_downsample_with_conv_pad1(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64)
210
        downsample = Downsample2D(channels=32, use_conv=True, padding=1)
patil-suraj's avatar
patil-suraj committed
211
212
213
214
215
216
217
218
219
220
221
        with torch.no_grad():
            downsampled = downsample(sample)

        assert downsampled.shape == (1, 32, 32, 32)
        output_slice = downsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([0.9267, 0.5878, 0.3337, 1.2321, -0.1191, -0.3984, -0.7532, -0.0715, -0.3913])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_downsample_with_conv_out_dim(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64)
222
        downsample = Downsample2D(channels=32, use_conv=True, out_channels=16)
patil-suraj's avatar
patil-suraj committed
223
224
225
226
227
228
229
        with torch.no_grad():
            downsampled = downsample(sample)

        assert downsampled.shape == (1, 16, 32, 32)
        output_slice = downsampled[0, -1, -3:, -3:]
        expected_slice = torch.tensor([-0.6586, 0.5985, 0.0721, 0.1256, -0.1492, 0.4436, -0.2544, 0.5021, 1.1522])
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)
Sid Sahai's avatar
Sid Sahai committed
230
231


Erin's avatar
Erin committed
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
class ResnetBlock2DTests(unittest.TestCase):
    def test_resnet_default(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 64, 64)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [-1.9010, -0.2974, -0.8245, -1.3533, 0.8742, -0.9645, -2.0584, 1.3387, -0.4746], device=torch_device
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_restnet_with_use_in_shortcut(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128, use_in_shortcut=True).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 64, 64)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [0.2226, -1.0791, -0.1629, 0.3659, -0.2889, -1.2376, 0.0582, 0.9206, 0.0044], device=torch_device
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_resnet_up(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128, up=True).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 128, 128)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [1.2130, -0.8753, -0.9027, 1.5783, -0.5362, -0.5001, 1.0726, -0.7732, -0.4182], device=torch_device
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_resnet_down(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128, down=True).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 32, 32)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [-0.3002, -0.7135, 0.1359, 0.0561, -0.7935, 0.0113, -0.1766, -0.6714, -0.0436], device=torch_device
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_restnet_with_kernel_fir(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128, kernel="fir", down=True).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 32, 32)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [-0.0934, -0.5729, 0.0909, -0.2710, -0.5044, 0.0243, -0.0665, -0.5267, -0.3136], device=torch_device
        )
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_restnet_with_kernel_sde_vp(self):
        torch.manual_seed(0)
        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        temb = torch.randn(1, 128).to(torch_device)
        resnet_block = ResnetBlock2D(in_channels=32, temb_channels=128, kernel="sde_vp", down=True).to(torch_device)
        with torch.no_grad():
            output_tensor = resnet_block(sample, temb)

        assert output_tensor.shape == (1, 32, 32, 32)
        output_slice = output_tensor[0, -1, -3:, -3:]
        expected_slice = torch.tensor(
            [-0.3002, -0.7135, 0.1359, 0.0561, -0.7935, 0.0113, -0.1766, -0.6714, -0.0436], device=torch_device
        )
Anton Lozhkov's avatar
Anton Lozhkov committed
321
322
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

Sid Sahai's avatar
Sid Sahai committed
323

Will Berman's avatar
Will Berman committed
324
class Transformer2DModelTests(unittest.TestCase):
Sid Sahai's avatar
Sid Sahai committed
325
326
    def test_spatial_transformer_default(self):
        torch.manual_seed(0)
Arsalan's avatar
Arsalan committed
327
        backend_manual_seed(torch_device, 0)
Sid Sahai's avatar
Sid Sahai committed
328
329

        sample = torch.randn(1, 32, 64, 64).to(torch_device)
Will Berman's avatar
Will Berman committed
330
        spatial_transformer_block = Transformer2DModel(
Sid Sahai's avatar
Sid Sahai committed
331
            in_channels=32,
Will Berman's avatar
Will Berman committed
332
333
            num_attention_heads=1,
            attention_head_dim=32,
Sid Sahai's avatar
Sid Sahai committed
334
            dropout=0.0,
Will Berman's avatar
Will Berman committed
335
            cross_attention_dim=None,
Sid Sahai's avatar
Sid Sahai committed
336
337
        ).to(torch_device)
        with torch.no_grad():
Will Berman's avatar
Will Berman committed
338
            attention_scores = spatial_transformer_block(sample).sample
Sid Sahai's avatar
Sid Sahai committed
339
340
341
342

        assert attention_scores.shape == (1, 32, 64, 64)
        output_slice = attention_scores[0, -1, -3:, -3:]

343
        expected_slice = torch.tensor(
344
            [-1.9455, -0.0066, -1.3933, -1.5878, 0.5325, -0.6486, -1.8648, 0.7515, -0.9689], device=torch_device
345
        )
Sid Sahai's avatar
Sid Sahai committed
346
347
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

Will Berman's avatar
Will Berman committed
348
    def test_spatial_transformer_cross_attention_dim(self):
Sid Sahai's avatar
Sid Sahai committed
349
        torch.manual_seed(0)
Arsalan's avatar
Arsalan committed
350
        backend_manual_seed(torch_device, 0)
Sid Sahai's avatar
Sid Sahai committed
351
352

        sample = torch.randn(1, 64, 64, 64).to(torch_device)
Will Berman's avatar
Will Berman committed
353
        spatial_transformer_block = Transformer2DModel(
Sid Sahai's avatar
Sid Sahai committed
354
            in_channels=64,
Will Berman's avatar
Will Berman committed
355
356
            num_attention_heads=2,
            attention_head_dim=32,
Sid Sahai's avatar
Sid Sahai committed
357
            dropout=0.0,
Will Berman's avatar
Will Berman committed
358
            cross_attention_dim=64,
Sid Sahai's avatar
Sid Sahai committed
359
360
361
        ).to(torch_device)
        with torch.no_grad():
            context = torch.randn(1, 4, 64).to(torch_device)
Will Berman's avatar
Will Berman committed
362
            attention_scores = spatial_transformer_block(sample, context).sample
Sid Sahai's avatar
Sid Sahai committed
363
364
365

        assert attention_scores.shape == (1, 64, 64, 64)
        output_slice = attention_scores[0, -1, -3:, -3:]
Patrick von Platen's avatar
Patrick von Platen committed
366
367
368
        expected_slice = torch.tensor(
            [0.0143, -0.6909, -2.1547, -1.8893, 1.4097, 0.1359, -0.2521, -1.3359, 0.2598], device=torch_device
        )
Sid Sahai's avatar
Sid Sahai committed
369
370
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

Will Berman's avatar
Will Berman committed
371
372
    def test_spatial_transformer_timestep(self):
        torch.manual_seed(0)
Arsalan's avatar
Arsalan committed
373
        backend_manual_seed(torch_device, 0)
Will Berman's avatar
Will Berman committed
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397

        num_embeds_ada_norm = 5

        sample = torch.randn(1, 64, 64, 64).to(torch_device)
        spatial_transformer_block = Transformer2DModel(
            in_channels=64,
            num_attention_heads=2,
            attention_head_dim=32,
            dropout=0.0,
            cross_attention_dim=64,
            num_embeds_ada_norm=num_embeds_ada_norm,
        ).to(torch_device)
        with torch.no_grad():
            timestep_1 = torch.tensor(1, dtype=torch.long).to(torch_device)
            timestep_2 = torch.tensor(2, dtype=torch.long).to(torch_device)
            attention_scores_1 = spatial_transformer_block(sample, timestep=timestep_1).sample
            attention_scores_2 = spatial_transformer_block(sample, timestep=timestep_2).sample

        assert attention_scores_1.shape == (1, 64, 64, 64)
        assert attention_scores_2.shape == (1, 64, 64, 64)

        output_slice_1 = attention_scores_1[0, -1, -3:, -3:]
        output_slice_2 = attention_scores_2[0, -1, -3:, -3:]

Patrick von Platen's avatar
Patrick von Platen committed
398
399
400
        expected_slice = torch.tensor(
            [-0.3923, -1.0923, -1.7144, -1.5570, 1.4154, 0.1738, -0.1157, -1.2998, -0.1703], device=torch_device
        )
Will Berman's avatar
Will Berman committed
401
        expected_slice_2 = torch.tensor(
Patrick von Platen's avatar
Patrick von Platen committed
402
            [-0.4311, -1.1376, -1.7732, -1.5997, 1.3450, 0.0964, -0.1569, -1.3590, -0.2348], device=torch_device
Will Berman's avatar
Will Berman committed
403
404
        )

405
        assert torch.allclose(output_slice_1.flatten(), expected_slice, atol=1e-3)
Will Berman's avatar
Will Berman committed
406
407
        assert torch.allclose(output_slice_2.flatten(), expected_slice_2, atol=1e-3)

Sid Sahai's avatar
Sid Sahai committed
408
409
    def test_spatial_transformer_dropout(self):
        torch.manual_seed(0)
Arsalan's avatar
Arsalan committed
410
        backend_manual_seed(torch_device, 0)
Sid Sahai's avatar
Sid Sahai committed
411
412
413

        sample = torch.randn(1, 32, 64, 64).to(torch_device)
        spatial_transformer_block = (
Will Berman's avatar
Will Berman committed
414
            Transformer2DModel(
Sid Sahai's avatar
Sid Sahai committed
415
                in_channels=32,
Will Berman's avatar
Will Berman committed
416
417
                num_attention_heads=2,
                attention_head_dim=16,
Sid Sahai's avatar
Sid Sahai committed
418
                dropout=0.3,
Will Berman's avatar
Will Berman committed
419
                cross_attention_dim=None,
Sid Sahai's avatar
Sid Sahai committed
420
421
422
423
424
            )
            .to(torch_device)
            .eval()
        )
        with torch.no_grad():
Will Berman's avatar
Will Berman committed
425
            attention_scores = spatial_transformer_block(sample).sample
Sid Sahai's avatar
Sid Sahai committed
426
427
428
429

        assert attention_scores.shape == (1, 32, 64, 64)
        output_slice = attention_scores[0, -1, -3:, -3:]

430
        expected_slice = torch.tensor(
431
            [-1.9380, -0.0083, -1.3771, -1.5819, 0.5209, -0.6441, -1.8545, 0.7563, -0.9615], device=torch_device
432
        )
Sid Sahai's avatar
Sid Sahai committed
433
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)
Will Berman's avatar
Will Berman committed
434

Arsalan's avatar
Arsalan committed
435
    @require_torch_accelerator_with_fp64
Will Berman's avatar
Will Berman committed
436
437
    def test_spatial_transformer_discrete(self):
        torch.manual_seed(0)
Arsalan's avatar
Arsalan committed
438
        backend_manual_seed(torch_device, 0)
Will Berman's avatar
Will Berman committed
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460

        num_embed = 5

        sample = torch.randint(0, num_embed, (1, 32)).to(torch_device)
        spatial_transformer_block = (
            Transformer2DModel(
                num_attention_heads=1,
                attention_head_dim=32,
                num_vector_embeds=num_embed,
                sample_size=16,
            )
            .to(torch_device)
            .eval()
        )

        with torch.no_grad():
            attention_scores = spatial_transformer_block(sample).sample

        assert attention_scores.shape == (1, num_embed - 1, 32)

        output_slice = attention_scores[0, -2:, -3:]

461
        expected_slice = torch.tensor([-1.7648, -1.0241, -2.0985, -1.8035, -1.6404, -1.2098], device=torch_device)
Will Berman's avatar
Will Berman committed
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
        assert torch.allclose(output_slice.flatten(), expected_slice, atol=1e-3)

    def test_spatial_transformer_default_norm_layers(self):
        spatial_transformer_block = Transformer2DModel(num_attention_heads=1, attention_head_dim=32, in_channels=32)

        assert spatial_transformer_block.transformer_blocks[0].norm1.__class__ == nn.LayerNorm
        assert spatial_transformer_block.transformer_blocks[0].norm3.__class__ == nn.LayerNorm

    def test_spatial_transformer_ada_norm_layers(self):
        spatial_transformer_block = Transformer2DModel(
            num_attention_heads=1,
            attention_head_dim=32,
            in_channels=32,
            num_embeds_ada_norm=5,
        )

        assert spatial_transformer_block.transformer_blocks[0].norm1.__class__ == AdaLayerNorm
        assert spatial_transformer_block.transformer_blocks[0].norm3.__class__ == nn.LayerNorm

    def test_spatial_transformer_default_ff_layers(self):
        spatial_transformer_block = Transformer2DModel(
            num_attention_heads=1,
            attention_head_dim=32,
            in_channels=32,
        )

        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].__class__ == GEGLU
        assert spatial_transformer_block.transformer_blocks[0].ff.net[1].__class__ == nn.Dropout
490
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].__class__ == nn.Linear
Will Berman's avatar
Will Berman committed
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513

        dim = 32
        inner_dim = 128

        # First dimension change
        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].proj.in_features == dim
        # NOTE: inner_dim * 2 because GEGLU
        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].proj.out_features == inner_dim * 2

        # Second dimension change
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].in_features == inner_dim
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].out_features == dim

    def test_spatial_transformer_geglu_approx_ff_layers(self):
        spatial_transformer_block = Transformer2DModel(
            num_attention_heads=1,
            attention_head_dim=32,
            in_channels=32,
            activation_fn="geglu-approximate",
        )

        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].__class__ == ApproximateGELU
        assert spatial_transformer_block.transformer_blocks[0].ff.net[1].__class__ == nn.Dropout
514
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].__class__ == nn.Linear
Will Berman's avatar
Will Berman committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534

        dim = 32
        inner_dim = 128

        # First dimension change
        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].proj.in_features == dim
        assert spatial_transformer_block.transformer_blocks[0].ff.net[0].proj.out_features == inner_dim

        # Second dimension change
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].in_features == inner_dim
        assert spatial_transformer_block.transformer_blocks[0].ff.net[2].out_features == dim

    def test_spatial_transformer_attention_bias(self):
        spatial_transformer_block = Transformer2DModel(
            num_attention_heads=1, attention_head_dim=32, in_channels=32, attention_bias=True
        )

        assert spatial_transformer_block.transformer_blocks[0].attn1.to_q.bias is not None
        assert spatial_transformer_block.transformer_blocks[0].attn1.to_k.bias is not None
        assert spatial_transformer_block.transformer_blocks[0].attn1.to_v.bias is not None