test_models_vae.py 41.5 KB
Newer Older
1
# coding=utf-8
2
# Copyright 2024 HuggingFace Inc.
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#
# 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 gc
import unittest

Will Berman's avatar
Will Berman committed
19
import numpy as np
20
import torch
21
from datasets import load_dataset
22
from parameterized import parameterized
23

Will Berman's avatar
Will Berman committed
24
25
26
from diffusers import (
    AsymmetricAutoencoderKL,
    AutoencoderKL,
Suraj Patil's avatar
Suraj Patil committed
27
    AutoencoderKLTemporalDecoder,
28
    AutoencoderOobleck,
Will Berman's avatar
Will Berman committed
29
30
31
32
    AutoencoderTiny,
    ConsistencyDecoderVAE,
    StableDiffusionPipeline,
)
33
from diffusers.utils.import_utils import is_xformers_available
Will Berman's avatar
Will Berman committed
34
from diffusers.utils.loading_utils import load_image
Dhruv Nair's avatar
Dhruv Nair committed
35
from diffusers.utils.testing_utils import (
Arsalan's avatar
Arsalan committed
36
    backend_empty_cache,
Dhruv Nair's avatar
Dhruv Nair committed
37
38
    enable_full_determinism,
    floats_tensor,
39
    is_peft_available,
Dhruv Nair's avatar
Dhruv Nair committed
40
    load_hf_numpy,
41
    require_peft_backend,
Arsalan's avatar
Arsalan committed
42
43
    require_torch_accelerator,
    require_torch_accelerator_with_fp16,
Dhruv Nair's avatar
Dhruv Nair committed
44
    require_torch_gpu,
Arsalan's avatar
Arsalan committed
45
    skip_mps,
Dhruv Nair's avatar
Dhruv Nair committed
46
47
48
49
    slow,
    torch_all_close,
    torch_device,
)
Will Berman's avatar
Will Berman committed
50
from diffusers.utils.torch_utils import randn_tensor
51

52
from ..test_modeling_common import ModelTesterMixin, UNetTesterMixin
53
54


55
56
57
58
if is_peft_available():
    from peft import LoraConfig


59
enable_full_determinism()
60
61


62
def get_autoencoder_kl_config(block_out_channels=None, norm_num_groups=None):
63
64
    block_out_channels = block_out_channels or [2, 4]
    norm_num_groups = norm_num_groups or 2
65
66
67
68
69
70
71
72
73
74
75
76
77
    init_dict = {
        "block_out_channels": block_out_channels,
        "in_channels": 3,
        "out_channels": 3,
        "down_block_types": ["DownEncoderBlock2D"] * len(block_out_channels),
        "up_block_types": ["UpDecoderBlock2D"] * len(block_out_channels),
        "latent_channels": 4,
        "norm_num_groups": norm_num_groups,
    }
    return init_dict


def get_asym_autoencoder_kl_config(block_out_channels=None, norm_num_groups=None):
78
79
    block_out_channels = block_out_channels or [2, 4]
    norm_num_groups = norm_num_groups or 2
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
    init_dict = {
        "in_channels": 3,
        "out_channels": 3,
        "down_block_types": ["DownEncoderBlock2D"] * len(block_out_channels),
        "down_block_out_channels": block_out_channels,
        "layers_per_down_block": 1,
        "up_block_types": ["UpDecoderBlock2D"] * len(block_out_channels),
        "up_block_out_channels": block_out_channels,
        "layers_per_up_block": 1,
        "act_fn": "silu",
        "latent_channels": 4,
        "norm_num_groups": norm_num_groups,
        "sample_size": 32,
        "scaling_factor": 0.18215,
    }
    return init_dict


def get_autoencoder_tiny_config(block_out_channels=None):
    block_out_channels = (len(block_out_channels) * [32]) if block_out_channels is not None else [32, 32]
    init_dict = {
        "in_channels": 3,
        "out_channels": 3,
        "encoder_block_out_channels": block_out_channels,
        "decoder_block_out_channels": block_out_channels,
        "num_encoder_blocks": [b // min(block_out_channels) for b in block_out_channels],
        "num_decoder_blocks": [b // min(block_out_channels) for b in reversed(block_out_channels)],
    }
    return init_dict


def get_consistency_vae_config(block_out_channels=None, norm_num_groups=None):
112
113
    block_out_channels = block_out_channels or [2, 4]
    norm_num_groups = norm_num_groups or 2
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
    return {
        "encoder_block_out_channels": block_out_channels,
        "encoder_in_channels": 3,
        "encoder_out_channels": 4,
        "encoder_down_block_types": ["DownEncoderBlock2D"] * len(block_out_channels),
        "decoder_add_attention": False,
        "decoder_block_out_channels": block_out_channels,
        "decoder_down_block_types": ["ResnetDownsampleBlock2D"] * len(block_out_channels),
        "decoder_downsample_padding": 1,
        "decoder_in_channels": 7,
        "decoder_layers_per_block": 1,
        "decoder_norm_eps": 1e-05,
        "decoder_norm_num_groups": norm_num_groups,
        "encoder_norm_num_groups": norm_num_groups,
        "decoder_num_train_timesteps": 1024,
        "decoder_out_channels": 6,
        "decoder_resnet_time_scale_shift": "scale_shift",
        "decoder_time_embedding_type": "learned",
        "decoder_up_block_types": ["ResnetUpsampleBlock2D"] * len(block_out_channels),
        "scaling_factor": 1,
        "latent_channels": 4,
    }


138
139
140
141
142
143
144
145
146
147
148
149
def get_autoencoder_oobleck_config(block_out_channels=None):
    init_dict = {
        "encoder_hidden_size": 12,
        "decoder_channels": 12,
        "decoder_input_channels": 6,
        "audio_channels": 2,
        "downsampling_ratios": [2, 4],
        "channel_multiples": [1, 2],
    }
    return init_dict


150
class AutoencoderKLTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase):
151
    model_class = AutoencoderKL
152
153
    main_input_name = "sample"
    base_precision = 1e-2
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)

        return {"sample": image}

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
174
        init_dict = get_autoencoder_kl_config()
