test_controlnet_flux.py 9.08 KB
Newer Older
王奇勋's avatar
王奇勋 committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# coding=utf-8
# Copyright 2024 HuggingFace Inc and The InstantX Team.
#
# 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
20
import pytest
王奇勋's avatar
王奇勋 committed
21
import torch
22
from huggingface_hub import hf_hub_download
王奇勋's avatar
王奇勋 committed
23
24
25
26
27
28
29
30
31
32
33
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast

from diffusers import (
    AutoencoderKL,
    FlowMatchEulerDiscreteScheduler,
    FluxControlNetPipeline,
    FluxTransformer2DModel,
)
from diffusers.models import FluxControlNetModel
from diffusers.utils import load_image
from diffusers.utils.testing_utils import (
34
    backend_empty_cache,
王奇勋's avatar
王奇勋 committed
35
    enable_full_determinism,
36
    nightly,
37
38
    numpy_cosine_similarity_distance,
    require_big_gpu_with_torch_cuda,
王奇勋's avatar
王奇勋 committed
39
40
41
42
    torch_device,
)
from diffusers.utils.torch_utils import randn_tensor

43
from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin
王奇勋's avatar
王奇勋 committed
44
45
46
47
48


enable_full_determinism()


49
class FluxControlNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin, FluxIPAdapterTesterMixin):
王奇勋's avatar
王奇勋 committed
50
51
52
53
    pipeline_class = FluxControlNetPipeline

    params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
    batch_params = frozenset(["prompt"])
Aryan's avatar
Aryan committed
54
    test_layerwise_casting = True
Aryan's avatar
Aryan committed
55
    test_group_offloading = True
王奇勋's avatar
王奇勋 committed
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
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

    def get_dummy_components(self):
        torch.manual_seed(0)
        transformer = FluxTransformer2DModel(
            patch_size=1,
            in_channels=16,
            num_layers=1,
            num_single_layers=1,
            attention_head_dim=16,
            num_attention_heads=2,
            joint_attention_dim=32,
            pooled_projection_dim=32,
            axes_dims_rope=[4, 4, 8],
        )

        torch.manual_seed(0)
        controlnet = FluxControlNetModel(
            patch_size=1,
            in_channels=16,
            num_layers=1,
            num_single_layers=1,
            attention_head_dim=16,
            num_attention_heads=2,
            joint_attention_dim=32,
            pooled_projection_dim=32,
            axes_dims_rope=[4, 4, 8],
        )

        clip_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,
            hidden_act="gelu",
            projection_dim=32,
        )
        torch.manual_seed(0)
        text_encoder = CLIPTextModel(clip_text_encoder_config)

        torch.manual_seed(0)
        text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")

        tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
        tokenizer_2 = T5TokenizerFast.from_pretrained("hf-internal-testing/tiny-random-t5")

        torch.manual_seed(0)
        vae = AutoencoderKL(
            sample_size=32,
            in_channels=3,
            out_channels=3,
            block_out_channels=(4,),
            layers_per_block=1,
            latent_channels=4,
            norm_num_groups=1,
            use_quant_conv=False,
            use_post_quant_conv=False,
            shift_factor=0.0609,
            scaling_factor=1.5035,
        )

        scheduler = FlowMatchEulerDiscreteScheduler()

        return {
            "scheduler": scheduler,
            "text_encoder": text_encoder,
            "text_encoder_2": text_encoder_2,
            "tokenizer": tokenizer,
            "tokenizer_2": tokenizer_2,
            "transformer": transformer,
            "vae": vae,
            "controlnet": controlnet,
132
133
            "image_encoder": None,
            "feature_extractor": None,
王奇勋's avatar
王奇勋 committed
134
135
136
137
138
139
140
141
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
169
170
171
172
173
174
175
176
177
        }

    def get_dummy_inputs(self, device, seed=0):
        if str(device).startswith("mps"):
            generator = torch.manual_seed(seed)
        else:
            generator = torch.Generator(device="cpu").manual_seed(seed)

        control_image = randn_tensor(
            (1, 3, 32, 32),
            generator=generator,
            device=torch.device(device),
            dtype=torch.float16,
        )

        controlnet_conditioning_scale = 0.5

        inputs = {
            "prompt": "A painting of a squirrel eating a burger",
            "generator": generator,
            "num_inference_steps": 2,
            "guidance_scale": 3.5,
            "output_type": "np",
            "control_image": control_image,
            "controlnet_conditioning_scale": controlnet_conditioning_scale,
        }

        return inputs

    def test_controlnet_flux(self):
        components = self.get_dummy_components()
        flux_pipe = FluxControlNetPipeline(**components)
        flux_pipe = flux_pipe.to(torch_device, dtype=torch.float16)
        flux_pipe.set_progress_bar_config(disable=None)

        inputs = self.get_dummy_inputs(torch_device)
        output = flux_pipe(**inputs)
        image = output.images

        image_slice = image[0, -3:, -3:, -1]

        assert image.shape == (1, 32, 32, 3)

        expected_slice = np.array(
178
            [0.47387695, 0.63134766, 0.5605469, 0.61621094, 0.7207031, 0.7089844, 0.70410156, 0.6113281, 0.64160156]
王奇勋's avatar
王奇勋 committed
179
180
        )

