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

import unittest

import numpy as np
import torch
from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer

from diffusers import AmusedInpaintPipeline, AmusedScheduler, UVit2DModel, VQModel
from diffusers.utils import load_image
Dhruv Nair's avatar
Dhruv Nair committed
24
from diffusers.utils.testing_utils import (
25
    Expectations,
Dhruv Nair's avatar
Dhruv Nair committed
26
    enable_full_determinism,
27
    require_torch_accelerator,
Dhruv Nair's avatar
Dhruv Nair committed
28
29
30
    slow,
    torch_device,
)
Will Berman's avatar
Will Berman committed
31
32
33
34
35
36
37
38
39
40
41
42

from ..pipeline_params import TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS, TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
from ..test_pipelines_common import PipelineTesterMixin


enable_full_determinism()


class AmusedInpaintPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
    pipeline_class = AmusedInpaintPipeline
    params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"}
    batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
Dhruv Nair's avatar
Dhruv Nair committed
43
    required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
Will Berman's avatar
Will Berman committed
44
45
46
47

    def get_dummy_components(self):
        torch.manual_seed(0)
        transformer = UVit2DModel(
48
            hidden_size=8,
Will Berman's avatar
Will Berman committed
49
50
            use_bias=False,
            hidden_dropout=0.0,
51
            cond_embed_dim=8,
Will Berman's avatar
Will Berman committed
52
53
            micro_cond_encode_dim=2,
            micro_cond_embed_dim=10,
54
            encoder_hidden_size=8,
Will Berman's avatar
Will Berman committed
55
            vocab_size=32,
Dhruv Nair's avatar
Dhruv Nair committed
56
            codebook_size=32,
57
58
            in_channels=8,
            block_out_channels=8,
Will Berman's avatar
Will Berman committed
59
60
61
62
63
64
65
            num_res_blocks=1,
            downsample=True,
            upsample=True,
            block_num_heads=1,
            num_hidden_layers=1,
            num_attention_heads=1,
            attention_dropout=0.0,
66
            intermediate_size=8,
Will Berman's avatar
Will Berman committed
67
68
69
70
71
72
73
            layer_norm_eps=1e-06,
            ln_elementwise_affine=True,
        )
        scheduler = AmusedScheduler(mask_token_id=31)
        torch.manual_seed(0)
        vqvae = VQModel(
            act_fn="silu",
74
            block_out_channels=[8],
Dhruv Nair's avatar
Dhruv Nair committed
75
            down_block_types=["DownEncoderBlock2D"],
Will Berman's avatar
Will Berman committed
76
            in_channels=3,
77
78
79
            latent_channels=8,
            layers_per_block=1,
            norm_num_groups=8,
Dhruv Nair's avatar
Dhruv Nair committed
80
            num_vq_embeddings=32,
Will Berman's avatar
Will Berman committed
81
            out_channels=3,
82
            sample_size=8,
Dhruv Nair's avatar
Dhruv Nair committed
83
            up_block_types=["UpDecoderBlock2D"],
Will Berman's avatar
Will Berman committed
84
85
86
87
88
89
90
            mid_block_add_attention=False,
            lookup_from_codebook=True,
        )
        torch.manual_seed(0)
        text_encoder_config = CLIPTextConfig(
            bos_token_id=0,
            eos_token_id=2,
91
92
            hidden_size=8,
            intermediate_size=8,
Will Berman's avatar
Will Berman committed
93
            layer_norm_eps=1e-05,
94
95
            num_attention_heads=1,
            num_hidden_layers=1,
Will Berman's avatar
Will Berman committed
96
97
            pad_token_id=1,
            vocab_size=1000,
98
            projection_dim=8,
Will Berman's avatar
Will Berman committed
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
        )
        text_encoder = CLIPTextModelWithProjection(text_encoder_config)
        tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
        components = {
            "transformer": transformer,
            "scheduler": scheduler,
            "vqvae": vqvae,
            "text_encoder": text_encoder,
            "tokenizer": tokenizer,
        }
        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)
        image = torch.full((1, 3, 4, 4), 1.0, dtype=torch.float32, device=device)
        mask_image = torch.full((1, 1, 4, 4), 1.0, dtype=torch.float32, device=device)
        mask_image[0, 0, 0, 0] = 0
        mask_image[0, 0, 0, 1] = 0
        inputs = {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "output_type": "np",
            "image": image,
            "mask_image": mask_image,
        }
        return inputs

    def test_inference_batch_consistent(self, batch_sizes=[2]):
        self._test_inference_batch_consistent(batch_sizes=batch_sizes, batch_generator=False)

    @unittest.skip("aMUSEd does not support lists of generators")
134
    def test_inference_batch_single_identical(self): ...