175
176
177
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

178
    @unittest.skip("Not tested.")
179
180
181
    def test_forward_signature(self):
        pass

182
    @unittest.skip("Not tested.")
183
184
185
    def test_training(self):
        pass

186
187
188
    def test_gradient_checkpointing_is_applied(self):
        expected_set = {"Decoder", "Encoder"}
        super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
189

190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
    def test_from_pretrained_hub(self):
        model, loading_info = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy", output_loading_info=True)
        self.assertIsNotNone(model)
        self.assertEqual(len(loading_info["missing_keys"]), 0)

        model.to(torch_device)
        image = model(**self.dummy_input)

        assert image is not None, "Make sure output is not None"

    def test_output_pretrained(self):
        model = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy")
        model = model.to(torch_device)
        model.eval()

Arsalan's avatar
Arsalan committed
205
206
207
208
        # Keep generator on CPU for non-CUDA devices to compare outputs with CPU result tensors
        generator_device = "cpu" if not torch_device.startswith("cuda") else "cuda"
        if torch_device != "mps":
            generator = torch.Generator(device=generator_device).manual_seed(0)
209
        else:
Arsalan's avatar
Arsalan committed
210
            generator = torch.manual_seed(0)
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240

        image = torch.randn(
            1,
            model.config.in_channels,
            model.config.sample_size,
            model.config.sample_size,
            generator=torch.manual_seed(0),
        )
        image = image.to(torch_device)
        with torch.no_grad():
            output = model(image, sample_posterior=True, generator=generator).sample

        output_slice = output[0, -1, -3:, -3:].flatten().cpu()

        # Since the VAE Gaussian prior's generator is seeded on the appropriate device,
        # the expected output slices are not the same for CPU and GPU.
        if torch_device == "mps":
            expected_output_slice = torch.tensor(
                [
                    -4.0078e-01,
                    -3.8323e-04,
                    -1.2681e-01,
                    -1.1462e-01,
                    2.0095e-01,
                    1.0893e-01,
                    -8.8247e-02,
                    -3.0361e-01,
                    -9.8644e-03,
                ]
            )
Arsalan's avatar
Arsalan committed
241
        elif generator_device == "cpu":
242
            expected_output_slice = torch.tensor(
Suraj Patil's avatar
Suraj Patil committed
243
244
245
246
247
248
249
250
251
252
253
                [
                    -0.1352,
                    0.0878,
                    0.0419,
                    -0.0818,
                    -0.1069,
                    0.0688,
                    -0.1458,
                    -0.4446,
                    -0.0026,
                ]
254
255
256
            )
        else:
            expected_output_slice = torch.tensor(
Suraj Patil's avatar
Suraj Patil committed
257
258
259
260
261
262
263
264
265
266
267
                [
                    -0.2421,
                    0.4642,
                    0.2507,
                    -0.0438,
                    0.0682,
                    0.3160,
                    -0.2018,
                    -0.0727,
                    0.2485,
                ]
268
269
            )

270
        self.assertTrue(torch_all_close(output_slice, expected_output_slice, rtol=1e-2))
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
    @require_peft_backend
    def test_lora_adapter(self):
        init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()
        vae = self.model_class(**init_dict)

        target_modules_vae = [
            "conv1",
            "conv2",
            "conv_in",
            "conv_shortcut",
            "conv",
            "conv_out",
            "skip_conv_1",
            "skip_conv_2",
            "skip_conv_3",
            "skip_conv_4",
            "to_k",
            "to_q",
            "to_v",
            "to_out.0",
        ]
        vae_lora_config = LoraConfig(
            r=16,
            init_lora_weights="gaussian",
            target_modules=target_modules_vae,
        )

        vae.add_adapter(vae_lora_config, adapter_name="vae_lora")
        active_lora = vae.active_adapters()
        self.assertTrue(len(active_lora) == 1)
        self.assertTrue(active_lora[0] == "vae_lora")

