test_pipelines_common.py 127 KB
Newer Older
1
2
import gc
import inspect
3
4
import json
import os
5
6
import tempfile
import unittest
7
import uuid
Aryan's avatar
Aryan committed
8
from typing import Any, Callable, Dict, Union
9
10

import numpy as np
Anh71me's avatar
Anh71me committed
11
import PIL.Image
12
import torch
13
import torch.nn as nn
14
15
from huggingface_hub import ModelCard, delete_repo
from huggingface_hub.utils import is_jinja_available
16
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
17

18
import diffusers
19
20
21
22
23
24
25
from diffusers import (
    AsymmetricAutoencoderKL,
    AutoencoderKL,
    AutoencoderTiny,
    ConsistencyDecoderVAE,
    DDIMScheduler,
    DiffusionPipeline,
Aryan's avatar
Aryan committed
26
    FasterCacheConfig,
Álvaro Somoza's avatar
Álvaro Somoza committed
27
    KolorsPipeline,
28
    PyramidAttentionBroadcastConfig,
29
    StableDiffusionPipeline,
30
    StableDiffusionXLPipeline,
31
    UNet2DConditionModel,
Aryan's avatar
Aryan committed
32
    apply_faster_cache,
33
)
Aryan's avatar
Aryan committed
34
from diffusers.hooks import apply_group_offloading
Aryan's avatar
Aryan committed
35
from diffusers.hooks.faster_cache import FasterCacheBlockHook, FasterCacheDenoiserHook
Aryan's avatar
Aryan committed
36
from diffusers.hooks.first_block_cache import FirstBlockCacheConfig
37
from diffusers.hooks.pyramid_attention_broadcast import PyramidAttentionBroadcastHook
38
from diffusers.image_processor import VaeImageProcessor
hlky's avatar
hlky committed
39
from diffusers.loaders import FluxIPAdapterMixin, IPAdapterMixin
40
from diffusers.models.attention import AttentionModuleMixin
41
from diffusers.models.attention_processor import AttnProcessor
42
from diffusers.models.controlnets.controlnet_xs import UNetControlNetXSModel
43
44
45
46
from diffusers.models.unets.unet_3d_condition import UNet3DConditionModel
from diffusers.models.unets.unet_i2vgen_xl import I2VGenXLUNet
from diffusers.models.unets.unet_motion_model import UNetMotionModel
from diffusers.pipelines.pipeline_utils import StableDiffusionMixin
47
from diffusers.schedulers import KarrasDiffusionSchedulers
48
from diffusers.utils import logging
49
from diffusers.utils.import_utils import is_xformers_available
50
from diffusers.utils.source_code_parsing_utils import ReturnNameVisitor
51
52
from diffusers.utils.testing_utils import (
    CaptureLogger,
53
    backend_empty_cache,
54
    numpy_cosine_similarity_distance,
55
56
    require_accelerate_version_greater,
    require_accelerator,
Marc Sun's avatar
Marc Sun committed
57
    require_hf_hub_version_greater,
58
    require_torch,
59
    require_torch_accelerator,
Marc Sun's avatar
Marc Sun committed
60
    require_transformers_version_greater,
61
62
63
    skip_mps,
    torch_device,
)
64

65
from ..models.autoencoders.vae import (
66
67
68
69
70
    get_asym_autoencoder_kl_config,
    get_autoencoder_kl_config,
    get_autoencoder_tiny_config,
    get_consistency_vae_config,
)
hlky's avatar
hlky committed
71
from ..models.transformers.test_models_transformer_flux import create_flux_ip_adapter_state_dict
72
73
74
75
from ..models.unets.test_models_unet_2d_condition import (
    create_ip_adapter_faceid_state_dict,
    create_ip_adapter_state_dict,
)
76
77
from ..others.test_utils import TOKEN, USER, is_staging_test

78

79
80
81
82
83
84
85
def to_np(tensor):
    if isinstance(tensor, torch.Tensor):
        tensor = tensor.detach().cpu().numpy()

    return tensor


86
87
88
89
90
def check_same_shape(tensor_list):
    shapes = [tensor.shape for tensor in tensor_list]
    return all(shape == shapes[0] for shape in shapes[1:])


91
92
93
94
95
96
97
98
99
100
101
def check_qkv_fusion_matches_attn_procs_length(model, original_attn_processors):
    current_attn_processors = model.attn_processors
    return len(current_attn_processors) == len(original_attn_processors)


def check_qkv_fusion_processors_exist(model):
    current_attn_processors = model.attn_processors
    proc_names = [v.__class__.__name__ for _, v in current_attn_processors.items()]
    return all(p.startswith("Fused") for p in proc_names)


102
103
104
105
106
107
108
109
110
111
112
113
114
115
def check_qkv_fused_layers_exist(model, layer_names):
    is_fused_submodules = []
    for submodule in model.modules():
        if not isinstance(submodule, AttentionModuleMixin):
            continue
        is_fused_attribute_set = submodule.fused_projections
        is_fused_layer = True
        for layer in layer_names:
            is_fused_layer = is_fused_layer and getattr(submodule, layer, None) is not None
        is_fused = is_fused_attribute_set and is_fused_layer
        is_fused_submodules.append(is_fused)
    return all(is_fused_submodules)


116
117
118
119
120
121
class SDFunctionTesterMixin:
    """
    This mixin is designed to be used with PipelineTesterMixin and unittest.TestCase classes.
    It provides a set of common tests for PyTorch pipeline that inherit from StableDiffusionMixin, e.g. vae_slicing, vae_tiling, freeu, etc.
    """

122
    def test_vae_slicing(self, image_count=4):
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
        components = self.get_dummy_components()
        # components["scheduler"] = LMSDiscreteScheduler.from_config(components["scheduler"].config)
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(device)
        inputs["prompt"] = [inputs["prompt"]] * image_count
        if "image" in inputs:  # fix batch size mismatch in I2V_Gen pipeline
            inputs["image"] = [inputs["image"]] * image_count
        output_1 = pipe(**inputs)

        # make sure sliced vae decode yields the same result
        pipe.enable_vae_slicing()
        inputs = self.get_dummy_inputs(device)
        inputs["prompt"] = [inputs["prompt"]] * image_count
        if "image" in inputs:
            inputs["image"] = [inputs["image"]] * image_count
        inputs["return_dict"] = False
        output_2 = pipe(**inputs)

        assert np.abs(output_2[0].flatten() - output_1[0].flatten()).max() < 1e-2

    def test_vae_tiling(self):
        components = self.get_dummy_components()

        # make sure here that pndm scheduler skips prk
        if "safety_checker" in components:
            components["safety_checker"] = None
        pipe = self.pipeline_class(**components)
154
        pipe = pipe.to(torch_device)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
        inputs["return_dict"] = False

        # Test that tiled decode at 512x512 yields the same result as the non-tiled decode
        output_1 = pipe(**inputs)[0]

        # make sure tiled vae decode yields the same result
        pipe.enable_vae_tiling()
        inputs = self.get_dummy_inputs(torch_device)
        inputs["return_dict"] = False
        output_2 = pipe(**inputs)[0]

169
        assert np.abs(to_np(output_2) - to_np(output_1)).max() < 5e-1
170
171

        # test that tiled decode works with various shapes
172
        shapes = [(1, 4, 73, 97), (1, 4, 65, 49)]
YiYi Xu's avatar
YiYi Xu committed
173
174
175
176
        with torch.no_grad():
            for shape in shapes:
                zeros = torch.zeros(shape).to(torch_device)
                pipe.vae.decode(zeros)
177

178
    # MPS currently doesn't support ComplexFloats, which are required for FreeU - see https://github.com/huggingface/diffusers/issues/7569.
179
    @skip_mps
180
    def test_freeu(self):
181
182
183
184
185
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

186
        # Normal inference
187
188
        inputs = self.get_dummy_inputs(torch_device)
        inputs["return_dict"] = False
Dhruv Nair's avatar
Dhruv Nair committed
189
        inputs["output_type"] = "np"
190
191
        output = pipe(**inputs)[0]

192
        # FreeU-enabled inference
193
194
195
        pipe.enable_freeu(s1=0.9, s2=0.2, b1=1.2, b2=1.4)
        inputs = self.get_dummy_inputs(torch_device)
        inputs["return_dict"] = False
Dhruv Nair's avatar
Dhruv Nair committed
196
        inputs["output_type"] = "np"
197
198
        output_freeu = pipe(**inputs)[0]

199
        # FreeU-disabled inference
200
201
202
203
204
205
206
207
        pipe.disable_freeu()
        freeu_keys = {"s1", "s2", "b1", "b2"}
        for upsample_block in pipe.unet.up_blocks:
            for key in freeu_keys:
                assert getattr(upsample_block, key) is None, f"Disabling of FreeU should have set {key} to None."

        inputs = self.get_dummy_inputs(torch_device)
        inputs["return_dict"] = False
Dhruv Nair's avatar
Dhruv Nair committed
208
        inputs["output_type"] = "np"
209
        output_no_freeu = pipe(**inputs)[0]
210

211
212
213
214
215
216
        assert not np.allclose(output[0, -3:, -3:, -1], output_freeu[0, -3:, -3:, -1]), (
            "Enabling of FreeU should lead to different results."
        )
        assert np.allclose(output, output_no_freeu, atol=1e-2), (
            f"Disabling of FreeU should lead to results similar to the default pipeline results but Max Abs Error={np.abs(output_no_freeu - output).max()}."
        )
217
218
219
220
221
222
223
224
225
226
227
228
229
230

    def test_fused_qkv_projections(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(device)
        inputs["return_dict"] = False
        image = pipe(**inputs)[0]
        original_image_slice = image[0, -3:, -3:, -1]

        pipe.fuse_qkv_projections()
231
232
233
234
235
236
        for _, component in pipe.components.items():
            if (
                isinstance(component, nn.Module)
                and hasattr(component, "original_attn_processors")
                and component.original_attn_processors is not None
            ):
237
238
239
240
241
242
                assert check_qkv_fusion_processors_exist(component), (
                    "Something wrong with the fused attention processors. Expected all the attention processors to be fused."
                )
                assert check_qkv_fusion_matches_attn_procs_length(component, component.original_attn_processors), (
                    "Something wrong with the attention processors concerning the fused QKV projections."
                )
243

244
245
246
247
248
249
250
251
252
253
254
        inputs = self.get_dummy_inputs(device)
        inputs["return_dict"] = False
        image_fused = pipe(**inputs)[0]
        image_slice_fused = image_fused[0, -3:, -3:, -1]

        pipe.unfuse_qkv_projections()
        inputs = self.get_dummy_inputs(device)
        inputs["return_dict"] = False
        image_disabled = pipe(**inputs)[0]
        image_slice_disabled = image_disabled[0, -3:, -3:, -1]

255
256
257
258
259
260
261
262
263
        assert np.allclose(original_image_slice, image_slice_fused, atol=1e-2, rtol=1e-2), (
            "Fusion of QKV projections shouldn't affect the outputs."
        )
        assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-2, rtol=1e-2), (
            "Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
        )
        assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
            "Original outputs should match when fused QKV projections are disabled."
        )
264
265


Aryan's avatar
Aryan committed
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
class IPAdapterTesterMixin:
    """
    This mixin is designed to be used with PipelineTesterMixin and unittest.TestCase classes.
    It provides a set of common tests for pipelines that support IP Adapters.
    """

    def test_pipeline_signature(self):
        parameters = inspect.signature(self.pipeline_class.__call__).parameters

        assert issubclass(self.pipeline_class, IPAdapterMixin)
        self.assertIn(
            "ip_adapter_image",
            parameters,
            "`ip_adapter_image` argument must be supported by the `__call__` method",
        )
        self.assertIn(
            "ip_adapter_image_embeds",
            parameters,
            "`ip_adapter_image_embeds` argument must be supported by the `__call__` method",
        )

    def _get_dummy_image_embeds(self, cross_attention_dim: int = 32):
        return torch.randn((2, 1, cross_attention_dim), device=torch_device)

290
291
292
    def _get_dummy_faceid_image_embeds(self, cross_attention_dim: int = 32):
        return torch.randn((2, 1, 1, cross_attention_dim), device=torch_device)

293
294
295
296
297
    def _get_dummy_masks(self, input_size: int = 64):
        _masks = torch.zeros((1, 1, input_size, input_size), device=torch_device)
        _masks[0, :, :, : int(input_size / 2)] = 1
        return _masks

Aryan's avatar
Aryan committed
298
299
300
301
302
303
304
305
306
    def _modify_inputs_for_ip_adapter_test(self, inputs: Dict[str, Any]):
        parameters = inspect.signature(self.pipeline_class.__call__).parameters
        if "image" in parameters.keys() and "strength" in parameters.keys():
            inputs["num_inference_steps"] = 4

        inputs["output_type"] = "np"
        inputs["return_dict"] = False
        return inputs

307
308
309
310
311
312
313
314
315
    def test_ip_adapter(self, expected_max_diff: float = 1e-4, expected_pipe_slice=None):
        r"""Tests for IP-Adapter.

        The following scenarios are tested:
          - Single IP-Adapter with scale=0 should produce same output as no IP-Adapter.
          - Multi IP-Adapter with scale=0 should produce same output as no IP-Adapter.
          - Single IP-Adapter with scale!=0 should produce different output compared to no IP-Adapter.
          - Multi IP-Adapter with scale!=0 should produce different output compared to no IP-Adapter.
        """
316
317
318
319
        # Raising the tolerance for this test when it's run on a CPU because we
        # compare against static slices and that can be shaky (with a VVVV low probability).
        expected_max_diff = 9e-4 if torch_device == "cpu" else expected_max_diff

Aryan's avatar
Aryan committed
320
321
322
323
324
325
326
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components).to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        cross_attention_dim = pipe.unet.config.get("cross_attention_dim", 32)

        # forward pass without ip adapter
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
327
328
329
330
        if expected_pipe_slice is None:
            output_without_adapter = pipe(**inputs)[0]
        else:
            output_without_adapter = expected_pipe_slice
Aryan's avatar
Aryan committed
331

332
        # 1. Single IP-Adapter test cases
Aryan's avatar
Aryan committed
333
334
335
336
337
338
339
340
        adapter_state_dict = create_ip_adapter_state_dict(pipe.unet)
        pipe.unet._load_ip_adapter_weights(adapter_state_dict)

        # forward pass with single ip adapter, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)]
        pipe.set_ip_adapter_scale(0.0)
        output_without_adapter_scale = pipe(**inputs)[0]