Will Berman's avatar
Will Berman committed
135
136
137


@slow
138
@require_torch_accelerator
Will Berman's avatar
Will Berman committed
139
140
class AmusedInpaintPipelineSlowTests(unittest.TestCase):
    def test_amused_256(self):
141
        pipe = AmusedInpaintPipeline.from_pretrained("amused/amused-256")
Will Berman's avatar
Will Berman committed
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
        pipe.to(torch_device)
        image = (
            load_image("https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg")
            .resize((256, 256))
            .convert("RGB")
        )
        mask_image = (
            load_image(
                "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
            )
            .resize((256, 256))
            .convert("L")
        )
        image = pipe(
            "winter mountains",
            image,
            mask_image,
            generator=torch.Generator().manual_seed(0),
            num_inference_steps=2,
            output_type="np",
        ).images
        image_slice = image[0, -3:, -3:, -1].flatten()
        assert image.shape == (1, 256, 256, 3)
        expected_slice = np.array([0.0699, 0.0716, 0.0608, 0.0715, 0.0797, 0.0638, 0.0802, 0.0924, 0.0634])
        assert np.abs(image_slice - expected_slice).max() < 0.1

    def test_amused_256_fp16(self):
169
        pipe = AmusedInpaintPipeline.from_pretrained("amused/amused-256", variant="fp16", torch_dtype=torch.float16)
Will Berman's avatar
Will Berman committed
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
        pipe.to(torch_device)
        image = (
            load_image("https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg")
            .resize((256, 256))
            .convert("RGB")
        )
        mask_image = (
            load_image(
                "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
            )
            .resize((256, 256))
            .convert("L")
        )
        image = pipe(
            "winter mountains",
            image,
            mask_image,
            generator=torch.Generator().manual_seed(0),
            num_inference_steps=2,
            output_type="np",
        ).images
        image_slice = image[0, -3:, -3:, -1].flatten()
        assert image.shape == (1, 256, 256, 3)
Dhruv Nair's avatar
Dhruv Nair committed
193
        expected_slice = np.array([0.0735, 0.0749, 0.065, 0.0739, 0.0805, 0.0667, 0.0802, 0.0923, 0.0622])
Will Berman's avatar
Will Berman committed
194
195
196
        assert np.abs(image_slice - expected_slice).max() < 0.1

    def test_amused_512(self):
197
        pipe = AmusedInpaintPipeline.from_pretrained("amused/amused-512")
Will Berman's avatar
Will Berman committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
        pipe.to(torch_device)
        image = (
            load_image("https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg")
            .resize((512, 512))
            .convert("RGB")
        )
        mask_image = (
            load_image(
                "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
            )
            .resize((512, 512))
            .convert("L")
        )
        image = pipe(
            "winter mountains",
            image,
            mask_image,
            generator=torch.Generator().manual_seed(0),
            num_inference_steps=2,
            output_type="np",
        ).images
        image_slice = image[0, -3:, -3:, -1].flatten()
        assert image.shape == (1, 512, 512, 3)
        expected_slice = np.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0005, 0.0])
        assert np.abs(image_slice - expected_slice).max() < 0.05

    def test_amused_512_fp16(self):
225
        pipe = AmusedInpaintPipeline.from_pretrained("amused/amused-512", variant="fp16", torch_dtype=torch.float16)
Will Berman's avatar
Will Berman committed
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
        pipe.to(torch_device)
        image = (
            load_image("https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1.jpg")
            .resize((512, 512))
            .convert("RGB")
        )
        mask_image = (
            load_image(
                "https://huggingface.co/datasets/diffusers/docs-images/resolve/main/open_muse/mountains_1_mask.png"
            )
            .resize((512, 512))
            .convert("L")
        )
        image = pipe(
            "winter mountains",
            image,
            mask_image,
            generator=torch.Generator().manual_seed(0),
            num_inference_steps=2,
            output_type="np",
        ).images
        image_slice = image[0, -3:, -3:, -1].flatten()

        assert image.shape == (1, 512, 512, 3)
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
        expected_slices = Expectations(
            {
                ("xpu", 3): np.array(
                    [
                        0.0274,
                        0.0211,
                        0.0154,
                        0.0257,
                        0.0299,
                        0.0170,
                        0.0326,
                        0.0420,
                        0.0150,
                    ]
                ),
                ("cuda", 7): np.array(
                    [
                        0.0227,
                        0.0157,
                        0.0098,
                        0.0213,
                        0.0250,
                        0.0127,
                        0.0280,
                        0.0380,
                        0.0095,
                    ]
                ),
            }
        )
        expected_slice = expected_slices.get_expectation()
Dhruv Nair's avatar
Dhruv Nair committed
281
        assert np.abs(image_slice - expected_slice).max() < 0.003