304

Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
class AsymmetricAutoencoderKLTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase):
    model_class = AsymmetricAutoencoderKL
    main_input_name = "sample"
    base_precision = 1e-2

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
        mask = torch.ones((batch_size, 1) + sizes).to(torch_device)

        return {"sample": image, "mask": mask}

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
330
        init_dict = get_asym_autoencoder_kl_config()
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
331
332
333
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

334
    @unittest.skip("Not tested.")
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
335
336
337
    def test_forward_signature(self):
        pass

338
    @unittest.skip("Not tested.")
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
339
340
341
342
    def test_forward_with_norm_groups(self):
        pass


343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
class AutoencoderTinyTests(ModelTesterMixin, unittest.TestCase):
    model_class = AutoencoderTiny
    main_input_name = "sample"
    base_precision = 1e-2

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)

        return {"sample": image}

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
367
        init_dict = get_autoencoder_tiny_config()
368
369
370
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

371
    @unittest.skip("Not tested.")
372
373
374
    def test_outputs_equivalence(self):
        pass

375
376
377
378
379
380
381
382
383
384
    def test_gradient_checkpointing_is_applied(self):
        expected_set = {"DecoderTiny", "EncoderTiny"}
        super().test_gradient_checkpointing_is_applied(expected_set=expected_set)

    @unittest.skip(
        "Gradient checkpointing is supported but this test doesn't apply to this class because it's forward is a bit different from the rest."
    )
    def test_effective_gradient_checkpointing(self):
        pass

385

Will Berman's avatar
Will Berman committed
386
387
388
389
390
391
392
class ConsistencyDecoderVAETests(ModelTesterMixin, unittest.TestCase):
    model_class = ConsistencyDecoderVAE
    main_input_name = "sample"
    base_precision = 1e-2
    forward_requires_fresh_args = True

    def inputs_dict(self, seed=None):
393
394
395
396
        if seed is None:
            generator = torch.Generator("cpu").manual_seed(0)
        else:
            generator = torch.Generator("cpu").manual_seed(seed)
Will Berman's avatar
Will Berman committed
397
398
399
400
401
402
403
404
405
406
407
408
409
410
        image = randn_tensor((4, 3, 32, 32), generator=generator, device=torch.device(torch_device))

        return {"sample": image, "generator": generator}

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    @property
    def init_dict(self):
411
        return get_consistency_vae_config()
Will Berman's avatar
Will Berman committed
412
413
414
415
416
417
418
419
420
421
422
423
424

    def prepare_init_args_and_inputs_for_common(self):
        return self.init_dict, self.inputs_dict()

    @unittest.skip
    def test_training(self):
        ...

    @unittest.skip
    def test_ema_training(self):
        ...


M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
425
class AutoencoderKLTemporalDecoderFastTests(ModelTesterMixin, unittest.TestCase):
Suraj Patil's avatar
Suraj Patil committed
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
    model_class = AutoencoderKLTemporalDecoder
    main_input_name = "sample"
    base_precision = 1e-2

    @property
    def dummy_input(self):
        batch_size = 3
        num_channels = 3
        sizes = (32, 32)

        image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)
        num_frames = 3

        return {"sample": image, "num_frames": num_frames}

    @property
    def input_shape(self):
        return (3, 32, 32)

    @property
    def output_shape(self):
        return (3, 32, 32)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = {
            "block_out_channels": [32, 64],
            "in_channels": 3,
            "out_channels": 3,
            "down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],
            "latent_channels": 4,
            "layers_per_block": 2,
        }
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

461
    @unittest.skip("Not tested.")
Suraj Patil's avatar
Suraj Patil committed
462
463
464
    def test_forward_signature(self):
        pass

465
    @unittest.skip("Not tested.")
Suraj Patil's avatar
Suraj Patil committed
466
467
468
    def test_training(self):
        pass

469
470
471
    def test_gradient_checkpointing_is_applied(self):
        expected_set = {"Encoder", "TemporalDecoder"}
        super().test_gradient_checkpointing_is_applied(expected_set=expected_set)
Suraj Patil's avatar
Suraj Patil committed
472
473


474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
class AutoencoderOobleckTests(ModelTesterMixin, UNetTesterMixin, unittest.TestCase):
    model_class = AutoencoderOobleck
    main_input_name = "sample"
    base_precision = 1e-2

    @property
    def dummy_input(self):
        batch_size = 4
        num_channels = 2
        seq_len = 24

        waveform = floats_tensor((batch_size, num_channels, seq_len)).to(torch_device)

        return {"sample": waveform, "sample_posterior": False}

    @property
    def input_shape(self):
        return (2, 24)

    @property
    def output_shape(self):
        return (2, 24)

    def prepare_init_args_and_inputs_for_common(self):
        init_dict = get_autoencoder_oobleck_config()
        inputs_dict = self.dummy_input
        return init_dict, inputs_dict

502
    @unittest.skip("Not tested.")
503
504
505
    def test_forward_signature(self):
        pass

506
    @unittest.skip("Not tested.")
507
508
509
    def test_forward_with_norm_groups(self):
        pass

510
511
512
513
    @unittest.skip("No attention module used in this model")
    def test_set_attn_processor_for_determinism(self):
        return

514