341
342
        if expected_pipe_slice is not None:
            output_without_adapter_scale = output_without_adapter_scale[0, -3:, -3:, -1].flatten()
Aryan's avatar
Aryan committed
343
344
345
346
347
348

        # forward pass with single ip adapter, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)]
        pipe.set_ip_adapter_scale(42.0)
        output_with_adapter_scale = pipe(**inputs)[0]
349
350
        if expected_pipe_slice is not None:
            output_with_adapter_scale = output_with_adapter_scale[0, -3:, -3:, -1].flatten()
Aryan's avatar
Aryan committed
351
352
353
354
355
356
357
358
359
360
361
362
363

        max_diff_without_adapter_scale = np.abs(output_without_adapter_scale - output_without_adapter).max()
        max_diff_with_adapter_scale = np.abs(output_with_adapter_scale - output_without_adapter).max()

        self.assertLess(
            max_diff_without_adapter_scale,
            expected_max_diff,
            "Output without ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_adapter_scale, 1e-2, "Output with ip-adapter must be different from normal inference"
        )

364
        # 2. Multi IP-Adapter test cases
Aryan's avatar
Aryan committed
365
366
367
368
369
370
371
372
373
        adapter_state_dict_1 = create_ip_adapter_state_dict(pipe.unet)
        adapter_state_dict_2 = create_ip_adapter_state_dict(pipe.unet)
        pipe.unet._load_ip_adapter_weights([adapter_state_dict_1, adapter_state_dict_2])

        # forward pass with multi ip adapter, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)] * 2
        pipe.set_ip_adapter_scale([0.0, 0.0])
        output_without_multi_adapter_scale = pipe(**inputs)[0]
374
375
        if expected_pipe_slice is not None:
            output_without_multi_adapter_scale = output_without_multi_adapter_scale[0, -3:, -3:, -1].flatten()
Aryan's avatar
Aryan committed
376
377
378
379
380
381

        # forward pass with multi ip adapter, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)] * 2
        pipe.set_ip_adapter_scale([42.0, 42.0])
        output_with_multi_adapter_scale = pipe(**inputs)[0]
382
383
        if expected_pipe_slice is not None:
            output_with_multi_adapter_scale = output_with_multi_adapter_scale[0, -3:, -3:, -1].flatten()
Aryan's avatar
Aryan committed
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399

        max_diff_without_multi_adapter_scale = np.abs(
            output_without_multi_adapter_scale - output_without_adapter
        ).max()
        max_diff_with_multi_adapter_scale = np.abs(output_with_multi_adapter_scale - output_without_adapter).max()
        self.assertLess(
            max_diff_without_multi_adapter_scale,
            expected_max_diff,
            "Output without multi-ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_multi_adapter_scale,
            1e-2,
            "Output with multi-ip-adapter scale must be different from normal inference",
        )

400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
    def test_ip_adapter_cfg(self, expected_max_diff: float = 1e-4):
        parameters = inspect.signature(self.pipeline_class.__call__).parameters

        if "guidance_scale" not in parameters:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components).to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        cross_attention_dim = pipe.unet.config.get("cross_attention_dim", 32)

        adapter_state_dict = create_ip_adapter_state_dict(pipe.unet)
        pipe.unet._load_ip_adapter_weights(adapter_state_dict)
        pipe.set_ip_adapter_scale(1.0)

        # forward pass with CFG not applied
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)[0].unsqueeze(0)]
        inputs["guidance_scale"] = 1.0
        out_no_cfg = pipe(**inputs)[0]

        # forward pass with CFG applied
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)]
        inputs["guidance_scale"] = 7.5
        out_cfg = pipe(**inputs)[0]

        assert out_cfg.shape == out_no_cfg.shape

429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
    def test_ip_adapter_masks(self, expected_max_diff: float = 1e-4):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components).to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        cross_attention_dim = pipe.unet.config.get("cross_attention_dim", 32)
        sample_size = pipe.unet.config.get("sample_size", 32)
        block_out_channels = pipe.vae.config.get("block_out_channels", [128, 256, 512, 512])
        input_size = sample_size * (2 ** (len(block_out_channels) - 1))

        # forward pass without ip adapter
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        output_without_adapter = pipe(**inputs)[0]
        output_without_adapter = output_without_adapter[0, -3:, -3:, -1].flatten()

        adapter_state_dict = create_ip_adapter_state_dict(pipe.unet)
        pipe.unet._load_ip_adapter_weights(adapter_state_dict)

        # forward pass with single ip adapter and masks, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)]
        inputs["cross_attention_kwargs"] = {"ip_adapter_masks": [self._get_dummy_masks(input_size)]}
        pipe.set_ip_adapter_scale(0.0)
        output_without_adapter_scale = pipe(**inputs)[0]
        output_without_adapter_scale = output_without_adapter_scale[0, -3:, -3:, -1].flatten()

        # forward pass with single ip adapter and masks, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(cross_attention_dim)]
        inputs["cross_attention_kwargs"] = {"ip_adapter_masks": [self._get_dummy_masks(input_size)]}
        pipe.set_ip_adapter_scale(42.0)
        output_with_adapter_scale = pipe(**inputs)[0]
        output_with_adapter_scale = output_with_adapter_scale[0, -3:, -3:, -1].flatten()

        max_diff_without_adapter_scale = np.abs(output_without_adapter_scale - output_without_adapter).max()
        max_diff_with_adapter_scale = np.abs(output_with_adapter_scale - output_without_adapter).max()

        self.assertLess(
            max_diff_without_adapter_scale,
            expected_max_diff,
            "Output without ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_adapter_scale, 1e-3, "Output with ip-adapter must be different from normal inference"
        )

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
502
503
504
505
506
507
508
509
510
511
512
513
    def test_ip_adapter_faceid(self, expected_max_diff: float = 1e-4):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components).to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        cross_attention_dim = pipe.unet.config.get("cross_attention_dim", 32)

        # forward pass without ip adapter
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        output_without_adapter = pipe(**inputs)[0]
        output_without_adapter = output_without_adapter[0, -3:, -3:, -1].flatten()

        adapter_state_dict = create_ip_adapter_faceid_state_dict(pipe.unet)
        pipe.unet._load_ip_adapter_weights(adapter_state_dict)

        # forward pass with single ip adapter, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_faceid_image_embeds(cross_attention_dim)]
        pipe.set_ip_adapter_scale(0.0)
        output_without_adapter_scale = pipe(**inputs)[0]
        output_without_adapter_scale = output_without_adapter_scale[0, -3:, -3:, -1].flatten()

        # forward pass with single ip adapter, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_faceid_image_embeds(cross_attention_dim)]
        pipe.set_ip_adapter_scale(42.0)
        output_with_adapter_scale = pipe(**inputs)[0]
        output_with_adapter_scale = output_with_adapter_scale[0, -3:, -3:, -1].flatten()

        max_diff_without_adapter_scale = np.abs(output_without_adapter_scale - output_without_adapter).max()
        max_diff_with_adapter_scale = np.abs(output_with_adapter_scale - output_without_adapter).max()

        self.assertLess(
            max_diff_without_adapter_scale,
            expected_max_diff,
            "Output without ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_adapter_scale, 1e-3, "Output with ip-adapter must be different from normal inference"
        )

Aryan's avatar
Aryan committed
514

hlky's avatar
hlky committed
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
class FluxIPAdapterTesterMixin:
    """
    This mixin is designed to be used with PipelineTesterMixin and unittest.TestCase classes.
    It provides a set of common tests for pipelines that support IP Adapters.
    """

    def test_pipeline_signature(self):
        parameters = inspect.signature(self.pipeline_class.__call__).parameters

        assert issubclass(self.pipeline_class, FluxIPAdapterMixin)
        self.assertIn(
            "ip_adapter_image",
            parameters,
            "`ip_adapter_image` argument must be supported by the `__call__` method",
        )
        self.assertIn(
            "ip_adapter_image_embeds",
            parameters,
            "`ip_adapter_image_embeds` argument must be supported by the `__call__` method",
        )

    def _get_dummy_image_embeds(self, image_embed_dim: int = 768):
        return torch.randn((1, 1, image_embed_dim), device=torch_device)

    def _modify_inputs_for_ip_adapter_test(self, inputs: Dict[str, Any]):
        inputs["negative_prompt"] = ""
Edna's avatar
Edna committed
541
542
        if "true_cfg_scale" in inspect.signature(self.pipeline_class.__call__).parameters:
            inputs["true_cfg_scale"] = 4.0
hlky's avatar
hlky committed
543
544
545
546
547
548
549
550
551
        inputs["output_type"] = "np"
        inputs["return_dict"] = False
        return inputs

    def test_ip_adapter(self, expected_max_diff: float = 1e-4, expected_pipe_slice=None):
        r"""Tests for IP-Adapter.

        The following scenarios are tested:
          - Single IP-Adapter with scale=0 should produce same output as no IP-Adapter.
552
          - Multi IP-Adapter with scale=0 should produce same output as no IP-Adapter.
hlky's avatar
hlky committed
553
          - Single IP-Adapter with scale!=0 should produce different output compared to no IP-Adapter.
554
          - Multi IP-Adapter with scale!=0 should produce different output compared to no IP-Adapter.
hlky's avatar
hlky committed
555
556
557
558
559
560
561
562
        """
        # Raising the tolerance for this test when it's run on a CPU because we
        # compare against static slices and that can be shaky (with a VVVV low probability).
        expected_max_diff = 9e-4 if torch_device == "cpu" else expected_max_diff

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components).to(torch_device)
        pipe.set_progress_bar_config(disable=None)
Edna's avatar
Edna committed
563
564
565
566
567
        image_embed_dim = (
            pipe.transformer.config.pooled_projection_dim
            if hasattr(pipe.transformer.config, "pooled_projection_dim")
            else 768
        )
hlky's avatar
hlky committed
568
569
570
571
572
573
574
575

        # forward pass without ip adapter
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        if expected_pipe_slice is None:
            output_without_adapter = pipe(**inputs)[0]
        else:
            output_without_adapter = expected_pipe_slice

576
        # 1. Single IP-Adapter test cases
hlky's avatar
hlky committed
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
        adapter_state_dict = create_flux_ip_adapter_state_dict(pipe.transformer)
        pipe.transformer._load_ip_adapter_weights(adapter_state_dict)

        # forward pass with single ip adapter, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)]
        inputs["negative_ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)]
        pipe.set_ip_adapter_scale(0.0)
        output_without_adapter_scale = pipe(**inputs)[0]
        if expected_pipe_slice is not None:
            output_without_adapter_scale = output_without_adapter_scale[0, -3:, -3:, -1].flatten()

        # forward pass with single ip adapter, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)]
        inputs["negative_ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)]
        pipe.set_ip_adapter_scale(42.0)
        output_with_adapter_scale = pipe(**inputs)[0]
        if expected_pipe_slice is not None:
            output_with_adapter_scale = output_with_adapter_scale[0, -3:, -3:, -1].flatten()

        max_diff_without_adapter_scale = np.abs(output_without_adapter_scale - output_without_adapter).max()
        max_diff_with_adapter_scale = np.abs(output_with_adapter_scale - output_without_adapter).max()

        self.assertLess(
            max_diff_without_adapter_scale,
            expected_max_diff,
            "Output without ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_adapter_scale, 1e-2, "Output with ip-adapter must be different from normal inference"
        )

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
639
640
641
642
643
644
645
646
647
        # 2. Multi IP-Adapter test cases
        adapter_state_dict_1 = create_flux_ip_adapter_state_dict(pipe.transformer)
        adapter_state_dict_2 = create_flux_ip_adapter_state_dict(pipe.transformer)
        pipe.transformer._load_ip_adapter_weights([adapter_state_dict_1, adapter_state_dict_2])

        # forward pass with multi ip adapter, but scale=0 which should have no effect
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)] * 2
        inputs["negative_ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)] * 2
        pipe.set_ip_adapter_scale([0.0, 0.0])
        output_without_multi_adapter_scale = pipe(**inputs)[0]
        if expected_pipe_slice is not None:
            output_without_multi_adapter_scale = output_without_multi_adapter_scale[0, -3:, -3:, -1].flatten()

        # forward pass with multi ip adapter, but with scale of adapter weights
        inputs = self._modify_inputs_for_ip_adapter_test(self.get_dummy_inputs(torch_device))
        inputs["ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)] * 2
        inputs["negative_ip_adapter_image_embeds"] = [self._get_dummy_image_embeds(image_embed_dim)] * 2
        pipe.set_ip_adapter_scale([42.0, 42.0])
        output_with_multi_adapter_scale = pipe(**inputs)[0]
        if expected_pipe_slice is not None:
            output_with_multi_adapter_scale = output_with_multi_adapter_scale[0, -3:, -3:, -1].flatten()

        max_diff_without_multi_adapter_scale = np.abs(
            output_without_multi_adapter_scale - output_without_adapter
        ).max()
        max_diff_with_multi_adapter_scale = np.abs(output_with_multi_adapter_scale - output_without_adapter).max()
        self.assertLess(
            max_diff_without_multi_adapter_scale,
            expected_max_diff,
            "Output without multi-ip-adapter must be same as normal inference",
        )
        self.assertGreater(
            max_diff_with_multi_adapter_scale,
            1e-2,
            "Output with multi-ip-adapter scale must be different from normal inference",
        )

hlky's avatar
hlky committed
648

649
650
651
652
653
654
655
656
657
658
659
660
661
662
class PipelineLatentTesterMixin:
    """
    This mixin is designed to be used with PipelineTesterMixin and unittest.TestCase classes.
    It provides a set of common tests for PyTorch pipeline that has vae, e.g.
    equivalence of different input and output types, etc.
    """

    @property
    def image_params(self) -> frozenset:
        raise NotImplementedError(
            "You need to set the attribute `image_params` in the child test class. "
            "`image_params` are tested for if all accepted input image types (i.e. `pt`,`pil`,`np`) are producing same results"
        )

663
664
665
666
667
668
669
    @property
    def image_latents_params(self) -> frozenset:
        raise NotImplementedError(
            "You need to set the attribute `image_latents_params` in the child test class. "
            "`image_latents_params` are tested for if passing latents directly are producing same results"
        )

670
671
672
    def get_dummy_inputs_by_type(self, device, seed=0, input_image_type="pt", output_type="np"):
        inputs = self.get_dummy_inputs(device, seed)

673
674
675
676
677
678
679
680
681
682
683
684
        def convert_to_pt(image):
            if isinstance(image, torch.Tensor):
                input_image = image
            elif isinstance(image, np.ndarray):
                input_image = VaeImageProcessor.numpy_to_pt(image)
            elif isinstance(image, PIL.Image.Image):
                input_image = VaeImageProcessor.pil_to_numpy(image)
                input_image = VaeImageProcessor.numpy_to_pt(input_image)
            else:
                raise ValueError(f"unsupported input_image_type {type(image)}")
            return input_image

685
686
687
688
689
690
691
692
693
694
695
696
697
698
        def convert_pt_to_type(image, input_image_type):
            if input_image_type == "pt":
                input_image = image
            elif input_image_type == "np":
                input_image = VaeImageProcessor.pt_to_numpy(image)
            elif input_image_type == "pil":
                input_image = VaeImageProcessor.pt_to_numpy(image)
                input_image = VaeImageProcessor.numpy_to_pil(input_image)
            else:
                raise ValueError(f"unsupported input_image_type {input_image_type}.")
            return input_image

        for image_param in self.image_params:
            if image_param in inputs.keys():
699
700
701
                inputs[image_param] = convert_pt_to_type(
                    convert_to_pt(inputs[image_param]).to(device), input_image_type
                )
702
703
704
705
706

        inputs["output_type"] = output_type

        return inputs

707
    def test_pt_np_pil_outputs_equivalent(self, expected_max_diff=1e-4):
708
709
710
        self._test_pt_np_pil_outputs_equivalent(expected_max_diff=expected_max_diff)

    def _test_pt_np_pil_outputs_equivalent(self, expected_max_diff=1e-4, input_image_type="pt"):
711
712
713
714
715
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

716
717
718
719
720
721
722
723
724
        output_pt = pipe(
            **self.get_dummy_inputs_by_type(torch_device, input_image_type=input_image_type, output_type="pt")
        )[0]
        output_np = pipe(
            **self.get_dummy_inputs_by_type(torch_device, input_image_type=input_image_type, output_type="np")
        )[0]
        output_pil = pipe(
            **self.get_dummy_inputs_by_type(torch_device, input_image_type=input_image_type, output_type="pil")
        )[0]
725
726

        max_diff = np.abs(output_pt.cpu().numpy().transpose(0, 2, 3, 1) - output_np).max()
727
728
729
        self.assertLess(
            max_diff, expected_max_diff, "`output_type=='pt'` generate different results from `output_type=='np'`"
        )
730
731

        max_diff = np.abs(np.array(output_pil[0]) - (output_np * 255).round()).max()
732
        self.assertLess(max_diff, 2.0, "`output_type=='pil'` generate different results from `output_type=='np'`")
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751

    def test_pt_np_pil_inputs_equivalent(self):
        if len(self.image_params) == 0:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        out_input_pt = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="pt"))[0]
        out_input_np = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]
        out_input_pil = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="pil"))[0]

        max_diff = np.abs(out_input_pt - out_input_np).max()
        self.assertLess(max_diff, 1e-4, "`input_type=='pt'` generate different result from `input_type=='np'`")
        max_diff = np.abs(out_input_pil - out_input_np).max()
        self.assertLess(max_diff, 1e-2, "`input_type=='pt'` generate different result from `input_type=='np'`")

