test_if_inpainting.py 5.5 KB
Newer Older
Patrick von Platen's avatar
Patrick von Platen committed
1
# coding=utf-8
2
# Copyright 2024 HuggingFace Inc.
Patrick von Platen's avatar
Patrick von Platen committed
3
4
5
6
7
8
9
10
11
12
13
14
15
#
# 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.

16
import gc
Patrick von Platen's avatar
Patrick von Platen committed
17
18
19
20
21
22
import random
import unittest

import torch

from diffusers import IFInpaintingPipeline
23
from diffusers.models.attention_processor import AttnAddedKVProcessor
24
from diffusers.utils.import_utils import is_xformers_available
25
from diffusers.utils.testing_utils import (
26
27
28
29
    backend_empty_cache,
    backend_max_memory_allocated,
    backend_reset_max_memory_allocated,
    backend_reset_peak_memory_stats,
30
31
32
    floats_tensor,
    load_numpy,
    require_accelerator,
Marc Sun's avatar
Marc Sun committed
33
    require_hf_hub_version_greater,
34
    require_torch_accelerator,
Marc Sun's avatar
Marc Sun committed
35
    require_transformers_version_greater,
36
37
38
39
    skip_mps,
    slow,
    torch_device,
)
Patrick von Platen's avatar
Patrick von Platen committed
40
41
42
43
44

from ..pipeline_params import (
    TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
    TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
)
45
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
Patrick von Platen's avatar
Patrick von Platen committed
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
from . import IFPipelineTesterMixin


@skip_mps
class IFInpaintingPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
    pipeline_class = IFInpaintingPipeline
    params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"}
    batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
    required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}

    def get_dummy_components(self):
        return self._get_dummy_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 = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
        mask_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)

        inputs = {
            "prompt": "A painting of a squirrel eating a burger",
            "image": image,
            "mask_image": mask_image,
            "generator": generator,
            "num_inference_steps": 2,
74
            "output_type": "np",
Patrick von Platen's avatar
Patrick von Platen committed
75
76
77
78
        }

        return inputs

79
80
81
82
83
84
85
    @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)

Patrick von Platen's avatar
Patrick von Platen committed
86
87
88
    def test_save_load_optional_components(self):
        self._test_save_load_optional_components()

89
90
    @unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
    @require_accelerator
Patrick von Platen's avatar
Patrick von Platen committed
91
92
    def test_save_load_float16(self):
        # Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
93
        super().test_save_load_float16(expected_max_diff=1e-1)
Patrick von Platen's avatar
Patrick von Platen committed
94
95
96
97
98
99
100
101
102
103
104

    def test_attention_slicing_forward_pass(self):
        self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)

    def test_save_load_local(self):
        self._test_save_load_local()

    def test_inference_batch_single_identical(self):
        self._test_inference_batch_single_identical(
            expected_max_diff=1e-2,
        )
105

Marc Sun's avatar
Marc Sun committed
106
107
108
109
110
    @require_hf_hub_version_greater("0.26.5")
    @require_transformers_version_greater("4.47.1")
    def test_save_load_dduf(self):
        super().test_save_load_dduf(atol=1e-2, rtol=1e-2)

111
112

@slow
113
@require_torch_accelerator
114
class IFInpaintingPipelineSlowTests(unittest.TestCase):
115
116
117
118
    def setUp(self):
        # clean up the VRAM before each test
        super().setUp()
        gc.collect()
119
        backend_empty_cache(torch_device)
120

121
122
123
124
    def tearDown(self):
        # clean up the VRAM after each test
        super().tearDown()
        gc.collect()
125
        backend_empty_cache(torch_device)
126
127
128
129
130
131

    def test_if_inpainting(self):
        pipe = IFInpaintingPipeline.from_pretrained(
            "DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
        )
        pipe.unet.set_attn_processor(AttnAddedKVProcessor())
132
        pipe.enable_model_cpu_offload(device=torch_device)
133

134
135
136
        backend_empty_cache(torch_device)
        backend_reset_max_memory_allocated(torch_device)
        backend_reset_peak_memory_stats(torch_device)
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151

        image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
        mask_image = floats_tensor((1, 3, 64, 64), rng=random.Random(1)).to(torch_device)

        generator = torch.Generator(device="cpu").manual_seed(0)
        output = pipe(
            prompt="anime prompts",
            image=image,
            mask_image=mask_image,
            num_inference_steps=2,
            generator=generator,
            output_type="np",
        )
        image = output.images[0]

152
        mem_bytes = backend_max_memory_allocated(torch_device)
153
154
155
156
157
158
159
        assert mem_bytes < 12 * 10**9

        expected_image = load_numpy(
            "https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"
        )
        assert_mean_pixel_difference(image, expected_image)
        pipe.remove_all_hooks()