515
516
517
518
519
520
@slow
class AutoencoderTinyIntegrationTests(unittest.TestCase):
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
521
        backend_empty_cache(torch_device)
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537

    def get_file_format(self, seed, shape):
        return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"

    def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False):
        dtype = torch.float16 if fp16 else torch.float32
        image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)
        return image

    def get_sd_vae_model(self, model_id="hf-internal-testing/taesd-diffusers", fp16=False):
        torch_dtype = torch.float16 if fp16 else torch.float32

        model = AutoencoderTiny.from_pretrained(model_id, torch_dtype=torch_dtype)
        model.to(torch_device).eval()
        return model

538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
    @parameterized.expand(
        [
            [(1, 4, 73, 97), (1, 3, 584, 776)],
            [(1, 4, 97, 73), (1, 3, 776, 584)],
            [(1, 4, 49, 65), (1, 3, 392, 520)],
            [(1, 4, 65, 49), (1, 3, 520, 392)],
            [(1, 4, 49, 49), (1, 3, 392, 392)],
        ]
    )
    def test_tae_tiling(self, in_shape, out_shape):
        model = self.get_sd_vae_model()
        model.enable_tiling()
        with torch.no_grad():
            zeros = torch.zeros(in_shape).to(torch_device)
            dec = model.decode(zeros).sample
            assert dec.shape == out_shape

555
556
557
558
559
560
561
562
563
564
    def test_stable_diffusion(self):
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed=33)

        with torch.no_grad():
            sample = model(image).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
565
        expected_output_slice = torch.tensor([0.0093, 0.6385, -0.1274, 0.1631, -0.1762, 0.5232, -0.3108, -0.0382])
566
567
568

        assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)

569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
    @parameterized.expand([(True,), (False,)])
    def test_tae_roundtrip(self, enable_tiling):
        # load the autoencoder
        model = self.get_sd_vae_model()
        if enable_tiling:
            model.enable_tiling()

        # make a black image with a white square in the middle,
        # which is large enough to split across multiple tiles
        image = -torch.ones(1, 3, 1024, 1024, device=torch_device)
        image[..., 256:768, 256:768] = 1.0

        # round-trip the image through the autoencoder
        with torch.no_grad():
            sample = model(image).sample

        # the autoencoder reconstruction should match original image, sorta
        def downscale(x):
            return torch.nn.functional.avg_pool2d(x, model.spatial_scale_factor)

        assert torch_all_close(downscale(sample), downscale(image), atol=0.125)

591

592
593
@slow
class AutoencoderKLIntegrationTests(unittest.TestCase):
Patrick von Platen's avatar
hot fix  
Patrick von Platen committed
594
595
596
    def get_file_format(self, seed, shape):
        return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"

597
598
599
600
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
601
        backend_empty_cache(torch_device)
602
603
604

    def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False):
        dtype = torch.float16 if fp16 else torch.float32
605
        image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)
606
607
608
609
610
611
612
        return image

    def get_sd_vae_model(self, model_id="CompVis/stable-diffusion-v1-4", fp16=False):
        revision = "fp16" if fp16 else None
        torch_dtype = torch.float16 if fp16 else torch.float32

        model = AutoencoderKL.from_pretrained(
613
614
615
616
            model_id,
            subfolder="vae",
            torch_dtype=torch_dtype,
            revision=revision,
617
        )
618
        model.to(torch_device)
619
620
621
622

        return model

    def get_generator(self, seed=0):
Arsalan's avatar
Arsalan committed
623
624
625
626
        generator_device = "cpu" if not torch_device.startswith("cuda") else "cuda"
        if torch_device != "mps":
            return torch.Generator(device=generator_device).manual_seed(seed)
        return torch.manual_seed(seed)
627
628
629
630

    @parameterized.expand(
        [
            # fmt: off
631
632
            [
                33,
633
                [-0.1556, 0.9848, -0.0410, -0.0642, -0.2685, 0.8381, -0.2004, -0.0700],
634
635
636
637
                [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824],
            ],
            [
                47,
638
                [-0.2376, 0.1200, 0.1337, -0.4830, -0.2504, -0.0759, -0.0486, -0.4077],
639
640
                [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131],
            ],
641
642
643
            # fmt: on
        ]
    )
644
    def test_stable_diffusion(self, seed, expected_slice, expected_slice_mps):
645
646
647
648
649
650
651
652
653
654
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)
        generator = self.get_generator(seed)

        with torch.no_grad():
            sample = model(image, generator=generator, sample_posterior=True).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
655
        expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
656

657
        assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)
658
659
660
661
662
663
664
665
666

    @parameterized.expand(
        [
            # fmt: off
            [33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],
            [47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],
            # fmt: on
        ]
    )
Arsalan's avatar
Arsalan committed
667
    @require_torch_accelerator_with_fp16
668
669
670
671
672
673
674
675
676
677
678
679
680
    def test_stable_diffusion_fp16(self, seed, expected_slice):
        model = self.get_sd_vae_model(fp16=True)
        image = self.get_sd_image(seed, fp16=True)
        generator = self.get_generator(seed)

        with torch.no_grad():
            sample = model(image, generator=generator, sample_posterior=True).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu()
        expected_output_slice = torch.tensor(expected_slice)