752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
    def test_latents_input(self):
        if len(self.image_latents_params) == 0:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.image_processor = VaeImageProcessor(do_resize=False, do_normalize=False)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        out = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="pt"))[0]

        vae = components["vae"]
        inputs = self.get_dummy_inputs_by_type(torch_device, input_image_type="pt")
        generator = inputs["generator"]
        for image_param in self.image_latents_params:
            if image_param in inputs.keys():
                inputs[image_param] = (
                    vae.encode(inputs[image_param]).latent_dist.sample(generator) * vae.config.scaling_factor
                )
        out_latents_inputs = pipe(**inputs)[0]

        max_diff = np.abs(out - out_latents_inputs).max()
        self.assertLess(max_diff, 1e-4, "passing latents as image input generate different result from passing image")

777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
    def test_multi_vae(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        block_out_channels = pipe.vae.config.block_out_channels
        norm_num_groups = pipe.vae.config.norm_num_groups

        vae_classes = [AutoencoderKL, AsymmetricAutoencoderKL, ConsistencyDecoderVAE, AutoencoderTiny]
        configs = [
            get_autoencoder_kl_config(block_out_channels, norm_num_groups),
            get_asym_autoencoder_kl_config(block_out_channels, norm_num_groups),
            get_consistency_vae_config(block_out_channels, norm_num_groups),
            get_autoencoder_tiny_config(block_out_channels),
        ]

        out_np = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]

        for vae_cls, config in zip(vae_classes, configs):
            vae = vae_cls(**config)
            vae = vae.to(torch_device)
            components["vae"] = vae
            vae_pipe = self.pipeline_class(**components)
            out_vae_np = vae_pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]

            assert out_vae_np.shape == out_np.shape

805

806
807
808
809
810
811
@require_torch
class PipelineFromPipeTesterMixin:
    @property
    def original_pipeline_class(self):
        if "xl" in self.pipeline_class.__name__.lower():
            original_pipeline_class = StableDiffusionXLPipeline
Álvaro Somoza's avatar
Álvaro Somoza committed
812
813
        elif "kolors" in self.pipeline_class.__name__.lower():
            original_pipeline_class = KolorsPipeline
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
        else:
            original_pipeline_class = StableDiffusionPipeline

        return original_pipeline_class

    def get_dummy_inputs_pipe(self, device, seed=0):
        inputs = self.get_dummy_inputs(device, seed=seed)
        inputs["output_type"] = "np"
        inputs["return_dict"] = False
        return inputs

    def get_dummy_inputs_for_pipe_original(self, device, seed=0):
        inputs = {}
        for k, v in self.get_dummy_inputs_pipe(device, seed=seed).items():
            if k in set(inspect.signature(self.original_pipeline_class.__call__).parameters.keys()):
                inputs[k] = v
        return inputs

    def test_from_pipe_consistent_config(self):
        if self.original_pipeline_class == StableDiffusionPipeline:
            original_repo = "hf-internal-testing/tiny-stable-diffusion-pipe"
            original_kwargs = {"requires_safety_checker": False}
        elif self.original_pipeline_class == StableDiffusionXLPipeline:
            original_repo = "hf-internal-testing/tiny-stable-diffusion-xl-pipe"
            original_kwargs = {"requires_aesthetics_score": True, "force_zeros_for_empty_prompt": False}
Álvaro Somoza's avatar
Álvaro Somoza committed
839
840
841
        elif self.original_pipeline_class == KolorsPipeline:
            original_repo = "hf-internal-testing/tiny-kolors-pipe"
            original_kwargs = {"force_zeros_for_empty_prompt": False}
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
        else:
            raise ValueError(
                "original_pipeline_class must be either StableDiffusionPipeline or StableDiffusionXLPipeline"
            )

        # create original_pipeline_class(sd/sdxl)
        pipe_original = self.original_pipeline_class.from_pretrained(original_repo, **original_kwargs)

        # original_pipeline_class(sd/sdxl) -> pipeline_class
        pipe_components = self.get_dummy_components()
        pipe_additional_components = {}
        for name, component in pipe_components.items():
            if name not in pipe_original.components:
                pipe_additional_components[name] = component

        pipe = self.pipeline_class.from_pipe(pipe_original, **pipe_additional_components)

        # pipeline_class -> original_pipeline_class(sd/sdxl)
        original_pipe_additional_components = {}
        for name, component in pipe_original.components.items():
            if name not in pipe.components or not isinstance(component, pipe.components[name].__class__):
                original_pipe_additional_components[name] = component

        pipe_original_2 = self.original_pipeline_class.from_pipe(pipe, **original_pipe_additional_components)

        # compare the config
        original_config = {k: v for k, v in pipe_original.config.items() if not k.startswith("_")}
        original_config_2 = {k: v for k, v in pipe_original_2.config.items() if not k.startswith("_")}
        assert original_config_2 == original_config

    def test_from_pipe_consistent_forward_pass(self, expected_max_diff=1e-3):
        components = self.get_dummy_components()
        original_expected_modules, _ = self.original_pipeline_class._get_signature_keys(self.original_pipeline_class)

        # pipeline components that are also expected to be in the original pipeline
        original_pipe_components = {}
        # additional components that are not in the pipeline, but expected in the original pipeline
        original_pipe_additional_components = {}
        # additional components that are in the pipeline, but not expected in the original pipeline
        current_pipe_additional_components = {}

        for name, component in components.items():
            if name in original_expected_modules:
                original_pipe_components[name] = component
            else:
                current_pipe_additional_components[name] = component
        for name in original_expected_modules:
            if name not in original_pipe_components:
                if name in self.original_pipeline_class._optional_components:
                    original_pipe_additional_components[name] = None
                else:
                    raise ValueError(f"missing required module for {self.original_pipeline_class.__class__}: {name}")

        pipe_original = self.original_pipeline_class(**original_pipe_components, **original_pipe_additional_components)
        for component in pipe_original.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
        pipe_original.to(torch_device)
        pipe_original.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs_for_pipe_original(torch_device)
        output_original = pipe_original(**inputs)[0]

        pipe = self.pipeline_class(**components)
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs_pipe(torch_device)
        output = pipe(**inputs)[0]

        pipe_from_original = self.pipeline_class.from_pipe(pipe_original, **current_pipe_additional_components)
        pipe_from_original.to(torch_device)
        pipe_from_original.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs_pipe(torch_device)
        output_from_original = pipe_from_original(**inputs)[0]

        max_diff = np.abs(to_np(output) - to_np(output_from_original)).max()
        self.assertLess(
            max_diff,
            expected_max_diff,
            "The outputs of the pipelines created with `from_pipe` and `__init__` are different.",
        )

        inputs = self.get_dummy_inputs_for_pipe_original(torch_device)
        output_original_2 = pipe_original(**inputs)[0]

        max_diff = np.abs(to_np(output_original) - to_np(output_original_2)).max()
        self.assertLess(max_diff, expected_max_diff, "`from_pipe` should not change the output of original pipeline.")

        for component in pipe_original.components.values():
            if hasattr(component, "attn_processors"):
934
935
936
                assert all(type(proc) == AttnProcessor for proc in component.attn_processors.values()), (
                    "`from_pipe` changed the attention processor in original pipeline."
                )
937

938
939
    @require_accelerator
    @require_accelerate_version_greater("0.14.0")
940
941
942
943
944
945
    def test_from_pipe_consistent_forward_pass_cpu_offload(self, expected_max_diff=1e-3):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
946
        pipe.enable_model_cpu_offload(device=torch_device)
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
        pipe.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs_pipe(torch_device)
        output = pipe(**inputs)[0]

        original_expected_modules, _ = self.original_pipeline_class._get_signature_keys(self.original_pipeline_class)
        # pipeline components that are also expected to be in the original pipeline
        original_pipe_components = {}
        # additional components that are not in the pipeline, but expected in the original pipeline
        original_pipe_additional_components = {}
        # additional components that are in the pipeline, but not expected in the original pipeline
        current_pipe_additional_components = {}
        for name, component in components.items():
            if name in original_expected_modules:
                original_pipe_components[name] = component
            else:
                current_pipe_additional_components[name] = component
        for name in original_expected_modules:
            if name not in original_pipe_components:
                if name in self.original_pipeline_class._optional_components:
                    original_pipe_additional_components[name] = None
                else:
                    raise ValueError(f"missing required module for {self.original_pipeline_class.__class__}: {name}")

        pipe_original = self.original_pipeline_class(**original_pipe_components, **original_pipe_additional_components)
        for component in pipe_original.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
        pipe_original.set_progress_bar_config(disable=None)
975

976
        pipe_from_original = self.pipeline_class.from_pipe(pipe_original, **current_pipe_additional_components)
977
978
979
980
        for component in pipe_from_original.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

981
        pipe_from_original.enable_model_cpu_offload(device=torch_device)
982
983
984
985
986
987
988
989
990
991
992
993
        pipe_from_original.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs_pipe(torch_device)
        output_from_original = pipe_from_original(**inputs)[0]

        max_diff = np.abs(to_np(output) - to_np(output_from_original)).max()
        self.assertLess(
            max_diff,
            expected_max_diff,
            "The outputs of the pipelines created with `from_pipe` and `__init__` are different.",
        )


994
995
996
997
998
999
1000
1001
@require_torch
class PipelineKarrasSchedulerTesterMixin:
    """
    This mixin is designed to be used with unittest.TestCase classes.
    It provides a set of common tests for each PyTorch pipeline that makes use of KarrasDiffusionSchedulers
    equivalence of dict and tuple outputs, etc.
    """

1002
1003
1004
    def test_karras_schedulers_shape(
        self, num_inference_steps_for_strength=4, num_inference_steps_for_strength_for_iterations=5
    ):
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)

        # make sure that PNDM does not need warm-up
        pipe.scheduler.register_to_config(skip_prk_steps=True)

        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        inputs = self.get_dummy_inputs(torch_device)
        inputs["num_inference_steps"] = 2

        if "strength" in inputs:
1017
            inputs["num_inference_steps"] = num_inference_steps_for_strength
1018
1019
1020
1021
1022
            inputs["strength"] = 0.5

        outputs = []
        for scheduler_enum in KarrasDiffusionSchedulers:
            if "KDPM2" in scheduler_enum.name:
1023
                inputs["num_inference_steps"] = num_inference_steps_for_strength_for_iterations
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035

            scheduler_cls = getattr(diffusers, scheduler_enum.name)
            pipe.scheduler = scheduler_cls.from_config(pipe.scheduler.config)
            output = pipe(**inputs)[0]
            outputs.append(output)

            if "KDPM2" in scheduler_enum.name:
                inputs["num_inference_steps"] = 2

        assert check_same_shape(outputs)


1036
1037
1038
1039
1040
1041
1042
1043
@require_torch
class PipelineTesterMixin:
    """
    This mixin is designed to be used with unittest.TestCase classes.
    It provides a set of common tests for each PyTorch pipeline, e.g. saving and loading the pipeline,
    equivalence of dict and tuple outputs, etc.
    """

