test_stable_diffusion.py 25.4 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
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 gc
import unittest

import numpy as np
import torch
21
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
22
23
24
25

from diffusers import (
    AutoencoderKL,
    DDIMScheduler,
26
    DPMSolverMultistepScheduler,
27
28
29
30
31
32
33
34
    EulerAncestralDiscreteScheduler,
    EulerDiscreteScheduler,
    LMSDiscreteScheduler,
    PNDMScheduler,
    StableDiffusionPipeline,
    UNet2DConditionModel,
    logging,
)
35
36
from diffusers.utils.testing_utils import (
    CaptureLogger,
Arsalan's avatar
Arsalan committed
37
    backend_empty_cache,
38
    enable_full_determinism,
Dhruv Nair's avatar
Dhruv Nair committed
39
40
    load_numpy,
    nightly,
41
    numpy_cosine_similarity_distance,
Arsalan's avatar
Arsalan committed
42
    require_torch_accelerator,
43
    require_torch_gpu,
Arsalan's avatar
Arsalan committed
44
    skip_mps,
Dhruv Nair's avatar
Dhruv Nair committed
45
46
    slow,
    torch_device,
47
)
48

49
50
51
52
53
54
from ..pipeline_params import (
    TEXT_TO_IMAGE_BATCH_PARAMS,
    TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
    TEXT_TO_IMAGE_IMAGE_PARAMS,
    TEXT_TO_IMAGE_PARAMS,
)
55
56
57
58
59
60
from ..test_pipelines_common import (
    PipelineKarrasSchedulerTesterMixin,
    PipelineLatentTesterMixin,
    PipelineTesterMixin,
    SDFunctionTesterMixin,
)
61
62


63
enable_full_determinism()
64
65


66
class StableDiffusion2PipelineFastTests(
67
68
69
70
71
    SDFunctionTesterMixin,
    PipelineLatentTesterMixin,
    PipelineKarrasSchedulerTesterMixin,
    PipelineTesterMixin,
    unittest.TestCase,
72
):
73
    pipeline_class = StableDiffusionPipeline
74
75
    params = TEXT_TO_IMAGE_PARAMS
    batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
76
    image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
77
    image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
78
    callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS
79

80
    def get_dummy_components(self):
81
        torch.manual_seed(0)
82
        unet = UNet2DConditionModel(
83
84
85
86
87
88
89
90
91
            block_out_channels=(32, 64),
            layers_per_block=2,
            sample_size=32,
            in_channels=4,
            out_channels=4,
            down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
            up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
            cross_attention_dim=32,
            # SD2-specific config below
Will Berman's avatar
Will Berman committed
92
            attention_head_dim=(2, 4),
93
94
            use_linear_projection=True,
        )
95
96
97
98
99
100
101
        scheduler = DDIMScheduler(
            beta_start=0.00085,
            beta_end=0.012,
            beta_schedule="scaled_linear",
            clip_sample=False,
            set_alpha_to_one=False,
        )
102
        torch.manual_seed(0)
103
        vae = AutoencoderKL(
104
105
106
107
108
109
110
111
112
            block_out_channels=[32, 64],
            in_channels=3,
            out_channels=3,
            down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
            up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
            latent_channels=4,
            sample_size=128,
        )
        torch.manual_seed(0)
113
        text_encoder_config = CLIPTextConfig(
114
115
116
117
118
119
120
121
122
123
124
125
126
            bos_token_id=0,
            eos_token_id=2,
            hidden_size=32,
            intermediate_size=37,
            layer_norm_eps=1e-05,
            num_attention_heads=4,
            num_hidden_layers=5,
            pad_token_id=1,
            vocab_size=1000,
            # SD2-specific config below
            hidden_act="gelu",
            projection_dim=512,
        )
127
        text_encoder = CLIPTextModel(text_encoder_config)
128
129
        tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")

130
131
132
133
134
135
136
137
        components = {
            "unet": unet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "safety_checker": None,
            "feature_extractor": None,
138
            "image_encoder": None,
139
140
141
142
        }
        return components

    def get_dummy_inputs(self, device, seed=0):
Arsalan's avatar
Arsalan committed
143
144
145
        generator_device = "cpu" if not device.startswith("cuda") else "cuda"
        if not str(device).startswith("mps"):
            generator = torch.Generator(device=generator_device).manual_seed(seed)
146
        else:
Arsalan's avatar
Arsalan committed
147
148
            generator = torch.manual_seed(seed)