Patrick von Platen's avatar
Patrick von Platen committed
681
        assert torch_all_close(output_slice, expected_output_slice, atol=1e-2)
682
683
684
685

    @parameterized.expand(
        [
            # fmt: off
686
687
688
689
690
691
692
693
694
695
            [
                33,
                [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814],
                [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824],
            ],
            [
                47,
                [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085],
                [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131],
            ],
696
697
698
            # fmt: on
        ]
    )
699
    def test_stable_diffusion_mode(self, seed, expected_slice, expected_slice_mps):
700
701
702
703
704
705
706
707
708
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)

        with torch.no_grad():
            sample = model(image).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
709
        expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)
710

711
        assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)
712
713
714
715
716
717
718
719
720

    @parameterized.expand(
        [
            # fmt: off
            [13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],
            [37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],
            # fmt: on
        ]
    )
Arsalan's avatar
Arsalan committed
721
722
    @require_torch_accelerator
    @skip_mps
723
724
725
726
727
728
729
730
731
732
733
734
    def test_stable_diffusion_decode(self, seed, expected_slice):
        model = self.get_sd_vae_model()
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))

        with torch.no_grad():
            sample = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        output_slice = sample[-1, -2:, :2, -2:].flatten().cpu()
        expected_output_slice = torch.tensor(expected_slice)

Patrick von Platen's avatar
Patrick von Platen committed
735
        assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)
736
737
738
739
740
741
742
743
744

    @parameterized.expand(
        [
            # fmt: off
            [27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],
            [16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],
            # fmt: on
        ]
    )
Arsalan's avatar
Arsalan committed
745
    @require_torch_accelerator_with_fp16
746
747
748
749
750
751
752
753
754
755
756
757
    def test_stable_diffusion_decode_fp16(self, seed, expected_slice):
        model = self.get_sd_vae_model(fp16=True)
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64), fp16=True)

        with torch.no_grad():
            sample = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu()
        expected_output_slice = torch.tensor(expected_slice)

Patrick von Platen's avatar
Patrick von Platen committed
758
        assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)
759

760
    @parameterized.expand([(13,), (16,), (27,)])
761
    @require_torch_gpu
Suraj Patil's avatar
Suraj Patil committed
762
763
764
765
    @unittest.skipIf(
        not is_xformers_available(),
        reason="xformers is not required when using PyTorch 2.0.",
    )
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
    def test_stable_diffusion_decode_xformers_vs_2_0_fp16(self, seed):
        model = self.get_sd_vae_model(fp16=True)
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64), fp16=True)

        with torch.no_grad():
            sample = model.decode(encoding).sample

        model.enable_xformers_memory_efficient_attention()
        with torch.no_grad():
            sample_2 = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        assert torch_all_close(sample, sample_2, atol=1e-1)

781
    @parameterized.expand([(13,), (16,), (37,)])
782
    @require_torch_gpu
Suraj Patil's avatar
Suraj Patil committed
783
784
785
786
    @unittest.skipIf(
        not is_xformers_available(),
        reason="xformers is not required when using PyTorch 2.0.",
    )
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
    def test_stable_diffusion_decode_xformers_vs_2_0(self, seed):
        model = self.get_sd_vae_model()
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))

        with torch.no_grad():
            sample = model.decode(encoding).sample

        model.enable_xformers_memory_efficient_attention()
        with torch.no_grad():
            sample_2 = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        assert torch_all_close(sample, sample_2, atol=1e-2)

802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
    @parameterized.expand(
        [
            # fmt: off
            [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
            [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
            # fmt: on
        ]
    )
    def test_stable_diffusion_encode_sample(self, seed, expected_slice):
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)
        generator = self.get_generator(seed)

        with torch.no_grad():
            dist = model.encode(image).latent_dist
            sample = dist.sample(generator=generator)

        assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

        output_slice = sample[0, -1, -3:, -3:].flatten().cpu()
        expected_output_slice = torch.tensor(expected_slice)

824
        tolerance = 3e-3 if torch_device != "mps" else 1e-2
825
        assert torch_all_close(output_slice, expected_output_slice, atol=tolerance)
826

Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
827
828
829
830
831
832
833
834
835
836

@slow
class AsymmetricAutoencoderKLIntegrationTests(unittest.TestCase):
    def get_file_format(self, seed, shape):
        return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"

    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
837
        backend_empty_cache(torch_device)
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857

    def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False):
        dtype = torch.float16 if fp16 else torch.float32
        image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)
        return image

    def get_sd_vae_model(self, model_id="cross-attention/asymmetric-autoencoder-kl-x-1-5", fp16=False):
        revision = "main"
        torch_dtype = torch.float32

        model = AsymmetricAutoencoderKL.from_pretrained(
            model_id,
            torch_dtype=torch_dtype,
            revision=revision,
        )
        model.to(torch_device).eval()

        return model

    def get_generator(self, seed=0):