1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
    # Canonical parameters that are passed to `__call__` regardless
    # of the type of pipeline. They are always optional and have common
    # sense default values.
    required_optional_params = frozenset(
        [
            "num_inference_steps",
            "num_images_per_prompt",
            "generator",
            "latents",
            "output_type",
            "return_dict",
        ]
    )
1057

1058
1059
    # set these parameters to False in the child class if the pipeline does not support the corresponding functionality
    test_attention_slicing = True
1060

1061
    test_xformers_attention = True
Aryan's avatar
Aryan committed
1062
    test_layerwise_casting = False
Aryan's avatar
Aryan committed
1063
    test_group_offloading = False
Marc Sun's avatar
Marc Sun committed
1064
1065
    supports_dduf = True

1066
1067
1068
1069
1070
    def get_generator(self, seed):
        device = torch_device if torch_device != "mps" else "cpu"
        generator = torch.Generator(device).manual_seed(seed)
        return generator

1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
    @property
    def pipeline_class(self) -> Union[Callable, DiffusionPipeline]:
        raise NotImplementedError(
            "You need to set the attribute `pipeline_class = ClassNameOfPipeline` in the child test class. "
            "See existing pipeline tests for reference."
        )

    def get_dummy_components(self):
        raise NotImplementedError(
            "You need to implement `get_dummy_components(self)` in the child test class. "
            "See existing pipeline tests for reference."
        )

    def get_dummy_inputs(self, device, seed=0):
        raise NotImplementedError(
            "You need to implement `get_dummy_inputs(self, device, seed)` in the child test class. "
            "See existing pipeline tests for reference."
        )

1090
1091
1092
1093
1094
    @property
    def params(self) -> frozenset:
        raise NotImplementedError(
            "You need to set the attribute `params` in the child test class. "
            "`params` are checked for if all values are present in `__call__`'s signature."
1095
            " You can set `params` using one of the common set of parameters defined in `pipeline_params.py`"
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
            " e.g., `TEXT_TO_IMAGE_PARAMS` defines the common parameters used in text to  "
            "image pipelines, including prompts and prompt embedding overrides."
            "If your pipeline's set of arguments has minor changes from one of the common sets of arguments, "
            "do not make modifications to the existing common sets of arguments. I.e. a text to image pipeline "
            "with non-configurable height and width arguments should set the attribute as "
            "`params = TEXT_TO_IMAGE_PARAMS - {'height', 'width'}`. "
            "See existing pipeline tests for reference."
        )

    @property
    def batch_params(self) -> frozenset:
        raise NotImplementedError(
            "You need to set the attribute `batch_params` in the child test class. "
            "`batch_params` are the parameters required to be batched when passed to the pipeline's "
            "`__call__` method. `pipeline_params.py` provides some common sets of parameters such as "
            "`TEXT_TO_IMAGE_BATCH_PARAMS`, `IMAGE_VARIATION_BATCH_PARAMS`, etc... If your pipeline's "
            "set of batch arguments has minor changes from one of the common sets of batch arguments, "
            "do not make modifications to the existing common sets of batch arguments. I.e. a text to "
            "image pipeline `negative_prompt` is not batched should set the attribute as "
            "`batch_params = TEXT_TO_IMAGE_BATCH_PARAMS - {'negative_prompt'}`. "
            "See existing pipeline tests for reference."
        )

1119
1120
1121
1122
1123
1124
1125
1126
1127
    @property
    def callback_cfg_params(self) -> frozenset:
        raise NotImplementedError(
            "You need to set the attribute `callback_cfg_params` in the child test class that requires to run test_callback_cfg. "
            "`callback_cfg_params` are the parameters that needs to be passed to the pipeline's callback "
            "function when dynamically adjusting `guidance_scale`. They are variables that require special"
            "treatment when `do_classifier_free_guidance` is `True`. `pipeline_params.py` provides some common"
            " sets of parameters such as `TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS`. If your pipeline's "
            "set of cfg arguments has minor changes from one of the common sets of cfg arguments, "
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
1128
            "do not make modifications to the existing common sets of cfg arguments. I.e. for inpaint pipeline, you "
1129
1130
1131
1132
            " need to adjust batch size of `mask` and `masked_image_latents` so should set the attribute as"
            "`callback_cfg_params = TEXT_TO_IMAGE_CFG_PARAMS.union({'mask', 'masked_image_latents'})`"
        )

1133
1134
1135
    def setUp(self):
        # clean up the VRAM before each test
        super().setUp()
1136
        torch.compiler.reset()
1137
        gc.collect()
1138
        backend_empty_cache(torch_device)
1139

1140
1141
1142
1143
1144
1145
1146
1147
        # Skip tests for pipelines that inherit from DeprecatedPipelineMixin
        from diffusers.pipelines.pipeline_utils import DeprecatedPipelineMixin

        if hasattr(self, "pipeline_class") and issubclass(self.pipeline_class, DeprecatedPipelineMixin):
            import pytest

            pytest.skip(reason=f"Deprecated Pipeline: {self.pipeline_class.__name__}")

1148
1149
1150
    def tearDown(self):
        # clean up the VRAM after each test in case of CUDA runtime errors
        super().tearDown()
1151
        torch.compiler.reset()
1152
        gc.collect()
1153
        backend_empty_cache(torch_device)
1154

1155
    def test_save_load_local(self, expected_max_difference=5e-4):
1156
1157
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1158
1159
1160
1161
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

1162
1163
1164
1165
1166
1167
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
        output = pipe(**inputs)[0]

1168
1169
1170
        logger = logging.get_logger("diffusers.pipelines.pipeline_utils")
        logger.setLevel(diffusers.logging.INFO)

1171
        with tempfile.TemporaryDirectory() as tmpdir:
1172
            pipe.save_pretrained(tmpdir, safe_serialization=False)
1173
1174
1175
1176

            with CaptureLogger(logger) as cap_logger:
                pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)

1177
1178
1179
1180
            for component in pipe_loaded.components.values():
                if hasattr(component, "set_default_attn_processor"):
                    component.set_default_attn_processor()

1181
1182
1183
1184
            for name in pipe_loaded.components.keys():
                if name not in pipe_loaded._optional_components:
                    assert name in str(cap_logger)

1185
1186
1187
1188
1189
1190
            pipe_loaded.to(torch_device)
            pipe_loaded.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
        output_loaded = pipe_loaded(**inputs)[0]

1191
        max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
1192
        self.assertLess(max_diff, expected_max_difference)
1193

1194
1195
1196
1197
1198
    def test_pipeline_call_signature(self):
        self.assertTrue(
            hasattr(self.pipeline_class, "__call__"), f"{self.pipeline_class} should have a `__call__` method"
        )

1199
1200
        parameters = inspect.signature(self.pipeline_class.__call__).parameters

1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
        optional_parameters = set()

        for k, v in parameters.items():
            if v.default != inspect._empty:
                optional_parameters.add(k)

        parameters = set(parameters.keys())
        parameters.remove("self")
        parameters.discard("kwargs")  # kwargs can be added if arguments of pipeline call function are deprecated

        remaining_required_parameters = set()

        for param in self.params:
            if param not in parameters:
                remaining_required_parameters.add(param)
1216

1217
1218
1219
1220
1221
1222
        self.assertTrue(
            len(remaining_required_parameters) == 0,
            f"Required parameters not present: {remaining_required_parameters}",
        )

        remaining_required_optional_parameters = set()
1223

1224
        for param in self.required_optional_params:
1225
1226
1227
1228
1229
1230
1231
            if param not in optional_parameters:
                remaining_required_optional_parameters.add(param)

        self.assertTrue(
            len(remaining_required_optional_parameters) == 0,
            f"Required optional parameters not present: {remaining_required_optional_parameters}",
        )
1232

1233
    def test_inference_batch_consistent(self, batch_sizes=[2]):
1234
        self._test_inference_batch_consistent(batch_sizes=batch_sizes)
1235

1236
    def _test_inference_batch_consistent(
Will Berman's avatar
Will Berman committed
1237
        self, batch_sizes=[2], additional_params_copy_to_batched_inputs=["num_inference_steps"], batch_generator=True
1238
    ):
1239
1240
1241
1242
1243
1244
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
1245
        inputs["generator"] = self.get_generator(0)
1246
1247
1248
1249

        logger = logging.get_logger(pipe.__module__)
        logger.setLevel(level=diffusers.logging.FATAL)

1250
1251
        # prepare batched inputs
        batched_inputs = []
1252
        for batch_size in batch_sizes:
1253
1254
            batched_input = {}
            batched_input.update(inputs)
1255

1256
1257
1258
            for name in self.batch_params:
                if name not in inputs:
                    continue
1259

1260
1261
1262
1263
1264
                value = inputs[name]
                if name == "prompt":
                    len_prompt = len(value)
                    # make unequal batch sizes
                    batched_input[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
1265

1266
1267
                    # make last batch super long
                    batched_input[name][-1] = 100 * "very long"
1268

1269
1270
                else:
                    batched_input[name] = batch_size * [value]
1271

Will Berman's avatar
Will Berman committed
1272
            if batch_generator and "generator" in inputs:
1273
                batched_input["generator"] = [self.get_generator(i) for i in range(batch_size)]
1274

1275
1276
            if "batch_size" in inputs:
                batched_input["batch_size"] = batch_size
1277

1278
            batched_inputs.append(batched_input)
1279
1280

        logger.setLevel(level=diffusers.logging.WARNING)
1281
1282
1283
        for batch_size, batched_input in zip(batch_sizes, batched_inputs):
            output = pipe(**batched_input)
            assert len(output[0]) == batch_size
1284

1285
1286
    def test_inference_batch_single_identical(self, batch_size=3, expected_max_diff=1e-4):
        self._test_inference_batch_single_identical(batch_size=batch_size, expected_max_diff=expected_max_diff)
1287
1288

    def _test_inference_batch_single_identical(
1289
        self,
1290
        batch_size=2,
1291
        expected_max_diff=1e-4,
1292
        additional_params_copy_to_batched_inputs=["num_inference_steps"],
1293
    ):
1294
1295
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1296
1297
1298
1299
        for components in pipe.components.values():
            if hasattr(components, "set_default_attn_processor"):
                components.set_default_attn_processor()

1300
1301
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
1302
1303
1304
        inputs = self.get_dummy_inputs(torch_device)
        # Reset generator in case it is has been used in self.get_dummy_inputs
        inputs["generator"] = self.get_generator(0)
1305
1306
1307
1308
1309
1310

        logger = logging.get_logger(pipe.__module__)
        logger.setLevel(level=diffusers.logging.FATAL)

        # batchify inputs
        batched_inputs = {}
1311
        batched_inputs.update(inputs)
1312

1313
1314
1315
        for name in self.batch_params:
            if name not in inputs:
                continue
1316

1317
1318
1319
1320
1321
            value = inputs[name]
            if name == "prompt":
                len_prompt = len(value)
                batched_inputs[name] = [value[: len_prompt // i] for i in range(1, batch_size + 1)]
                batched_inputs[name][-1] = 100 * "very long"
1322

1323
1324
            else:
                batched_inputs[name] = batch_size * [value]
1325

1326
1327
        if "generator" in inputs:
            batched_inputs["generator"] = [self.get_generator(i) for i in range(batch_size)]
1328

1329
1330
1331
1332
1333
        if "batch_size" in inputs:
            batched_inputs["batch_size"] = batch_size

        for arg in additional_params_copy_to_batched_inputs:
            batched_inputs[arg] = inputs[arg]
1334
1335

        output = pipe(**inputs)
1336
        output_batch = pipe(**batched_inputs)
1337

1338
        assert output_batch[0].shape[0] == batch_size
1339

YiYi Xu's avatar
YiYi Xu committed
1340
        max_diff = np.abs(to_np(output_batch[0][0]) - to_np(output[0][0])).max()
1341
        assert max_diff < expected_max_diff
1342

1343
    def test_dict_tuple_outputs_equivalent(self, expected_slice=None, expected_max_difference=1e-4):
1344
1345
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1346
1347
1348
1349
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

1350
1351
1352
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

1353
        generator_device = "cpu"
1354
1355
1356
1357
1358
        if expected_slice is None:
            output = pipe(**self.get_dummy_inputs(generator_device))[0]
        else:
            output = expected_slice

1359
        output_tuple = pipe(**self.get_dummy_inputs(generator_device), return_dict=False)[0]
1360

1361
1362
1363
1364
1365
1366
1367
1368
        if expected_slice is None:
            max_diff = np.abs(to_np(output) - to_np(output_tuple)).max()
        else:
            if output_tuple.ndim != 5:
                max_diff = np.abs(to_np(output) - to_np(output_tuple)[0, -3:, -3:, -1].flatten()).max()
            else:
                max_diff = np.abs(to_np(output) - to_np(output_tuple)[0, -3:, -3:, -1, -1].flatten()).max()

1369
        self.assertLess(max_diff, expected_max_difference)
1370
1371
1372

    def test_components_function(self):
        init_components = self.get_dummy_components()
Kashif Rasul's avatar
Kashif Rasul committed
1373
1374
        init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}

1375
1376
1377
1378
1379
        pipe = self.pipeline_class(**init_components)

        self.assertTrue(hasattr(pipe, "components"))
        self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))

1380
1381
    @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
    @require_accelerator
1382
    def test_float16_inference(self, expected_max_diff=5e-2):
1383
1384
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1385
1386
1387
1388
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

1389
1390
1391
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

YiYi Xu's avatar
YiYi Xu committed
1392
        components = self.get_dummy_components()
1393
        pipe_fp16 = self.pipeline_class(**components)
1394
1395
1396
        for component in pipe_fp16.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1397
        pipe_fp16.to(torch_device, torch.float16)
1398
1399
        pipe_fp16.set_progress_bar_config(disable=None)

1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
        inputs = self.get_dummy_inputs(torch_device)
        # Reset generator in case it is used inside dummy inputs
        if "generator" in inputs:
            inputs["generator"] = self.get_generator(0)
        output = pipe(**inputs)[0]

        fp16_inputs = self.get_dummy_inputs(torch_device)
        # Reset generator in case it is used inside dummy inputs
        if "generator" in fp16_inputs:
            fp16_inputs["generator"] = self.get_generator(0)
        output_fp16 = pipe_fp16(**fp16_inputs)[0]