149
150
151
152
153
        inputs = {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 6.0,
154
            "output_type": "np",
155
156
        }
        return inputs
157
158
159

    def test_stable_diffusion_ddim(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
160
161
        components = self.get_dummy_components()
        sd_pipe = StableDiffusionPipeline(**components)
162
163
164
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

165
166
        inputs = self.get_dummy_inputs(device)
        image = sd_pipe(**inputs).images
167
168
169
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
170
        expected_slice = np.array([0.5753, 0.6113, 0.5005, 0.5036, 0.5464, 0.4725, 0.4982, 0.4865, 0.4861])
171
172
173
174
175

        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

    def test_stable_diffusion_pndm(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
176
177
178
        components = self.get_dummy_components()
        components["scheduler"] = PNDMScheduler(skip_prk_steps=True)
        sd_pipe = StableDiffusionPipeline(**components)
179
180
181
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

182
183
        inputs = self.get_dummy_inputs(device)
        image = sd_pipe(**inputs).images
184
185
186
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
187
        expected_slice = np.array([0.5121, 0.5714, 0.4827, 0.5057, 0.5646, 0.4766, 0.5189, 0.4895, 0.4990])
188

189
190
191
192
        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

    def test_stable_diffusion_k_lms(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
193
194
195
        components = self.get_dummy_components()
        components["scheduler"] = LMSDiscreteScheduler.from_config(components["scheduler"].config)
        sd_pipe = StableDiffusionPipeline(**components)
196
197
198
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

199
200
        inputs = self.get_dummy_inputs(device)
        image = sd_pipe(**inputs).images
201
202
203
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
204
        expected_slice = np.array([0.4865, 0.5439, 0.4840, 0.4995, 0.5543, 0.4846, 0.5199, 0.4942, 0.5061])
205

206
207
208
209
        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

    def test_stable_diffusion_k_euler_ancestral(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
210
211
212
        components = self.get_dummy_components()
        components["scheduler"] = EulerAncestralDiscreteScheduler.from_config(components["scheduler"].config)
        sd_pipe = StableDiffusionPipeline(**components)
213
214
215
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

216
217
        inputs = self.get_dummy_inputs(device)
        image = sd_pipe(**inputs).images
218
219
220
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
221
        expected_slice = np.array([0.4864, 0.5440, 0.4842, 0.4994, 0.5543, 0.4846, 0.5196, 0.4942, 0.5063])
222

223
224
225
226
        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

    def test_stable_diffusion_k_euler(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
227
228
229
        components = self.get_dummy_components()
        components["scheduler"] = EulerDiscreteScheduler.from_config(components["scheduler"].config)
        sd_pipe = StableDiffusionPipeline(**components)
230
231
232
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

233
234
        inputs = self.get_dummy_inputs(device)
        image = sd_pipe(**inputs).images
235
236
237
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
238
        expected_slice = np.array([0.4865, 0.5439, 0.4840, 0.4995, 0.5543, 0.4846, 0.5199, 0.4942, 0.5061])
239

240
241
        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
    def test_stable_diffusion_unflawed(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
        components = self.get_dummy_components()
        components["scheduler"] = DDIMScheduler.from_config(
            components["scheduler"].config, timestep_spacing="trailing"
        )
        sd_pipe = StableDiffusionPipeline(**components)
        sd_pipe = sd_pipe.to(device)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(device)
        inputs["guidance_rescale"] = 0.7
        inputs["num_inference_steps"] = 10
        image = sd_pipe(**inputs).images
        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 64, 64, 3)
        expected_slice = np.array([0.4736, 0.5405, 0.4705, 0.4955, 0.5675, 0.4812, 0.5310, 0.4967, 0.5064])

        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2

263
    def test_stable_diffusion_long_prompt(self):
264
265
266
        components = self.get_dummy_components()
        components["scheduler"] = LMSDiscreteScheduler.from_config(components["scheduler"].config)
        sd_pipe = StableDiffusionPipeline(**components)
267
268
269
270
271
272
273
        sd_pipe = sd_pipe.to(torch_device)
        sd_pipe.set_progress_bar_config(disable=None)

        do_classifier_free_guidance = True
        negative_prompt = None
        num_images_per_prompt = 1
        logger = logging.get_logger("diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion")
274
        logger.setLevel(logging.WARNING)
275
276
277

        prompt = 25 * "@"
        with CaptureLogger(logger) as cap_logger_3:
278
            text_embeddings_3, negeative_text_embeddings_3 = sd_pipe.encode_prompt(
279
280
                prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
            )
281
282
            if negeative_text_embeddings_3 is not None:
                text_embeddings_3 = torch.cat([negeative_text_embeddings_3, text_embeddings_3])
283
284
285

        prompt = 100 * "@"
        with CaptureLogger(logger) as cap_logger:
286
            text_embeddings, negative_embeddings = sd_pipe.encode_prompt(
287
288
                prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
            )
289
290
            if negative_embeddings is not None:
                text_embeddings = torch.cat([negative_embeddings, text_embeddings])
291
292
293

        negative_prompt = "Hello"
        with CaptureLogger(logger) as cap_logger_2:
294
            text_embeddings_2, negative_text_embeddings_2 = sd_pipe.encode_prompt(
295
296
                prompt, torch_device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
            )
297
298
            if negative_text_embeddings_2 is not None:
                text_embeddings_2 = torch.cat([negative_text_embeddings_2, text_embeddings_2])
299
300
301
302
303
304
305
306
307

        assert text_embeddings_3.shape == text_embeddings_2.shape == text_embeddings.shape
        assert text_embeddings.shape[1] == 77

        assert cap_logger.out == cap_logger_2.out
        # 100 - 77 + 1 (BOS token) + 1 (EOS token) = 25
        assert cap_logger.out.count("@") == 25
        assert cap_logger_3.out == ""

308
309
310
311
312
313
    def test_attention_slicing_forward_pass(self):
        super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)

    def test_inference_batch_single_identical(self):
        super().test_inference_batch_single_identical(expected_max_diff=3e-3)

314
315

@slow
Arsalan's avatar
Arsalan committed
316
317
@require_torch_accelerator
@skip_mps
318
class StableDiffusion2PipelineSlowTests(unittest.TestCase):
319
320
321
    def tearDown(self):
        super().tearDown()
        gc.collect()
322
        backend_empty_cache(torch_device)
323

324
    def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
Arsalan's avatar
Arsalan committed
325
326
327
328
329
330
        _generator_device = "cpu" if not generator_device.startswith("cuda") else "cuda"
        if not str(device).startswith("mps"):
            generator = torch.Generator(device=_generator_device).manual_seed(seed)
        else:
            generator = torch.manual_seed(seed)

331
332
333
334
335
336
337
338
        latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
        latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
        inputs = {
            "prompt": "a photograph of an astronaut riding a horse",
            "latents": latents,
            "generator": generator,
            "num_inference_steps": 3,
            "guidance_scale": 7.5,
339
            "output_type": "np",
340
341
        }
        return inputs
342

343
344
345
346
    def test_stable_diffusion_default_ddim(self):
        pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
347

348
349
350
        inputs = self.get_inputs(torch_device)
        image = pipe(**inputs).images
        image_slice = image[0, -3:, -3:, -1].flatten()
351
352

        assert image.shape == (1, 512, 512, 3)
353
        expected_slice = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])
354
        assert np.abs(image_slice - expected_slice).max() < 7e-3
355

356
357
358
359
360
    def test_stable_diffusion_pndm(self):
        pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")
        pipe.scheduler = PNDMScheduler.from_config(pipe.scheduler.config)
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
361

362
363
364
        inputs = self.get_inputs(torch_device)
        image = pipe(**inputs).images
        image_slice = image[0, -3:, -3:, -1].flatten()
365
366

        assert image.shape == (1, 512, 512, 3)
367
        expected_slice = np.array([0.49493, 0.47896, 0.40798, 0.54214, 0.53212, 0.48202, 0.47656, 0.46329, 0.48506])
368
        assert np.abs(image_slice - expected_slice).max() < 7e-3
369
370

    def test_stable_diffusion_k_lms(self):
371
372
373
374
        pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base")
        pipe.scheduler = LMSDiscreteScheduler.from_config(pipe.scheduler.config)
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
375

376
377
378
        inputs = self.get_inputs(torch_device)
        image = pipe(**inputs).images
        image_slice = image[0, -3:, -3:, -1].flatten()
379
380

        assert image.shape == (1, 512, 512, 3)
381
        expected_slice = np.array([0.10440, 0.13115, 0.11100, 0.10141, 0.11440, 0.07215, 0.11332, 0.09693, 0.10006])
382
        assert np.abs(image_slice - expected_slice).max() < 3e-3
383

Arsalan's avatar
Arsalan committed
384
    @require_torch_gpu
385
    def test_stable_diffusion_attention_slicing(self):
386
        torch.cuda.reset_peak_memory_stats()
387
        pipe = StableDiffusionPipeline.from_pretrained(
388
            "stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16
389
        )
390
        pipe.unet.set_default_attn_processor()
391
        pipe = pipe.to(torch_device)
392
393
        pipe.set_progress_bar_config(disable=None)

394
        # enable attention slicing
395
        pipe.enable_attention_slicing()
396
397
        inputs = self.get_inputs(torch_device, dtype=torch.float16)
        image_sliced = pipe(**inputs).images
398
399
400

        mem_bytes = torch.cuda.max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()
401
402
        # make sure that less than 3.3 GB is allocated
        assert mem_bytes < 3.3 * 10**9
403

404
        # disable slicing
405
        pipe.disable_attention_slicing()
406
        pipe.unet.set_default_attn_processor()
407
408
        inputs = self.get_inputs(torch_device, dtype=torch.float16)
        image = pipe(**inputs).images
409

410
        # make sure that more than 3.3 GB is allocated
411
        mem_bytes = torch.cuda.max_memory_allocated()
412
        assert mem_bytes > 3.3 * 10**9
413
414
        max_diff = numpy_cosine_similarity_distance(image.flatten(), image_sliced.flatten())
        assert max_diff < 5e-3
415
416
417
418

    def test_stable_diffusion_text2img_intermediate_state(self):
        number_of_steps = 0

419
        def callback_fn(step: int, timestep: int, latents: torch.Tensor) -> None:
420
            callback_fn.has_been_called = True
421
422
            nonlocal number_of_steps
            number_of_steps += 1
423
            if step == 1:
424
425
426
                latents = latents.detach().cpu().numpy()
                assert latents.shape == (1, 4, 64, 64)
                latents_slice = latents[0, -3:, -3:, -1]
427
428
429
430
431
                expected_slice = np.array(
                    [-0.3862, -0.4507, -1.1729, 0.0686, -1.1045, 0.7124, -1.8301, 0.1903, 1.2773]
                )

                assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2
432
            elif step == 2:
433
434
435
                latents = latents.detach().cpu().numpy()
                assert latents.shape == (1, 4, 64, 64)
                latents_slice = latents[0, -3:, -3:, -1]
436
437
438
439
440
                expected_slice = np.array(
                    [0.2720, -0.1863, -0.7383, -0.5029, -0.7534, 0.3970, -0.7646, 0.4468, 1.2686]
                )

                assert np.abs(latents_slice.flatten() - expected_slice).max() < 5e-2
441

442
        callback_fn.has_been_called = False
443
444

        pipe = StableDiffusionPipeline.from_pretrained(
445
            "stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16
446
447
448
449
450
        )
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        pipe.enable_attention_slicing()

451
452
453
454
        inputs = self.get_inputs(torch_device, dtype=torch.float16)
        pipe(**inputs, callback=callback_fn, callback_steps=1)
        assert callback_fn.has_been_called
        assert number_of_steps == inputs["num_inference_steps"]
455

Arsalan's avatar
Arsalan committed
456
    @require_torch_gpu
457
458
459
460
461
    def test_stable_diffusion_pipeline_with_sequential_cpu_offloading(self):
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

462
        pipe = StableDiffusionPipeline.from_pretrained(
463
            "stabilityai/stable-diffusion-2-base", torch_dtype=torch.float16
464
465
466
467
468
        )
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        pipe.enable_attention_slicing(1)
        pipe.enable_sequential_cpu_offload()
469

470
471
        inputs = self.get_inputs(torch_device, dtype=torch.float16)
        _ = pipe(**inputs)
472
473
474
475

        mem_bytes = torch.cuda.max_memory_allocated()
        # make sure that less than 2.8 GB is allocated
        assert mem_bytes < 2.8 * 10**9
476

Arsalan's avatar
Arsalan committed
477
    @require_torch_gpu
478
479
480
481
482
483
484
485
486
487
488
489
490
    def test_stable_diffusion_pipeline_with_model_offloading(self):
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        inputs = self.get_inputs(torch_device, dtype=torch.float16)

        # Normal inference

        pipe = StableDiffusionPipeline.from_pretrained(
            "stabilityai/stable-diffusion-2-base",
            torch_dtype=torch.float16,
        )
491
        pipe.unet.set_default_attn_processor()
492
493
494
495
496
497
498
499
500
501
502
503
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        outputs = pipe(**inputs)
        mem_bytes = torch.cuda.max_memory_allocated()

        # With model offloading

        # Reload but don't move to cuda
        pipe = StableDiffusionPipeline.from_pretrained(
            "stabilityai/stable-diffusion-2-base",
            torch_dtype=torch.float16,
        )
504
        pipe.unet.set_default_attn_processor()
505
506
507
508
509
510
511

        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        pipe.enable_model_cpu_offload()
        pipe.set_progress_bar_config(disable=None)
512
        inputs = self.get_inputs(torch_device, dtype=torch.float16)
513
514
515
        outputs_offloaded = pipe(**inputs)
        mem_bytes_offloaded = torch.cuda.max_memory_allocated()

516
517
518
519
        images = outputs.images
        images_offloaded = outputs_offloaded.images
        max_diff = numpy_cosine_similarity_distance(images.flatten(), images_offloaded.flatten())
        assert max_diff < 1e-3
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
        assert mem_bytes_offloaded < mem_bytes
        assert mem_bytes_offloaded < 3 * 10**9
        for module in pipe.text_encoder, pipe.unet, pipe.vae:
            assert module.device == torch.device("cpu")

        # With attention slicing
        torch.cuda.empty_cache()
        torch.cuda.reset_max_memory_allocated()
        torch.cuda.reset_peak_memory_stats()

        pipe.enable_attention_slicing()
        _ = pipe(**inputs)
        mem_bytes_slicing = torch.cuda.max_memory_allocated()
        assert mem_bytes_slicing < mem_bytes_offloaded

535
536

@nightly
Arsalan's avatar
Arsalan committed
537
538
@require_torch_accelerator
@skip_mps
539
540
541
542
class StableDiffusion2PipelineNightlyTests(unittest.TestCase):
    def tearDown(self):
        super().tearDown()
        gc.collect()
543
        backend_empty_cache(torch_device)
544

545
    def get_inputs(self, device, generator_device="cpu", dtype=torch.float32, seed=0):
Arsalan's avatar
Arsalan committed
546
547
548
549
550
551
        _generator_device = "cpu" if not generator_device.startswith("cuda") else "cuda"
        if not str(device).startswith("mps"):
            generator = torch.Generator(device=_generator_device).manual_seed(seed)
        else:
            generator = torch.manual_seed(seed)

552
553
554
555
556
557
558
559
        latents = np.random.RandomState(seed).standard_normal((1, 4, 64, 64))
        latents = torch.from_numpy(latents).to(device=device, dtype=dtype)
        inputs = {
            "prompt": "a photograph of an astronaut riding a horse",
            "latents": latents,
            "generator": generator,
            "num_inference_steps": 50,
            "guidance_scale": 7.5,
560
            "output_type": "np",
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
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
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
        }
        return inputs

    def test_stable_diffusion_2_0_default_ddim(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-base").to(torch_device)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_0_base_ddim.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3

    def test_stable_diffusion_2_1_default_pndm(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_1_base_pndm.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3

    def test_stable_diffusion_ddim(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)
        sd_pipe.scheduler = DDIMScheduler.from_config(sd_pipe.scheduler.config)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_1_base_ddim.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3

    def test_stable_diffusion_lms(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)
        sd_pipe.scheduler = LMSDiscreteScheduler.from_config(sd_pipe.scheduler.config)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_1_base_lms.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3

    def test_stable_diffusion_euler(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)
        sd_pipe.scheduler = EulerDiscreteScheduler.from_config(sd_pipe.scheduler.config)
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_1_base_euler.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3

    def test_stable_diffusion_dpm(self):
        sd_pipe = StableDiffusionPipeline.from_pretrained("stabilityai/stable-diffusion-2-1-base").to(torch_device)
639
640
641
        sd_pipe.scheduler = DPMSolverMultistepScheduler.from_config(
            sd_pipe.scheduler.config, final_sigmas_type="sigma_min"
        )
642
643
644
645
646
647
648
649
650
651
652
653
        sd_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_inputs(torch_device)
        inputs["num_inference_steps"] = 25
        image = sd_pipe(**inputs).images[0]

        expected_image = load_numpy(
            "https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
            "/stable_diffusion_2_text2img/stable_diffusion_2_1_base_dpm_multi.npy"
        )
        max_diff = np.abs(expected_image - image).max()
        assert max_diff < 1e-3