Arsalan's avatar
Arsalan committed
858
859
860
861
        generator_device = "cpu" if not torch_device.startswith("cuda") else "cuda"
        if torch_device != "mps":
            return torch.Generator(device=generator_device).manual_seed(seed)
        return torch.manual_seed(seed)
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
862
863
864
865

    @parameterized.expand(
        [
            # fmt: off
866
867
            [
                33,
868
                [-0.0336, 0.3011, 0.1764, 0.0087, -0.3401, 0.3645, -0.1247, 0.1205],
869
870
871
872
873
874
875
                [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824],
            ],
            [
                47,
                [0.4400, 0.0543, 0.2873, 0.2946, 0.0553, 0.0839, -0.1585, 0.2529],
                [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089],
            ],
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
            # fmt: on
        ]
    )
    def test_stable_diffusion(self, seed, expected_slice, expected_slice_mps):
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)
        generator = self.get_generator(seed)

        with torch.no_grad():
            sample = model(image, generator=generator, sample_posterior=True).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
        expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)

        assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)

    @parameterized.expand(
        [
            # fmt: off
897
898
899
900
901
902
903
904
905
906
            [
                33,
                [-0.0340, 0.2870, 0.1698, -0.0105, -0.3448, 0.3529, -0.1321, 0.1097],
                [-0.0344, 0.2912, 0.1687, -0.0137, -0.3462, 0.3552, -0.1337, 0.1078],
            ],
            [
                47,
                [0.4397, 0.0550, 0.2873, 0.2946, 0.0567, 0.0855, -0.1580, 0.2531],
                [0.4397, 0.0550, 0.2873, 0.2946, 0.0567, 0.0855, -0.1580, 0.2531],
            ],
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
            # fmt: on
        ]
    )
    def test_stable_diffusion_mode(self, seed, expected_slice, expected_slice_mps):
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)

        with torch.no_grad():
            sample = model(image).sample

        assert sample.shape == image.shape

        output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()
        expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)

        assert torch_all_close(output_slice, expected_output_slice, atol=3e-3)

    @parameterized.expand(
        [
            # fmt: off
927
            [13, [-0.0521, -0.2939, 0.1540, -0.1855, -0.5936, -0.3138, -0.4579, -0.2275]],
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
928
929
930
931
            [37, [-0.1820, -0.4345, -0.0455, -0.2923, -0.8035, -0.5089, -0.4795, -0.3106]],
            # fmt: on
        ]
    )
Arsalan's avatar
Arsalan committed
932
933
    @require_torch_accelerator
    @skip_mps
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
    def test_stable_diffusion_decode(self, seed, expected_slice):
        model = self.get_sd_vae_model()
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))

        with torch.no_grad():
            sample = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        output_slice = sample[-1, -2:, :2, -2:].flatten().cpu()
        expected_output_slice = torch.tensor(expected_slice)

        assert torch_all_close(output_slice, expected_output_slice, atol=2e-3)

    @parameterized.expand([(13,), (16,), (37,)])
    @require_torch_gpu
Suraj Patil's avatar
Suraj Patil committed
950
951
952
953
    @unittest.skipIf(
        not is_xformers_available(),
        reason="xformers is not required when using PyTorch 2.0.",
    )
Ruslan Vorovchenko's avatar
Ruslan Vorovchenko committed
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
989
990
991
992
    def test_stable_diffusion_decode_xformers_vs_2_0(self, seed):
        model = self.get_sd_vae_model()
        encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))

        with torch.no_grad():
            sample = model.decode(encoding).sample

        model.enable_xformers_memory_efficient_attention()
        with torch.no_grad():
            sample_2 = model.decode(encoding).sample

        assert list(sample.shape) == [3, 3, 512, 512]

        assert torch_all_close(sample, sample_2, atol=5e-2)

    @parameterized.expand(
        [
            # fmt: off
            [33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],
            [47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],
            # fmt: on
        ]
    )
    def test_stable_diffusion_encode_sample(self, seed, expected_slice):
        model = self.get_sd_vae_model()
        image = self.get_sd_image(seed)
        generator = self.get_generator(seed)

        with torch.no_grad():
            dist = model.encode(image).latent_dist
            sample = dist.sample(generator=generator)

        assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]

        output_slice = sample[0, -1, -3:, -3:].flatten().cpu()
        expected_output_slice = torch.tensor(expected_slice)

        tolerance = 3e-3 if torch_device != "mps" else 1e-2
        assert torch_all_close(output_slice, expected_output_slice, atol=tolerance)
Will Berman's avatar
Will Berman committed
993
994
995
996


@slow
class ConsistencyDecoderVAEIntegrationTests(unittest.TestCase):
997
998
999
1000
1001
1002
    def setUp(self):
        # clean up the VRAM before each test
        super().setUp()
        gc.collect()
        torch.cuda.empty_cache()

Will Berman's avatar
Will Berman committed
1003
1004
1005
1006
1007
1008
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        torch.cuda.empty_cache()

1009
    @torch.no_grad()
Will Berman's avatar
Will Berman committed
1010
1011
1012
1013
1014
1015
1016
1017
    def test_encode_decode(self):
        vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder")  # TODO - update
        vae.to(torch_device)

        image = load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"
        ).resize((256, 256))