1411
1412
1413
1414
1415

        if isinstance(output, torch.Tensor):
            output = output.cpu()
            output_fp16 = output_fp16.cpu()

1416
        max_diff = numpy_cosine_similarity_distance(output.flatten(), output_fp16.flatten())
1417
        assert max_diff < expected_max_diff
1418

1419
1420
    @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
    @require_accelerator
1421
    def test_save_load_float16(self, expected_max_diff=1e-2):
1422
1423
1424
1425
        components = self.get_dummy_components()
        for name, module in components.items():
            if hasattr(module, "half"):
                components[name] = module.to(torch_device).half()
1426

1427
        pipe = self.pipeline_class(**components)
1428
1429
1430
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1431
1432
1433
1434
1435
1436
1437
1438
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
        output = pipe(**inputs)[0]

        with tempfile.TemporaryDirectory() as tmpdir:
            pipe.save_pretrained(tmpdir)
1439
            pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, torch_dtype=torch.float16)
1440
1441
1442
            for component in pipe_loaded.components.values():
                if hasattr(component, "set_default_attn_processor"):
                    component.set_default_attn_processor()
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
            pipe_loaded.to(torch_device)
            pipe_loaded.set_progress_bar_config(disable=None)

        for name, component in pipe_loaded.components.items():
            if hasattr(component, "dtype"):
                self.assertTrue(
                    component.dtype == torch.float16,
                    f"`{name}.dtype` switched from `float16` to {component.dtype} after loading.",
                )

        inputs = self.get_dummy_inputs(torch_device)
        output_loaded = pipe_loaded(**inputs)[0]
1455
        max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
1456
1457
1458
        self.assertLess(
            max_diff, expected_max_diff, "The output of the fp16 pipeline changed after saving and loading."
        )
1459

1460
    def test_save_load_optional_components(self, expected_max_difference=1e-4):
1461
1462
1463
1464
        if not hasattr(self.pipeline_class, "_optional_components"):
            return
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1465
1466
1467
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1468
1469
1470
1471
1472
1473
1474
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        # set all optional components to None
        for optional_component in pipe._optional_components:
            setattr(pipe, optional_component, None)

Dhruv Nair's avatar
Dhruv Nair committed
1475
1476
        generator_device = "cpu"
        inputs = self.get_dummy_inputs(generator_device)
1477
        torch.manual_seed(0)
1478
1479
1480
        output = pipe(**inputs)[0]

        with tempfile.TemporaryDirectory() as tmpdir:
1481
            pipe.save_pretrained(tmpdir, safe_serialization=False)
1482
            pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
1483
1484
1485
            for component in pipe_loaded.components.values():
                if hasattr(component, "set_default_attn_processor"):
                    component.set_default_attn_processor()
1486
1487
1488
1489
1490
1491
1492
1493
1494
            pipe_loaded.to(torch_device)
            pipe_loaded.set_progress_bar_config(disable=None)

        for optional_component in pipe._optional_components:
            self.assertTrue(
                getattr(pipe_loaded, optional_component) is None,
                f"`{optional_component}` did not stay set to None after loading.",
            )

Dhruv Nair's avatar
Dhruv Nair committed
1495
        inputs = self.get_dummy_inputs(generator_device)
1496
        torch.manual_seed(0)
1497
1498
        output_loaded = pipe_loaded(**inputs)[0]

1499
        max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
1500
        self.assertLess(max_diff, expected_max_difference)
1501

1502
    @require_accelerator
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
    def test_to_device(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.set_progress_bar_config(disable=None)

        pipe.to("cpu")
        model_devices = [component.device.type for component in components.values() if hasattr(component, "device")]
        self.assertTrue(all(device == "cpu" for device in model_devices))

        output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
        self.assertTrue(np.isnan(output_cpu).sum() == 0)

1515
        pipe.to(torch_device)
1516
        model_devices = [component.device.type for component in components.values() if hasattr(component, "device")]
1517
        self.assertTrue(all(device == torch_device for device in model_devices))
1518

1519
1520
        output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
        self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
1521

1522
1523
1524
1525
1526
1527
1528
1529
    def test_to_dtype(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.set_progress_bar_config(disable=None)

        model_dtypes = [component.dtype for component in components.values() if hasattr(component, "dtype")]
        self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))

1530
        pipe.to(dtype=torch.float16)
1531
1532
1533
        model_dtypes = [component.dtype for component in components.values() if hasattr(component, "dtype")]
        self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))

1534
1535
    def test_attention_slicing_forward_pass(self, expected_max_diff=1e-3):
        self._test_attention_slicing_forward_pass(expected_max_diff=expected_max_diff)
1536

1537
1538
1539
    def _test_attention_slicing_forward_pass(
        self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
    ):
1540
1541
1542
1543
1544
        if not self.test_attention_slicing:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1545
1546
1547
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1548
1549
1550
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

1551
1552
        generator_device = "cpu"
        inputs = self.get_dummy_inputs(generator_device)
1553
1554
1555
        output_without_slicing = pipe(**inputs)[0]

        pipe.enable_attention_slicing(slice_size=1)
1556
        inputs = self.get_dummy_inputs(generator_device)
1557
1558
1559
1560
1561
        output_with_slicing1 = pipe(**inputs)[0]

        pipe.enable_attention_slicing(slice_size=2)
        inputs = self.get_dummy_inputs(generator_device)
        output_with_slicing2 = pipe(**inputs)[0]
1562

1563
        if test_max_difference:
1564
1565
1566
1567
1568
1569
1570
            max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
            max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
            self.assertLess(
                max(max_diff1, max_diff2),
                expected_max_diff,
                "Attention slicing should not affect the inference results",
            )
1571

1572
        if test_mean_pixel_difference:
1573
1574
            assert_mean_pixel_difference(to_np(output_with_slicing1[0]), to_np(output_without_slicing[0]))
            assert_mean_pixel_difference(to_np(output_with_slicing2[0]), to_np(output_without_slicing[0]))
1575

1576
1577
    @require_accelerator
    @require_accelerate_version_greater("0.14.0")
1578
    def test_sequential_cpu_offload_forward_pass(self, expected_max_diff=1e-4):
1579
1580
        import accelerate

1581
1582
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1583
1584
1585
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1586
1587
1588
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

1589
1590
        generator_device = "cpu"
        inputs = self.get_dummy_inputs(generator_device)
1591
        torch.manual_seed(0)
1592
1593
        output_without_offload = pipe(**inputs)[0]

1594
1595
        pipe.enable_sequential_cpu_offload(device=torch_device)
        assert pipe._execution_device.type == torch_device
1596
1597

        inputs = self.get_dummy_inputs(generator_device)
1598
        torch.manual_seed(0)
1599
1600
1601
1602
1603
        output_with_offload = pipe(**inputs)[0]

        max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
        self.assertLess(max_diff, expected_max_diff, "CPU offloading should not affect the inference results")

1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
        # make sure all `torch.nn.Module` components (except those in `self._exclude_from_cpu_offload`) are offloaded correctly
        offloaded_modules = {
            k: v
            for k, v in pipe.components.items()
            if isinstance(v, torch.nn.Module) and k not in pipe._exclude_from_cpu_offload
        }
        # 1. all offloaded modules should be saved to cpu and moved to meta device
        self.assertTrue(
            all(v.device.type == "meta" for v in offloaded_modules.values()),
            f"Not offloaded: {[k for k, v in offloaded_modules.items() if v.device.type != 'meta']}",
        )
        # 2. all offloaded modules should have hook installed
        self.assertTrue(
            all(hasattr(v, "_hf_hook") for k, v in offloaded_modules.items()),
            f"No hook attached: {[k for k, v in offloaded_modules.items() if not hasattr(v, '_hf_hook')]}",
        )
        # 3. all offloaded modules should have correct hooks installed, should be either one of these two
        #    - `AlignDevicesHook`
        #    - a SequentialHook` that contains `AlignDevicesHook`
        offloaded_modules_with_incorrect_hooks = {}
        for k, v in offloaded_modules.items():
            if hasattr(v, "_hf_hook"):
                if isinstance(v._hf_hook, accelerate.hooks.SequentialHook):
                    # if it is a `SequentialHook`, we loop through its `hooks` attribute to check if it only contains `AlignDevicesHook`
                    for hook in v._hf_hook.hooks:
                        if not isinstance(hook, accelerate.hooks.AlignDevicesHook):
                            offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook.hooks[0])
                elif not isinstance(v._hf_hook, accelerate.hooks.AlignDevicesHook):
                    offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook)

        self.assertTrue(
            len(offloaded_modules_with_incorrect_hooks) == 0,
            f"Not installed correct hook: {offloaded_modules_with_incorrect_hooks}",
        )

1639
1640
    @require_accelerator
    @require_accelerate_version_greater("0.17.0")
1641
    def test_model_cpu_offload_forward_pass(self, expected_max_diff=2e-4):
1642
1643
        import accelerate

1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
        generator_device = "cpu"
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)

        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(generator_device)
1656
        torch.manual_seed(0)
1657
1658
        output_without_offload = pipe(**inputs)[0]

1659
1660
        pipe.enable_model_cpu_offload(device=torch_device)
        assert pipe._execution_device.type == torch_device
1661

1662
        inputs = self.get_dummy_inputs(generator_device)
1663
        torch.manual_seed(0)
1664
1665
        output_with_offload = pipe(**inputs)[0]

1666
        max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
1667
        self.assertLess(max_diff, expected_max_diff, "CPU offloading should not affect the inference results")
1668
1669
1670
1671

        # make sure all `torch.nn.Module` components (except those in `self._exclude_from_cpu_offload`) are offloaded correctly
        offloaded_modules = {
            k: v
1672
1673
            for k, v in pipe.components.items()
            if isinstance(v, torch.nn.Module) and k not in pipe._exclude_from_cpu_offload
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
        }
        # 1. check if all offloaded modules are saved to cpu
        self.assertTrue(
            all(v.device.type == "cpu" for v in offloaded_modules.values()),
            f"Not offloaded: {[k for k, v in offloaded_modules.items() if v.device.type != 'cpu']}",
        )
        # 2. check if all offloaded modules have hooks installed
        self.assertTrue(
            all(hasattr(v, "_hf_hook") for k, v in offloaded_modules.items()),
            f"No hook attached: {[k for k, v in offloaded_modules.items() if not hasattr(v, '_hf_hook')]}",
        )
        # 3. check if all offloaded modules have correct type of hooks installed, should be `CpuOffload`
        offloaded_modules_with_incorrect_hooks = {}
        for k, v in offloaded_modules.items():
            if hasattr(v, "_hf_hook") and not isinstance(v._hf_hook, accelerate.hooks.CpuOffload):
                offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook)

        self.assertTrue(
            len(offloaded_modules_with_incorrect_hooks) == 0,
            f"Not installed correct hook: {offloaded_modules_with_incorrect_hooks}",
1694
        )
1695

1696
1697
    @require_accelerator
    @require_accelerate_version_greater("0.17.0")
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
    def test_cpu_offload_forward_pass_twice(self, expected_max_diff=2e-4):
        import accelerate

        generator_device = "cpu"
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)

        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

        pipe.set_progress_bar_config(disable=None)

1711
        pipe.enable_model_cpu_offload()
1712
1713
1714
        inputs = self.get_dummy_inputs(generator_device)
        output_with_offload = pipe(**inputs)[0]

1715
        pipe.enable_model_cpu_offload()
1716
1717
1718
1719
1720
1721
1722
        inputs = self.get_dummy_inputs(generator_device)
        output_with_offload_twice = pipe(**inputs)[0]

        max_diff = np.abs(to_np(output_with_offload) - to_np(output_with_offload_twice)).max()
        self.assertLess(
            max_diff, expected_max_diff, "running CPU offloading 2nd time should not affect the inference results"
        )
1723
1724

        # make sure all `torch.nn.Module` components (except those in `self._exclude_from_cpu_offload`) are offloaded correctly
YiYi Xu's avatar
YiYi Xu committed
1725
1726
        offloaded_modules = {
            k: v
1727
1728
            for k, v in pipe.components.items()
            if isinstance(v, torch.nn.Module) and k not in pipe._exclude_from_cpu_offload
YiYi Xu's avatar
YiYi Xu committed
1729
        }
1730
        # 1. check if all offloaded modules are saved to cpu
YiYi Xu's avatar
YiYi Xu committed
1731
1732
1733
        self.assertTrue(
            all(v.device.type == "cpu" for v in offloaded_modules.values()),
            f"Not offloaded: {[k for k, v in offloaded_modules.items() if v.device.type != 'cpu']}",
1734
        )
1735
1736
1737
1738
1739
1740
        # 2. check if all offloaded modules have hooks installed
        self.assertTrue(
            all(hasattr(v, "_hf_hook") for k, v in offloaded_modules.items()),
            f"No hook attached: {[k for k, v in offloaded_modules.items() if not hasattr(v, '_hf_hook')]}",
        )
        # 3. check if all offloaded modules have correct type of hooks installed, should be `CpuOffload`
YiYi Xu's avatar
YiYi Xu committed
1741
1742
1743
1744
1745
1746
1747
1748
        offloaded_modules_with_incorrect_hooks = {}
        for k, v in offloaded_modules.items():
            if hasattr(v, "_hf_hook") and not isinstance(v._hf_hook, accelerate.hooks.CpuOffload):
                offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook)

        self.assertTrue(
            len(offloaded_modules_with_incorrect_hooks) == 0,
            f"Not installed correct hook: {offloaded_modules_with_incorrect_hooks}",
1749
1750
        )

1751
1752
    @require_accelerator
    @require_accelerate_version_greater("0.14.0")
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
    def test_sequential_offload_forward_pass_twice(self, expected_max_diff=2e-4):
        import accelerate

        generator_device = "cpu"
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)

        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()

        pipe.set_progress_bar_config(disable=None)

1766
        pipe.enable_sequential_cpu_offload(device=torch_device)
1767
1768
1769
        inputs = self.get_dummy_inputs(generator_device)
        output_with_offload = pipe(**inputs)[0]

1770
        pipe.enable_sequential_cpu_offload(device=torch_device)