181
182
183
        assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
            f"Expected: {expected_slice}, got: {image_slice.flatten()}"
        )
王奇勋's avatar
王奇勋 committed
184
185
186
187
188

    @unittest.skip("xFormersAttnProcessor does not work with SD3 Joint Attention")
    def test_xformers_attention_forwardGenerator_pass(self):
        pass

Dhruv Nair's avatar
Dhruv Nair committed
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
    def test_flux_image_output_shape(self):
        pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
        inputs = self.get_dummy_inputs(torch_device)

        height_width_pairs = [(32, 32), (72, 56)]
        for height, width in height_width_pairs:
            expected_height = height - height % (pipe.vae_scale_factor * 2)
            expected_width = width - width % (pipe.vae_scale_factor * 2)

            inputs.update(
                {
                    "control_image": randn_tensor(
                        (1, 3, height, width),
                        device=torch_device,
                        dtype=torch.float16,
                    )
                }
            )
            image = pipe(**inputs).images[0]
            output_height, output_width, _ = image.shape
            assert (output_height, output_width) == (expected_height, expected_width)

王奇勋's avatar
王奇勋 committed
211

212
@nightly
213
214
@require_big_gpu_with_torch_cuda
@pytest.mark.big_gpu_with_torch_cuda
王奇勋's avatar
王奇勋 committed
215
216
217
218
219
220
class FluxControlNetPipelineSlowTests(unittest.TestCase):
    pipeline_class = FluxControlNetPipeline

    def setUp(self):
        super().setUp()
        gc.collect()
221
        backend_empty_cache(torch_device)
王奇勋's avatar
王奇勋 committed
222
223
224
225

    def tearDown(self):
        super().tearDown()
        gc.collect()
226
        backend_empty_cache(torch_device)
王奇勋's avatar
王奇勋 committed
227
228
229
230
231
232

    def test_canny(self):
        controlnet = FluxControlNetModel.from_pretrained(
            "InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16
        )
        pipe = FluxControlNetPipeline.from_pretrained(
233
234
235
236
237
            "black-forest-labs/FLUX.1-dev",
            text_encoder=None,
            text_encoder_2=None,
            controlnet=controlnet,
            torch_dtype=torch.bfloat16,
238
        ).to(torch_device)
王奇勋's avatar
王奇勋 committed
239
240
241
242
243
        pipe.set_progress_bar_config(disable=None)

        generator = torch.Generator(device="cpu").manual_seed(0)
        control_image = load_image(
            "https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
244
245
246
247
        ).resize((512, 512))

        prompt_embeds = torch.load(
            hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
248
        ).to(torch_device)
249
250
251
252
        pooled_prompt_embeds = torch.load(
            hf_hub_download(
                repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
            )
253
        ).to(torch_device)
王奇勋's avatar
王奇勋 committed
254
255

        output = pipe(
256
257
            prompt_embeds=prompt_embeds,
            pooled_prompt_embeds=pooled_prompt_embeds,
王奇勋's avatar
王奇勋 committed
258
259
260
261
            control_image=control_image,
            controlnet_conditioning_scale=0.6,
            num_inference_steps=2,
            guidance_scale=3.5,
262
            max_sequence_length=256,
王奇勋's avatar
王奇勋 committed
263
            output_type="np",
264
265
            height=512,
            width=512,
王奇勋's avatar
王奇勋 committed
266
267
268
269
270
            generator=generator,
        )

        image = output.images[0]

271
        assert image.shape == (512, 512, 3)
王奇勋's avatar
王奇勋 committed
272
273
274

        original_image = image[-3:, -3:, -1].flatten()

275
        expected_image = np.array([0.2734, 0.2852, 0.2852, 0.2734, 0.2754, 0.2891, 0.2617, 0.2637, 0.2773])
王奇勋's avatar
王奇勋 committed
276

277
        assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2