1018
1019
1020
        image = torch.from_numpy(np.array(image).transpose(2, 0, 1).astype(np.float32) / 127.5 - 1)[None, :, :, :].to(
            torch_device
        )
Will Berman's avatar
Will Berman committed
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032

        latent = vae.encode(image).latent_dist.mean

        sample = vae.decode(latent, generator=torch.Generator("cpu").manual_seed(0)).sample

        actual_output = sample[0, :2, :2, :2].flatten().cpu()
        expected_output = torch.tensor([-0.0141, -0.0014, 0.0115, 0.0086, 0.1051, 0.1053, 0.1031, 0.1024])

        assert torch_all_close(actual_output, expected_output, atol=5e-3)

    def test_sd(self):
        vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder")  # TODO - update
1033
1034
1035
        pipe = StableDiffusionPipeline.from_pretrained(
            "stable-diffusion-v1-5/stable-diffusion-v1-5", vae=vae, safety_checker=None
        )
Will Berman's avatar
Will Berman committed
1036
1037
1038
        pipe.to(torch_device)

        out = pipe(
Suraj Patil's avatar
Suraj Patil committed
1039
1040
1041
1042
            "horse",
            num_inference_steps=2,
            output_type="pt",
            generator=torch.Generator("cpu").manual_seed(0),
Will Berman's avatar
Will Berman committed
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
        ).images[0]

        actual_output = out[:2, :2, :2].flatten().cpu()
        expected_output = torch.tensor([0.7686, 0.8228, 0.6489, 0.7455, 0.8661, 0.8797, 0.8241, 0.8759])

        assert torch_all_close(actual_output, expected_output, atol=5e-3)

    def test_encode_decode_f16(self):
        vae = ConsistencyDecoderVAE.from_pretrained(
            "openai/consistency-decoder", torch_dtype=torch.float16
        )  # TODO - update
        vae.to(torch_device)

        image = load_image(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"
            "/img2img/sketch-mountains-input.jpg"
        ).resize((256, 256))
        image = (
            torch.from_numpy(np.array(image).transpose(2, 0, 1).astype(np.float32) / 127.5 - 1)[None, :, :, :]
            .half()
1063
            .to(torch_device)
Will Berman's avatar
Will Berman committed
1064
1065
1066
1067
1068
1069
1070
1071
        )

        latent = vae.encode(image).latent_dist.mean

        sample = vae.decode(latent, generator=torch.Generator("cpu").manual_seed(0)).sample

        actual_output = sample[0, :2, :2, :2].flatten().cpu()
        expected_output = torch.tensor(
Suraj Patil's avatar
Suraj Patil committed
1072
1073
            [-0.0111, -0.0125, -0.0017, -0.0007, 0.1257, 0.1465, 0.1450, 0.1471],
            dtype=torch.float16,
Will Berman's avatar
Will Berman committed
1074
1075
1076
1077
1078
1079
1080
1081
1082
        )

        assert torch_all_close(actual_output, expected_output, atol=5e-3)

    def test_sd_f16(self):
        vae = ConsistencyDecoderVAE.from_pretrained(
            "openai/consistency-decoder", torch_dtype=torch.float16
        )  # TODO - update
        pipe = StableDiffusionPipeline.from_pretrained(
1083
            "stable-diffusion-v1-5/stable-diffusion-v1-5",
Suraj Patil's avatar
Suraj Patil committed
1084
1085
1086
            torch_dtype=torch.float16,
            vae=vae,
            safety_checker=None,
Will Berman's avatar
Will Berman committed
1087
1088
1089
1090
        )
        pipe.to(torch_device)

        out = pipe(
Suraj Patil's avatar
Suraj Patil committed
1091
1092
1093
1094
            "horse",
            num_inference_steps=2,
            output_type="pt",
            generator=torch.Generator("cpu").manual_seed(0),
Will Berman's avatar
Will Berman committed
1095
1096
1097
1098
        ).images[0]

        actual_output = out[:2, :2, :2].flatten().cpu()
        expected_output = torch.tensor(
Suraj Patil's avatar
Suraj Patil committed
1099
1100
            [0.0000, 0.0249, 0.0000, 0.0000, 0.1709, 0.2773, 0.0471, 0.1035],
            dtype=torch.float16,
Will Berman's avatar
Will Berman committed
1101
1102
1103
        )

        assert torch_all_close(actual_output, expected_output, atol=5e-3)
1104
1105

    def test_vae_tiling(self):