1771
1772
1773
1774
1775
1776
1777
        inputs = self.get_dummy_inputs(generator_device)
        output_with_offload_twice = pipe(**inputs)[0]

        max_diff = np.abs(to_np(output_with_offload) - to_np(output_with_offload_twice)).max()
        self.assertLess(
            max_diff, expected_max_diff, "running sequential offloading second time should have the inference results"
        )
1778
1779

        # make sure all `torch.nn.Module` components (except those in `self._exclude_from_cpu_offload`) are offloaded correctly
YiYi Xu's avatar
YiYi Xu committed
1780
1781
        offloaded_modules = {
            k: v
1782
1783
            for k, v in pipe.components.items()
            if isinstance(v, torch.nn.Module) and k not in pipe._exclude_from_cpu_offload
YiYi Xu's avatar
YiYi Xu committed
1784
        }
1785
        # 1. check if all offloaded modules are moved to meta device
YiYi Xu's avatar
YiYi Xu committed
1786
1787
1788
        self.assertTrue(
            all(v.device.type == "meta" for v in offloaded_modules.values()),
            f"Not offloaded: {[k for k, v in offloaded_modules.items() if v.device.type != 'meta']}",
1789
        )
1790
1791
1792
1793
1794
1795
1796
1797
        # 2. check if all offloaded modules have hook installed
        self.assertTrue(
            all(hasattr(v, "_hf_hook") for k, v in offloaded_modules.items()),
            f"No hook attached: {[k for k, v in offloaded_modules.items() if not hasattr(v, '_hf_hook')]}",
        )
        # 3. check if all offloaded modules have correct hooks installed, should be either one of these two
        #    - `AlignDevicesHook`
        #    - a SequentialHook` that contains `AlignDevicesHook`
YiYi Xu's avatar
YiYi Xu committed
1798
1799
        offloaded_modules_with_incorrect_hooks = {}
        for k, v in offloaded_modules.items():
1800
1801
1802
1803
1804
1805
1806
1807
            if hasattr(v, "_hf_hook"):
                if isinstance(v._hf_hook, accelerate.hooks.SequentialHook):
                    # if it is a `SequentialHook`, we loop through its `hooks` attribute to check if it only contains `AlignDevicesHook`
                    for hook in v._hf_hook.hooks:
                        if not isinstance(hook, accelerate.hooks.AlignDevicesHook):
                            offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook.hooks[0])
                elif not isinstance(v._hf_hook, accelerate.hooks.AlignDevicesHook):
                    offloaded_modules_with_incorrect_hooks[k] = type(v._hf_hook)
1808

YiYi Xu's avatar
YiYi Xu committed
1809
1810
1811
        self.assertTrue(
            len(offloaded_modules_with_incorrect_hooks) == 0,
            f"Not installed correct hook: {offloaded_modules_with_incorrect_hooks}",
1812
1813
        )

1814
1815
1816
1817
    @unittest.skipIf(
        torch_device != "cuda" or not is_xformers_available(),
        reason="XFormers attention is only available with CUDA and `xformers` installed",
    )
Kashif Rasul's avatar
Kashif Rasul committed
1818
    def test_xformers_attention_forwardGenerator_pass(self):
Will Berman's avatar
Will Berman committed
1819
1820
        self._test_xformers_attention_forwardGenerator_pass()

1821
1822
1823
    def _test_xformers_attention_forwardGenerator_pass(
        self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-4
    ):
1824
1825
1826
1827
1828
        if not self.test_xformers_attention:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
1829
1830
1831
        for component in pipe.components.values():
            if hasattr(component, "set_default_attn_processor"):
                component.set_default_attn_processor()
1832
1833
1834
1835
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
1836
        output_without_offload = pipe(**inputs)[0]
1837
1838
1839
        output_without_offload = (
            output_without_offload.cpu() if torch.is_tensor(output_without_offload) else output_without_offload
        )
1840
1841
1842

        pipe.enable_xformers_memory_efficient_attention()
        inputs = self.get_dummy_inputs(torch_device)
1843
        output_with_offload = pipe(**inputs)[0]
1844
1845
1846
        output_with_offload = (
            output_with_offload.cpu() if torch.is_tensor(output_with_offload) else output_without_offload
        )
1847

Will Berman's avatar
Will Berman committed
1848
        if test_max_difference:
1849
            max_diff = np.abs(to_np(output_with_offload) - to_np(output_without_offload)).max()
1850
            self.assertLess(max_diff, expected_max_diff, "XFormers attention should not affect the inference results")
Will Berman's avatar
Will Berman committed
1851

1852
1853
        if test_mean_pixel_difference:
            assert_mean_pixel_difference(output_with_offload[0], output_without_offload[0])
1854

1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
    def test_num_images_per_prompt(self):
        sig = inspect.signature(self.pipeline_class.__call__)

        if "num_images_per_prompt" not in sig.parameters:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        batch_sizes = [1, 2]
        num_images_per_prompts = [1, 2]

        for batch_size in batch_sizes:
            for num_images_per_prompt in num_images_per_prompts:
                inputs = self.get_dummy_inputs(torch_device)

                for key in inputs.keys():
                    if key in self.batch_params:
                        inputs[key] = batch_size * [inputs[key]]

1877
                images = pipe(**inputs, num_images_per_prompt=num_images_per_prompt)[0]
1878
1879
1880

                assert images.shape[0] == batch_size * num_images_per_prompt

1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
    def test_cfg(self):
        sig = inspect.signature(self.pipeline_class.__call__)

        if "guidance_scale" not in sig.parameters:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)

        inputs["guidance_scale"] = 1.0
        out_no_cfg = pipe(**inputs)[0]

        inputs["guidance_scale"] = 7.5
        out_cfg = pipe(**inputs)[0]

        assert out_cfg.shape == out_no_cfg.shape

1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
    def test_callback_inputs(self):
        sig = inspect.signature(self.pipeline_class.__call__)
        has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
        has_callback_step_end = "callback_on_step_end" in sig.parameters

        if not (has_callback_tensor_inputs and has_callback_step_end):
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        self.assertTrue(
            hasattr(pipe, "_callback_tensor_inputs"),
            f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
        )

        def callback_inputs_subset(pipe, i, t, callback_kwargs):
M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
1920
            # iterate over callback args
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
            for tensor_name, tensor_value in callback_kwargs.items():
                # check that we're only passing in allowed tensor inputs
                assert tensor_name in pipe._callback_tensor_inputs

            return callback_kwargs

        def callback_inputs_all(pipe, i, t, callback_kwargs):
            for tensor_name in pipe._callback_tensor_inputs:
                assert tensor_name in callback_kwargs

M. Tolga Cangöz's avatar
M. Tolga Cangöz committed
1931
            # iterate over callback args
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
            for tensor_name, tensor_value in callback_kwargs.items():
                # check that we're only passing in allowed tensor inputs
                assert tensor_name in pipe._callback_tensor_inputs

            return callback_kwargs

        inputs = self.get_dummy_inputs(torch_device)

        # Test passing in a subset
        inputs["callback_on_step_end"] = callback_inputs_subset
        inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
        inputs["output_type"] = "latent"
        output = pipe(**inputs)[0]

        # Test passing in a everything
        inputs["callback_on_step_end"] = callback_inputs_all
        inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
        inputs["output_type"] = "latent"
        output = pipe(**inputs)[0]

        def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
            is_last = i == (pipe.num_timesteps - 1)
            if is_last:
                callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
            return callback_kwargs

        inputs["callback_on_step_end"] = callback_inputs_change_tensor
        inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
        inputs["output_type"] = "latent"
        output = pipe(**inputs)[0]
        assert output.abs().sum() == 0

    def test_callback_cfg(self):
        sig = inspect.signature(self.pipeline_class.__call__)
        has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
        has_callback_step_end = "callback_on_step_end" in sig.parameters

        if not (has_callback_tensor_inputs and has_callback_step_end):
            return

        if "guidance_scale" not in sig.parameters:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)
        self.assertTrue(
            hasattr(pipe, "_callback_tensor_inputs"),
            f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
        )

        def callback_increase_guidance(pipe, i, t, callback_kwargs):
            pipe._guidance_scale += 1.0

            return callback_kwargs

        inputs = self.get_dummy_inputs(torch_device)

        # use cfg guidance because some pipelines modify the shape of the latents
        # outside of the denoising loop
        inputs["guidance_scale"] = 2.0
        inputs["callback_on_step_end"] = callback_increase_guidance
        inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
        _ = pipe(**inputs)[0]

        # we increase the guidance scale by 1.0 at every step
        # check that the guidance scale is increased by the number of scheduler timesteps
        # accounts for models that modify the number of inference steps based on strength
        assert pipe.guidance_scale == (inputs["guidance_scale"] + pipe.num_timesteps)

