test_dit.py 5.56 KB
Newer Older
Kashif Rasul's avatar
Kashif Rasul committed
1
# coding=utf-8
2
# Copyright 2025 HuggingFace Inc.
Kashif Rasul's avatar
Kashif Rasul committed
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import gc
import unittest

import numpy as np
import torch

22
from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DiTTransformer2DModel, DPMSolverMultistepScheduler
Dhruv Nair's avatar
Dhruv Nair committed
23
from diffusers.utils import is_xformers_available
24
25

from ...testing_utils import (
26
27
28
29
30
31
32
33
    backend_empty_cache,
    enable_full_determinism,
    load_numpy,
    nightly,
    numpy_cosine_similarity_distance,
    require_torch_accelerator,
    torch_device,
)
34
from ..pipeline_params import (
35
36
37
    CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
    CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
)
38
from ..test_pipelines_common import PipelineTesterMixin
Kashif Rasul's avatar
Kashif Rasul committed
39
40


41
enable_full_determinism()
Kashif Rasul's avatar
Kashif Rasul committed
42
43
44
45


class DiTPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
    pipeline_class = DiTPipeline
46
47
48
49
50
51
52
53
    params = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
    required_optional_params = PipelineTesterMixin.required_optional_params - {
        "latents",
        "num_images_per_prompt",
        "callback",
        "callback_steps",
    }
    batch_params = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
Kashif Rasul's avatar
Kashif Rasul committed
54
55
56

    def get_dummy_components(self):
        torch.manual_seed(0)
57
        transformer = DiTTransformer2DModel(
58
            sample_size=16,
Kashif Rasul's avatar
Kashif Rasul committed
59
            num_layers=2,
60
61
            patch_size=4,
            attention_head_dim=8,
Kashif Rasul's avatar
Kashif Rasul committed
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
            num_attention_heads=2,
            in_channels=4,
            out_channels=8,
            attention_bias=True,
            activation_fn="gelu-approximate",
            num_embeds_ada_norm=1000,
            norm_type="ada_norm_zero",
            norm_elementwise_affine=False,
        )
        vae = AutoencoderKL()
        scheduler = DDIMScheduler()
        components = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler}
        return components

    def get_dummy_inputs(self, device, seed=0):
        if str(device).startswith("mps"):
            generator = torch.manual_seed(seed)
        else:
            generator = torch.Generator(device=device).manual_seed(seed)
        inputs = {
            "class_labels": [1],
            "generator": generator,
            "num_inference_steps": 2,
85
            "output_type": "np",
Kashif Rasul's avatar
Kashif Rasul committed
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
        }
        return inputs

    def test_inference(self):
        device = "cpu"

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

        inputs = self.get_dummy_inputs(device)
        image = pipe(**inputs).images
        image_slice = image[0, -3:, -3:, -1]

101
        self.assertEqual(image.shape, (1, 16, 16, 3))
102
        expected_slice = np.array([0.2946, 0.6601, 0.4329, 0.3296, 0.4144, 0.5319, 0.7273, 0.5013, 0.4457])
Kashif Rasul's avatar
Kashif Rasul committed
103
104
105
106
        max_diff = np.abs(image_slice.flatten() - expected_slice).max()
        self.assertLessEqual(max_diff, 1e-3)

    def test_inference_batch_single_identical(self):
107
        self._test_inference_batch_single_identical(expected_max_diff=1e-3)
Kashif Rasul's avatar
Kashif Rasul committed
108
109
110
111
112
113
114

    @unittest.skipIf(
        torch_device != "cuda" or not is_xformers_available(),
        reason="XFormers attention is only available with CUDA and `xformers` installed",
    )
    def test_xformers_attention_forwardGenerator_pass(self):
        self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
Kashif Rasul's avatar
Kashif Rasul committed
115
116


Dhruv Nair's avatar
Dhruv Nair committed
117
@nightly
118
@require_torch_accelerator
Kashif Rasul's avatar
Kashif Rasul committed
119
class DiTPipelineIntegrationTests(unittest.TestCase):
120
121
122
    def setUp(self):
        super().setUp()
        gc.collect()
123
        backend_empty_cache(torch_device)
124

Kashif Rasul's avatar
Kashif Rasul committed
125
126
127
    def tearDown(self):
        super().tearDown()
        gc.collect()
128
        backend_empty_cache(torch_device)
Kashif Rasul's avatar
Kashif Rasul committed
129
130
131
132
133

    def test_dit_256(self):
        generator = torch.manual_seed(0)

        pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256")
134
        pipe.to(torch_device)
Kashif Rasul's avatar
Kashif Rasul committed
135
136
137
138
139
140
141
142
143
144

        words = ["vase", "umbrella", "white shark", "white wolf"]
        ids = pipe.get_label_ids(words)

        images = pipe(ids, generator=generator, num_inference_steps=40, output_type="np").images

        for word, image in zip(words, images):
            expected_image = load_numpy(
                f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy"
            )
Kashif Rasul's avatar
Kashif Rasul committed
145
            assert np.abs((expected_image - image).max()) < 1e-2
Kashif Rasul's avatar
Kashif Rasul committed
146

147
148
    def test_dit_512(self):
        pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512")
Kashif Rasul's avatar
Kashif Rasul committed
149
        pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
150
        pipe.to(torch_device)
Kashif Rasul's avatar
Kashif Rasul committed
151

152
        words = ["vase", "umbrella"]
Kashif Rasul's avatar
Kashif Rasul committed
153
154
        ids = pipe.get_label_ids(words)

155
        generator = torch.manual_seed(0)
Kashif Rasul's avatar
Kashif Rasul committed
156
157
158
159
        images = pipe(ids, generator=generator, num_inference_steps=25, output_type="np").images

        for word, image in zip(words, images):
            expected_image = load_numpy(
160
                f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}_512.npy"
Kashif Rasul's avatar
Kashif Rasul committed
161
            )
162

163
164
165
166
            expected_slice = expected_image.flatten()
            output_slice = image.flatten()

            assert numpy_cosine_similarity_distance(expected_slice, output_slice) < 1e-2