YiYi Xu's avatar
YiYi Xu committed
1106
1107
        vae = ConsistencyDecoderVAE.from_pretrained("openai/consistency-decoder", torch_dtype=torch.float16)
        pipe = StableDiffusionPipeline.from_pretrained(
1108
            "stable-diffusion-v1-5/stable-diffusion-v1-5", vae=vae, safety_checker=None, torch_dtype=torch.float16
YiYi Xu's avatar
YiYi Xu committed
1109
        )
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        out_1 = pipe(
            "horse",
            num_inference_steps=2,
            output_type="pt",
            generator=torch.Generator("cpu").manual_seed(0),
        ).images[0]

        # make sure tiled vae decode yields the same result
        pipe.enable_vae_tiling()
        out_2 = pipe(
            "horse",
            num_inference_steps=2,
            output_type="pt",
            generator=torch.Generator("cpu").manual_seed(0),
        ).images[0]

        assert torch_all_close(out_1, out_2, atol=5e-3)

        # test that tiled decode works with various shapes
        shapes = [(1, 4, 73, 97), (1, 4, 97, 73), (1, 4, 49, 65), (1, 4, 65, 49)]
YiYi Xu's avatar
YiYi Xu committed
1133
1134
        with torch.no_grad():
            for shape in shapes:
1135
                image = torch.zeros(shape, device=torch_device, dtype=pipe.vae.dtype)
YiYi Xu's avatar
YiYi Xu committed
1136
                pipe.vae.decode(image)
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169


@slow
class AutoencoderOobleckIntegrationTests(unittest.TestCase):
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
        backend_empty_cache(torch_device)

    def _load_datasamples(self, num_samples):
        ds = load_dataset(
            "hf-internal-testing/librispeech_asr_dummy", "clean", split="validation", trust_remote_code=True
        )
        # automatic decoding with librispeech
        speech_samples = ds.sort("id").select(range(num_samples))[:num_samples]["audio"]

        return torch.nn.utils.rnn.pad_sequence(
            [torch.from_numpy(x["array"]) for x in speech_samples], batch_first=True
        )

    def get_audio(self, audio_sample_size=2097152, fp16=False):
        dtype = torch.float16 if fp16 else torch.float32
        audio = self._load_datasamples(2).to(torch_device).to(dtype)

        # pad / crop to audio_sample_size
        audio = torch.nn.functional.pad(audio[:, :audio_sample_size], pad=(0, audio_sample_size - audio.shape[-1]))

        # todo channel
        audio = audio.unsqueeze(1).repeat(1, 2, 1).to(torch_device)

        return audio

1170
    def get_oobleck_vae_model(self, model_id="stabilityai/stable-audio-open-1.0", fp16=False):
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
        torch_dtype = torch.float16 if fp16 else torch.float32

        model = AutoencoderOobleck.from_pretrained(
            model_id,
            subfolder="vae",
            torch_dtype=torch_dtype,
        )
        model.to(torch_device)

        return model

    def get_generator(self, seed=0):
        generator_device = "cpu" if not torch_device.startswith("cuda") else "cuda"
        if torch_device != "mps":
            return torch.Generator(device=generator_device).manual_seed(seed)
        return torch.manual_seed(seed)

    @parameterized.expand(
        [
            # fmt: off
            [33, [1.193e-4, 6.56e-05, 1.314e-4, 3.80e-05, -4.01e-06], 0.001192],
            [44, [2.77e-05, -2.65e-05, 1.18e-05, -6.94e-05, -9.57e-05], 0.001196],
            # fmt: on
        ]
    )
    def test_stable_diffusion(self, seed, expected_slice, expected_mean_absolute_diff):
        model = self.get_oobleck_vae_model()
        audio = self.get_audio()
        generator = self.get_generator(seed)

        with torch.no_grad():
            sample = model(audio, generator=generator, sample_posterior=True).sample

        assert sample.shape == audio.shape
        assert ((sample - audio).abs().mean() - expected_mean_absolute_diff).abs() <= 1e-6

        output_slice = sample[-1, 1, 5:10].cpu()
        expected_output_slice = torch.tensor(expected_slice)

        assert torch_all_close(output_slice, expected_output_slice, atol=1e-5)

    def test_stable_diffusion_mode(self):
        model = self.get_oobleck_vae_model()
        audio = self.get_audio()

        with torch.no_grad():
            sample = model(audio, sample_posterior=False).sample

        assert sample.shape == audio.shape

    @parameterized.expand(
        [
            # fmt: off
            [33, [1.193e-4, 6.56e-05, 1.314e-4, 3.80e-05, -4.01e-06], 0.001192],
            [44, [2.77e-05, -2.65e-05, 1.18e-05, -6.94e-05, -9.57e-05], 0.001196],
            # fmt: on
        ]
    )
    def test_stable_diffusion_encode_decode(self, seed, expected_slice, expected_mean_absolute_diff):
        model = self.get_oobleck_vae_model()
        audio = self.get_audio()
        generator = self.get_generator(seed)

        with torch.no_grad():
            x = audio
            posterior = model.encode(x).latent_dist
            z = posterior.sample(generator=generator)
            sample = model.decode(z).sample

        # (batch_size, latent_dim, sequence_length)
        assert posterior.mean.shape == (audio.shape[0], model.config.decoder_input_channels, 1024)

        assert sample.shape == audio.shape
        assert ((sample - audio).abs().mean() - expected_mean_absolute_diff).abs() <= 1e-6

        output_slice = sample[-1, 1, 5:10].cpu()
        expected_output_slice = torch.tensor(expected_slice)

        assert torch_all_close(output_slice, expected_output_slice, atol=1e-5)