2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
    def test_serialization_with_variants(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        model_components = [
            component_name for component_name, component in pipe.components.items() if isinstance(component, nn.Module)
        ]
        variant = "fp16"

        with tempfile.TemporaryDirectory() as tmpdir:
            pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)

            with open(f"{tmpdir}/model_index.json", "r") as f:
                config = json.load(f)

            for subfolder in os.listdir(tmpdir):
                if not os.path.isfile(subfolder) and subfolder in model_components:
                    folder_path = os.path.join(tmpdir, subfolder)
                    is_folder = os.path.isdir(folder_path) and subfolder in config
                    assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))

    def test_loading_with_variants(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        variant = "fp16"

        def is_nan(tensor):
            if tensor.ndimension() == 0:
                has_nan = torch.isnan(tensor).item()
            else:
                has_nan = torch.isnan(tensor).any()
            return has_nan

        with tempfile.TemporaryDirectory() as tmpdir:
            pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
            pipe_loaded = self.pipeline_class.from_pretrained(tmpdir, variant=variant)

            model_components_pipe = {
                component_name: component
                for component_name, component in pipe.components.items()
                if isinstance(component, nn.Module)
            }
            model_components_pipe_loaded = {
                component_name: component
                for component_name, component in pipe_loaded.components.items()
                if isinstance(component, nn.Module)
            }
            for component_name in model_components_pipe:
                pipe_component = model_components_pipe[component_name]
                pipe_loaded_component = model_components_pipe_loaded[component_name]
                for p1, p2 in zip(pipe_component.parameters(), pipe_loaded_component.parameters()):
                    # nan check for luminanext (mps).
                    if not (is_nan(p1) and is_nan(p2)):
                        self.assertTrue(torch.equal(p1, p2))

    def test_loading_with_incorrect_variants_raises_error(self):
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        variant = "fp16"

        with tempfile.TemporaryDirectory() as tmpdir:
            # Don't save with variants.
            pipe.save_pretrained(tmpdir, safe_serialization=False)

            with self.assertRaises(ValueError) as error:
                _ = self.pipeline_class.from_pretrained(tmpdir, variant=variant)

            assert f"You are trying to load the model files of the `variant={variant}`" in str(error.exception)

2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
    def test_encode_prompt_works_in_isolation(self, extra_required_param_value_dict=None, atol=1e-4, rtol=1e-4):
        if not hasattr(self.pipeline_class, "encode_prompt"):
            return

        components = self.get_dummy_components()

        # We initialize the pipeline with only text encoders and tokenizers,
        # mimicking a real-world scenario.
        components_with_text_encoders = {}
        for k in components:
            if "text" in k or "tokenizer" in k:
                components_with_text_encoders[k] = components[k]
            else:
                components_with_text_encoders[k] = None
        pipe_with_just_text_encoder = self.pipeline_class(**components_with_text_encoders)
        pipe_with_just_text_encoder = pipe_with_just_text_encoder.to(torch_device)

        # Get inputs and also the args of `encode_prompts`.
        inputs = self.get_dummy_inputs(torch_device)
        encode_prompt_signature = inspect.signature(pipe_with_just_text_encoder.encode_prompt)
        encode_prompt_parameters = list(encode_prompt_signature.parameters.values())

        # Required args in encode_prompt with those with no default.
        required_params = []
        for param in encode_prompt_parameters:
            if param.name == "self" or param.name == "kwargs":
                continue
            if param.default is inspect.Parameter.empty:
                required_params.append(param.name)

        # Craft inputs for the `encode_prompt()` method to run in isolation.
        encode_prompt_param_names = [p.name for p in encode_prompt_parameters if p.name != "self"]
        input_keys = list(inputs.keys())
        encode_prompt_inputs = {k: inputs.pop(k) for k in input_keys if k in encode_prompt_param_names}

        pipe_call_signature = inspect.signature(pipe_with_just_text_encoder.__call__)
        pipe_call_parameters = pipe_call_signature.parameters

        # For each required arg in encode_prompt, check if it's missing
        # in encode_prompt_inputs. If so, see if __call__ has a default
        # for that arg and use it if available.
        for required_param_name in required_params:
            if required_param_name not in encode_prompt_inputs:
                pipe_call_param = pipe_call_parameters.get(required_param_name, None)
                if pipe_call_param is not None and pipe_call_param.default is not inspect.Parameter.empty:
                    # Use the default from pipe.__call__
                    encode_prompt_inputs[required_param_name] = pipe_call_param.default
                elif extra_required_param_value_dict is not None and isinstance(extra_required_param_value_dict, dict):
                    encode_prompt_inputs[required_param_name] = extra_required_param_value_dict[required_param_name]
                else:
                    raise ValueError(
                        f"Required parameter '{required_param_name}' in "
                        f"encode_prompt has no default in either encode_prompt or __call__."
                    )

        # Compute `encode_prompt()`.
        with torch.no_grad():
            encoded_prompt_outputs = pipe_with_just_text_encoder.encode_prompt(**encode_prompt_inputs)

2130
2131
2132
2133
2134
        # Programmatically determine the return names of `encode_prompt.`
        ast_visitor = ReturnNameVisitor()
        encode_prompt_tree = ast_visitor.get_ast_tree(cls=self.pipeline_class)
        ast_visitor.visit(encode_prompt_tree)
        prompt_embed_kwargs = ast_visitor.return_names
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
        prompt_embeds_kwargs = dict(zip(prompt_embed_kwargs, encoded_prompt_outputs))

        # Pack the outputs of `encode_prompt`.
        adapted_prompt_embeds_kwargs = {
            k: prompt_embeds_kwargs.pop(k) for k in list(prompt_embeds_kwargs.keys()) if k in pipe_call_parameters
        }

        # now initialize a pipeline without text encoders and compute outputs with the
        # `encode_prompt()` outputs and other relevant inputs.
        components_with_text_encoders = {}
        for k in components:
            if "text" in k or "tokenizer" in k:
                components_with_text_encoders[k] = None
            else:
                components_with_text_encoders[k] = components[k]
        pipe_without_text_encoders = self.pipeline_class(**components_with_text_encoders).to(torch_device)

        # Set `negative_prompt` to None as we have already calculated its embeds
        # if it was present in `inputs`. This is because otherwise we will interfere wrongly
        # for non-None `negative_prompt` values as defaults (PixArt for example).
        pipe_without_tes_inputs = {**inputs, **adapted_prompt_embeds_kwargs}
        if (
            pipe_call_parameters.get("negative_prompt", None) is not None
            and pipe_call_parameters.get("negative_prompt").default is not None
        ):
            pipe_without_tes_inputs.update({"negative_prompt": None})

        # Pipelines like attend and excite have `prompt` as a required argument.
        if (
            pipe_call_parameters.get("prompt", None) is not None
            and pipe_call_parameters.get("prompt").default is inspect.Parameter.empty
            and pipe_call_parameters.get("prompt_embeds", None) is not None
            and pipe_call_parameters.get("prompt_embeds").default is None
        ):
            pipe_without_tes_inputs.update({"prompt": None})

        pipe_out = pipe_without_text_encoders(**pipe_without_tes_inputs)[0]

        # Compare against regular pipeline outputs.
        full_pipe = self.pipeline_class(**components).to(torch_device)
        inputs = self.get_dummy_inputs(torch_device)
        pipe_out_2 = full_pipe(**inputs)[0]

        if isinstance(pipe_out, np.ndarray) and isinstance(pipe_out_2, np.ndarray):
            self.assertTrue(np.allclose(pipe_out, pipe_out_2, atol=atol, rtol=rtol))
        elif isinstance(pipe_out, torch.Tensor) and isinstance(pipe_out_2, torch.Tensor):
            self.assertTrue(torch.allclose(pipe_out, pipe_out_2, atol=atol, rtol=rtol))

2183
2184
2185
2186
2187
2188
2189
2190
2191
    def test_StableDiffusionMixin_component(self):
        """Any pipeline that have LDMFuncMixin should have vae and unet components."""
        if not issubclass(self.pipeline_class, StableDiffusionMixin):
            return
        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        self.assertTrue(hasattr(pipe, "vae") and isinstance(pipe.vae, (AutoencoderKL, AutoencoderTiny)))
        self.assertTrue(
            hasattr(pipe, "unet")
2192
2193
2194
2195
            and isinstance(
                pipe.unet,
                (UNet2DConditionModel, UNet3DConditionModel, I2VGenXLUNet, UNetMotionModel, UNetControlNetXSModel),
            )
2196
2197
        )

Marc Sun's avatar
Marc Sun committed
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
    @require_hf_hub_version_greater("0.26.5")
    @require_transformers_version_greater("4.47.1")
    def test_save_load_dduf(self, atol=1e-4, rtol=1e-4):
        if not self.supports_dduf:
            return

        from huggingface_hub import export_folder_as_dduf

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(torch_device)
        pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(device="cpu")
        inputs.pop("generator")
        inputs["generator"] = torch.manual_seed(0)

        pipeline_out = pipe(**inputs)[0]

        with tempfile.TemporaryDirectory() as tmpdir:
            dduf_filename = os.path.join(tmpdir, f"{pipe.__class__.__name__.lower()}.dduf")
            pipe.save_pretrained(tmpdir, safe_serialization=True)
            export_folder_as_dduf(dduf_filename, folder_path=tmpdir)
            loaded_pipe = self.pipeline_class.from_pretrained(tmpdir, dduf_file=dduf_filename).to(torch_device)

        inputs["generator"] = torch.manual_seed(0)
        loaded_pipeline_out = loaded_pipe(**inputs)[0]

        if isinstance(pipeline_out, np.ndarray) and isinstance(loaded_pipeline_out, np.ndarray):
            assert np.allclose(pipeline_out, loaded_pipeline_out, atol=atol, rtol=rtol)
        elif isinstance(pipeline_out, torch.Tensor) and isinstance(loaded_pipeline_out, torch.Tensor):
            assert torch.allclose(pipeline_out, loaded_pipeline_out, atol=atol, rtol=rtol)

Aryan's avatar
Aryan committed
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
    def test_layerwise_casting_inference(self):
        if not self.test_layerwise_casting:
            return

        components = self.get_dummy_components()
        pipe = self.pipeline_class(**components)
        pipe.to(torch_device, dtype=torch.bfloat16)
        pipe.set_progress_bar_config(disable=None)

        denoiser = pipe.transformer if hasattr(pipe, "transformer") else pipe.unet
        denoiser.enable_layerwise_casting(storage_dtype=torch.float8_e4m3fn, compute_dtype=torch.bfloat16)

        inputs = self.get_dummy_inputs(torch_device)
        _ = pipe(**inputs)[0]

2246
    @require_torch_accelerator
Aryan's avatar
Aryan committed
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
    def test_group_offloading_inference(self):
        if not self.test_group_offloading:
            return

        def create_pipe():
            torch.manual_seed(0)
            components = self.get_dummy_components()
            pipe = self.pipeline_class(**components)
            pipe.set_progress_bar_config(disable=None)
            return pipe

        def enable_group_offload_on_component(pipe, group_offloading_kwargs):
            # We intentionally don't test VAE's here. This is because some tests enable tiling on the VAE. If
2260
            # tiling is enabled and a forward pass is run, when accelerator streams are used, the execution order of
Aryan's avatar
Aryan committed
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
            # the layers is not traced correctly. This causes errors. For apply group offloading to VAE, a
            # warmup forward pass (even with dummy small inputs) is recommended.
            for component_name in [
                "text_encoder",
                "text_encoder_2",
                "text_encoder_3",
                "transformer",
                "unet",
                "controlnet",
            ]:
                if not hasattr(pipe, component_name):
                    continue
                component = getattr(pipe, component_name)
                if not getattr(component, "_supports_group_offloading", True):
                    continue
                if hasattr(component, "enable_group_offload"):
                    # For diffusers ModelMixin implementations
                    component.enable_group_offload(torch.device(torch_device), **group_offloading_kwargs)
                else:
                    # For other models not part of diffusers
                    apply_group_offloading(
                        component, onload_device=torch.device(torch_device), **group_offloading_kwargs
                    )
                self.assertTrue(
                    all(
                        module._diffusers_hook.get_hook("group_offloading") is not None
                        for module in component.modules()
                        if hasattr(module, "_diffusers_hook")
                    )
                )
2291
2292
2293
2294
            for component_name in ["vae", "vqvae", "image_encoder"]:
                component = getattr(pipe, component_name, None)
                if isinstance(component, torch.nn.Module):
                    component.to(torch_device)
Aryan's avatar
Aryan committed
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319

        def run_forward(pipe):
            torch.manual_seed(0)
            inputs = self.get_dummy_inputs(torch_device)
            return pipe(**inputs)[0]

        pipe = create_pipe().to(torch_device)
        output_without_group_offloading = run_forward(pipe)

        pipe = create_pipe()
        enable_group_offload_on_component(pipe, {"offload_type": "block_level", "num_blocks_per_group": 1})
        output_with_group_offloading1 = run_forward(pipe)

        pipe = create_pipe()
        enable_group_offload_on_component(pipe, {"offload_type": "leaf_level"})
        output_with_group_offloading2 = run_forward(pipe)

        if torch.is_tensor(output_without_group_offloading):
            output_without_group_offloading = output_without_group_offloading.detach().cpu().numpy()
            output_with_group_offloading1 = output_with_group_offloading1.detach().cpu().numpy()
            output_with_group_offloading2 = output_with_group_offloading2.detach().cpu().numpy()

        self.assertTrue(np.allclose(output_without_group_offloading, output_with_group_offloading1, atol=1e-4))
        self.assertTrue(np.allclose(output_without_group_offloading, output_with_group_offloading2, atol=1e-4))

2320
2321
2322
2323
2324
2325
2326
2327
2328
    def test_torch_dtype_dict(self):
        components = self.get_dummy_components()
        if not components:
            self.skipTest("No dummy components defined.")

        pipe = self.pipeline_class(**components)
        specified_key = next(iter(components.keys()))

        with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
2329
            pipe.save_pretrained(tmpdirname, safe_serialization=False)
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
            torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
            loaded_pipe = self.pipeline_class.from_pretrained(tmpdirname, torch_dtype=torch_dtype_dict)

        for name, component in loaded_pipe.components.items():
            if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
                expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
                self.assertEqual(
                    component.dtype,
                    expected_dtype,
                    f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
                )

2342

2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
@is_staging_test
class PipelinePushToHubTester(unittest.TestCase):
    identifier = uuid.uuid4()
    repo_id = f"test-pipeline-{identifier}"
    org_repo_id = f"valid_org/{repo_id}-org"

    def get_pipeline_components(self):
        unet = UNet2DConditionModel(
            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,
        )

        scheduler = DDIMScheduler(
            beta_start=0.00085,
            beta_end=0.012,
            beta_schedule="scaled_linear",
            clip_sample=False,
            set_alpha_to_one=False,
        )

        vae = AutoencoderKL(
            block_out_channels=[32, 64],
            in_channels=3,
            out_channels=3,
            down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
            up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
            latent_channels=4,
        )

        text_encoder_config = CLIPTextConfig(
            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,
        )
        text_encoder = CLIPTextModel(text_encoder_config)

        with tempfile.TemporaryDirectory() as tmpdir:
            dummy_vocab = {"<|startoftext|>": 0, "<|endoftext|>": 1, "!": 2}
            vocab_path = os.path.join(tmpdir, "vocab.json")
            with open(vocab_path, "w") as f:
                json.dump(dummy_vocab, f)

            merges = "Ġ t\nĠt h"
            merges_path = os.path.join(tmpdir, "merges.txt")
            with open(merges_path, "w") as f:
                f.writelines(merges)
            tokenizer = CLIPTokenizer(vocab_file=vocab_path, merges_file=merges_path)

        components = {
            "unet": unet,
            "scheduler": scheduler,
            "vae": vae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
            "safety_checker": None,
            "feature_extractor": None,
        }
        return components

    def test_push_to_hub(self):
        components = self.get_pipeline_components()
        pipeline = StableDiffusionPipeline(**components)
        pipeline.push_to_hub(self.repo_id, token=TOKEN)

        new_model = UNet2DConditionModel.from_pretrained(f"{USER}/{self.repo_id}", subfolder="unet")
        unet = components["unet"]
        for p1, p2 in zip(unet.parameters(), new_model.parameters()):
            self.assertTrue(torch.equal(p1, p2))

        # Reset repo
        delete_repo(token=TOKEN, repo_id=self.repo_id)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
            pipeline.save_pretrained(tmp_dir, repo_id=self.repo_id, push_to_hub=True, token=TOKEN)

        new_model = UNet2DConditionModel.from_pretrained(f"{USER}/{self.repo_id}", subfolder="unet")
        for p1, p2 in zip(unet.parameters(), new_model.parameters()):
            self.assertTrue(torch.equal(p1, p2))

        # Reset repo
        delete_repo(self.repo_id, token=TOKEN)

    def test_push_to_hub_in_organization(self):
        components = self.get_pipeline_components()
        pipeline = StableDiffusionPipeline(**components)
        pipeline.push_to_hub(self.org_repo_id, token=TOKEN)

        new_model = UNet2DConditionModel.from_pretrained(self.org_repo_id, subfolder="unet")
        unet = components["unet"]
        for p1, p2 in zip(unet.parameters(), new_model.parameters()):
            self.assertTrue(torch.equal(p1, p2))

        # Reset repo
        delete_repo(token=TOKEN, repo_id=self.org_repo_id)

        # Push to hub via save_pretrained
        with tempfile.TemporaryDirectory() as tmp_dir:
            pipeline.save_pretrained(tmp_dir, push_to_hub=True, token=TOKEN, repo_id=self.org_repo_id)

        new_model = UNet2DConditionModel.from_pretrained(self.org_repo_id, subfolder="unet")
        for p1, p2 in zip(unet.parameters(), new_model.parameters()):
            self.assertTrue(torch.equal(p1, p2))

        # Reset repo
        delete_repo(self.org_repo_id, token=TOKEN)
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475

    @unittest.skipIf(
        not is_jinja_available(),
        reason="Model card tests cannot be performed without Jinja installed.",
    )
    def test_push_to_hub_library_name(self):
        components = self.get_pipeline_components()
        pipeline = StableDiffusionPipeline(**components)
        pipeline.push_to_hub(self.repo_id, token=TOKEN)

        model_card = ModelCard.load(f"{USER}/{self.repo_id}", token=TOKEN).data
        assert model_card.library_name == "diffusers"

        # Reset repo
        delete_repo(self.repo_id, token=TOKEN)
2476
2477


2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
class PyramidAttentionBroadcastTesterMixin:
    pab_config = PyramidAttentionBroadcastConfig(
        spatial_attention_block_skip_range=2,
        spatial_attention_timestep_skip_range=(100, 800),
        spatial_attention_block_identifiers=["transformer_blocks"],
    )

    def test_pyramid_attention_broadcast_layers(self):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator

        num_layers = 0
        num_single_layers = 0
        dummy_component_kwargs = {}
        dummy_component_parameters = inspect.signature(self.get_dummy_components).parameters
        if "num_layers" in dummy_component_parameters:
            num_layers = 2
            dummy_component_kwargs["num_layers"] = num_layers
        if "num_single_layers" in dummy_component_parameters:
            num_single_layers = 2
            dummy_component_kwargs["num_single_layers"] = num_single_layers

        components = self.get_dummy_components(**dummy_component_kwargs)
        pipe = self.pipeline_class(**components)
        pipe.set_progress_bar_config(disable=None)

        self.pab_config.current_timestep_callback = lambda: pipe.current_timestep
        denoiser = pipe.transformer if hasattr(pipe, "transformer") else pipe.unet
        denoiser.enable_cache(self.pab_config)

        expected_hooks = 0
        if self.pab_config.spatial_attention_block_skip_range is not None:
            expected_hooks += num_layers + num_single_layers
        if self.pab_config.temporal_attention_block_skip_range is not None:
            expected_hooks += num_layers + num_single_layers
        if self.pab_config.cross_attention_block_skip_range is not None:
            expected_hooks += num_layers + num_single_layers

        denoiser = pipe.transformer if hasattr(pipe, "transformer") else pipe.unet
        count = 0
        for module in denoiser.modules():
            if hasattr(module, "_diffusers_hook"):
                hook = module._diffusers_hook.get_hook("pyramid_attention_broadcast")
                if hook is None:
                    continue
                count += 1
                self.assertTrue(
                    isinstance(hook, PyramidAttentionBroadcastHook),
                    "Hook should be of type PyramidAttentionBroadcastHook.",
                )
                self.assertTrue(hook.state.cache is None, "Cache should be None at initialization.")
        self.assertEqual(count, expected_hooks, "Number of hooks should match the expected number.")

        # Perform dummy inference step to ensure state is updated
        def pab_state_check_callback(pipe, i, t, kwargs):
            for module in denoiser.modules():
                if hasattr(module, "_diffusers_hook"):
                    hook = module._diffusers_hook.get_hook("pyramid_attention_broadcast")
                    if hook is None:
                        continue
                    self.assertTrue(
                        hook.state.cache is not None,
                        "Cache should have updated during inference.",
                    )
                    self.assertTrue(
                        hook.state.iteration == i + 1,
                        "Hook iteration state should have updated during inference.",
                    )
            return {}

        inputs = self.get_dummy_inputs(device)
        inputs["num_inference_steps"] = 2
        inputs["callback_on_step_end"] = pab_state_check_callback
        pipe(**inputs)[0]

        # After inference, reset_stateful_hooks is called within the pipeline, which should have reset the states
        for module in denoiser.modules():
            if hasattr(module, "_diffusers_hook"):
                hook = module._diffusers_hook.get_hook("pyramid_attention_broadcast")
                if hook is None:
                    continue
                self.assertTrue(
                    hook.state.cache is None,
                    "Cache should be reset to None after inference.",
                )
                self.assertTrue(
                    hook.state.iteration == 0,
                    "Iteration should be reset to 0 after inference.",
                )

    def test_pyramid_attention_broadcast_inference(self, expected_atol: float = 0.2):
        # We need to use higher tolerance because we are using a random model. With a converged/trained
        # model, the tolerance can be lower.

        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
        num_layers = 2
        components = self.get_dummy_components(num_layers=num_layers)
        pipe = self.pipeline_class(**components)
        pipe = pipe.to(device)
        pipe.set_progress_bar_config(disable=None)

        # Run inference without PAB
        inputs = self.get_dummy_inputs(device)
        inputs["num_inference_steps"] = 4
        output = pipe(**inputs)[0]
        original_image_slice = output.flatten()
        original_image_slice = np.concatenate((original_image_slice[:8], original_image_slice[-8:]))

        # Run inference with PAB enabled
        self.pab_config.current_timestep_callback = lambda: pipe.current_timestep
        denoiser = pipe.transformer if hasattr(pipe, "transformer") else pipe.unet
        denoiser.enable_cache(self.pab_config)

        inputs = self.get_dummy_inputs(device)
        inputs["num_inference_steps"] = 4
        output = pipe(**inputs)[0]
        image_slice_pab_enabled = output.flatten()
        image_slice_pab_enabled = np.concatenate((image_slice_pab_enabled[:8], image_slice_pab_enabled[-8:]))

        # Run inference with PAB disabled
        denoiser.disable_cache()

        inputs = self.get_dummy_inputs(device)
        inputs["num_inference_steps"] = 4
        output = pipe(**inputs)[0]
        image_slice_pab_disabled = output.flatten()
        image_slice_pab_disabled = np.concatenate((image_slice_pab_disabled[:8], image_slice_pab_disabled[-8:]))

2605
2606
2607
2608
2609
2610
        assert np.allclose(original_image_slice, image_slice_pab_enabled, atol=expected_atol), (
            "PAB outputs should not differ much in specified timestep range."
        )
        assert np.allclose(original_image_slice, image_slice_pab_disabled, atol=1e-4), (
            "Outputs from normal inference and after disabling cache should not differ."
        )
2611
2612


Aryan's avatar
Aryan committed
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
class FasterCacheTesterMixin:
    faster_cache_config = FasterCacheConfig(
        spatial_attention_block_skip_range=2,
        spatial_attention_timestep_skip_range=(-1, 901),
        unconditional_batch_skip_range=2,
        attention_weight_callback=lambda _: 0.5,
    )

    def test_faster_cache_basic_warning_or_errors_raised(self):
        components = self.get_dummy_components()

        logger = logging.get_logger("diffusers.hooks.faster_cache")
        logger.setLevel(logging.INFO)

        # Check if warning is raise when no attention_weight_callback is provided
        pipe = self.pipeline_class(**components)
        with CaptureLogger(logger) as cap_logger:
            config = FasterCacheConfig(spatial_attention_block_skip_range=2, attention_weight_callback=None)
            apply_faster_cache(pipe.transformer, config)
        self.assertTrue("No `attention_weight_callback` provided when enabling FasterCache" in cap_logger.out)

        # Check if error raised when unsupported tensor format used
        pipe = self.pipeline_class(**components)
        with self.assertRaises(ValueError):
            config = FasterCacheConfig(spatial_attention_block_skip_range=2, tensor_format="BFHWC")
            apply_faster_cache(pipe.transformer, config)

    def test_faster_cache_inference(self, expected_atol: float = 0.1):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator

        def create_pipe():
            torch.manual_seed(0)
            num_layers = 2
            components = self.get_dummy_components(num_layers=num_layers)
            pipe = self.pipeline_class(**components)
            pipe = pipe.to(device)
            pipe.set_progress_bar_config(disable=None)
            return pipe

        def run_forward(pipe):
            torch.manual_seed(0)
            inputs = self.get_dummy_inputs(device)
            inputs["num_inference_steps"] = 4
            return pipe(**inputs)[0]

        # Run inference without FasterCache
        pipe = create_pipe()
        output = run_forward(pipe).flatten()
        original_image_slice = np.concatenate((output[:8], output[-8:]))

        # Run inference with FasterCache enabled
        self.faster_cache_config.current_timestep_callback = lambda: pipe.current_timestep
        pipe = create_pipe()
        pipe.transformer.enable_cache(self.faster_cache_config)
Aryan's avatar
Aryan committed
2667
        output = run_forward(pipe).flatten()
Aryan's avatar
Aryan committed
2668
2669
2670
2671
2672
2673
2674
        image_slice_faster_cache_enabled = np.concatenate((output[:8], output[-8:]))

        # Run inference with FasterCache disabled
        pipe.transformer.disable_cache()
        output = run_forward(pipe).flatten()
        image_slice_faster_cache_disabled = np.concatenate((output[:8], output[-8:]))

2675
2676
2677
2678
2679
2680
        assert np.allclose(original_image_slice, image_slice_faster_cache_enabled, atol=expected_atol), (
            "FasterCache outputs should not differ much in specified timestep range."
        )
        assert np.allclose(original_image_slice, image_slice_faster_cache_disabled, atol=1e-4), (
            "Outputs from normal inference and after disabling cache should not differ."
        )
Aryan's avatar
Aryan committed
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773

    def test_faster_cache_state(self):
        from diffusers.hooks.faster_cache import _FASTER_CACHE_BLOCK_HOOK, _FASTER_CACHE_DENOISER_HOOK

        device = "cpu"  # ensure determinism for the device-dependent torch.Generator
        num_layers = 0
        num_single_layers = 0
        dummy_component_kwargs = {}
        dummy_component_parameters = inspect.signature(self.get_dummy_components).parameters
        if "num_layers" in dummy_component_parameters:
            num_layers = 2
            dummy_component_kwargs["num_layers"] = num_layers
        if "num_single_layers" in dummy_component_parameters:
            num_single_layers = 2
            dummy_component_kwargs["num_single_layers"] = num_single_layers

        components = self.get_dummy_components(**dummy_component_kwargs)
        pipe = self.pipeline_class(**components)
        pipe.set_progress_bar_config(disable=None)

        self.faster_cache_config.current_timestep_callback = lambda: pipe.current_timestep
        pipe.transformer.enable_cache(self.faster_cache_config)

        expected_hooks = 0
        if self.faster_cache_config.spatial_attention_block_skip_range is not None:
            expected_hooks += num_layers + num_single_layers
        if self.faster_cache_config.temporal_attention_block_skip_range is not None:
            expected_hooks += num_layers + num_single_layers

        # Check if faster_cache denoiser hook is attached
        denoiser = pipe.transformer if hasattr(pipe, "transformer") else pipe.unet
        self.assertTrue(
            hasattr(denoiser, "_diffusers_hook")
            and isinstance(denoiser._diffusers_hook.get_hook(_FASTER_CACHE_DENOISER_HOOK), FasterCacheDenoiserHook),
            "Hook should be of type FasterCacheDenoiserHook.",
        )

        # Check if all blocks have faster_cache block hook attached
        count = 0
        for name, module in denoiser.named_modules():
            if hasattr(module, "_diffusers_hook"):
                if name == "":
                    # Skip the root denoiser module
                    continue
                count += 1
                self.assertTrue(
                    isinstance(module._diffusers_hook.get_hook(_FASTER_CACHE_BLOCK_HOOK), FasterCacheBlockHook),
                    "Hook should be of type FasterCacheBlockHook.",
                )
        self.assertEqual(count, expected_hooks, "Number of hooks should match expected number.")

        # Perform inference to ensure that states are updated correctly
        def faster_cache_state_check_callback(pipe, i, t, kwargs):
            for name, module in denoiser.named_modules():
                if not hasattr(module, "_diffusers_hook"):
                    continue
                if name == "":
                    # Root denoiser module
                    state = module._diffusers_hook.get_hook(_FASTER_CACHE_DENOISER_HOOK).state
                    if not self.faster_cache_config.is_guidance_distilled:
                        self.assertTrue(state.low_frequency_delta is not None, "Low frequency delta should be set.")
                        self.assertTrue(state.high_frequency_delta is not None, "High frequency delta should be set.")
                else:
                    # Internal blocks
                    state = module._diffusers_hook.get_hook(_FASTER_CACHE_BLOCK_HOOK).state
                    self.assertTrue(state.cache is not None and len(state.cache) == 2, "Cache should be set.")
                self.assertTrue(state.iteration == i + 1, "Hook iteration state should have updated during inference.")
            return {}

        inputs = self.get_dummy_inputs(device)
        inputs["num_inference_steps"] = 4
        inputs["callback_on_step_end"] = faster_cache_state_check_callback
        _ = pipe(**inputs)[0]

        # After inference, reset_stateful_hooks is called within the pipeline, which should have reset the states
        for name, module in denoiser.named_modules():
            if not hasattr(module, "_diffusers_hook"):
                continue

            if name == "":
                # Root denoiser module
                state = module._diffusers_hook.get_hook(_FASTER_CACHE_DENOISER_HOOK).state
                self.assertTrue(state.iteration == 0, "Iteration should be reset to 0.")
                self.assertTrue(state.low_frequency_delta is None, "Low frequency delta should be reset to None.")
                self.assertTrue(state.high_frequency_delta is None, "High frequency delta should be reset to None.")
            else:
                # Internal blocks
                state = module._diffusers_hook.get_hook(_FASTER_CACHE_BLOCK_HOOK).state
                self.assertTrue(state.iteration == 0, "Iteration should be reset to 0.")
                self.assertTrue(state.batch_size is None, "Batch size should be reset to None.")
                self.assertTrue(state.cache is None, "Cache should be reset to None.")


Aryan's avatar
Aryan committed
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
# TODO(aryan, dhruv): the cache tester mixins should probably be rewritten so that more models can be tested out
# of the box once there is better cache support/implementation
class FirstBlockCacheTesterMixin:
    # threshold is intentionally set higher than usual values since we're testing with random unconverged models
    # that will not satisfy the expected properties of the denoiser for caching to be effective
    first_block_cache_config = FirstBlockCacheConfig(threshold=0.8)

    def test_first_block_cache_inference(self, expected_atol: float = 0.1):
        device = "cpu"  # ensure determinism for the device-dependent torch.Generator

        def create_pipe():
            torch.manual_seed(0)
            num_layers = 2
            components = self.get_dummy_components(num_layers=num_layers)
            pipe = self.pipeline_class(**components)
            pipe = pipe.to(device)
            pipe.set_progress_bar_config(disable=None)
            return pipe

        def run_forward(pipe):
            torch.manual_seed(0)
            inputs = self.get_dummy_inputs(device)
            inputs["num_inference_steps"] = 4
            return pipe(**inputs)[0]

        # Run inference without FirstBlockCache
        pipe = create_pipe()
        output = run_forward(pipe).flatten()
        original_image_slice = np.concatenate((output[:8], output[-8:]))

        # Run inference with FirstBlockCache enabled
        pipe = create_pipe()
        pipe.transformer.enable_cache(self.first_block_cache_config)
        output = run_forward(pipe).flatten()
        image_slice_fbc_enabled = np.concatenate((output[:8], output[-8:]))

        # Run inference with FirstBlockCache disabled
        pipe.transformer.disable_cache()
        output = run_forward(pipe).flatten()
        image_slice_fbc_disabled = np.concatenate((output[:8], output[-8:]))

        assert np.allclose(original_image_slice, image_slice_fbc_enabled, atol=expected_atol), (
            "FirstBlockCache outputs should not differ much."
        )
        assert np.allclose(original_image_slice, image_slice_fbc_disabled, atol=1e-4), (
            "Outputs from normal inference and after disabling cache should not differ."
        )


2823
2824
2825
# Some models (e.g. unCLIP) are extremely likely to significantly deviate depending on which hardware is used.
# This helper function is used to check that the image doesn't deviate on average more than 10 pixels from a
# reference image.
2826
def assert_mean_pixel_difference(image, expected_image, expected_max_diff=10):
2827
2828
2829
    image = np.asarray(DiffusionPipeline.numpy_to_pil(image)[0], dtype=np.float32)
    expected_image = np.asarray(DiffusionPipeline.numpy_to_pil(expected_image)[0], dtype=np.float32)
    avg_diff = np.abs(image - expected_image).mean()
2830
    assert avg_diff < expected_max_diff, f"Error image deviates {avg_diff} pixels on average"