Stage Harbor release files 67001-67500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cogview4/test_cogview4.py +234 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consisid/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consisid/test_consisid.py +362 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consistency_models/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consistency_models/test_consistency_models.py +309 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet.py +1081 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_blip_diffusion.py +228 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_img2img.py +459 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_inpaint.py +575 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_inpaint_sdxl.py +356 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_sdxl.py +1082 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_sdxl_img2img.py +329 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_flax_controlnet.py +127 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux.py +277 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux_img2img.py +225 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux_inpaint.py +226 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_hunyuandit/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_hunyuandit/test_controlnet_hunyuandit.py +364 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/test_controlnet_inpaint_sd3.py +203 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/test_controlnet_sd3.py +367 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_xs/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_xs/test_controlnetxs.py +352 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_xs/test_controlnetxs_sdxl.py +393 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/cosmos_guardrail.py +47 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos.py +350 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos2_text2image.py +337 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos2_video2world.py +351 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos_video2world.py +363 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dance_diffusion/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dance_diffusion/test_dance_diffusion.py +174 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddim/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddim/test_ddim.py +142 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddpm/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddpm/test_ddpm.py +110 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/__init__.py +272 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if.py +146 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img.py +163 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img_superresolution.py +168 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting.py +160 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting_superresolution.py +170 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_superresolution.py +157 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dit/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dit/test_dit.py +166 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/easyanimate/__init__.py +0 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/easyanimate/test_easyanimate.py +295 -0
- tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/flux/__init__.py +0 -0
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cogview4/test_cogview4.py
ADDED
|
@@ -0,0 +1,234 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import AutoTokenizer, GlmConfig, GlmForCausalLM
|
| 21 |
+
|
| 22 |
+
from diffusers import AutoencoderKL, CogView4Pipeline, CogView4Transformer2DModel, FlowMatchEulerDiscreteScheduler
|
| 23 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 24 |
+
|
| 25 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 26 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
enable_full_determinism()
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class CogView4PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 33 |
+
pipeline_class = CogView4Pipeline
|
| 34 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 35 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 36 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 37 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 38 |
+
required_optional_params = frozenset(
|
| 39 |
+
[
|
| 40 |
+
"num_inference_steps",
|
| 41 |
+
"generator",
|
| 42 |
+
"latents",
|
| 43 |
+
"return_dict",
|
| 44 |
+
"callback_on_step_end",
|
| 45 |
+
"callback_on_step_end_tensor_inputs",
|
| 46 |
+
]
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
supports_dduf = False
|
| 50 |
+
test_xformers_attention = False
|
| 51 |
+
test_layerwise_casting = True
|
| 52 |
+
|
| 53 |
+
def get_dummy_components(self):
|
| 54 |
+
torch.manual_seed(0)
|
| 55 |
+
transformer = CogView4Transformer2DModel(
|
| 56 |
+
patch_size=2,
|
| 57 |
+
in_channels=4,
|
| 58 |
+
num_layers=2,
|
| 59 |
+
attention_head_dim=4,
|
| 60 |
+
num_attention_heads=4,
|
| 61 |
+
out_channels=4,
|
| 62 |
+
text_embed_dim=32,
|
| 63 |
+
time_embed_dim=8,
|
| 64 |
+
condition_dim=4,
|
| 65 |
+
)
|
| 66 |
+
|
| 67 |
+
torch.manual_seed(0)
|
| 68 |
+
vae = AutoencoderKL(
|
| 69 |
+
block_out_channels=[32, 64],
|
| 70 |
+
in_channels=3,
|
| 71 |
+
out_channels=3,
|
| 72 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 73 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 74 |
+
latent_channels=4,
|
| 75 |
+
sample_size=128,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
scheduler = FlowMatchEulerDiscreteScheduler(
|
| 80 |
+
base_shift=0.25,
|
| 81 |
+
max_shift=0.75,
|
| 82 |
+
base_image_seq_len=256,
|
| 83 |
+
use_dynamic_shifting=True,
|
| 84 |
+
time_shift_type="linear",
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
text_encoder_config = GlmConfig(
|
| 89 |
+
hidden_size=32, intermediate_size=8, num_hidden_layers=2, num_attention_heads=4, head_dim=8
|
| 90 |
+
)
|
| 91 |
+
text_encoder = GlmForCausalLM(text_encoder_config)
|
| 92 |
+
# TODO(aryan): change this to THUDM/CogView4 once released
|
| 93 |
+
tokenizer = AutoTokenizer.from_pretrained("THUDM/glm-4-9b-chat", trust_remote_code=True)
|
| 94 |
+
|
| 95 |
+
components = {
|
| 96 |
+
"transformer": transformer,
|
| 97 |
+
"vae": vae,
|
| 98 |
+
"scheduler": scheduler,
|
| 99 |
+
"text_encoder": text_encoder,
|
| 100 |
+
"tokenizer": tokenizer,
|
| 101 |
+
}
|
| 102 |
+
return components
|
| 103 |
+
|
| 104 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 105 |
+
if str(device).startswith("mps"):
|
| 106 |
+
generator = torch.manual_seed(seed)
|
| 107 |
+
else:
|
| 108 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 109 |
+
inputs = {
|
| 110 |
+
"prompt": "dance monkey",
|
| 111 |
+
"negative_prompt": "",
|
| 112 |
+
"generator": generator,
|
| 113 |
+
"num_inference_steps": 2,
|
| 114 |
+
"guidance_scale": 6.0,
|
| 115 |
+
"height": 16,
|
| 116 |
+
"width": 16,
|
| 117 |
+
"max_sequence_length": 16,
|
| 118 |
+
"output_type": "pt",
|
| 119 |
+
}
|
| 120 |
+
return inputs
|
| 121 |
+
|
| 122 |
+
def test_inference(self):
|
| 123 |
+
device = "cpu"
|
| 124 |
+
|
| 125 |
+
components = self.get_dummy_components()
|
| 126 |
+
pipe = self.pipeline_class(**components)
|
| 127 |
+
pipe.to(device)
|
| 128 |
+
pipe.set_progress_bar_config(disable=None)
|
| 129 |
+
|
| 130 |
+
inputs = self.get_dummy_inputs(device)
|
| 131 |
+
image = pipe(**inputs)[0]
|
| 132 |
+
generated_image = image[0]
|
| 133 |
+
|
| 134 |
+
self.assertEqual(generated_image.shape, (3, 16, 16))
|
| 135 |
+
expected_image = torch.randn(3, 16, 16)
|
| 136 |
+
max_diff = np.abs(generated_image - expected_image).max()
|
| 137 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 138 |
+
|
| 139 |
+
def test_callback_inputs(self):
|
| 140 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 141 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 142 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 143 |
+
|
| 144 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 145 |
+
return
|
| 146 |
+
|
| 147 |
+
components = self.get_dummy_components()
|
| 148 |
+
pipe = self.pipeline_class(**components)
|
| 149 |
+
pipe = pipe.to(torch_device)
|
| 150 |
+
pipe.set_progress_bar_config(disable=None)
|
| 151 |
+
self.assertTrue(
|
| 152 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 153 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 157 |
+
# iterate over callback args
|
| 158 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 159 |
+
# check that we're only passing in allowed tensor inputs
|
| 160 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 161 |
+
|
| 162 |
+
return callback_kwargs
|
| 163 |
+
|
| 164 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 165 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 166 |
+
assert tensor_name in callback_kwargs
|
| 167 |
+
|
| 168 |
+
# iterate over callback args
|
| 169 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 170 |
+
# check that we're only passing in allowed tensor inputs
|
| 171 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 172 |
+
|
| 173 |
+
return callback_kwargs
|
| 174 |
+
|
| 175 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 176 |
+
|
| 177 |
+
# Test passing in a subset
|
| 178 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 179 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 180 |
+
output = pipe(**inputs)[0]
|
| 181 |
+
|
| 182 |
+
# Test passing in a everything
|
| 183 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 184 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 185 |
+
output = pipe(**inputs)[0]
|
| 186 |
+
|
| 187 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 188 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 189 |
+
if is_last:
|
| 190 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 191 |
+
return callback_kwargs
|
| 192 |
+
|
| 193 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 194 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 195 |
+
output = pipe(**inputs)[0]
|
| 196 |
+
assert output.abs().sum() < 1e10
|
| 197 |
+
|
| 198 |
+
def test_inference_batch_single_identical(self):
|
| 199 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
|
| 200 |
+
|
| 201 |
+
def test_attention_slicing_forward_pass(
|
| 202 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 203 |
+
):
|
| 204 |
+
if not self.test_attention_slicing:
|
| 205 |
+
return
|
| 206 |
+
|
| 207 |
+
components = self.get_dummy_components()
|
| 208 |
+
pipe = self.pipeline_class(**components)
|
| 209 |
+
for component in pipe.components.values():
|
| 210 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 211 |
+
component.set_default_attn_processor()
|
| 212 |
+
pipe.to(torch_device)
|
| 213 |
+
pipe.set_progress_bar_config(disable=None)
|
| 214 |
+
|
| 215 |
+
generator_device = "cpu"
|
| 216 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 217 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 218 |
+
|
| 219 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 220 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 221 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 222 |
+
|
| 223 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 224 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 225 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 226 |
+
|
| 227 |
+
if test_max_difference:
|
| 228 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 229 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 230 |
+
self.assertLess(
|
| 231 |
+
max(max_diff1, max_diff2),
|
| 232 |
+
expected_max_diff,
|
| 233 |
+
"Attention slicing should not affect the inference results",
|
| 234 |
+
)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consisid/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consisid/test_consisid.py
ADDED
|
@@ -0,0 +1,362 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import inspect
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from PIL import Image
|
| 22 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 23 |
+
|
| 24 |
+
from diffusers import AutoencoderKLCogVideoX, ConsisIDPipeline, ConsisIDTransformer3DModel, DDIMScheduler
|
| 25 |
+
from diffusers.utils import load_image
|
| 26 |
+
from diffusers.utils.testing_utils import (
|
| 27 |
+
backend_empty_cache,
|
| 28 |
+
enable_full_determinism,
|
| 29 |
+
numpy_cosine_similarity_distance,
|
| 30 |
+
require_torch_accelerator,
|
| 31 |
+
slow,
|
| 32 |
+
torch_device,
|
| 33 |
+
)
|
| 34 |
+
|
| 35 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 36 |
+
from ..test_pipelines_common import (
|
| 37 |
+
PipelineTesterMixin,
|
| 38 |
+
to_np,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
enable_full_determinism()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class ConsisIDPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 46 |
+
pipeline_class = ConsisIDPipeline
|
| 47 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 48 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image"})
|
| 49 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 50 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 51 |
+
required_optional_params = frozenset(
|
| 52 |
+
[
|
| 53 |
+
"num_inference_steps",
|
| 54 |
+
"generator",
|
| 55 |
+
"latents",
|
| 56 |
+
"return_dict",
|
| 57 |
+
"callback_on_step_end",
|
| 58 |
+
"callback_on_step_end_tensor_inputs",
|
| 59 |
+
]
|
| 60 |
+
)
|
| 61 |
+
test_xformers_attention = False
|
| 62 |
+
test_layerwise_casting = True
|
| 63 |
+
test_group_offloading = True
|
| 64 |
+
|
| 65 |
+
def get_dummy_components(self):
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
transformer = ConsisIDTransformer3DModel(
|
| 68 |
+
num_attention_heads=2,
|
| 69 |
+
attention_head_dim=16,
|
| 70 |
+
in_channels=8,
|
| 71 |
+
out_channels=4,
|
| 72 |
+
time_embed_dim=2,
|
| 73 |
+
text_embed_dim=32,
|
| 74 |
+
num_layers=1,
|
| 75 |
+
sample_width=2,
|
| 76 |
+
sample_height=2,
|
| 77 |
+
sample_frames=9,
|
| 78 |
+
patch_size=2,
|
| 79 |
+
temporal_compression_ratio=4,
|
| 80 |
+
max_text_seq_length=16,
|
| 81 |
+
use_rotary_positional_embeddings=True,
|
| 82 |
+
use_learned_positional_embeddings=True,
|
| 83 |
+
cross_attn_interval=1,
|
| 84 |
+
is_kps=False,
|
| 85 |
+
is_train_face=True,
|
| 86 |
+
cross_attn_dim_head=1,
|
| 87 |
+
cross_attn_num_heads=1,
|
| 88 |
+
LFE_id_dim=2,
|
| 89 |
+
LFE_vit_dim=2,
|
| 90 |
+
LFE_depth=5,
|
| 91 |
+
LFE_dim_head=8,
|
| 92 |
+
LFE_num_heads=2,
|
| 93 |
+
LFE_num_id_token=1,
|
| 94 |
+
LFE_num_querie=1,
|
| 95 |
+
LFE_output_dim=21,
|
| 96 |
+
LFE_ff_mult=1,
|
| 97 |
+
LFE_num_scale=1,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
torch.manual_seed(0)
|
| 101 |
+
vae = AutoencoderKLCogVideoX(
|
| 102 |
+
in_channels=3,
|
| 103 |
+
out_channels=3,
|
| 104 |
+
down_block_types=(
|
| 105 |
+
"CogVideoXDownBlock3D",
|
| 106 |
+
"CogVideoXDownBlock3D",
|
| 107 |
+
"CogVideoXDownBlock3D",
|
| 108 |
+
"CogVideoXDownBlock3D",
|
| 109 |
+
),
|
| 110 |
+
up_block_types=(
|
| 111 |
+
"CogVideoXUpBlock3D",
|
| 112 |
+
"CogVideoXUpBlock3D",
|
| 113 |
+
"CogVideoXUpBlock3D",
|
| 114 |
+
"CogVideoXUpBlock3D",
|
| 115 |
+
),
|
| 116 |
+
block_out_channels=(8, 8, 8, 8),
|
| 117 |
+
latent_channels=4,
|
| 118 |
+
layers_per_block=1,
|
| 119 |
+
norm_num_groups=2,
|
| 120 |
+
temporal_compression_ratio=4,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
torch.manual_seed(0)
|
| 124 |
+
scheduler = DDIMScheduler()
|
| 125 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 126 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 127 |
+
|
| 128 |
+
components = {
|
| 129 |
+
"transformer": transformer,
|
| 130 |
+
"vae": vae,
|
| 131 |
+
"scheduler": scheduler,
|
| 132 |
+
"text_encoder": text_encoder,
|
| 133 |
+
"tokenizer": tokenizer,
|
| 134 |
+
}
|
| 135 |
+
return components
|
| 136 |
+
|
| 137 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 138 |
+
if str(device).startswith("mps"):
|
| 139 |
+
generator = torch.manual_seed(seed)
|
| 140 |
+
else:
|
| 141 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 142 |
+
|
| 143 |
+
image_height = 16
|
| 144 |
+
image_width = 16
|
| 145 |
+
image = Image.new("RGB", (image_width, image_height))
|
| 146 |
+
id_vit_hidden = [torch.ones([1, 2, 2])] * 1
|
| 147 |
+
id_cond = torch.ones(1, 2)
|
| 148 |
+
inputs = {
|
| 149 |
+
"image": image,
|
| 150 |
+
"prompt": "dance monkey",
|
| 151 |
+
"negative_prompt": "",
|
| 152 |
+
"generator": generator,
|
| 153 |
+
"num_inference_steps": 2,
|
| 154 |
+
"guidance_scale": 6.0,
|
| 155 |
+
"height": image_height,
|
| 156 |
+
"width": image_width,
|
| 157 |
+
"num_frames": 8,
|
| 158 |
+
"max_sequence_length": 16,
|
| 159 |
+
"id_vit_hidden": id_vit_hidden,
|
| 160 |
+
"id_cond": id_cond,
|
| 161 |
+
"output_type": "pt",
|
| 162 |
+
}
|
| 163 |
+
return inputs
|
| 164 |
+
|
| 165 |
+
def test_inference(self):
|
| 166 |
+
device = "cpu"
|
| 167 |
+
|
| 168 |
+
components = self.get_dummy_components()
|
| 169 |
+
pipe = self.pipeline_class(**components)
|
| 170 |
+
pipe.to(device)
|
| 171 |
+
pipe.set_progress_bar_config(disable=None)
|
| 172 |
+
|
| 173 |
+
inputs = self.get_dummy_inputs(device)
|
| 174 |
+
video = pipe(**inputs).frames
|
| 175 |
+
generated_video = video[0]
|
| 176 |
+
|
| 177 |
+
self.assertEqual(generated_video.shape, (8, 3, 16, 16))
|
| 178 |
+
expected_video = torch.randn(8, 3, 16, 16)
|
| 179 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 180 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 181 |
+
|
| 182 |
+
def test_callback_inputs(self):
|
| 183 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 184 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 185 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 186 |
+
|
| 187 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
components = self.get_dummy_components()
|
| 191 |
+
pipe = self.pipeline_class(**components)
|
| 192 |
+
pipe = pipe.to(torch_device)
|
| 193 |
+
pipe.set_progress_bar_config(disable=None)
|
| 194 |
+
self.assertTrue(
|
| 195 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 196 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 200 |
+
# iterate over callback args
|
| 201 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 202 |
+
# check that we're only passing in allowed tensor inputs
|
| 203 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 204 |
+
|
| 205 |
+
return callback_kwargs
|
| 206 |
+
|
| 207 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 208 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 209 |
+
assert tensor_name in callback_kwargs
|
| 210 |
+
|
| 211 |
+
# iterate over callback args
|
| 212 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 213 |
+
# check that we're only passing in allowed tensor inputs
|
| 214 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 215 |
+
|
| 216 |
+
return callback_kwargs
|
| 217 |
+
|
| 218 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 219 |
+
|
| 220 |
+
# Test passing in a subset
|
| 221 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 222 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 223 |
+
output = pipe(**inputs)[0]
|
| 224 |
+
|
| 225 |
+
# Test passing in a everything
|
| 226 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 227 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 228 |
+
output = pipe(**inputs)[0]
|
| 229 |
+
|
| 230 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 231 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 232 |
+
if is_last:
|
| 233 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 234 |
+
return callback_kwargs
|
| 235 |
+
|
| 236 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 237 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 238 |
+
output = pipe(**inputs)[0]
|
| 239 |
+
assert output.abs().sum() < 1e10
|
| 240 |
+
|
| 241 |
+
def test_inference_batch_single_identical(self):
|
| 242 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
|
| 243 |
+
|
| 244 |
+
def test_attention_slicing_forward_pass(
|
| 245 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 246 |
+
):
|
| 247 |
+
if not self.test_attention_slicing:
|
| 248 |
+
return
|
| 249 |
+
|
| 250 |
+
components = self.get_dummy_components()
|
| 251 |
+
pipe = self.pipeline_class(**components)
|
| 252 |
+
for component in pipe.components.values():
|
| 253 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 254 |
+
component.set_default_attn_processor()
|
| 255 |
+
pipe.to(torch_device)
|
| 256 |
+
pipe.set_progress_bar_config(disable=None)
|
| 257 |
+
|
| 258 |
+
generator_device = "cpu"
|
| 259 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 260 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 261 |
+
|
| 262 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 263 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 264 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 265 |
+
|
| 266 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 267 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 268 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 269 |
+
|
| 270 |
+
if test_max_difference:
|
| 271 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 272 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 273 |
+
self.assertLess(
|
| 274 |
+
max(max_diff1, max_diff2),
|
| 275 |
+
expected_max_diff,
|
| 276 |
+
"Attention slicing should not affect the inference results",
|
| 277 |
+
)
|
| 278 |
+
|
| 279 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.4):
|
| 280 |
+
generator_device = "cpu"
|
| 281 |
+
components = self.get_dummy_components()
|
| 282 |
+
|
| 283 |
+
# The reason to modify it this way is because ConsisID Transformer limits the generation to resolutions used during initialization.
|
| 284 |
+
# This limitation comes from using learned positional embeddings which cannot be generated on-the-fly like sincos or RoPE embeddings.
|
| 285 |
+
# See the if-statement on "self.use_learned_positional_embeddings" in diffusers/models/embeddings.py
|
| 286 |
+
components["transformer"] = ConsisIDTransformer3DModel.from_config(
|
| 287 |
+
components["transformer"].config,
|
| 288 |
+
sample_height=16,
|
| 289 |
+
sample_width=16,
|
| 290 |
+
)
|
| 291 |
+
|
| 292 |
+
pipe = self.pipeline_class(**components)
|
| 293 |
+
pipe.to("cpu")
|
| 294 |
+
pipe.set_progress_bar_config(disable=None)
|
| 295 |
+
|
| 296 |
+
# Without tiling
|
| 297 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 298 |
+
inputs["height"] = inputs["width"] = 128
|
| 299 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 300 |
+
|
| 301 |
+
# With tiling
|
| 302 |
+
pipe.vae.enable_tiling(
|
| 303 |
+
tile_sample_min_height=96,
|
| 304 |
+
tile_sample_min_width=96,
|
| 305 |
+
tile_overlap_factor_height=1 / 12,
|
| 306 |
+
tile_overlap_factor_width=1 / 12,
|
| 307 |
+
)
|
| 308 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 309 |
+
inputs["height"] = inputs["width"] = 128
|
| 310 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 311 |
+
|
| 312 |
+
self.assertLess(
|
| 313 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 314 |
+
expected_diff_max,
|
| 315 |
+
"VAE tiling should not affect the inference results",
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
@slow
|
| 320 |
+
@require_torch_accelerator
|
| 321 |
+
class ConsisIDPipelineIntegrationTests(unittest.TestCase):
|
| 322 |
+
prompt = "A painting of a squirrel eating a burger."
|
| 323 |
+
|
| 324 |
+
def setUp(self):
|
| 325 |
+
super().setUp()
|
| 326 |
+
gc.collect()
|
| 327 |
+
backend_empty_cache(torch_device)
|
| 328 |
+
|
| 329 |
+
def tearDown(self):
|
| 330 |
+
super().tearDown()
|
| 331 |
+
gc.collect()
|
| 332 |
+
backend_empty_cache(torch_device)
|
| 333 |
+
|
| 334 |
+
def test_consisid(self):
|
| 335 |
+
generator = torch.Generator("cpu").manual_seed(0)
|
| 336 |
+
|
| 337 |
+
pipe = ConsisIDPipeline.from_pretrained("BestWishYsh/ConsisID-preview", torch_dtype=torch.bfloat16)
|
| 338 |
+
pipe.enable_model_cpu_offload()
|
| 339 |
+
|
| 340 |
+
prompt = self.prompt
|
| 341 |
+
image = load_image("https://github.com/PKU-YuanGroup/ConsisID/blob/main/asserts/example_images/2.png?raw=true")
|
| 342 |
+
id_vit_hidden = [torch.ones([1, 577, 1024])] * 5
|
| 343 |
+
id_cond = torch.ones(1, 1280)
|
| 344 |
+
|
| 345 |
+
videos = pipe(
|
| 346 |
+
image=image,
|
| 347 |
+
prompt=prompt,
|
| 348 |
+
height=480,
|
| 349 |
+
width=720,
|
| 350 |
+
num_frames=16,
|
| 351 |
+
id_vit_hidden=id_vit_hidden,
|
| 352 |
+
id_cond=id_cond,
|
| 353 |
+
generator=generator,
|
| 354 |
+
num_inference_steps=1,
|
| 355 |
+
output_type="pt",
|
| 356 |
+
).frames
|
| 357 |
+
|
| 358 |
+
video = videos[0]
|
| 359 |
+
expected_video = torch.randn(1, 16, 480, 720, 3).numpy()
|
| 360 |
+
|
| 361 |
+
max_diff = numpy_cosine_similarity_distance(video.cpu(), expected_video)
|
| 362 |
+
assert max_diff < 1e-3, f"Max diff is too high. got {video}"
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consistency_models/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/consistency_models/test_consistency_models.py
ADDED
|
@@ -0,0 +1,309 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from torch.backends.cuda import sdp_kernel
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
CMStochasticIterativeScheduler,
|
| 10 |
+
ConsistencyModelPipeline,
|
| 11 |
+
UNet2DModel,
|
| 12 |
+
)
|
| 13 |
+
from diffusers.utils.testing_utils import (
|
| 14 |
+
Expectations,
|
| 15 |
+
backend_empty_cache,
|
| 16 |
+
enable_full_determinism,
|
| 17 |
+
nightly,
|
| 18 |
+
require_torch_2,
|
| 19 |
+
require_torch_accelerator,
|
| 20 |
+
torch_device,
|
| 21 |
+
)
|
| 22 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 23 |
+
|
| 24 |
+
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
|
| 25 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
enable_full_determinism()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class ConsistencyModelPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 32 |
+
pipeline_class = ConsistencyModelPipeline
|
| 33 |
+
params = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
|
| 34 |
+
batch_params = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
|
| 35 |
+
|
| 36 |
+
# Override required_optional_params to remove num_images_per_prompt
|
| 37 |
+
required_optional_params = frozenset(
|
| 38 |
+
[
|
| 39 |
+
"num_inference_steps",
|
| 40 |
+
"generator",
|
| 41 |
+
"latents",
|
| 42 |
+
"output_type",
|
| 43 |
+
"return_dict",
|
| 44 |
+
"callback",
|
| 45 |
+
"callback_steps",
|
| 46 |
+
]
|
| 47 |
+
)
|
| 48 |
+
|
| 49 |
+
@property
|
| 50 |
+
def dummy_uncond_unet(self):
|
| 51 |
+
unet = UNet2DModel.from_pretrained(
|
| 52 |
+
"diffusers/consistency-models-test",
|
| 53 |
+
subfolder="test_unet",
|
| 54 |
+
)
|
| 55 |
+
return unet
|
| 56 |
+
|
| 57 |
+
@property
|
| 58 |
+
def dummy_cond_unet(self):
|
| 59 |
+
unet = UNet2DModel.from_pretrained(
|
| 60 |
+
"diffusers/consistency-models-test",
|
| 61 |
+
subfolder="test_unet_class_cond",
|
| 62 |
+
)
|
| 63 |
+
return unet
|
| 64 |
+
|
| 65 |
+
def get_dummy_components(self, class_cond=False):
|
| 66 |
+
if class_cond:
|
| 67 |
+
unet = self.dummy_cond_unet
|
| 68 |
+
else:
|
| 69 |
+
unet = self.dummy_uncond_unet
|
| 70 |
+
|
| 71 |
+
# Default to CM multistep sampler
|
| 72 |
+
scheduler = CMStochasticIterativeScheduler(
|
| 73 |
+
num_train_timesteps=40,
|
| 74 |
+
sigma_min=0.002,
|
| 75 |
+
sigma_max=80.0,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
components = {
|
| 79 |
+
"unet": unet,
|
| 80 |
+
"scheduler": scheduler,
|
| 81 |
+
}
|
| 82 |
+
|
| 83 |
+
return components
|
| 84 |
+
|
| 85 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 86 |
+
if str(device).startswith("mps"):
|
| 87 |
+
generator = torch.manual_seed(seed)
|
| 88 |
+
else:
|
| 89 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 90 |
+
|
| 91 |
+
inputs = {
|
| 92 |
+
"batch_size": 1,
|
| 93 |
+
"num_inference_steps": None,
|
| 94 |
+
"timesteps": [22, 0],
|
| 95 |
+
"generator": generator,
|
| 96 |
+
"output_type": "np",
|
| 97 |
+
}
|
| 98 |
+
|
| 99 |
+
return inputs
|
| 100 |
+
|
| 101 |
+
def test_consistency_model_pipeline_multistep(self):
|
| 102 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 103 |
+
components = self.get_dummy_components()
|
| 104 |
+
pipe = ConsistencyModelPipeline(**components)
|
| 105 |
+
pipe = pipe.to(device)
|
| 106 |
+
pipe.set_progress_bar_config(disable=None)
|
| 107 |
+
|
| 108 |
+
inputs = self.get_dummy_inputs(device)
|
| 109 |
+
image = pipe(**inputs).images
|
| 110 |
+
assert image.shape == (1, 32, 32, 3)
|
| 111 |
+
|
| 112 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 113 |
+
expected_slice = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004])
|
| 114 |
+
|
| 115 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 116 |
+
|
| 117 |
+
def test_consistency_model_pipeline_multistep_class_cond(self):
|
| 118 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 119 |
+
components = self.get_dummy_components(class_cond=True)
|
| 120 |
+
pipe = ConsistencyModelPipeline(**components)
|
| 121 |
+
pipe = pipe.to(device)
|
| 122 |
+
pipe.set_progress_bar_config(disable=None)
|
| 123 |
+
|
| 124 |
+
inputs = self.get_dummy_inputs(device)
|
| 125 |
+
inputs["class_labels"] = 0
|
| 126 |
+
image = pipe(**inputs).images
|
| 127 |
+
assert image.shape == (1, 32, 32, 3)
|
| 128 |
+
|
| 129 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 130 |
+
expected_slice = np.array([0.3572, 0.6273, 0.4031, 0.3961, 0.4321, 0.5730, 0.5266, 0.4780, 0.5004])
|
| 131 |
+
|
| 132 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 133 |
+
|
| 134 |
+
def test_consistency_model_pipeline_onestep(self):
|
| 135 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 136 |
+
components = self.get_dummy_components()
|
| 137 |
+
pipe = ConsistencyModelPipeline(**components)
|
| 138 |
+
pipe = pipe.to(device)
|
| 139 |
+
pipe.set_progress_bar_config(disable=None)
|
| 140 |
+
|
| 141 |
+
inputs = self.get_dummy_inputs(device)
|
| 142 |
+
inputs["num_inference_steps"] = 1
|
| 143 |
+
inputs["timesteps"] = None
|
| 144 |
+
image = pipe(**inputs).images
|
| 145 |
+
assert image.shape == (1, 32, 32, 3)
|
| 146 |
+
|
| 147 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 148 |
+
expected_slice = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987])
|
| 149 |
+
|
| 150 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 151 |
+
|
| 152 |
+
def test_consistency_model_pipeline_onestep_class_cond(self):
|
| 153 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 154 |
+
components = self.get_dummy_components(class_cond=True)
|
| 155 |
+
pipe = ConsistencyModelPipeline(**components)
|
| 156 |
+
pipe = pipe.to(device)
|
| 157 |
+
pipe.set_progress_bar_config(disable=None)
|
| 158 |
+
|
| 159 |
+
inputs = self.get_dummy_inputs(device)
|
| 160 |
+
inputs["num_inference_steps"] = 1
|
| 161 |
+
inputs["timesteps"] = None
|
| 162 |
+
inputs["class_labels"] = 0
|
| 163 |
+
image = pipe(**inputs).images
|
| 164 |
+
assert image.shape == (1, 32, 32, 3)
|
| 165 |
+
|
| 166 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 167 |
+
expected_slice = np.array([0.5004, 0.5004, 0.4994, 0.5008, 0.4976, 0.5018, 0.4990, 0.4982, 0.4987])
|
| 168 |
+
|
| 169 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 170 |
+
|
| 171 |
+
|
| 172 |
+
@nightly
|
| 173 |
+
@require_torch_accelerator
|
| 174 |
+
class ConsistencyModelPipelineSlowTests(unittest.TestCase):
|
| 175 |
+
def setUp(self):
|
| 176 |
+
super().setUp()
|
| 177 |
+
gc.collect()
|
| 178 |
+
backend_empty_cache(torch_device)
|
| 179 |
+
|
| 180 |
+
def tearDown(self):
|
| 181 |
+
super().tearDown()
|
| 182 |
+
gc.collect()
|
| 183 |
+
backend_empty_cache(torch_device)
|
| 184 |
+
|
| 185 |
+
def get_inputs(self, seed=0, get_fixed_latents=False, device="cpu", dtype=torch.float32, shape=(1, 3, 64, 64)):
|
| 186 |
+
generator = torch.manual_seed(seed)
|
| 187 |
+
|
| 188 |
+
inputs = {
|
| 189 |
+
"num_inference_steps": None,
|
| 190 |
+
"timesteps": [22, 0],
|
| 191 |
+
"class_labels": 0,
|
| 192 |
+
"generator": generator,
|
| 193 |
+
"output_type": "np",
|
| 194 |
+
}
|
| 195 |
+
|
| 196 |
+
if get_fixed_latents:
|
| 197 |
+
latents = self.get_fixed_latents(seed=seed, device=device, dtype=dtype, shape=shape)
|
| 198 |
+
inputs["latents"] = latents
|
| 199 |
+
|
| 200 |
+
return inputs
|
| 201 |
+
|
| 202 |
+
def get_fixed_latents(self, seed=0, device="cpu", dtype=torch.float32, shape=(1, 3, 64, 64)):
|
| 203 |
+
if isinstance(device, str):
|
| 204 |
+
device = torch.device(device)
|
| 205 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 206 |
+
latents = randn_tensor(shape, generator=generator, device=device, dtype=dtype)
|
| 207 |
+
return latents
|
| 208 |
+
|
| 209 |
+
def test_consistency_model_cd_multistep(self):
|
| 210 |
+
unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
|
| 211 |
+
scheduler = CMStochasticIterativeScheduler(
|
| 212 |
+
num_train_timesteps=40,
|
| 213 |
+
sigma_min=0.002,
|
| 214 |
+
sigma_max=80.0,
|
| 215 |
+
)
|
| 216 |
+
pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
|
| 217 |
+
pipe.to(torch_device=torch_device)
|
| 218 |
+
pipe.set_progress_bar_config(disable=None)
|
| 219 |
+
|
| 220 |
+
inputs = self.get_inputs()
|
| 221 |
+
image = pipe(**inputs).images
|
| 222 |
+
assert image.shape == (1, 64, 64, 3)
|
| 223 |
+
|
| 224 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 225 |
+
|
| 226 |
+
expected_slice = np.array([0.0146, 0.0158, 0.0092, 0.0086, 0.0000, 0.0000, 0.0000, 0.0000, 0.0058])
|
| 227 |
+
|
| 228 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 229 |
+
|
| 230 |
+
def test_consistency_model_cd_onestep(self):
|
| 231 |
+
unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
|
| 232 |
+
scheduler = CMStochasticIterativeScheduler(
|
| 233 |
+
num_train_timesteps=40,
|
| 234 |
+
sigma_min=0.002,
|
| 235 |
+
sigma_max=80.0,
|
| 236 |
+
)
|
| 237 |
+
pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
|
| 238 |
+
pipe.to(torch_device=torch_device)
|
| 239 |
+
pipe.set_progress_bar_config(disable=None)
|
| 240 |
+
|
| 241 |
+
inputs = self.get_inputs()
|
| 242 |
+
inputs["num_inference_steps"] = 1
|
| 243 |
+
inputs["timesteps"] = None
|
| 244 |
+
image = pipe(**inputs).images
|
| 245 |
+
assert image.shape == (1, 64, 64, 3)
|
| 246 |
+
|
| 247 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 248 |
+
|
| 249 |
+
expected_slice = np.array([0.0059, 0.0003, 0.0000, 0.0023, 0.0052, 0.0007, 0.0165, 0.0081, 0.0095])
|
| 250 |
+
|
| 251 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 252 |
+
|
| 253 |
+
@require_torch_2
|
| 254 |
+
def test_consistency_model_cd_multistep_flash_attn(self):
|
| 255 |
+
unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
|
| 256 |
+
scheduler = CMStochasticIterativeScheduler(
|
| 257 |
+
num_train_timesteps=40,
|
| 258 |
+
sigma_min=0.002,
|
| 259 |
+
sigma_max=80.0,
|
| 260 |
+
)
|
| 261 |
+
pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
|
| 262 |
+
pipe.to(torch_device=torch_device, torch_dtype=torch.float16)
|
| 263 |
+
pipe.set_progress_bar_config(disable=None)
|
| 264 |
+
|
| 265 |
+
inputs = self.get_inputs(get_fixed_latents=True, device=torch_device)
|
| 266 |
+
# Ensure usage of flash attention in torch 2.0
|
| 267 |
+
with sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
|
| 268 |
+
image = pipe(**inputs).images
|
| 269 |
+
|
| 270 |
+
assert image.shape == (1, 64, 64, 3)
|
| 271 |
+
|
| 272 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 273 |
+
|
| 274 |
+
expected_slices = Expectations(
|
| 275 |
+
{
|
| 276 |
+
("xpu", 3): np.array([0.0816, 0.0518, 0.0445, 0.0594, 0.0739, 0.0534, 0.0805, 0.0457, 0.0765]),
|
| 277 |
+
("cuda", 7): np.array([0.1845, 0.1371, 0.1211, 0.2035, 0.1954, 0.1323, 0.1773, 0.1593, 0.1314]),
|
| 278 |
+
("cuda", 8): np.array([0.0816, 0.0518, 0.0445, 0.0594, 0.0739, 0.0534, 0.0805, 0.0457, 0.0765]),
|
| 279 |
+
}
|
| 280 |
+
)
|
| 281 |
+
expected_slice = expected_slices.get_expectation()
|
| 282 |
+
|
| 283 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
| 284 |
+
|
| 285 |
+
@require_torch_2
|
| 286 |
+
def test_consistency_model_cd_onestep_flash_attn(self):
|
| 287 |
+
unet = UNet2DModel.from_pretrained("diffusers/consistency_models", subfolder="diffusers_cd_imagenet64_l2")
|
| 288 |
+
scheduler = CMStochasticIterativeScheduler(
|
| 289 |
+
num_train_timesteps=40,
|
| 290 |
+
sigma_min=0.002,
|
| 291 |
+
sigma_max=80.0,
|
| 292 |
+
)
|
| 293 |
+
pipe = ConsistencyModelPipeline(unet=unet, scheduler=scheduler)
|
| 294 |
+
pipe.to(torch_device=torch_device, torch_dtype=torch.float16)
|
| 295 |
+
pipe.set_progress_bar_config(disable=None)
|
| 296 |
+
|
| 297 |
+
inputs = self.get_inputs(get_fixed_latents=True, device=torch_device)
|
| 298 |
+
inputs["num_inference_steps"] = 1
|
| 299 |
+
inputs["timesteps"] = None
|
| 300 |
+
# Ensure usage of flash attention in torch 2.0
|
| 301 |
+
with sdp_kernel(enable_flash=True, enable_math=False, enable_mem_efficient=False):
|
| 302 |
+
image = pipe(**inputs).images
|
| 303 |
+
assert image.shape == (1, 64, 64, 3)
|
| 304 |
+
|
| 305 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 306 |
+
|
| 307 |
+
expected_slice = np.array([0.1623, 0.2009, 0.2387, 0.1731, 0.1168, 0.1202, 0.2031, 0.1327, 0.2447])
|
| 308 |
+
|
| 309 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-3
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet.py
ADDED
|
@@ -0,0 +1,1081 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import tempfile
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
|
| 23 |
+
|
| 24 |
+
from diffusers import (
|
| 25 |
+
AutoencoderKL,
|
| 26 |
+
ControlNetModel,
|
| 27 |
+
DDIMScheduler,
|
| 28 |
+
EulerDiscreteScheduler,
|
| 29 |
+
LCMScheduler,
|
| 30 |
+
StableDiffusionControlNetPipeline,
|
| 31 |
+
UNet2DConditionModel,
|
| 32 |
+
)
|
| 33 |
+
from diffusers.pipelines.controlnet.pipeline_controlnet import MultiControlNetModel
|
| 34 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 35 |
+
from diffusers.utils.testing_utils import (
|
| 36 |
+
backend_empty_cache,
|
| 37 |
+
backend_max_memory_allocated,
|
| 38 |
+
backend_reset_max_memory_allocated,
|
| 39 |
+
backend_reset_peak_memory_stats,
|
| 40 |
+
enable_full_determinism,
|
| 41 |
+
load_image,
|
| 42 |
+
load_numpy,
|
| 43 |
+
require_torch_accelerator,
|
| 44 |
+
slow,
|
| 45 |
+
torch_device,
|
| 46 |
+
)
|
| 47 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 48 |
+
|
| 49 |
+
from ..pipeline_params import (
|
| 50 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 51 |
+
TEXT_TO_IMAGE_BATCH_PARAMS,
|
| 52 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 53 |
+
TEXT_TO_IMAGE_PARAMS,
|
| 54 |
+
)
|
| 55 |
+
from ..test_pipelines_common import (
|
| 56 |
+
IPAdapterTesterMixin,
|
| 57 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 58 |
+
PipelineLatentTesterMixin,
|
| 59 |
+
PipelineTesterMixin,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
enable_full_determinism()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class ControlNetPipelineFastTests(
|
| 67 |
+
IPAdapterTesterMixin,
|
| 68 |
+
PipelineLatentTesterMixin,
|
| 69 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 70 |
+
PipelineTesterMixin,
|
| 71 |
+
unittest.TestCase,
|
| 72 |
+
):
|
| 73 |
+
pipeline_class = StableDiffusionControlNetPipeline
|
| 74 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 75 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 76 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 77 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 78 |
+
test_layerwise_casting = True
|
| 79 |
+
test_group_offloading = True
|
| 80 |
+
|
| 81 |
+
def get_dummy_components(self, time_cond_proj_dim=None):
|
| 82 |
+
torch.manual_seed(0)
|
| 83 |
+
unet = UNet2DConditionModel(
|
| 84 |
+
block_out_channels=(4, 8),
|
| 85 |
+
layers_per_block=2,
|
| 86 |
+
sample_size=32,
|
| 87 |
+
in_channels=4,
|
| 88 |
+
out_channels=4,
|
| 89 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 90 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 91 |
+
cross_attention_dim=32,
|
| 92 |
+
norm_num_groups=1,
|
| 93 |
+
time_cond_proj_dim=time_cond_proj_dim,
|
| 94 |
+
)
|
| 95 |
+
torch.manual_seed(0)
|
| 96 |
+
controlnet = ControlNetModel(
|
| 97 |
+
block_out_channels=(4, 8),
|
| 98 |
+
layers_per_block=2,
|
| 99 |
+
in_channels=4,
|
| 100 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 101 |
+
cross_attention_dim=32,
|
| 102 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 103 |
+
norm_num_groups=1,
|
| 104 |
+
)
|
| 105 |
+
torch.manual_seed(0)
|
| 106 |
+
scheduler = DDIMScheduler(
|
| 107 |
+
beta_start=0.00085,
|
| 108 |
+
beta_end=0.012,
|
| 109 |
+
beta_schedule="scaled_linear",
|
| 110 |
+
clip_sample=False,
|
| 111 |
+
set_alpha_to_one=False,
|
| 112 |
+
)
|
| 113 |
+
torch.manual_seed(0)
|
| 114 |
+
vae = AutoencoderKL(
|
| 115 |
+
block_out_channels=[4, 8],
|
| 116 |
+
in_channels=3,
|
| 117 |
+
out_channels=3,
|
| 118 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 119 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 120 |
+
latent_channels=4,
|
| 121 |
+
norm_num_groups=2,
|
| 122 |
+
)
|
| 123 |
+
torch.manual_seed(0)
|
| 124 |
+
text_encoder_config = CLIPTextConfig(
|
| 125 |
+
bos_token_id=0,
|
| 126 |
+
eos_token_id=2,
|
| 127 |
+
hidden_size=32,
|
| 128 |
+
intermediate_size=37,
|
| 129 |
+
layer_norm_eps=1e-05,
|
| 130 |
+
num_attention_heads=4,
|
| 131 |
+
num_hidden_layers=5,
|
| 132 |
+
pad_token_id=1,
|
| 133 |
+
vocab_size=1000,
|
| 134 |
+
)
|
| 135 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 136 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 137 |
+
|
| 138 |
+
components = {
|
| 139 |
+
"unet": unet,
|
| 140 |
+
"controlnet": controlnet,
|
| 141 |
+
"scheduler": scheduler,
|
| 142 |
+
"vae": vae,
|
| 143 |
+
"text_encoder": text_encoder,
|
| 144 |
+
"tokenizer": tokenizer,
|
| 145 |
+
"safety_checker": None,
|
| 146 |
+
"feature_extractor": None,
|
| 147 |
+
"image_encoder": None,
|
| 148 |
+
}
|
| 149 |
+
return components
|
| 150 |
+
|
| 151 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 152 |
+
if str(device).startswith("mps"):
|
| 153 |
+
generator = torch.manual_seed(seed)
|
| 154 |
+
else:
|
| 155 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 156 |
+
|
| 157 |
+
controlnet_embedder_scale_factor = 2
|
| 158 |
+
image = randn_tensor(
|
| 159 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 160 |
+
generator=generator,
|
| 161 |
+
device=torch.device(device),
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
inputs = {
|
| 165 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 166 |
+
"generator": generator,
|
| 167 |
+
"num_inference_steps": 2,
|
| 168 |
+
"guidance_scale": 6.0,
|
| 169 |
+
"output_type": "np",
|
| 170 |
+
"image": image,
|
| 171 |
+
}
|
| 172 |
+
|
| 173 |
+
return inputs
|
| 174 |
+
|
| 175 |
+
def test_attention_slicing_forward_pass(self):
|
| 176 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 177 |
+
|
| 178 |
+
def test_ip_adapter(self):
|
| 179 |
+
expected_pipe_slice = None
|
| 180 |
+
if torch_device == "cpu":
|
| 181 |
+
expected_pipe_slice = np.array([0.5234, 0.3333, 0.1745, 0.7605, 0.6224, 0.4637, 0.6989, 0.7526, 0.4665])
|
| 182 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 183 |
+
|
| 184 |
+
@unittest.skipIf(
|
| 185 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 186 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 187 |
+
)
|
| 188 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 189 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 190 |
+
|
| 191 |
+
def test_inference_batch_single_identical(self):
|
| 192 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 193 |
+
|
| 194 |
+
def test_controlnet_lcm(self):
|
| 195 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 196 |
+
|
| 197 |
+
components = self.get_dummy_components(time_cond_proj_dim=256)
|
| 198 |
+
sd_pipe = StableDiffusionControlNetPipeline(**components)
|
| 199 |
+
sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
|
| 200 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 201 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 202 |
+
|
| 203 |
+
inputs = self.get_dummy_inputs(device)
|
| 204 |
+
output = sd_pipe(**inputs)
|
| 205 |
+
image = output.images
|
| 206 |
+
|
| 207 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 208 |
+
|
| 209 |
+
assert image.shape == (1, 64, 64, 3)
|
| 210 |
+
expected_slice = np.array(
|
| 211 |
+
[0.52700454, 0.3930534, 0.25509018, 0.7132304, 0.53696585, 0.46568912, 0.7095368, 0.7059624, 0.4744786]
|
| 212 |
+
)
|
| 213 |
+
|
| 214 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 215 |
+
|
| 216 |
+
def test_controlnet_lcm_custom_timesteps(self):
|
| 217 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 218 |
+
|
| 219 |
+
components = self.get_dummy_components(time_cond_proj_dim=256)
|
| 220 |
+
sd_pipe = StableDiffusionControlNetPipeline(**components)
|
| 221 |
+
sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
|
| 222 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 223 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 224 |
+
|
| 225 |
+
inputs = self.get_dummy_inputs(device)
|
| 226 |
+
del inputs["num_inference_steps"]
|
| 227 |
+
inputs["timesteps"] = [999, 499]
|
| 228 |
+
output = sd_pipe(**inputs)
|
| 229 |
+
image = output.images
|
| 230 |
+
|
| 231 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 232 |
+
|
| 233 |
+
assert image.shape == (1, 64, 64, 3)
|
| 234 |
+
expected_slice = np.array(
|
| 235 |
+
[0.52700454, 0.3930534, 0.25509018, 0.7132304, 0.53696585, 0.46568912, 0.7095368, 0.7059624, 0.4744786]
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 239 |
+
|
| 240 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 241 |
+
extra_required_param_value_dict = {
|
| 242 |
+
"device": torch.device(torch_device).type,
|
| 243 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 244 |
+
}
|
| 245 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
class StableDiffusionMultiControlNetPipelineFastTests(
|
| 249 |
+
IPAdapterTesterMixin, PipelineTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
|
| 250 |
+
):
|
| 251 |
+
pipeline_class = StableDiffusionControlNetPipeline
|
| 252 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 253 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 254 |
+
image_params = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
|
| 255 |
+
|
| 256 |
+
supports_dduf = False
|
| 257 |
+
|
| 258 |
+
def get_dummy_components(self):
|
| 259 |
+
torch.manual_seed(0)
|
| 260 |
+
unet = UNet2DConditionModel(
|
| 261 |
+
block_out_channels=(4, 8),
|
| 262 |
+
layers_per_block=2,
|
| 263 |
+
sample_size=32,
|
| 264 |
+
in_channels=4,
|
| 265 |
+
out_channels=4,
|
| 266 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 267 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 268 |
+
cross_attention_dim=32,
|
| 269 |
+
norm_num_groups=1,
|
| 270 |
+
)
|
| 271 |
+
torch.manual_seed(0)
|
| 272 |
+
|
| 273 |
+
def init_weights(m):
|
| 274 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 275 |
+
torch.nn.init.normal_(m.weight)
|
| 276 |
+
m.bias.data.fill_(1.0)
|
| 277 |
+
|
| 278 |
+
controlnet1 = ControlNetModel(
|
| 279 |
+
block_out_channels=(4, 8),
|
| 280 |
+
layers_per_block=2,
|
| 281 |
+
in_channels=4,
|
| 282 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 283 |
+
cross_attention_dim=32,
|
| 284 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 285 |
+
norm_num_groups=1,
|
| 286 |
+
)
|
| 287 |
+
controlnet1.controlnet_down_blocks.apply(init_weights)
|
| 288 |
+
|
| 289 |
+
torch.manual_seed(0)
|
| 290 |
+
controlnet2 = ControlNetModel(
|
| 291 |
+
block_out_channels=(4, 8),
|
| 292 |
+
layers_per_block=2,
|
| 293 |
+
in_channels=4,
|
| 294 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 295 |
+
cross_attention_dim=32,
|
| 296 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 297 |
+
norm_num_groups=1,
|
| 298 |
+
)
|
| 299 |
+
controlnet2.controlnet_down_blocks.apply(init_weights)
|
| 300 |
+
|
| 301 |
+
torch.manual_seed(0)
|
| 302 |
+
scheduler = DDIMScheduler(
|
| 303 |
+
beta_start=0.00085,
|
| 304 |
+
beta_end=0.012,
|
| 305 |
+
beta_schedule="scaled_linear",
|
| 306 |
+
clip_sample=False,
|
| 307 |
+
set_alpha_to_one=False,
|
| 308 |
+
)
|
| 309 |
+
torch.manual_seed(0)
|
| 310 |
+
vae = AutoencoderKL(
|
| 311 |
+
block_out_channels=[4, 8],
|
| 312 |
+
in_channels=3,
|
| 313 |
+
out_channels=3,
|
| 314 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 315 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 316 |
+
latent_channels=4,
|
| 317 |
+
norm_num_groups=2,
|
| 318 |
+
)
|
| 319 |
+
torch.manual_seed(0)
|
| 320 |
+
text_encoder_config = CLIPTextConfig(
|
| 321 |
+
bos_token_id=0,
|
| 322 |
+
eos_token_id=2,
|
| 323 |
+
hidden_size=32,
|
| 324 |
+
intermediate_size=37,
|
| 325 |
+
layer_norm_eps=1e-05,
|
| 326 |
+
num_attention_heads=4,
|
| 327 |
+
num_hidden_layers=5,
|
| 328 |
+
pad_token_id=1,
|
| 329 |
+
vocab_size=1000,
|
| 330 |
+
)
|
| 331 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 332 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 333 |
+
|
| 334 |
+
controlnet = MultiControlNetModel([controlnet1, controlnet2])
|
| 335 |
+
|
| 336 |
+
components = {
|
| 337 |
+
"unet": unet,
|
| 338 |
+
"controlnet": controlnet,
|
| 339 |
+
"scheduler": scheduler,
|
| 340 |
+
"vae": vae,
|
| 341 |
+
"text_encoder": text_encoder,
|
| 342 |
+
"tokenizer": tokenizer,
|
| 343 |
+
"safety_checker": None,
|
| 344 |
+
"feature_extractor": None,
|
| 345 |
+
"image_encoder": None,
|
| 346 |
+
}
|
| 347 |
+
return components
|
| 348 |
+
|
| 349 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 350 |
+
if str(device).startswith("mps"):
|
| 351 |
+
generator = torch.manual_seed(seed)
|
| 352 |
+
else:
|
| 353 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 354 |
+
|
| 355 |
+
controlnet_embedder_scale_factor = 2
|
| 356 |
+
|
| 357 |
+
images = [
|
| 358 |
+
randn_tensor(
|
| 359 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 360 |
+
generator=generator,
|
| 361 |
+
device=torch.device(device),
|
| 362 |
+
),
|
| 363 |
+
randn_tensor(
|
| 364 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 365 |
+
generator=generator,
|
| 366 |
+
device=torch.device(device),
|
| 367 |
+
),
|
| 368 |
+
]
|
| 369 |
+
|
| 370 |
+
inputs = {
|
| 371 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 372 |
+
"generator": generator,
|
| 373 |
+
"num_inference_steps": 2,
|
| 374 |
+
"guidance_scale": 6.0,
|
| 375 |
+
"output_type": "np",
|
| 376 |
+
"image": images,
|
| 377 |
+
}
|
| 378 |
+
|
| 379 |
+
return inputs
|
| 380 |
+
|
| 381 |
+
def test_control_guidance_switch(self):
|
| 382 |
+
components = self.get_dummy_components()
|
| 383 |
+
pipe = self.pipeline_class(**components)
|
| 384 |
+
pipe.to(torch_device)
|
| 385 |
+
|
| 386 |
+
scale = 10.0
|
| 387 |
+
steps = 4
|
| 388 |
+
|
| 389 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 390 |
+
inputs["num_inference_steps"] = steps
|
| 391 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 392 |
+
output_1 = pipe(**inputs)[0]
|
| 393 |
+
|
| 394 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 395 |
+
inputs["num_inference_steps"] = steps
|
| 396 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 397 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 398 |
+
|
| 399 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 400 |
+
inputs["num_inference_steps"] = steps
|
| 401 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 402 |
+
output_3 = pipe(**inputs, control_guidance_start=[0.1, 0.3], control_guidance_end=[0.2, 0.7])[0]
|
| 403 |
+
|
| 404 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 405 |
+
inputs["num_inference_steps"] = steps
|
| 406 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 407 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5, 0.8])[0]
|
| 408 |
+
|
| 409 |
+
# make sure that all outputs are different
|
| 410 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 411 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 412 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 413 |
+
|
| 414 |
+
def test_attention_slicing_forward_pass(self):
|
| 415 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 416 |
+
|
| 417 |
+
@unittest.skipIf(
|
| 418 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 419 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 420 |
+
)
|
| 421 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 422 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 423 |
+
|
| 424 |
+
def test_inference_batch_single_identical(self):
|
| 425 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 426 |
+
|
| 427 |
+
def test_ip_adapter(self):
|
| 428 |
+
expected_pipe_slice = None
|
| 429 |
+
if torch_device == "cpu":
|
| 430 |
+
expected_pipe_slice = np.array([0.2422, 0.3425, 0.4048, 0.5351, 0.3503, 0.2419, 0.4645, 0.4570, 0.3804])
|
| 431 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 432 |
+
|
| 433 |
+
def test_save_pretrained_raise_not_implemented_exception(self):
|
| 434 |
+
components = self.get_dummy_components()
|
| 435 |
+
pipe = self.pipeline_class(**components)
|
| 436 |
+
pipe.to(torch_device)
|
| 437 |
+
pipe.set_progress_bar_config(disable=None)
|
| 438 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 439 |
+
try:
|
| 440 |
+
# save_pretrained is not implemented for Multi-ControlNet
|
| 441 |
+
pipe.save_pretrained(tmpdir)
|
| 442 |
+
except NotImplementedError:
|
| 443 |
+
pass
|
| 444 |
+
|
| 445 |
+
def test_inference_multiple_prompt_input(self):
|
| 446 |
+
device = "cpu"
|
| 447 |
+
|
| 448 |
+
components = self.get_dummy_components()
|
| 449 |
+
sd_pipe = StableDiffusionControlNetPipeline(**components)
|
| 450 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 451 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 452 |
+
|
| 453 |
+
inputs = self.get_dummy_inputs(device)
|
| 454 |
+
inputs["prompt"] = [inputs["prompt"], inputs["prompt"]]
|
| 455 |
+
inputs["image"] = [inputs["image"], inputs["image"]]
|
| 456 |
+
output = sd_pipe(**inputs)
|
| 457 |
+
image = output.images
|
| 458 |
+
|
| 459 |
+
assert image.shape == (2, 64, 64, 3)
|
| 460 |
+
|
| 461 |
+
image_1, image_2 = image
|
| 462 |
+
# make sure that the outputs are different
|
| 463 |
+
assert np.sum(np.abs(image_1 - image_2)) > 1e-3
|
| 464 |
+
|
| 465 |
+
# multiple prompts, single image conditioning
|
| 466 |
+
inputs = self.get_dummy_inputs(device)
|
| 467 |
+
inputs["prompt"] = [inputs["prompt"], inputs["prompt"]]
|
| 468 |
+
output_1 = sd_pipe(**inputs)
|
| 469 |
+
|
| 470 |
+
assert np.abs(image - output_1.images).max() < 1e-3
|
| 471 |
+
|
| 472 |
+
# multiple prompts, multiple image conditioning
|
| 473 |
+
inputs = self.get_dummy_inputs(device)
|
| 474 |
+
inputs["prompt"] = [inputs["prompt"], inputs["prompt"], inputs["prompt"], inputs["prompt"]]
|
| 475 |
+
inputs["image"] = [inputs["image"], inputs["image"], inputs["image"], inputs["image"]]
|
| 476 |
+
output_2 = sd_pipe(**inputs)
|
| 477 |
+
image = output_2.images
|
| 478 |
+
|
| 479 |
+
assert image.shape == (4, 64, 64, 3)
|
| 480 |
+
|
| 481 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 482 |
+
extra_required_param_value_dict = {
|
| 483 |
+
"device": torch.device(torch_device).type,
|
| 484 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 485 |
+
}
|
| 486 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 487 |
+
|
| 488 |
+
|
| 489 |
+
class StableDiffusionMultiControlNetOneModelPipelineFastTests(
|
| 490 |
+
IPAdapterTesterMixin, PipelineTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
|
| 491 |
+
):
|
| 492 |
+
pipeline_class = StableDiffusionControlNetPipeline
|
| 493 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 494 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 495 |
+
image_params = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
|
| 496 |
+
|
| 497 |
+
supports_dduf = False
|
| 498 |
+
|
| 499 |
+
def get_dummy_components(self):
|
| 500 |
+
torch.manual_seed(0)
|
| 501 |
+
unet = UNet2DConditionModel(
|
| 502 |
+
block_out_channels=(4, 8),
|
| 503 |
+
layers_per_block=2,
|
| 504 |
+
sample_size=32,
|
| 505 |
+
in_channels=4,
|
| 506 |
+
out_channels=4,
|
| 507 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 508 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 509 |
+
cross_attention_dim=32,
|
| 510 |
+
norm_num_groups=1,
|
| 511 |
+
)
|
| 512 |
+
torch.manual_seed(0)
|
| 513 |
+
|
| 514 |
+
def init_weights(m):
|
| 515 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 516 |
+
torch.nn.init.normal_(m.weight)
|
| 517 |
+
m.bias.data.fill_(1.0)
|
| 518 |
+
|
| 519 |
+
controlnet = ControlNetModel(
|
| 520 |
+
block_out_channels=(4, 8),
|
| 521 |
+
layers_per_block=2,
|
| 522 |
+
in_channels=4,
|
| 523 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 524 |
+
cross_attention_dim=32,
|
| 525 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 526 |
+
norm_num_groups=1,
|
| 527 |
+
)
|
| 528 |
+
controlnet.controlnet_down_blocks.apply(init_weights)
|
| 529 |
+
|
| 530 |
+
torch.manual_seed(0)
|
| 531 |
+
scheduler = DDIMScheduler(
|
| 532 |
+
beta_start=0.00085,
|
| 533 |
+
beta_end=0.012,
|
| 534 |
+
beta_schedule="scaled_linear",
|
| 535 |
+
clip_sample=False,
|
| 536 |
+
set_alpha_to_one=False,
|
| 537 |
+
)
|
| 538 |
+
torch.manual_seed(0)
|
| 539 |
+
vae = AutoencoderKL(
|
| 540 |
+
block_out_channels=[4, 8],
|
| 541 |
+
in_channels=3,
|
| 542 |
+
out_channels=3,
|
| 543 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 544 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 545 |
+
latent_channels=4,
|
| 546 |
+
norm_num_groups=2,
|
| 547 |
+
)
|
| 548 |
+
torch.manual_seed(0)
|
| 549 |
+
text_encoder_config = CLIPTextConfig(
|
| 550 |
+
bos_token_id=0,
|
| 551 |
+
eos_token_id=2,
|
| 552 |
+
hidden_size=32,
|
| 553 |
+
intermediate_size=37,
|
| 554 |
+
layer_norm_eps=1e-05,
|
| 555 |
+
num_attention_heads=4,
|
| 556 |
+
num_hidden_layers=5,
|
| 557 |
+
pad_token_id=1,
|
| 558 |
+
vocab_size=1000,
|
| 559 |
+
)
|
| 560 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 561 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 562 |
+
|
| 563 |
+
controlnet = MultiControlNetModel([controlnet])
|
| 564 |
+
|
| 565 |
+
components = {
|
| 566 |
+
"unet": unet,
|
| 567 |
+
"controlnet": controlnet,
|
| 568 |
+
"scheduler": scheduler,
|
| 569 |
+
"vae": vae,
|
| 570 |
+
"text_encoder": text_encoder,
|
| 571 |
+
"tokenizer": tokenizer,
|
| 572 |
+
"safety_checker": None,
|
| 573 |
+
"feature_extractor": None,
|
| 574 |
+
"image_encoder": None,
|
| 575 |
+
}
|
| 576 |
+
return components
|
| 577 |
+
|
| 578 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 579 |
+
if str(device).startswith("mps"):
|
| 580 |
+
generator = torch.manual_seed(seed)
|
| 581 |
+
else:
|
| 582 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 583 |
+
|
| 584 |
+
controlnet_embedder_scale_factor = 2
|
| 585 |
+
|
| 586 |
+
images = [
|
| 587 |
+
randn_tensor(
|
| 588 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 589 |
+
generator=generator,
|
| 590 |
+
device=torch.device(device),
|
| 591 |
+
),
|
| 592 |
+
]
|
| 593 |
+
|
| 594 |
+
inputs = {
|
| 595 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 596 |
+
"generator": generator,
|
| 597 |
+
"num_inference_steps": 2,
|
| 598 |
+
"guidance_scale": 6.0,
|
| 599 |
+
"output_type": "np",
|
| 600 |
+
"image": images,
|
| 601 |
+
}
|
| 602 |
+
|
| 603 |
+
return inputs
|
| 604 |
+
|
| 605 |
+
def test_control_guidance_switch(self):
|
| 606 |
+
components = self.get_dummy_components()
|
| 607 |
+
pipe = self.pipeline_class(**components)
|
| 608 |
+
pipe.to(torch_device)
|
| 609 |
+
|
| 610 |
+
scale = 10.0
|
| 611 |
+
steps = 4
|
| 612 |
+
|
| 613 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 614 |
+
inputs["num_inference_steps"] = steps
|
| 615 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 616 |
+
output_1 = pipe(**inputs)[0]
|
| 617 |
+
|
| 618 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 619 |
+
inputs["num_inference_steps"] = steps
|
| 620 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 621 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 622 |
+
|
| 623 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 624 |
+
inputs["num_inference_steps"] = steps
|
| 625 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 626 |
+
output_3 = pipe(
|
| 627 |
+
**inputs,
|
| 628 |
+
control_guidance_start=[0.1],
|
| 629 |
+
control_guidance_end=[0.2],
|
| 630 |
+
)[0]
|
| 631 |
+
|
| 632 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 633 |
+
inputs["num_inference_steps"] = steps
|
| 634 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 635 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5])[0]
|
| 636 |
+
|
| 637 |
+
# make sure that all outputs are different
|
| 638 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 639 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 640 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 641 |
+
|
| 642 |
+
def test_attention_slicing_forward_pass(self):
|
| 643 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 644 |
+
|
| 645 |
+
@unittest.skipIf(
|
| 646 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 647 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 648 |
+
)
|
| 649 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 650 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 651 |
+
|
| 652 |
+
def test_inference_batch_single_identical(self):
|
| 653 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 654 |
+
|
| 655 |
+
def test_ip_adapter(self):
|
| 656 |
+
expected_pipe_slice = None
|
| 657 |
+
if torch_device == "cpu":
|
| 658 |
+
expected_pipe_slice = np.array([0.5264, 0.3203, 0.1602, 0.8235, 0.6332, 0.4593, 0.7226, 0.7777, 0.4780])
|
| 659 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 660 |
+
|
| 661 |
+
def test_save_pretrained_raise_not_implemented_exception(self):
|
| 662 |
+
components = self.get_dummy_components()
|
| 663 |
+
pipe = self.pipeline_class(**components)
|
| 664 |
+
pipe.to(torch_device)
|
| 665 |
+
pipe.set_progress_bar_config(disable=None)
|
| 666 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 667 |
+
try:
|
| 668 |
+
# save_pretrained is not implemented for Multi-ControlNet
|
| 669 |
+
pipe.save_pretrained(tmpdir)
|
| 670 |
+
except NotImplementedError:
|
| 671 |
+
pass
|
| 672 |
+
|
| 673 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 674 |
+
extra_required_param_value_dict = {
|
| 675 |
+
"device": torch.device(torch_device).type,
|
| 676 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 677 |
+
}
|
| 678 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 679 |
+
|
| 680 |
+
|
| 681 |
+
@slow
|
| 682 |
+
@require_torch_accelerator
|
| 683 |
+
class ControlNetPipelineSlowTests(unittest.TestCase):
|
| 684 |
+
def setUp(self):
|
| 685 |
+
super().setUp()
|
| 686 |
+
gc.collect()
|
| 687 |
+
backend_empty_cache(torch_device)
|
| 688 |
+
|
| 689 |
+
def tearDown(self):
|
| 690 |
+
super().tearDown()
|
| 691 |
+
gc.collect()
|
| 692 |
+
backend_empty_cache(torch_device)
|
| 693 |
+
|
| 694 |
+
def test_canny(self):
|
| 695 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 696 |
+
|
| 697 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 698 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 699 |
+
)
|
| 700 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 701 |
+
pipe.set_progress_bar_config(disable=None)
|
| 702 |
+
|
| 703 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 704 |
+
prompt = "bird"
|
| 705 |
+
image = load_image(
|
| 706 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 707 |
+
)
|
| 708 |
+
|
| 709 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 710 |
+
|
| 711 |
+
image = output.images[0]
|
| 712 |
+
|
| 713 |
+
assert image.shape == (768, 512, 3)
|
| 714 |
+
|
| 715 |
+
expected_image = load_numpy(
|
| 716 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny_out.npy"
|
| 717 |
+
)
|
| 718 |
+
|
| 719 |
+
assert np.abs(expected_image - image).max() < 9e-2
|
| 720 |
+
|
| 721 |
+
def test_depth(self):
|
| 722 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-depth")
|
| 723 |
+
|
| 724 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 725 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 726 |
+
)
|
| 727 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 728 |
+
pipe.set_progress_bar_config(disable=None)
|
| 729 |
+
|
| 730 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 731 |
+
prompt = "Stormtrooper's lecture"
|
| 732 |
+
image = load_image(
|
| 733 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/stormtrooper_depth.png"
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 737 |
+
|
| 738 |
+
image = output.images[0]
|
| 739 |
+
|
| 740 |
+
assert image.shape == (512, 512, 3)
|
| 741 |
+
|
| 742 |
+
expected_image = load_numpy(
|
| 743 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/stormtrooper_depth_out.npy"
|
| 744 |
+
)
|
| 745 |
+
|
| 746 |
+
assert np.abs(expected_image - image).max() < 8e-1
|
| 747 |
+
|
| 748 |
+
def test_hed(self):
|
| 749 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-hed")
|
| 750 |
+
|
| 751 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 752 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 753 |
+
)
|
| 754 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 755 |
+
pipe.set_progress_bar_config(disable=None)
|
| 756 |
+
|
| 757 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 758 |
+
prompt = "oil painting of handsome old man, masterpiece"
|
| 759 |
+
image = load_image(
|
| 760 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/man_hed.png"
|
| 761 |
+
)
|
| 762 |
+
|
| 763 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 764 |
+
|
| 765 |
+
image = output.images[0]
|
| 766 |
+
|
| 767 |
+
assert image.shape == (704, 512, 3)
|
| 768 |
+
|
| 769 |
+
expected_image = load_numpy(
|
| 770 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/man_hed_out.npy"
|
| 771 |
+
)
|
| 772 |
+
|
| 773 |
+
assert np.abs(expected_image - image).max() < 8e-2
|
| 774 |
+
|
| 775 |
+
def test_mlsd(self):
|
| 776 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-mlsd")
|
| 777 |
+
|
| 778 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 779 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 780 |
+
)
|
| 781 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 782 |
+
pipe.set_progress_bar_config(disable=None)
|
| 783 |
+
|
| 784 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 785 |
+
prompt = "room"
|
| 786 |
+
image = load_image(
|
| 787 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/room_mlsd.png"
|
| 788 |
+
)
|
| 789 |
+
|
| 790 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 791 |
+
|
| 792 |
+
image = output.images[0]
|
| 793 |
+
|
| 794 |
+
assert image.shape == (704, 512, 3)
|
| 795 |
+
|
| 796 |
+
expected_image = load_numpy(
|
| 797 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/room_mlsd_out.npy"
|
| 798 |
+
)
|
| 799 |
+
|
| 800 |
+
assert np.abs(expected_image - image).max() < 5e-2
|
| 801 |
+
|
| 802 |
+
def test_normal(self):
|
| 803 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-normal")
|
| 804 |
+
|
| 805 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 806 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 807 |
+
)
|
| 808 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 809 |
+
pipe.set_progress_bar_config(disable=None)
|
| 810 |
+
|
| 811 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 812 |
+
prompt = "cute toy"
|
| 813 |
+
image = load_image(
|
| 814 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/cute_toy_normal.png"
|
| 815 |
+
)
|
| 816 |
+
|
| 817 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 818 |
+
|
| 819 |
+
image = output.images[0]
|
| 820 |
+
|
| 821 |
+
assert image.shape == (512, 512, 3)
|
| 822 |
+
|
| 823 |
+
expected_image = load_numpy(
|
| 824 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/cute_toy_normal_out.npy"
|
| 825 |
+
)
|
| 826 |
+
|
| 827 |
+
assert np.abs(expected_image - image).max() < 5e-2
|
| 828 |
+
|
| 829 |
+
def test_openpose(self):
|
| 830 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-openpose")
|
| 831 |
+
|
| 832 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 833 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 834 |
+
)
|
| 835 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 836 |
+
pipe.set_progress_bar_config(disable=None)
|
| 837 |
+
|
| 838 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 839 |
+
prompt = "Chef in the kitchen"
|
| 840 |
+
image = load_image(
|
| 841 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png"
|
| 842 |
+
)
|
| 843 |
+
|
| 844 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 845 |
+
|
| 846 |
+
image = output.images[0]
|
| 847 |
+
|
| 848 |
+
assert image.shape == (768, 512, 3)
|
| 849 |
+
|
| 850 |
+
expected_image = load_numpy(
|
| 851 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/chef_pose_out.npy"
|
| 852 |
+
)
|
| 853 |
+
|
| 854 |
+
assert np.abs(expected_image - image).max() < 8e-2
|
| 855 |
+
|
| 856 |
+
def test_scribble(self):
|
| 857 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-scribble")
|
| 858 |
+
|
| 859 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 860 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 861 |
+
)
|
| 862 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 863 |
+
pipe.set_progress_bar_config(disable=None)
|
| 864 |
+
|
| 865 |
+
generator = torch.Generator(device="cpu").manual_seed(5)
|
| 866 |
+
prompt = "bag"
|
| 867 |
+
image = load_image(
|
| 868 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bag_scribble.png"
|
| 869 |
+
)
|
| 870 |
+
|
| 871 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 872 |
+
|
| 873 |
+
image = output.images[0]
|
| 874 |
+
|
| 875 |
+
assert image.shape == (640, 512, 3)
|
| 876 |
+
|
| 877 |
+
expected_image = load_numpy(
|
| 878 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bag_scribble_out.npy"
|
| 879 |
+
)
|
| 880 |
+
|
| 881 |
+
assert np.abs(expected_image - image).max() < 8e-2
|
| 882 |
+
|
| 883 |
+
def test_seg(self):
|
| 884 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-seg")
|
| 885 |
+
|
| 886 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 887 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 888 |
+
)
|
| 889 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 890 |
+
pipe.set_progress_bar_config(disable=None)
|
| 891 |
+
|
| 892 |
+
generator = torch.Generator(device="cpu").manual_seed(5)
|
| 893 |
+
prompt = "house"
|
| 894 |
+
image = load_image(
|
| 895 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/house_seg.png"
|
| 896 |
+
)
|
| 897 |
+
|
| 898 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 899 |
+
|
| 900 |
+
image = output.images[0]
|
| 901 |
+
|
| 902 |
+
assert image.shape == (512, 512, 3)
|
| 903 |
+
|
| 904 |
+
expected_image = load_numpy(
|
| 905 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/house_seg_out.npy"
|
| 906 |
+
)
|
| 907 |
+
|
| 908 |
+
assert np.abs(expected_image - image).max() < 8e-2
|
| 909 |
+
|
| 910 |
+
def test_sequential_cpu_offloading(self):
|
| 911 |
+
backend_empty_cache(torch_device)
|
| 912 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 913 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 914 |
+
|
| 915 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-seg")
|
| 916 |
+
|
| 917 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 918 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 919 |
+
)
|
| 920 |
+
pipe.set_progress_bar_config(disable=None)
|
| 921 |
+
pipe.enable_attention_slicing()
|
| 922 |
+
pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 923 |
+
|
| 924 |
+
prompt = "house"
|
| 925 |
+
image = load_image(
|
| 926 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/house_seg.png"
|
| 927 |
+
)
|
| 928 |
+
|
| 929 |
+
_ = pipe(
|
| 930 |
+
prompt,
|
| 931 |
+
image,
|
| 932 |
+
num_inference_steps=2,
|
| 933 |
+
output_type="np",
|
| 934 |
+
)
|
| 935 |
+
|
| 936 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 937 |
+
# make sure that less than 7 GB is allocated
|
| 938 |
+
assert mem_bytes < 4 * 10**9
|
| 939 |
+
|
| 940 |
+
def test_canny_guess_mode(self):
|
| 941 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 942 |
+
|
| 943 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 944 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 945 |
+
)
|
| 946 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 947 |
+
pipe.set_progress_bar_config(disable=None)
|
| 948 |
+
|
| 949 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 950 |
+
prompt = ""
|
| 951 |
+
image = load_image(
|
| 952 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 953 |
+
)
|
| 954 |
+
|
| 955 |
+
output = pipe(
|
| 956 |
+
prompt,
|
| 957 |
+
image,
|
| 958 |
+
generator=generator,
|
| 959 |
+
output_type="np",
|
| 960 |
+
num_inference_steps=3,
|
| 961 |
+
guidance_scale=3.0,
|
| 962 |
+
guess_mode=True,
|
| 963 |
+
)
|
| 964 |
+
|
| 965 |
+
image = output.images[0]
|
| 966 |
+
assert image.shape == (768, 512, 3)
|
| 967 |
+
|
| 968 |
+
image_slice = image[-3:, -3:, -1]
|
| 969 |
+
expected_slice = np.array([0.2724, 0.2846, 0.2724, 0.3843, 0.3682, 0.2736, 0.4675, 0.3862, 0.2887])
|
| 970 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 971 |
+
|
| 972 |
+
def test_canny_guess_mode_euler(self):
|
| 973 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 974 |
+
|
| 975 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 976 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 977 |
+
)
|
| 978 |
+
pipe.scheduler = EulerDiscreteScheduler.from_config(pipe.scheduler.config)
|
| 979 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 980 |
+
pipe.set_progress_bar_config(disable=None)
|
| 981 |
+
|
| 982 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 983 |
+
prompt = ""
|
| 984 |
+
image = load_image(
|
| 985 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 986 |
+
)
|
| 987 |
+
|
| 988 |
+
output = pipe(
|
| 989 |
+
prompt,
|
| 990 |
+
image,
|
| 991 |
+
generator=generator,
|
| 992 |
+
output_type="np",
|
| 993 |
+
num_inference_steps=3,
|
| 994 |
+
guidance_scale=3.0,
|
| 995 |
+
guess_mode=True,
|
| 996 |
+
)
|
| 997 |
+
|
| 998 |
+
image = output.images[0]
|
| 999 |
+
assert image.shape == (768, 512, 3)
|
| 1000 |
+
|
| 1001 |
+
image_slice = image[-3:, -3:, -1]
|
| 1002 |
+
expected_slice = np.array([0.1655, 0.1721, 0.1623, 0.1685, 0.1711, 0.1646, 0.1651, 0.1631, 0.1494])
|
| 1003 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 1004 |
+
|
| 1005 |
+
def test_v11_shuffle_global_pool_conditions(self):
|
| 1006 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11e_sd15_shuffle")
|
| 1007 |
+
|
| 1008 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 1009 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 1010 |
+
)
|
| 1011 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 1012 |
+
pipe.set_progress_bar_config(disable=None)
|
| 1013 |
+
|
| 1014 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 1015 |
+
prompt = "New York"
|
| 1016 |
+
image = load_image(
|
| 1017 |
+
"https://huggingface.co/lllyasviel/control_v11e_sd15_shuffle/resolve/main/images/control.png"
|
| 1018 |
+
)
|
| 1019 |
+
|
| 1020 |
+
output = pipe(
|
| 1021 |
+
prompt,
|
| 1022 |
+
image,
|
| 1023 |
+
generator=generator,
|
| 1024 |
+
output_type="np",
|
| 1025 |
+
num_inference_steps=3,
|
| 1026 |
+
guidance_scale=7.0,
|
| 1027 |
+
)
|
| 1028 |
+
|
| 1029 |
+
image = output.images[0]
|
| 1030 |
+
assert image.shape == (512, 640, 3)
|
| 1031 |
+
|
| 1032 |
+
image_slice = image[-3:, -3:, -1]
|
| 1033 |
+
expected_slice = np.array([0.1338, 0.1597, 0.1202, 0.1687, 0.1377, 0.1017, 0.2070, 0.1574, 0.1348])
|
| 1034 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 1035 |
+
|
| 1036 |
+
|
| 1037 |
+
@slow
|
| 1038 |
+
@require_torch_accelerator
|
| 1039 |
+
class StableDiffusionMultiControlNetPipelineSlowTests(unittest.TestCase):
|
| 1040 |
+
def setUp(self):
|
| 1041 |
+
super().setUp()
|
| 1042 |
+
gc.collect()
|
| 1043 |
+
backend_empty_cache(torch_device)
|
| 1044 |
+
|
| 1045 |
+
def tearDown(self):
|
| 1046 |
+
super().tearDown()
|
| 1047 |
+
gc.collect()
|
| 1048 |
+
backend_empty_cache(torch_device)
|
| 1049 |
+
|
| 1050 |
+
def test_pose_and_canny(self):
|
| 1051 |
+
controlnet_canny = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 1052 |
+
controlnet_pose = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-openpose")
|
| 1053 |
+
|
| 1054 |
+
pipe = StableDiffusionControlNetPipeline.from_pretrained(
|
| 1055 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5",
|
| 1056 |
+
safety_checker=None,
|
| 1057 |
+
controlnet=[controlnet_pose, controlnet_canny],
|
| 1058 |
+
)
|
| 1059 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 1060 |
+
pipe.set_progress_bar_config(disable=None)
|
| 1061 |
+
|
| 1062 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 1063 |
+
prompt = "bird and Chef"
|
| 1064 |
+
image_canny = load_image(
|
| 1065 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 1066 |
+
)
|
| 1067 |
+
image_pose = load_image(
|
| 1068 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png"
|
| 1069 |
+
)
|
| 1070 |
+
|
| 1071 |
+
output = pipe(prompt, [image_pose, image_canny], generator=generator, output_type="np", num_inference_steps=3)
|
| 1072 |
+
|
| 1073 |
+
image = output.images[0]
|
| 1074 |
+
|
| 1075 |
+
assert image.shape == (768, 512, 3)
|
| 1076 |
+
|
| 1077 |
+
expected_image = load_numpy(
|
| 1078 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose_canny_out.npy"
|
| 1079 |
+
)
|
| 1080 |
+
|
| 1081 |
+
assert np.abs(expected_image - image).max() < 5e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_blip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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
import unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from PIL import Image
|
| 20 |
+
from transformers import CLIPTokenizer
|
| 21 |
+
from transformers.models.blip_2.configuration_blip_2 import Blip2Config
|
| 22 |
+
from transformers.models.clip.configuration_clip import CLIPTextConfig
|
| 23 |
+
|
| 24 |
+
from diffusers import (
|
| 25 |
+
AutoencoderKL,
|
| 26 |
+
BlipDiffusionControlNetPipeline,
|
| 27 |
+
ControlNetModel,
|
| 28 |
+
PNDMScheduler,
|
| 29 |
+
UNet2DConditionModel,
|
| 30 |
+
)
|
| 31 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 32 |
+
from src.diffusers.pipelines.blip_diffusion.blip_image_processing import BlipImageProcessor
|
| 33 |
+
from src.diffusers.pipelines.blip_diffusion.modeling_blip2 import Blip2QFormerModel
|
| 34 |
+
from src.diffusers.pipelines.blip_diffusion.modeling_ctx_clip import ContextCLIPTextModel
|
| 35 |
+
|
| 36 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
enable_full_determinism()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class BlipDiffusionControlNetPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 43 |
+
pipeline_class = BlipDiffusionControlNetPipeline
|
| 44 |
+
params = [
|
| 45 |
+
"prompt",
|
| 46 |
+
"reference_image",
|
| 47 |
+
"source_subject_category",
|
| 48 |
+
"target_subject_category",
|
| 49 |
+
"condtioning_image",
|
| 50 |
+
]
|
| 51 |
+
batch_params = [
|
| 52 |
+
"prompt",
|
| 53 |
+
"reference_image",
|
| 54 |
+
"source_subject_category",
|
| 55 |
+
"target_subject_category",
|
| 56 |
+
"condtioning_image",
|
| 57 |
+
]
|
| 58 |
+
required_optional_params = [
|
| 59 |
+
"generator",
|
| 60 |
+
"height",
|
| 61 |
+
"width",
|
| 62 |
+
"latents",
|
| 63 |
+
"guidance_scale",
|
| 64 |
+
"num_inference_steps",
|
| 65 |
+
"neg_prompt",
|
| 66 |
+
"guidance_scale",
|
| 67 |
+
"prompt_strength",
|
| 68 |
+
"prompt_reps",
|
| 69 |
+
]
|
| 70 |
+
|
| 71 |
+
supports_dduf = False
|
| 72 |
+
|
| 73 |
+
def get_dummy_components(self):
|
| 74 |
+
torch.manual_seed(0)
|
| 75 |
+
text_encoder_config = CLIPTextConfig(
|
| 76 |
+
vocab_size=1000,
|
| 77 |
+
hidden_size=16,
|
| 78 |
+
intermediate_size=16,
|
| 79 |
+
projection_dim=16,
|
| 80 |
+
num_hidden_layers=1,
|
| 81 |
+
num_attention_heads=1,
|
| 82 |
+
max_position_embeddings=77,
|
| 83 |
+
)
|
| 84 |
+
text_encoder = ContextCLIPTextModel(text_encoder_config)
|
| 85 |
+
|
| 86 |
+
vae = AutoencoderKL(
|
| 87 |
+
in_channels=4,
|
| 88 |
+
out_channels=4,
|
| 89 |
+
down_block_types=("DownEncoderBlock2D",),
|
| 90 |
+
up_block_types=("UpDecoderBlock2D",),
|
| 91 |
+
block_out_channels=(32,),
|
| 92 |
+
layers_per_block=1,
|
| 93 |
+
act_fn="silu",
|
| 94 |
+
latent_channels=4,
|
| 95 |
+
norm_num_groups=16,
|
| 96 |
+
sample_size=16,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
blip_vision_config = {
|
| 100 |
+
"hidden_size": 16,
|
| 101 |
+
"intermediate_size": 16,
|
| 102 |
+
"num_hidden_layers": 1,
|
| 103 |
+
"num_attention_heads": 1,
|
| 104 |
+
"image_size": 224,
|
| 105 |
+
"patch_size": 14,
|
| 106 |
+
"hidden_act": "quick_gelu",
|
| 107 |
+
}
|
| 108 |
+
|
| 109 |
+
blip_qformer_config = {
|
| 110 |
+
"vocab_size": 1000,
|
| 111 |
+
"hidden_size": 16,
|
| 112 |
+
"num_hidden_layers": 1,
|
| 113 |
+
"num_attention_heads": 1,
|
| 114 |
+
"intermediate_size": 16,
|
| 115 |
+
"max_position_embeddings": 512,
|
| 116 |
+
"cross_attention_frequency": 1,
|
| 117 |
+
"encoder_hidden_size": 16,
|
| 118 |
+
}
|
| 119 |
+
qformer_config = Blip2Config(
|
| 120 |
+
vision_config=blip_vision_config,
|
| 121 |
+
qformer_config=blip_qformer_config,
|
| 122 |
+
num_query_tokens=16,
|
| 123 |
+
tokenizer="hf-internal-testing/tiny-random-bert",
|
| 124 |
+
)
|
| 125 |
+
qformer = Blip2QFormerModel(qformer_config)
|
| 126 |
+
|
| 127 |
+
unet = UNet2DConditionModel(
|
| 128 |
+
block_out_channels=(4, 16),
|
| 129 |
+
layers_per_block=1,
|
| 130 |
+
norm_num_groups=4,
|
| 131 |
+
sample_size=16,
|
| 132 |
+
in_channels=4,
|
| 133 |
+
out_channels=4,
|
| 134 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 135 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 136 |
+
cross_attention_dim=16,
|
| 137 |
+
)
|
| 138 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 139 |
+
|
| 140 |
+
scheduler = PNDMScheduler(
|
| 141 |
+
beta_start=0.00085,
|
| 142 |
+
beta_end=0.012,
|
| 143 |
+
beta_schedule="scaled_linear",
|
| 144 |
+
set_alpha_to_one=False,
|
| 145 |
+
skip_prk_steps=True,
|
| 146 |
+
)
|
| 147 |
+
controlnet = ControlNetModel(
|
| 148 |
+
block_out_channels=(4, 16),
|
| 149 |
+
layers_per_block=1,
|
| 150 |
+
in_channels=4,
|
| 151 |
+
norm_num_groups=4,
|
| 152 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 153 |
+
cross_attention_dim=16,
|
| 154 |
+
conditioning_embedding_out_channels=(8, 16),
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
vae.eval()
|
| 158 |
+
qformer.eval()
|
| 159 |
+
text_encoder.eval()
|
| 160 |
+
|
| 161 |
+
image_processor = BlipImageProcessor()
|
| 162 |
+
|
| 163 |
+
components = {
|
| 164 |
+
"text_encoder": text_encoder,
|
| 165 |
+
"vae": vae,
|
| 166 |
+
"qformer": qformer,
|
| 167 |
+
"unet": unet,
|
| 168 |
+
"tokenizer": tokenizer,
|
| 169 |
+
"scheduler": scheduler,
|
| 170 |
+
"controlnet": controlnet,
|
| 171 |
+
"image_processor": image_processor,
|
| 172 |
+
}
|
| 173 |
+
return components
|
| 174 |
+
|
| 175 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 176 |
+
np.random.seed(seed)
|
| 177 |
+
reference_image = np.random.rand(32, 32, 3) * 255
|
| 178 |
+
reference_image = Image.fromarray(reference_image.astype("uint8")).convert("RGBA")
|
| 179 |
+
cond_image = np.random.rand(32, 32, 3) * 255
|
| 180 |
+
cond_image = Image.fromarray(cond_image.astype("uint8")).convert("RGBA")
|
| 181 |
+
|
| 182 |
+
if str(device).startswith("mps"):
|
| 183 |
+
generator = torch.manual_seed(seed)
|
| 184 |
+
else:
|
| 185 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 186 |
+
inputs = {
|
| 187 |
+
"prompt": "swimming underwater",
|
| 188 |
+
"generator": generator,
|
| 189 |
+
"reference_image": reference_image,
|
| 190 |
+
"condtioning_image": cond_image,
|
| 191 |
+
"source_subject_category": "dog",
|
| 192 |
+
"target_subject_category": "dog",
|
| 193 |
+
"height": 32,
|
| 194 |
+
"width": 32,
|
| 195 |
+
"guidance_scale": 7.5,
|
| 196 |
+
"num_inference_steps": 2,
|
| 197 |
+
"output_type": "np",
|
| 198 |
+
}
|
| 199 |
+
return inputs
|
| 200 |
+
|
| 201 |
+
def test_dict_tuple_outputs_equivalent(self):
|
| 202 |
+
expected_slice = None
|
| 203 |
+
if torch_device == "cpu":
|
| 204 |
+
expected_slice = np.array([0.4803, 0.3865, 0.1422, 0.6119, 0.2283, 0.6365, 0.5453, 0.5205, 0.3581])
|
| 205 |
+
super().test_dict_tuple_outputs_equivalent(expected_slice=expected_slice)
|
| 206 |
+
|
| 207 |
+
def test_blipdiffusion_controlnet(self):
|
| 208 |
+
device = "cpu"
|
| 209 |
+
components = self.get_dummy_components()
|
| 210 |
+
|
| 211 |
+
pipe = self.pipeline_class(**components)
|
| 212 |
+
pipe = pipe.to(device)
|
| 213 |
+
|
| 214 |
+
pipe.set_progress_bar_config(disable=None)
|
| 215 |
+
|
| 216 |
+
image = pipe(**self.get_dummy_inputs(device))[0]
|
| 217 |
+
image_slice = image[0, -3:, -3:, 0]
|
| 218 |
+
|
| 219 |
+
assert image.shape == (1, 16, 16, 4)
|
| 220 |
+
expected_slice = np.array([0.7953, 0.7136, 0.6597, 0.4779, 0.7389, 0.4111, 0.5826, 0.4150, 0.8422])
|
| 221 |
+
|
| 222 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
|
| 223 |
+
f" expected_slice {expected_slice}, but got {image_slice.flatten()}"
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
@unittest.skip("Test not supported because of complexities in deriving query_embeds.")
|
| 227 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 228 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_img2img.py
ADDED
|
@@ -0,0 +1,459 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# This model implementation is heavily inspired by https://github.com/haofanwang/ControlNet-for-Diffusers/
|
| 17 |
+
|
| 18 |
+
import gc
|
| 19 |
+
import random
|
| 20 |
+
import tempfile
|
| 21 |
+
import unittest
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
|
| 27 |
+
|
| 28 |
+
from diffusers import (
|
| 29 |
+
AutoencoderKL,
|
| 30 |
+
ControlNetModel,
|
| 31 |
+
DDIMScheduler,
|
| 32 |
+
StableDiffusionControlNetImg2ImgPipeline,
|
| 33 |
+
UNet2DConditionModel,
|
| 34 |
+
)
|
| 35 |
+
from diffusers.pipelines.controlnet.pipeline_controlnet import MultiControlNetModel
|
| 36 |
+
from diffusers.utils import load_image
|
| 37 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 38 |
+
from diffusers.utils.testing_utils import (
|
| 39 |
+
backend_empty_cache,
|
| 40 |
+
enable_full_determinism,
|
| 41 |
+
floats_tensor,
|
| 42 |
+
load_numpy,
|
| 43 |
+
require_torch_accelerator,
|
| 44 |
+
slow,
|
| 45 |
+
torch_device,
|
| 46 |
+
)
|
| 47 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 48 |
+
|
| 49 |
+
from ..pipeline_params import (
|
| 50 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 51 |
+
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
|
| 52 |
+
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
|
| 53 |
+
)
|
| 54 |
+
from ..test_pipelines_common import (
|
| 55 |
+
IPAdapterTesterMixin,
|
| 56 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 57 |
+
PipelineLatentTesterMixin,
|
| 58 |
+
PipelineTesterMixin,
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
enable_full_determinism()
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
class ControlNetImg2ImgPipelineFastTests(
|
| 66 |
+
IPAdapterTesterMixin,
|
| 67 |
+
PipelineLatentTesterMixin,
|
| 68 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 69 |
+
PipelineTesterMixin,
|
| 70 |
+
unittest.TestCase,
|
| 71 |
+
):
|
| 72 |
+
pipeline_class = StableDiffusionControlNetImg2ImgPipeline
|
| 73 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
|
| 74 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
|
| 75 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"control_image"})
|
| 76 |
+
image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 77 |
+
|
| 78 |
+
def get_dummy_components(self):
|
| 79 |
+
torch.manual_seed(0)
|
| 80 |
+
unet = UNet2DConditionModel(
|
| 81 |
+
block_out_channels=(4, 8),
|
| 82 |
+
layers_per_block=2,
|
| 83 |
+
sample_size=32,
|
| 84 |
+
in_channels=4,
|
| 85 |
+
out_channels=4,
|
| 86 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 87 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 88 |
+
cross_attention_dim=32,
|
| 89 |
+
norm_num_groups=1,
|
| 90 |
+
)
|
| 91 |
+
torch.manual_seed(0)
|
| 92 |
+
controlnet = ControlNetModel(
|
| 93 |
+
block_out_channels=(4, 8),
|
| 94 |
+
layers_per_block=2,
|
| 95 |
+
in_channels=4,
|
| 96 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 97 |
+
cross_attention_dim=32,
|
| 98 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 99 |
+
norm_num_groups=1,
|
| 100 |
+
)
|
| 101 |
+
torch.manual_seed(0)
|
| 102 |
+
scheduler = DDIMScheduler(
|
| 103 |
+
beta_start=0.00085,
|
| 104 |
+
beta_end=0.012,
|
| 105 |
+
beta_schedule="scaled_linear",
|
| 106 |
+
clip_sample=False,
|
| 107 |
+
set_alpha_to_one=False,
|
| 108 |
+
)
|
| 109 |
+
torch.manual_seed(0)
|
| 110 |
+
vae = AutoencoderKL(
|
| 111 |
+
block_out_channels=[4, 8],
|
| 112 |
+
in_channels=3,
|
| 113 |
+
out_channels=3,
|
| 114 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 115 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 116 |
+
latent_channels=4,
|
| 117 |
+
norm_num_groups=2,
|
| 118 |
+
)
|
| 119 |
+
torch.manual_seed(0)
|
| 120 |
+
text_encoder_config = CLIPTextConfig(
|
| 121 |
+
bos_token_id=0,
|
| 122 |
+
eos_token_id=2,
|
| 123 |
+
hidden_size=32,
|
| 124 |
+
intermediate_size=37,
|
| 125 |
+
layer_norm_eps=1e-05,
|
| 126 |
+
num_attention_heads=4,
|
| 127 |
+
num_hidden_layers=5,
|
| 128 |
+
pad_token_id=1,
|
| 129 |
+
vocab_size=1000,
|
| 130 |
+
)
|
| 131 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 132 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 133 |
+
|
| 134 |
+
components = {
|
| 135 |
+
"unet": unet,
|
| 136 |
+
"controlnet": controlnet,
|
| 137 |
+
"scheduler": scheduler,
|
| 138 |
+
"vae": vae,
|
| 139 |
+
"text_encoder": text_encoder,
|
| 140 |
+
"tokenizer": tokenizer,
|
| 141 |
+
"safety_checker": None,
|
| 142 |
+
"feature_extractor": None,
|
| 143 |
+
"image_encoder": None,
|
| 144 |
+
}
|
| 145 |
+
return components
|
| 146 |
+
|
| 147 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 148 |
+
if str(device).startswith("mps"):
|
| 149 |
+
generator = torch.manual_seed(seed)
|
| 150 |
+
else:
|
| 151 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 152 |
+
|
| 153 |
+
controlnet_embedder_scale_factor = 2
|
| 154 |
+
control_image = randn_tensor(
|
| 155 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 156 |
+
generator=generator,
|
| 157 |
+
device=torch.device(device),
|
| 158 |
+
)
|
| 159 |
+
image = floats_tensor(control_image.shape, rng=random.Random(seed)).to(device)
|
| 160 |
+
image = image.cpu().permute(0, 2, 3, 1)[0]
|
| 161 |
+
image = Image.fromarray(np.uint8(image)).convert("RGB").resize((64, 64))
|
| 162 |
+
inputs = {
|
| 163 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 164 |
+
"generator": generator,
|
| 165 |
+
"num_inference_steps": 2,
|
| 166 |
+
"guidance_scale": 6.0,
|
| 167 |
+
"output_type": "np",
|
| 168 |
+
"image": image,
|
| 169 |
+
"control_image": control_image,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
return inputs
|
| 173 |
+
|
| 174 |
+
def test_attention_slicing_forward_pass(self):
|
| 175 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 176 |
+
|
| 177 |
+
def test_ip_adapter(self):
|
| 178 |
+
expected_pipe_slice = None
|
| 179 |
+
if torch_device == "cpu":
|
| 180 |
+
expected_pipe_slice = np.array([0.7096, 0.5149, 0.3571, 0.5897, 0.4715, 0.4052, 0.6098, 0.6886, 0.4213])
|
| 181 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 182 |
+
|
| 183 |
+
@unittest.skipIf(
|
| 184 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 185 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 186 |
+
)
|
| 187 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 188 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 189 |
+
|
| 190 |
+
def test_inference_batch_single_identical(self):
|
| 191 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 192 |
+
|
| 193 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 194 |
+
extra_required_param_value_dict = {
|
| 195 |
+
"device": torch.device(torch_device).type,
|
| 196 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 197 |
+
}
|
| 198 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 199 |
+
|
| 200 |
+
|
| 201 |
+
class StableDiffusionMultiControlNetPipelineFastTests(
|
| 202 |
+
IPAdapterTesterMixin, PipelineTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
|
| 203 |
+
):
|
| 204 |
+
pipeline_class = StableDiffusionControlNetImg2ImgPipeline
|
| 205 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"height", "width"}
|
| 206 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
|
| 207 |
+
image_params = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
|
| 208 |
+
|
| 209 |
+
supports_dduf = False
|
| 210 |
+
|
| 211 |
+
def get_dummy_components(self):
|
| 212 |
+
torch.manual_seed(0)
|
| 213 |
+
unet = UNet2DConditionModel(
|
| 214 |
+
block_out_channels=(4, 8),
|
| 215 |
+
layers_per_block=2,
|
| 216 |
+
sample_size=32,
|
| 217 |
+
in_channels=4,
|
| 218 |
+
out_channels=4,
|
| 219 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 220 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 221 |
+
cross_attention_dim=32,
|
| 222 |
+
norm_num_groups=1,
|
| 223 |
+
)
|
| 224 |
+
torch.manual_seed(0)
|
| 225 |
+
|
| 226 |
+
def init_weights(m):
|
| 227 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 228 |
+
torch.nn.init.normal_(m.weight)
|
| 229 |
+
m.bias.data.fill_(1.0)
|
| 230 |
+
|
| 231 |
+
controlnet1 = ControlNetModel(
|
| 232 |
+
block_out_channels=(4, 8),
|
| 233 |
+
layers_per_block=2,
|
| 234 |
+
in_channels=4,
|
| 235 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 236 |
+
cross_attention_dim=32,
|
| 237 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 238 |
+
norm_num_groups=1,
|
| 239 |
+
)
|
| 240 |
+
controlnet1.controlnet_down_blocks.apply(init_weights)
|
| 241 |
+
|
| 242 |
+
torch.manual_seed(0)
|
| 243 |
+
controlnet2 = ControlNetModel(
|
| 244 |
+
block_out_channels=(4, 8),
|
| 245 |
+
layers_per_block=2,
|
| 246 |
+
in_channels=4,
|
| 247 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 248 |
+
cross_attention_dim=32,
|
| 249 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 250 |
+
norm_num_groups=1,
|
| 251 |
+
)
|
| 252 |
+
controlnet2.controlnet_down_blocks.apply(init_weights)
|
| 253 |
+
|
| 254 |
+
torch.manual_seed(0)
|
| 255 |
+
scheduler = DDIMScheduler(
|
| 256 |
+
beta_start=0.00085,
|
| 257 |
+
beta_end=0.012,
|
| 258 |
+
beta_schedule="scaled_linear",
|
| 259 |
+
clip_sample=False,
|
| 260 |
+
set_alpha_to_one=False,
|
| 261 |
+
)
|
| 262 |
+
torch.manual_seed(0)
|
| 263 |
+
vae = AutoencoderKL(
|
| 264 |
+
block_out_channels=[4, 8],
|
| 265 |
+
in_channels=3,
|
| 266 |
+
out_channels=3,
|
| 267 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 268 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 269 |
+
latent_channels=4,
|
| 270 |
+
norm_num_groups=2,
|
| 271 |
+
)
|
| 272 |
+
torch.manual_seed(0)
|
| 273 |
+
text_encoder_config = CLIPTextConfig(
|
| 274 |
+
bos_token_id=0,
|
| 275 |
+
eos_token_id=2,
|
| 276 |
+
hidden_size=32,
|
| 277 |
+
intermediate_size=37,
|
| 278 |
+
layer_norm_eps=1e-05,
|
| 279 |
+
num_attention_heads=4,
|
| 280 |
+
num_hidden_layers=5,
|
| 281 |
+
pad_token_id=1,
|
| 282 |
+
vocab_size=1000,
|
| 283 |
+
)
|
| 284 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 285 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 286 |
+
|
| 287 |
+
controlnet = MultiControlNetModel([controlnet1, controlnet2])
|
| 288 |
+
|
| 289 |
+
components = {
|
| 290 |
+
"unet": unet,
|
| 291 |
+
"controlnet": controlnet,
|
| 292 |
+
"scheduler": scheduler,
|
| 293 |
+
"vae": vae,
|
| 294 |
+
"text_encoder": text_encoder,
|
| 295 |
+
"tokenizer": tokenizer,
|
| 296 |
+
"safety_checker": None,
|
| 297 |
+
"feature_extractor": None,
|
| 298 |
+
"image_encoder": None,
|
| 299 |
+
}
|
| 300 |
+
return components
|
| 301 |
+
|
| 302 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 303 |
+
if str(device).startswith("mps"):
|
| 304 |
+
generator = torch.manual_seed(seed)
|
| 305 |
+
else:
|
| 306 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 307 |
+
|
| 308 |
+
controlnet_embedder_scale_factor = 2
|
| 309 |
+
|
| 310 |
+
control_image = [
|
| 311 |
+
randn_tensor(
|
| 312 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 313 |
+
generator=generator,
|
| 314 |
+
device=torch.device(device),
|
| 315 |
+
),
|
| 316 |
+
randn_tensor(
|
| 317 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 318 |
+
generator=generator,
|
| 319 |
+
device=torch.device(device),
|
| 320 |
+
),
|
| 321 |
+
]
|
| 322 |
+
|
| 323 |
+
image = floats_tensor(control_image[0].shape, rng=random.Random(seed)).to(device)
|
| 324 |
+
image = image.cpu().permute(0, 2, 3, 1)[0]
|
| 325 |
+
image = Image.fromarray(np.uint8(image)).convert("RGB").resize((64, 64))
|
| 326 |
+
inputs = {
|
| 327 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 328 |
+
"generator": generator,
|
| 329 |
+
"num_inference_steps": 2,
|
| 330 |
+
"guidance_scale": 6.0,
|
| 331 |
+
"output_type": "np",
|
| 332 |
+
"image": image,
|
| 333 |
+
"control_image": control_image,
|
| 334 |
+
}
|
| 335 |
+
|
| 336 |
+
return inputs
|
| 337 |
+
|
| 338 |
+
def test_control_guidance_switch(self):
|
| 339 |
+
components = self.get_dummy_components()
|
| 340 |
+
pipe = self.pipeline_class(**components)
|
| 341 |
+
pipe.to(torch_device)
|
| 342 |
+
|
| 343 |
+
scale = 10.0
|
| 344 |
+
steps = 4
|
| 345 |
+
|
| 346 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 347 |
+
inputs["num_inference_steps"] = steps
|
| 348 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 349 |
+
output_1 = pipe(**inputs)[0]
|
| 350 |
+
|
| 351 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 352 |
+
inputs["num_inference_steps"] = steps
|
| 353 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 354 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 355 |
+
|
| 356 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 357 |
+
inputs["num_inference_steps"] = steps
|
| 358 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 359 |
+
output_3 = pipe(**inputs, control_guidance_start=[0.1, 0.3], control_guidance_end=[0.2, 0.7])[0]
|
| 360 |
+
|
| 361 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 362 |
+
inputs["num_inference_steps"] = steps
|
| 363 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 364 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5, 0.8])[0]
|
| 365 |
+
|
| 366 |
+
# make sure that all outputs are different
|
| 367 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 368 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 369 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 370 |
+
|
| 371 |
+
def test_attention_slicing_forward_pass(self):
|
| 372 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 373 |
+
|
| 374 |
+
@unittest.skipIf(
|
| 375 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 376 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 377 |
+
)
|
| 378 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 379 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 380 |
+
|
| 381 |
+
def test_inference_batch_single_identical(self):
|
| 382 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 383 |
+
|
| 384 |
+
def test_ip_adapter(self):
|
| 385 |
+
expected_pipe_slice = None
|
| 386 |
+
if torch_device == "cpu":
|
| 387 |
+
expected_pipe_slice = np.array([0.5293, 0.7339, 0.6642, 0.3950, 0.5212, 0.5175, 0.7002, 0.5907, 0.5182])
|
| 388 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 389 |
+
|
| 390 |
+
def test_save_pretrained_raise_not_implemented_exception(self):
|
| 391 |
+
components = self.get_dummy_components()
|
| 392 |
+
pipe = self.pipeline_class(**components)
|
| 393 |
+
pipe.to(torch_device)
|
| 394 |
+
pipe.set_progress_bar_config(disable=None)
|
| 395 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 396 |
+
try:
|
| 397 |
+
# save_pretrained is not implemented for Multi-ControlNet
|
| 398 |
+
pipe.save_pretrained(tmpdir)
|
| 399 |
+
except NotImplementedError:
|
| 400 |
+
pass
|
| 401 |
+
|
| 402 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 403 |
+
extra_required_param_value_dict = {
|
| 404 |
+
"device": torch.device(torch_device).type,
|
| 405 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 406 |
+
}
|
| 407 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 408 |
+
|
| 409 |
+
|
| 410 |
+
@slow
|
| 411 |
+
@require_torch_accelerator
|
| 412 |
+
class ControlNetImg2ImgPipelineSlowTests(unittest.TestCase):
|
| 413 |
+
def setUp(self):
|
| 414 |
+
super().setUp()
|
| 415 |
+
gc.collect()
|
| 416 |
+
backend_empty_cache(torch_device)
|
| 417 |
+
|
| 418 |
+
def tearDown(self):
|
| 419 |
+
super().tearDown()
|
| 420 |
+
gc.collect()
|
| 421 |
+
backend_empty_cache(torch_device)
|
| 422 |
+
|
| 423 |
+
def test_canny(self):
|
| 424 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 425 |
+
|
| 426 |
+
pipe = StableDiffusionControlNetImg2ImgPipeline.from_pretrained(
|
| 427 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 428 |
+
)
|
| 429 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 430 |
+
pipe.set_progress_bar_config(disable=None)
|
| 431 |
+
|
| 432 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 433 |
+
prompt = "evil space-punk bird"
|
| 434 |
+
control_image = load_image(
|
| 435 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 436 |
+
).resize((512, 512))
|
| 437 |
+
image = load_image(
|
| 438 |
+
"https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png"
|
| 439 |
+
).resize((512, 512))
|
| 440 |
+
|
| 441 |
+
output = pipe(
|
| 442 |
+
prompt,
|
| 443 |
+
image,
|
| 444 |
+
control_image=control_image,
|
| 445 |
+
generator=generator,
|
| 446 |
+
output_type="np",
|
| 447 |
+
num_inference_steps=50,
|
| 448 |
+
strength=0.6,
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
image = output.images[0]
|
| 452 |
+
|
| 453 |
+
assert image.shape == (512, 512, 3)
|
| 454 |
+
|
| 455 |
+
expected_image = load_numpy(
|
| 456 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/img2img.npy"
|
| 457 |
+
)
|
| 458 |
+
|
| 459 |
+
assert np.abs(expected_image - image).max() < 9e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_inpaint.py
ADDED
|
@@ -0,0 +1,575 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
# This model implementation is heavily based on:
|
| 17 |
+
|
| 18 |
+
import gc
|
| 19 |
+
import random
|
| 20 |
+
import tempfile
|
| 21 |
+
import unittest
|
| 22 |
+
|
| 23 |
+
import numpy as np
|
| 24 |
+
import torch
|
| 25 |
+
from PIL import Image
|
| 26 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
|
| 27 |
+
|
| 28 |
+
from diffusers import (
|
| 29 |
+
AutoencoderKL,
|
| 30 |
+
ControlNetModel,
|
| 31 |
+
DDIMScheduler,
|
| 32 |
+
StableDiffusionControlNetInpaintPipeline,
|
| 33 |
+
UNet2DConditionModel,
|
| 34 |
+
)
|
| 35 |
+
from diffusers.pipelines.controlnet.pipeline_controlnet import MultiControlNetModel
|
| 36 |
+
from diffusers.utils import load_image
|
| 37 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 38 |
+
from diffusers.utils.testing_utils import (
|
| 39 |
+
backend_empty_cache,
|
| 40 |
+
enable_full_determinism,
|
| 41 |
+
floats_tensor,
|
| 42 |
+
load_numpy,
|
| 43 |
+
numpy_cosine_similarity_distance,
|
| 44 |
+
require_torch_accelerator,
|
| 45 |
+
slow,
|
| 46 |
+
torch_device,
|
| 47 |
+
)
|
| 48 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 49 |
+
|
| 50 |
+
from ..pipeline_params import (
|
| 51 |
+
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
|
| 52 |
+
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
|
| 53 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 54 |
+
)
|
| 55 |
+
from ..test_pipelines_common import PipelineKarrasSchedulerTesterMixin, PipelineLatentTesterMixin, PipelineTesterMixin
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
enable_full_determinism()
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
class ControlNetInpaintPipelineFastTests(
|
| 62 |
+
PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
|
| 63 |
+
):
|
| 64 |
+
pipeline_class = StableDiffusionControlNetInpaintPipeline
|
| 65 |
+
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
|
| 66 |
+
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
|
| 67 |
+
image_params = frozenset({"control_image"}) # skip `image` and `mask` for now, only test for control_image
|
| 68 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 69 |
+
|
| 70 |
+
def get_dummy_components(self):
|
| 71 |
+
torch.manual_seed(0)
|
| 72 |
+
unet = UNet2DConditionModel(
|
| 73 |
+
block_out_channels=(32, 64),
|
| 74 |
+
layers_per_block=2,
|
| 75 |
+
sample_size=32,
|
| 76 |
+
in_channels=9,
|
| 77 |
+
out_channels=4,
|
| 78 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 79 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 80 |
+
cross_attention_dim=32,
|
| 81 |
+
)
|
| 82 |
+
torch.manual_seed(0)
|
| 83 |
+
controlnet = ControlNetModel(
|
| 84 |
+
block_out_channels=(32, 64),
|
| 85 |
+
layers_per_block=2,
|
| 86 |
+
in_channels=4,
|
| 87 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 88 |
+
cross_attention_dim=32,
|
| 89 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 90 |
+
)
|
| 91 |
+
torch.manual_seed(0)
|
| 92 |
+
scheduler = DDIMScheduler(
|
| 93 |
+
beta_start=0.00085,
|
| 94 |
+
beta_end=0.012,
|
| 95 |
+
beta_schedule="scaled_linear",
|
| 96 |
+
clip_sample=False,
|
| 97 |
+
set_alpha_to_one=False,
|
| 98 |
+
)
|
| 99 |
+
torch.manual_seed(0)
|
| 100 |
+
vae = AutoencoderKL(
|
| 101 |
+
block_out_channels=[32, 64],
|
| 102 |
+
in_channels=3,
|
| 103 |
+
out_channels=3,
|
| 104 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 105 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 106 |
+
latent_channels=4,
|
| 107 |
+
)
|
| 108 |
+
torch.manual_seed(0)
|
| 109 |
+
text_encoder_config = CLIPTextConfig(
|
| 110 |
+
bos_token_id=0,
|
| 111 |
+
eos_token_id=2,
|
| 112 |
+
hidden_size=32,
|
| 113 |
+
intermediate_size=37,
|
| 114 |
+
layer_norm_eps=1e-05,
|
| 115 |
+
num_attention_heads=4,
|
| 116 |
+
num_hidden_layers=5,
|
| 117 |
+
pad_token_id=1,
|
| 118 |
+
vocab_size=1000,
|
| 119 |
+
)
|
| 120 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 121 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 122 |
+
|
| 123 |
+
components = {
|
| 124 |
+
"unet": unet,
|
| 125 |
+
"controlnet": controlnet,
|
| 126 |
+
"scheduler": scheduler,
|
| 127 |
+
"vae": vae,
|
| 128 |
+
"text_encoder": text_encoder,
|
| 129 |
+
"tokenizer": tokenizer,
|
| 130 |
+
"safety_checker": None,
|
| 131 |
+
"feature_extractor": None,
|
| 132 |
+
"image_encoder": None,
|
| 133 |
+
}
|
| 134 |
+
return components
|
| 135 |
+
|
| 136 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 137 |
+
if str(device).startswith("mps"):
|
| 138 |
+
generator = torch.manual_seed(seed)
|
| 139 |
+
else:
|
| 140 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 141 |
+
|
| 142 |
+
controlnet_embedder_scale_factor = 2
|
| 143 |
+
control_image = randn_tensor(
|
| 144 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 145 |
+
generator=generator,
|
| 146 |
+
device=torch.device(device),
|
| 147 |
+
)
|
| 148 |
+
init_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 149 |
+
init_image = init_image.cpu().permute(0, 2, 3, 1)[0]
|
| 150 |
+
|
| 151 |
+
image = Image.fromarray(np.uint8(init_image)).convert("RGB").resize((64, 64))
|
| 152 |
+
mask_image = Image.fromarray(np.uint8(init_image + 4)).convert("RGB").resize((64, 64))
|
| 153 |
+
|
| 154 |
+
inputs = {
|
| 155 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 156 |
+
"generator": generator,
|
| 157 |
+
"num_inference_steps": 2,
|
| 158 |
+
"guidance_scale": 6.0,
|
| 159 |
+
"output_type": "np",
|
| 160 |
+
"image": image,
|
| 161 |
+
"mask_image": mask_image,
|
| 162 |
+
"control_image": control_image,
|
| 163 |
+
}
|
| 164 |
+
|
| 165 |
+
return inputs
|
| 166 |
+
|
| 167 |
+
def test_attention_slicing_forward_pass(self):
|
| 168 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 169 |
+
|
| 170 |
+
@unittest.skipIf(
|
| 171 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 172 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 173 |
+
)
|
| 174 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 175 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 176 |
+
|
| 177 |
+
def test_inference_batch_single_identical(self):
|
| 178 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 179 |
+
|
| 180 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 181 |
+
extra_required_param_value_dict = {
|
| 182 |
+
"device": torch.device(torch_device).type,
|
| 183 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 184 |
+
}
|
| 185 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 186 |
+
|
| 187 |
+
|
| 188 |
+
class ControlNetSimpleInpaintPipelineFastTests(ControlNetInpaintPipelineFastTests):
|
| 189 |
+
pipeline_class = StableDiffusionControlNetInpaintPipeline
|
| 190 |
+
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
|
| 191 |
+
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
|
| 192 |
+
image_params = frozenset([])
|
| 193 |
+
|
| 194 |
+
def get_dummy_components(self):
|
| 195 |
+
torch.manual_seed(0)
|
| 196 |
+
unet = UNet2DConditionModel(
|
| 197 |
+
block_out_channels=(32, 64),
|
| 198 |
+
layers_per_block=2,
|
| 199 |
+
sample_size=32,
|
| 200 |
+
in_channels=4,
|
| 201 |
+
out_channels=4,
|
| 202 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 203 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 204 |
+
cross_attention_dim=32,
|
| 205 |
+
)
|
| 206 |
+
torch.manual_seed(0)
|
| 207 |
+
controlnet = ControlNetModel(
|
| 208 |
+
block_out_channels=(32, 64),
|
| 209 |
+
layers_per_block=2,
|
| 210 |
+
in_channels=4,
|
| 211 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 212 |
+
cross_attention_dim=32,
|
| 213 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 214 |
+
)
|
| 215 |
+
torch.manual_seed(0)
|
| 216 |
+
scheduler = DDIMScheduler(
|
| 217 |
+
beta_start=0.00085,
|
| 218 |
+
beta_end=0.012,
|
| 219 |
+
beta_schedule="scaled_linear",
|
| 220 |
+
clip_sample=False,
|
| 221 |
+
set_alpha_to_one=False,
|
| 222 |
+
)
|
| 223 |
+
torch.manual_seed(0)
|
| 224 |
+
vae = AutoencoderKL(
|
| 225 |
+
block_out_channels=[32, 64],
|
| 226 |
+
in_channels=3,
|
| 227 |
+
out_channels=3,
|
| 228 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 229 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 230 |
+
latent_channels=4,
|
| 231 |
+
)
|
| 232 |
+
torch.manual_seed(0)
|
| 233 |
+
text_encoder_config = CLIPTextConfig(
|
| 234 |
+
bos_token_id=0,
|
| 235 |
+
eos_token_id=2,
|
| 236 |
+
hidden_size=32,
|
| 237 |
+
intermediate_size=37,
|
| 238 |
+
layer_norm_eps=1e-05,
|
| 239 |
+
num_attention_heads=4,
|
| 240 |
+
num_hidden_layers=5,
|
| 241 |
+
pad_token_id=1,
|
| 242 |
+
vocab_size=1000,
|
| 243 |
+
)
|
| 244 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 245 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 246 |
+
|
| 247 |
+
components = {
|
| 248 |
+
"unet": unet,
|
| 249 |
+
"controlnet": controlnet,
|
| 250 |
+
"scheduler": scheduler,
|
| 251 |
+
"vae": vae,
|
| 252 |
+
"text_encoder": text_encoder,
|
| 253 |
+
"tokenizer": tokenizer,
|
| 254 |
+
"safety_checker": None,
|
| 255 |
+
"feature_extractor": None,
|
| 256 |
+
"image_encoder": None,
|
| 257 |
+
}
|
| 258 |
+
return components
|
| 259 |
+
|
| 260 |
+
|
| 261 |
+
class MultiControlNetInpaintPipelineFastTests(
|
| 262 |
+
PipelineTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
|
| 263 |
+
):
|
| 264 |
+
pipeline_class = StableDiffusionControlNetInpaintPipeline
|
| 265 |
+
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS
|
| 266 |
+
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
|
| 267 |
+
|
| 268 |
+
supports_dduf = False
|
| 269 |
+
|
| 270 |
+
def get_dummy_components(self):
|
| 271 |
+
torch.manual_seed(0)
|
| 272 |
+
unet = UNet2DConditionModel(
|
| 273 |
+
block_out_channels=(32, 64),
|
| 274 |
+
layers_per_block=2,
|
| 275 |
+
sample_size=32,
|
| 276 |
+
in_channels=9,
|
| 277 |
+
out_channels=4,
|
| 278 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 279 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 280 |
+
cross_attention_dim=32,
|
| 281 |
+
)
|
| 282 |
+
torch.manual_seed(0)
|
| 283 |
+
|
| 284 |
+
def init_weights(m):
|
| 285 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 286 |
+
torch.nn.init.normal_(m.weight)
|
| 287 |
+
m.bias.data.fill_(1.0)
|
| 288 |
+
|
| 289 |
+
controlnet1 = ControlNetModel(
|
| 290 |
+
block_out_channels=(32, 64),
|
| 291 |
+
layers_per_block=2,
|
| 292 |
+
in_channels=4,
|
| 293 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 294 |
+
cross_attention_dim=32,
|
| 295 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 296 |
+
)
|
| 297 |
+
controlnet1.controlnet_down_blocks.apply(init_weights)
|
| 298 |
+
|
| 299 |
+
torch.manual_seed(0)
|
| 300 |
+
controlnet2 = ControlNetModel(
|
| 301 |
+
block_out_channels=(32, 64),
|
| 302 |
+
layers_per_block=2,
|
| 303 |
+
in_channels=4,
|
| 304 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 305 |
+
cross_attention_dim=32,
|
| 306 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 307 |
+
)
|
| 308 |
+
controlnet2.controlnet_down_blocks.apply(init_weights)
|
| 309 |
+
|
| 310 |
+
torch.manual_seed(0)
|
| 311 |
+
scheduler = DDIMScheduler(
|
| 312 |
+
beta_start=0.00085,
|
| 313 |
+
beta_end=0.012,
|
| 314 |
+
beta_schedule="scaled_linear",
|
| 315 |
+
clip_sample=False,
|
| 316 |
+
set_alpha_to_one=False,
|
| 317 |
+
)
|
| 318 |
+
torch.manual_seed(0)
|
| 319 |
+
vae = AutoencoderKL(
|
| 320 |
+
block_out_channels=[32, 64],
|
| 321 |
+
in_channels=3,
|
| 322 |
+
out_channels=3,
|
| 323 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 324 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 325 |
+
latent_channels=4,
|
| 326 |
+
)
|
| 327 |
+
torch.manual_seed(0)
|
| 328 |
+
text_encoder_config = CLIPTextConfig(
|
| 329 |
+
bos_token_id=0,
|
| 330 |
+
eos_token_id=2,
|
| 331 |
+
hidden_size=32,
|
| 332 |
+
intermediate_size=37,
|
| 333 |
+
layer_norm_eps=1e-05,
|
| 334 |
+
num_attention_heads=4,
|
| 335 |
+
num_hidden_layers=5,
|
| 336 |
+
pad_token_id=1,
|
| 337 |
+
vocab_size=1000,
|
| 338 |
+
)
|
| 339 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 340 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 341 |
+
|
| 342 |
+
controlnet = MultiControlNetModel([controlnet1, controlnet2])
|
| 343 |
+
|
| 344 |
+
components = {
|
| 345 |
+
"unet": unet,
|
| 346 |
+
"controlnet": controlnet,
|
| 347 |
+
"scheduler": scheduler,
|
| 348 |
+
"vae": vae,
|
| 349 |
+
"text_encoder": text_encoder,
|
| 350 |
+
"tokenizer": tokenizer,
|
| 351 |
+
"safety_checker": None,
|
| 352 |
+
"feature_extractor": None,
|
| 353 |
+
"image_encoder": None,
|
| 354 |
+
}
|
| 355 |
+
return components
|
| 356 |
+
|
| 357 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 358 |
+
if str(device).startswith("mps"):
|
| 359 |
+
generator = torch.manual_seed(seed)
|
| 360 |
+
else:
|
| 361 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 362 |
+
|
| 363 |
+
controlnet_embedder_scale_factor = 2
|
| 364 |
+
|
| 365 |
+
control_image = [
|
| 366 |
+
randn_tensor(
|
| 367 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 368 |
+
generator=generator,
|
| 369 |
+
device=torch.device(device),
|
| 370 |
+
),
|
| 371 |
+
randn_tensor(
|
| 372 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 373 |
+
generator=generator,
|
| 374 |
+
device=torch.device(device),
|
| 375 |
+
),
|
| 376 |
+
]
|
| 377 |
+
init_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 378 |
+
init_image = init_image.cpu().permute(0, 2, 3, 1)[0]
|
| 379 |
+
|
| 380 |
+
image = Image.fromarray(np.uint8(init_image)).convert("RGB").resize((64, 64))
|
| 381 |
+
mask_image = Image.fromarray(np.uint8(init_image + 4)).convert("RGB").resize((64, 64))
|
| 382 |
+
|
| 383 |
+
inputs = {
|
| 384 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 385 |
+
"generator": generator,
|
| 386 |
+
"num_inference_steps": 2,
|
| 387 |
+
"guidance_scale": 6.0,
|
| 388 |
+
"output_type": "np",
|
| 389 |
+
"image": image,
|
| 390 |
+
"mask_image": mask_image,
|
| 391 |
+
"control_image": control_image,
|
| 392 |
+
}
|
| 393 |
+
|
| 394 |
+
return inputs
|
| 395 |
+
|
| 396 |
+
def test_control_guidance_switch(self):
|
| 397 |
+
components = self.get_dummy_components()
|
| 398 |
+
pipe = self.pipeline_class(**components)
|
| 399 |
+
pipe.to(torch_device)
|
| 400 |
+
|
| 401 |
+
scale = 10.0
|
| 402 |
+
steps = 4
|
| 403 |
+
|
| 404 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 405 |
+
inputs["num_inference_steps"] = steps
|
| 406 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 407 |
+
output_1 = pipe(**inputs)[0]
|
| 408 |
+
|
| 409 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 410 |
+
inputs["num_inference_steps"] = steps
|
| 411 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 412 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 413 |
+
|
| 414 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 415 |
+
inputs["num_inference_steps"] = steps
|
| 416 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 417 |
+
output_3 = pipe(**inputs, control_guidance_start=[0.1, 0.3], control_guidance_end=[0.2, 0.7])[0]
|
| 418 |
+
|
| 419 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 420 |
+
inputs["num_inference_steps"] = steps
|
| 421 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 422 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5, 0.8])[0]
|
| 423 |
+
|
| 424 |
+
# make sure that all outputs are different
|
| 425 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 426 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 427 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 428 |
+
|
| 429 |
+
def test_attention_slicing_forward_pass(self):
|
| 430 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 431 |
+
|
| 432 |
+
@unittest.skipIf(
|
| 433 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 434 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 435 |
+
)
|
| 436 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 437 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 438 |
+
|
| 439 |
+
def test_inference_batch_single_identical(self):
|
| 440 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 441 |
+
|
| 442 |
+
def test_save_pretrained_raise_not_implemented_exception(self):
|
| 443 |
+
components = self.get_dummy_components()
|
| 444 |
+
pipe = self.pipeline_class(**components)
|
| 445 |
+
pipe.to(torch_device)
|
| 446 |
+
pipe.set_progress_bar_config(disable=None)
|
| 447 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 448 |
+
try:
|
| 449 |
+
# save_pretrained is not implemented for Multi-ControlNet
|
| 450 |
+
pipe.save_pretrained(tmpdir)
|
| 451 |
+
except NotImplementedError:
|
| 452 |
+
pass
|
| 453 |
+
|
| 454 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 455 |
+
extra_required_param_value_dict = {
|
| 456 |
+
"device": torch.device(torch_device).type,
|
| 457 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 458 |
+
}
|
| 459 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 460 |
+
|
| 461 |
+
|
| 462 |
+
@slow
|
| 463 |
+
@require_torch_accelerator
|
| 464 |
+
class ControlNetInpaintPipelineSlowTests(unittest.TestCase):
|
| 465 |
+
def setUp(self):
|
| 466 |
+
super().setUp()
|
| 467 |
+
gc.collect()
|
| 468 |
+
backend_empty_cache(torch_device)
|
| 469 |
+
|
| 470 |
+
def tearDown(self):
|
| 471 |
+
super().tearDown()
|
| 472 |
+
gc.collect()
|
| 473 |
+
backend_empty_cache(torch_device)
|
| 474 |
+
|
| 475 |
+
def test_canny(self):
|
| 476 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/sd-controlnet-canny")
|
| 477 |
+
|
| 478 |
+
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
|
| 479 |
+
"botp/stable-diffusion-v1-5-inpainting", safety_checker=None, controlnet=controlnet
|
| 480 |
+
)
|
| 481 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 482 |
+
pipe.set_progress_bar_config(disable=None)
|
| 483 |
+
|
| 484 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 485 |
+
image = load_image(
|
| 486 |
+
"https://huggingface.co/lllyasviel/sd-controlnet-canny/resolve/main/images/bird.png"
|
| 487 |
+
).resize((512, 512))
|
| 488 |
+
|
| 489 |
+
mask_image = load_image(
|
| 490 |
+
"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main"
|
| 491 |
+
"/stable_diffusion_inpaint/input_bench_mask.png"
|
| 492 |
+
).resize((512, 512))
|
| 493 |
+
|
| 494 |
+
prompt = "pitch black hole"
|
| 495 |
+
|
| 496 |
+
control_image = load_image(
|
| 497 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 498 |
+
).resize((512, 512))
|
| 499 |
+
|
| 500 |
+
output = pipe(
|
| 501 |
+
prompt,
|
| 502 |
+
image=image,
|
| 503 |
+
mask_image=mask_image,
|
| 504 |
+
control_image=control_image,
|
| 505 |
+
generator=generator,
|
| 506 |
+
output_type="np",
|
| 507 |
+
num_inference_steps=3,
|
| 508 |
+
)
|
| 509 |
+
|
| 510 |
+
image = output.images[0]
|
| 511 |
+
|
| 512 |
+
assert image.shape == (512, 512, 3)
|
| 513 |
+
|
| 514 |
+
expected_image = load_numpy(
|
| 515 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/inpaint.npy"
|
| 516 |
+
)
|
| 517 |
+
|
| 518 |
+
assert np.abs(expected_image - image).max() < 9e-2
|
| 519 |
+
|
| 520 |
+
def test_inpaint(self):
|
| 521 |
+
controlnet = ControlNetModel.from_pretrained("lllyasviel/control_v11p_sd15_inpaint")
|
| 522 |
+
|
| 523 |
+
pipe = StableDiffusionControlNetInpaintPipeline.from_pretrained(
|
| 524 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", safety_checker=None, controlnet=controlnet
|
| 525 |
+
)
|
| 526 |
+
pipe.scheduler = DDIMScheduler.from_config(pipe.scheduler.config)
|
| 527 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 528 |
+
pipe.set_progress_bar_config(disable=None)
|
| 529 |
+
|
| 530 |
+
generator = torch.Generator(device="cpu").manual_seed(33)
|
| 531 |
+
|
| 532 |
+
init_image = load_image(
|
| 533 |
+
"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy.png"
|
| 534 |
+
)
|
| 535 |
+
init_image = init_image.resize((512, 512))
|
| 536 |
+
|
| 537 |
+
mask_image = load_image(
|
| 538 |
+
"https://huggingface.co/datasets/diffusers/test-arrays/resolve/main/stable_diffusion_inpaint/boy_mask.png"
|
| 539 |
+
)
|
| 540 |
+
mask_image = mask_image.resize((512, 512))
|
| 541 |
+
|
| 542 |
+
prompt = "a handsome man with ray-ban sunglasses"
|
| 543 |
+
|
| 544 |
+
def make_inpaint_condition(image, image_mask):
|
| 545 |
+
image = np.array(image.convert("RGB")).astype(np.float32) / 255.0
|
| 546 |
+
image_mask = np.array(image_mask.convert("L")).astype(np.float32) / 255.0
|
| 547 |
+
|
| 548 |
+
assert image.shape[0:1] == image_mask.shape[0:1], "image and image_mask must have the same image size"
|
| 549 |
+
image[image_mask > 0.5] = -1.0 # set as masked pixel
|
| 550 |
+
image = np.expand_dims(image, 0).transpose(0, 3, 1, 2)
|
| 551 |
+
image = torch.from_numpy(image)
|
| 552 |
+
return image
|
| 553 |
+
|
| 554 |
+
control_image = make_inpaint_condition(init_image, mask_image)
|
| 555 |
+
|
| 556 |
+
output = pipe(
|
| 557 |
+
prompt,
|
| 558 |
+
image=init_image,
|
| 559 |
+
mask_image=mask_image,
|
| 560 |
+
control_image=control_image,
|
| 561 |
+
guidance_scale=9.0,
|
| 562 |
+
eta=1.0,
|
| 563 |
+
generator=generator,
|
| 564 |
+
num_inference_steps=20,
|
| 565 |
+
output_type="np",
|
| 566 |
+
)
|
| 567 |
+
image = output.images[0]
|
| 568 |
+
|
| 569 |
+
assert image.shape == (512, 512, 3)
|
| 570 |
+
|
| 571 |
+
expected_image = load_numpy(
|
| 572 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/boy_ray_ban.npy"
|
| 573 |
+
)
|
| 574 |
+
|
| 575 |
+
assert numpy_cosine_similarity_distance(expected_image.flatten(), image.flatten()) < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_inpaint_sdxl.py
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import random
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from PIL import Image
|
| 22 |
+
from transformers import (
|
| 23 |
+
CLIPImageProcessor,
|
| 24 |
+
CLIPTextConfig,
|
| 25 |
+
CLIPTextModel,
|
| 26 |
+
CLIPTextModelWithProjection,
|
| 27 |
+
CLIPTokenizer,
|
| 28 |
+
CLIPVisionConfig,
|
| 29 |
+
CLIPVisionModelWithProjection,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from diffusers import (
|
| 33 |
+
AutoencoderKL,
|
| 34 |
+
ControlNetModel,
|
| 35 |
+
EulerDiscreteScheduler,
|
| 36 |
+
StableDiffusionXLControlNetInpaintPipeline,
|
| 37 |
+
UNet2DConditionModel,
|
| 38 |
+
)
|
| 39 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 40 |
+
from diffusers.utils.testing_utils import (
|
| 41 |
+
enable_full_determinism,
|
| 42 |
+
floats_tensor,
|
| 43 |
+
require_torch_accelerator,
|
| 44 |
+
torch_device,
|
| 45 |
+
)
|
| 46 |
+
|
| 47 |
+
from ..pipeline_params import (
|
| 48 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 49 |
+
TEXT_TO_IMAGE_BATCH_PARAMS,
|
| 50 |
+
TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
|
| 51 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 52 |
+
TEXT_TO_IMAGE_PARAMS,
|
| 53 |
+
)
|
| 54 |
+
from ..test_pipelines_common import (
|
| 55 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 56 |
+
PipelineLatentTesterMixin,
|
| 57 |
+
PipelineTesterMixin,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
enable_full_determinism()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class ControlNetPipelineSDXLFastTests(
|
| 65 |
+
PipelineLatentTesterMixin, PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
|
| 66 |
+
):
|
| 67 |
+
pipeline_class = StableDiffusionXLControlNetInpaintPipeline
|
| 68 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 69 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 70 |
+
image_params = frozenset(IMAGE_TO_IMAGE_IMAGE_PARAMS.union({"mask_image", "control_image"}))
|
| 71 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 72 |
+
callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union(
|
| 73 |
+
{
|
| 74 |
+
"add_text_embeds",
|
| 75 |
+
"add_time_ids",
|
| 76 |
+
"mask",
|
| 77 |
+
"masked_image_latents",
|
| 78 |
+
}
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
supports_dduf = False
|
| 82 |
+
|
| 83 |
+
def get_dummy_components(self):
|
| 84 |
+
torch.manual_seed(0)
|
| 85 |
+
unet = UNet2DConditionModel(
|
| 86 |
+
block_out_channels=(32, 64),
|
| 87 |
+
layers_per_block=2,
|
| 88 |
+
sample_size=32,
|
| 89 |
+
in_channels=4,
|
| 90 |
+
out_channels=4,
|
| 91 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 92 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 93 |
+
# SD2-specific config below
|
| 94 |
+
attention_head_dim=(2, 4),
|
| 95 |
+
use_linear_projection=True,
|
| 96 |
+
addition_embed_type="text_time",
|
| 97 |
+
addition_time_embed_dim=8,
|
| 98 |
+
transformer_layers_per_block=(1, 2),
|
| 99 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 100 |
+
cross_attention_dim=64,
|
| 101 |
+
)
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
controlnet = ControlNetModel(
|
| 104 |
+
block_out_channels=(32, 64),
|
| 105 |
+
layers_per_block=2,
|
| 106 |
+
in_channels=4,
|
| 107 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 108 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 109 |
+
# SD2-specific config below
|
| 110 |
+
attention_head_dim=(2, 4),
|
| 111 |
+
use_linear_projection=True,
|
| 112 |
+
addition_embed_type="text_time",
|
| 113 |
+
addition_time_embed_dim=8,
|
| 114 |
+
transformer_layers_per_block=(1, 2),
|
| 115 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 116 |
+
cross_attention_dim=64,
|
| 117 |
+
)
|
| 118 |
+
scheduler = EulerDiscreteScheduler(
|
| 119 |
+
beta_start=0.00085,
|
| 120 |
+
beta_end=0.012,
|
| 121 |
+
steps_offset=1,
|
| 122 |
+
beta_schedule="scaled_linear",
|
| 123 |
+
timestep_spacing="leading",
|
| 124 |
+
)
|
| 125 |
+
torch.manual_seed(0)
|
| 126 |
+
vae = AutoencoderKL(
|
| 127 |
+
block_out_channels=[32, 64],
|
| 128 |
+
in_channels=3,
|
| 129 |
+
out_channels=3,
|
| 130 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 131 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 132 |
+
latent_channels=4,
|
| 133 |
+
)
|
| 134 |
+
torch.manual_seed(0)
|
| 135 |
+
text_encoder_config = CLIPTextConfig(
|
| 136 |
+
bos_token_id=0,
|
| 137 |
+
eos_token_id=2,
|
| 138 |
+
hidden_size=32,
|
| 139 |
+
intermediate_size=37,
|
| 140 |
+
layer_norm_eps=1e-05,
|
| 141 |
+
num_attention_heads=4,
|
| 142 |
+
num_hidden_layers=5,
|
| 143 |
+
pad_token_id=1,
|
| 144 |
+
vocab_size=1000,
|
| 145 |
+
# SD2-specific config below
|
| 146 |
+
hidden_act="gelu",
|
| 147 |
+
projection_dim=32,
|
| 148 |
+
)
|
| 149 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 150 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 151 |
+
|
| 152 |
+
torch.manual_seed(0)
|
| 153 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 154 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 155 |
+
|
| 156 |
+
image_encoder_config = CLIPVisionConfig(
|
| 157 |
+
hidden_size=32,
|
| 158 |
+
image_size=224,
|
| 159 |
+
projection_dim=32,
|
| 160 |
+
intermediate_size=37,
|
| 161 |
+
num_attention_heads=4,
|
| 162 |
+
num_channels=3,
|
| 163 |
+
num_hidden_layers=5,
|
| 164 |
+
patch_size=14,
|
| 165 |
+
)
|
| 166 |
+
|
| 167 |
+
image_encoder = CLIPVisionModelWithProjection(image_encoder_config)
|
| 168 |
+
|
| 169 |
+
feature_extractor = CLIPImageProcessor(
|
| 170 |
+
crop_size=224,
|
| 171 |
+
do_center_crop=True,
|
| 172 |
+
do_normalize=True,
|
| 173 |
+
do_resize=True,
|
| 174 |
+
image_mean=[0.48145466, 0.4578275, 0.40821073],
|
| 175 |
+
image_std=[0.26862954, 0.26130258, 0.27577711],
|
| 176 |
+
resample=3,
|
| 177 |
+
size=224,
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
components = {
|
| 181 |
+
"unet": unet,
|
| 182 |
+
"controlnet": controlnet,
|
| 183 |
+
"scheduler": scheduler,
|
| 184 |
+
"vae": vae,
|
| 185 |
+
"text_encoder": text_encoder,
|
| 186 |
+
"tokenizer": tokenizer,
|
| 187 |
+
"text_encoder_2": text_encoder_2,
|
| 188 |
+
"tokenizer_2": tokenizer_2,
|
| 189 |
+
"image_encoder": image_encoder,
|
| 190 |
+
"feature_extractor": feature_extractor,
|
| 191 |
+
}
|
| 192 |
+
return components
|
| 193 |
+
|
| 194 |
+
def get_dummy_inputs(self, device, seed=0, img_res=64):
|
| 195 |
+
if str(device).startswith("mps"):
|
| 196 |
+
generator = torch.manual_seed(seed)
|
| 197 |
+
else:
|
| 198 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 199 |
+
|
| 200 |
+
# Get random floats in [0, 1] as image
|
| 201 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 202 |
+
image = image.cpu().permute(0, 2, 3, 1)[0]
|
| 203 |
+
mask_image = torch.ones_like(image)
|
| 204 |
+
controlnet_embedder_scale_factor = 2
|
| 205 |
+
control_image = (
|
| 206 |
+
floats_tensor(
|
| 207 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 208 |
+
rng=random.Random(seed),
|
| 209 |
+
)
|
| 210 |
+
.to(device)
|
| 211 |
+
.cpu()
|
| 212 |
+
)
|
| 213 |
+
control_image = control_image.cpu().permute(0, 2, 3, 1)[0]
|
| 214 |
+
# Convert image and mask_image to [0, 255]
|
| 215 |
+
image = 255 * image
|
| 216 |
+
mask_image = 255 * mask_image
|
| 217 |
+
control_image = 255 * control_image
|
| 218 |
+
# Convert to PIL image
|
| 219 |
+
init_image = Image.fromarray(np.uint8(image)).convert("RGB").resize((img_res, img_res))
|
| 220 |
+
mask_image = Image.fromarray(np.uint8(mask_image)).convert("L").resize((img_res, img_res))
|
| 221 |
+
control_image = Image.fromarray(np.uint8(control_image)).convert("RGB").resize((img_res, img_res))
|
| 222 |
+
|
| 223 |
+
inputs = {
|
| 224 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 225 |
+
"generator": generator,
|
| 226 |
+
"num_inference_steps": 2,
|
| 227 |
+
"guidance_scale": 6.0,
|
| 228 |
+
"output_type": "np",
|
| 229 |
+
"image": init_image,
|
| 230 |
+
"mask_image": mask_image,
|
| 231 |
+
"control_image": control_image,
|
| 232 |
+
}
|
| 233 |
+
return inputs
|
| 234 |
+
|
| 235 |
+
def test_attention_slicing_forward_pass(self):
|
| 236 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 237 |
+
|
| 238 |
+
@unittest.skipIf(
|
| 239 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 240 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 241 |
+
)
|
| 242 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 243 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 244 |
+
|
| 245 |
+
def test_inference_batch_single_identical(self):
|
| 246 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 247 |
+
|
| 248 |
+
@require_torch_accelerator
|
| 249 |
+
def test_stable_diffusion_xl_offloads(self):
|
| 250 |
+
pipes = []
|
| 251 |
+
components = self.get_dummy_components()
|
| 252 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 253 |
+
pipes.append(sd_pipe)
|
| 254 |
+
|
| 255 |
+
components = self.get_dummy_components()
|
| 256 |
+
sd_pipe = self.pipeline_class(**components)
|
| 257 |
+
sd_pipe.enable_model_cpu_offload(device=torch_device)
|
| 258 |
+
pipes.append(sd_pipe)
|
| 259 |
+
|
| 260 |
+
components = self.get_dummy_components()
|
| 261 |
+
sd_pipe = self.pipeline_class(**components)
|
| 262 |
+
sd_pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 263 |
+
pipes.append(sd_pipe)
|
| 264 |
+
|
| 265 |
+
image_slices = []
|
| 266 |
+
for pipe in pipes:
|
| 267 |
+
pipe.unet.set_default_attn_processor()
|
| 268 |
+
|
| 269 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 270 |
+
image = pipe(**inputs).images
|
| 271 |
+
|
| 272 |
+
image_slices.append(image[0, -3:, -3:, -1].flatten())
|
| 273 |
+
|
| 274 |
+
assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
|
| 275 |
+
assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
|
| 276 |
+
|
| 277 |
+
def test_stable_diffusion_xl_multi_prompts(self):
|
| 278 |
+
components = self.get_dummy_components()
|
| 279 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 280 |
+
|
| 281 |
+
# forward with single prompt
|
| 282 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 283 |
+
output = sd_pipe(**inputs)
|
| 284 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 285 |
+
|
| 286 |
+
# forward with same prompt duplicated
|
| 287 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 288 |
+
inputs["prompt_2"] = inputs["prompt"]
|
| 289 |
+
output = sd_pipe(**inputs)
|
| 290 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 291 |
+
|
| 292 |
+
# ensure the results are equal
|
| 293 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 294 |
+
|
| 295 |
+
# forward with different prompt
|
| 296 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 297 |
+
inputs["prompt_2"] = "different prompt"
|
| 298 |
+
output = sd_pipe(**inputs)
|
| 299 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 300 |
+
|
| 301 |
+
# ensure the results are not equal
|
| 302 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 303 |
+
|
| 304 |
+
# manually set a negative_prompt
|
| 305 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 306 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 307 |
+
output = sd_pipe(**inputs)
|
| 308 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 309 |
+
|
| 310 |
+
# forward with same negative_prompt duplicated
|
| 311 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 312 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 313 |
+
inputs["negative_prompt_2"] = inputs["negative_prompt"]
|
| 314 |
+
output = sd_pipe(**inputs)
|
| 315 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 316 |
+
|
| 317 |
+
# ensure the results are equal
|
| 318 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 319 |
+
|
| 320 |
+
# forward with different negative_prompt
|
| 321 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 322 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 323 |
+
inputs["negative_prompt_2"] = "different negative prompt"
|
| 324 |
+
output = sd_pipe(**inputs)
|
| 325 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 326 |
+
|
| 327 |
+
# ensure the results are not equal
|
| 328 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 329 |
+
|
| 330 |
+
def test_controlnet_sdxl_guess(self):
|
| 331 |
+
device = "cpu"
|
| 332 |
+
|
| 333 |
+
components = self.get_dummy_components()
|
| 334 |
+
|
| 335 |
+
sd_pipe = self.pipeline_class(**components)
|
| 336 |
+
sd_pipe = sd_pipe.to(device)
|
| 337 |
+
|
| 338 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 339 |
+
|
| 340 |
+
inputs = self.get_dummy_inputs(device)
|
| 341 |
+
inputs["guess_mode"] = True
|
| 342 |
+
|
| 343 |
+
output = sd_pipe(**inputs)
|
| 344 |
+
image_slice = output.images[0, -3:, -3:, -1]
|
| 345 |
+
|
| 346 |
+
expected_slice = np.array([0.5460, 0.4943, 0.4635, 0.5832, 0.5366, 0.4815, 0.6034, 0.5741, 0.4341])
|
| 347 |
+
|
| 348 |
+
# make sure that it's equal
|
| 349 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-4
|
| 350 |
+
|
| 351 |
+
# TODO(Patrick, Sayak) - skip for now as this requires more refiner tests
|
| 352 |
+
def test_save_load_optional_components(self):
|
| 353 |
+
pass
|
| 354 |
+
|
| 355 |
+
def test_float16_inference(self):
|
| 356 |
+
super().test_float16_inference(expected_max_diff=5e-1)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_sdxl.py
ADDED
|
@@ -0,0 +1,1082 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import copy
|
| 17 |
+
import gc
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import torch
|
| 22 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
| 23 |
+
|
| 24 |
+
from diffusers import (
|
| 25 |
+
AutoencoderKL,
|
| 26 |
+
ControlNetModel,
|
| 27 |
+
EulerDiscreteScheduler,
|
| 28 |
+
HeunDiscreteScheduler,
|
| 29 |
+
LCMScheduler,
|
| 30 |
+
StableDiffusionXLControlNetPipeline,
|
| 31 |
+
StableDiffusionXLImg2ImgPipeline,
|
| 32 |
+
UNet2DConditionModel,
|
| 33 |
+
)
|
| 34 |
+
from diffusers.models.unets.unet_2d_blocks import UNetMidBlock2D
|
| 35 |
+
from diffusers.pipelines.controlnet.pipeline_controlnet import MultiControlNetModel
|
| 36 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 37 |
+
from diffusers.utils.testing_utils import (
|
| 38 |
+
backend_empty_cache,
|
| 39 |
+
enable_full_determinism,
|
| 40 |
+
load_image,
|
| 41 |
+
require_torch_accelerator,
|
| 42 |
+
slow,
|
| 43 |
+
torch_device,
|
| 44 |
+
)
|
| 45 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 46 |
+
|
| 47 |
+
from ..pipeline_params import (
|
| 48 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 49 |
+
TEXT_TO_IMAGE_BATCH_PARAMS,
|
| 50 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 51 |
+
TEXT_TO_IMAGE_PARAMS,
|
| 52 |
+
)
|
| 53 |
+
from ..test_pipelines_common import (
|
| 54 |
+
IPAdapterTesterMixin,
|
| 55 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 56 |
+
PipelineLatentTesterMixin,
|
| 57 |
+
PipelineTesterMixin,
|
| 58 |
+
)
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
enable_full_determinism()
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
class StableDiffusionXLControlNetPipelineFastTests(
|
| 65 |
+
IPAdapterTesterMixin,
|
| 66 |
+
PipelineLatentTesterMixin,
|
| 67 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 68 |
+
PipelineTesterMixin,
|
| 69 |
+
unittest.TestCase,
|
| 70 |
+
):
|
| 71 |
+
pipeline_class = StableDiffusionXLControlNetPipeline
|
| 72 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 73 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 74 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 75 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 76 |
+
test_layerwise_casting = True
|
| 77 |
+
test_group_offloading = True
|
| 78 |
+
|
| 79 |
+
def get_dummy_components(self, time_cond_proj_dim=None):
|
| 80 |
+
torch.manual_seed(0)
|
| 81 |
+
unet = UNet2DConditionModel(
|
| 82 |
+
block_out_channels=(32, 64),
|
| 83 |
+
layers_per_block=2,
|
| 84 |
+
sample_size=32,
|
| 85 |
+
in_channels=4,
|
| 86 |
+
out_channels=4,
|
| 87 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 88 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 89 |
+
# SD2-specific config below
|
| 90 |
+
attention_head_dim=(2, 4),
|
| 91 |
+
use_linear_projection=True,
|
| 92 |
+
addition_embed_type="text_time",
|
| 93 |
+
addition_time_embed_dim=8,
|
| 94 |
+
transformer_layers_per_block=(1, 2),
|
| 95 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 96 |
+
cross_attention_dim=64,
|
| 97 |
+
time_cond_proj_dim=time_cond_proj_dim,
|
| 98 |
+
)
|
| 99 |
+
torch.manual_seed(0)
|
| 100 |
+
controlnet = ControlNetModel(
|
| 101 |
+
block_out_channels=(32, 64),
|
| 102 |
+
layers_per_block=2,
|
| 103 |
+
in_channels=4,
|
| 104 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 105 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 106 |
+
# SD2-specific config below
|
| 107 |
+
attention_head_dim=(2, 4),
|
| 108 |
+
use_linear_projection=True,
|
| 109 |
+
addition_embed_type="text_time",
|
| 110 |
+
addition_time_embed_dim=8,
|
| 111 |
+
transformer_layers_per_block=(1, 2),
|
| 112 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 113 |
+
cross_attention_dim=64,
|
| 114 |
+
)
|
| 115 |
+
torch.manual_seed(0)
|
| 116 |
+
scheduler = EulerDiscreteScheduler(
|
| 117 |
+
beta_start=0.00085,
|
| 118 |
+
beta_end=0.012,
|
| 119 |
+
steps_offset=1,
|
| 120 |
+
beta_schedule="scaled_linear",
|
| 121 |
+
timestep_spacing="leading",
|
| 122 |
+
)
|
| 123 |
+
torch.manual_seed(0)
|
| 124 |
+
vae = AutoencoderKL(
|
| 125 |
+
block_out_channels=[32, 64],
|
| 126 |
+
in_channels=3,
|
| 127 |
+
out_channels=3,
|
| 128 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 129 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 130 |
+
latent_channels=4,
|
| 131 |
+
)
|
| 132 |
+
torch.manual_seed(0)
|
| 133 |
+
text_encoder_config = CLIPTextConfig(
|
| 134 |
+
bos_token_id=0,
|
| 135 |
+
eos_token_id=2,
|
| 136 |
+
hidden_size=32,
|
| 137 |
+
intermediate_size=37,
|
| 138 |
+
layer_norm_eps=1e-05,
|
| 139 |
+
num_attention_heads=4,
|
| 140 |
+
num_hidden_layers=5,
|
| 141 |
+
pad_token_id=1,
|
| 142 |
+
vocab_size=1000,
|
| 143 |
+
# SD2-specific config below
|
| 144 |
+
hidden_act="gelu",
|
| 145 |
+
projection_dim=32,
|
| 146 |
+
)
|
| 147 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 148 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 149 |
+
|
| 150 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 151 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 152 |
+
|
| 153 |
+
components = {
|
| 154 |
+
"unet": unet,
|
| 155 |
+
"controlnet": controlnet,
|
| 156 |
+
"scheduler": scheduler,
|
| 157 |
+
"vae": vae,
|
| 158 |
+
"text_encoder": text_encoder,
|
| 159 |
+
"tokenizer": tokenizer,
|
| 160 |
+
"text_encoder_2": text_encoder_2,
|
| 161 |
+
"tokenizer_2": tokenizer_2,
|
| 162 |
+
"feature_extractor": None,
|
| 163 |
+
"image_encoder": None,
|
| 164 |
+
}
|
| 165 |
+
return components
|
| 166 |
+
|
| 167 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 168 |
+
if str(device).startswith("mps"):
|
| 169 |
+
generator = torch.manual_seed(seed)
|
| 170 |
+
else:
|
| 171 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 172 |
+
|
| 173 |
+
controlnet_embedder_scale_factor = 2
|
| 174 |
+
image = randn_tensor(
|
| 175 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 176 |
+
generator=generator,
|
| 177 |
+
device=torch.device(device),
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
inputs = {
|
| 181 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 182 |
+
"generator": generator,
|
| 183 |
+
"num_inference_steps": 2,
|
| 184 |
+
"guidance_scale": 6.0,
|
| 185 |
+
"output_type": "np",
|
| 186 |
+
"image": image,
|
| 187 |
+
}
|
| 188 |
+
|
| 189 |
+
return inputs
|
| 190 |
+
|
| 191 |
+
def test_attention_slicing_forward_pass(self):
|
| 192 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 193 |
+
|
| 194 |
+
def test_ip_adapter(self, from_ssd1b=False, expected_pipe_slice=None):
|
| 195 |
+
if not from_ssd1b:
|
| 196 |
+
expected_pipe_slice = None
|
| 197 |
+
if torch_device == "cpu":
|
| 198 |
+
expected_pipe_slice = np.array(
|
| 199 |
+
[0.7335, 0.5866, 0.5623, 0.6242, 0.5751, 0.5999, 0.4091, 0.4590, 0.5054]
|
| 200 |
+
)
|
| 201 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 202 |
+
|
| 203 |
+
@unittest.skipIf(
|
| 204 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 205 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 206 |
+
)
|
| 207 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 208 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 209 |
+
|
| 210 |
+
def test_inference_batch_single_identical(self):
|
| 211 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 212 |
+
|
| 213 |
+
@unittest.skip("We test this functionality elsewhere already.")
|
| 214 |
+
def test_save_load_optional_components(self):
|
| 215 |
+
pass
|
| 216 |
+
|
| 217 |
+
@require_torch_accelerator
|
| 218 |
+
def test_stable_diffusion_xl_offloads(self):
|
| 219 |
+
pipes = []
|
| 220 |
+
components = self.get_dummy_components()
|
| 221 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 222 |
+
pipes.append(sd_pipe)
|
| 223 |
+
|
| 224 |
+
components = self.get_dummy_components()
|
| 225 |
+
sd_pipe = self.pipeline_class(**components)
|
| 226 |
+
sd_pipe.enable_model_cpu_offload(device=torch_device)
|
| 227 |
+
pipes.append(sd_pipe)
|
| 228 |
+
|
| 229 |
+
components = self.get_dummy_components()
|
| 230 |
+
sd_pipe = self.pipeline_class(**components)
|
| 231 |
+
sd_pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 232 |
+
pipes.append(sd_pipe)
|
| 233 |
+
|
| 234 |
+
image_slices = []
|
| 235 |
+
for pipe in pipes:
|
| 236 |
+
pipe.unet.set_default_attn_processor()
|
| 237 |
+
|
| 238 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 239 |
+
image = pipe(**inputs).images
|
| 240 |
+
|
| 241 |
+
image_slices.append(image[0, -3:, -3:, -1].flatten())
|
| 242 |
+
|
| 243 |
+
assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
|
| 244 |
+
assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
|
| 245 |
+
|
| 246 |
+
def test_stable_diffusion_xl_multi_prompts(self):
|
| 247 |
+
components = self.get_dummy_components()
|
| 248 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 249 |
+
|
| 250 |
+
# forward with single prompt
|
| 251 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 252 |
+
output = sd_pipe(**inputs)
|
| 253 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 254 |
+
|
| 255 |
+
# forward with same prompt duplicated
|
| 256 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 257 |
+
inputs["prompt_2"] = inputs["prompt"]
|
| 258 |
+
output = sd_pipe(**inputs)
|
| 259 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 260 |
+
|
| 261 |
+
# ensure the results are equal
|
| 262 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 263 |
+
|
| 264 |
+
# forward with different prompt
|
| 265 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 266 |
+
inputs["prompt_2"] = "different prompt"
|
| 267 |
+
output = sd_pipe(**inputs)
|
| 268 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 269 |
+
|
| 270 |
+
# ensure the results are not equal
|
| 271 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 272 |
+
|
| 273 |
+
# manually set a negative_prompt
|
| 274 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 275 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 276 |
+
output = sd_pipe(**inputs)
|
| 277 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 278 |
+
|
| 279 |
+
# forward with same negative_prompt duplicated
|
| 280 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 281 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 282 |
+
inputs["negative_prompt_2"] = inputs["negative_prompt"]
|
| 283 |
+
output = sd_pipe(**inputs)
|
| 284 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 285 |
+
|
| 286 |
+
# ensure the results are equal
|
| 287 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 288 |
+
|
| 289 |
+
# forward with different negative_prompt
|
| 290 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 291 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 292 |
+
inputs["negative_prompt_2"] = "different negative prompt"
|
| 293 |
+
output = sd_pipe(**inputs)
|
| 294 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 295 |
+
|
| 296 |
+
# ensure the results are not equal
|
| 297 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 298 |
+
|
| 299 |
+
def test_controlnet_sdxl_guess(self):
|
| 300 |
+
device = "cpu"
|
| 301 |
+
|
| 302 |
+
components = self.get_dummy_components()
|
| 303 |
+
|
| 304 |
+
sd_pipe = self.pipeline_class(**components)
|
| 305 |
+
sd_pipe = sd_pipe.to(device)
|
| 306 |
+
|
| 307 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 308 |
+
|
| 309 |
+
inputs = self.get_dummy_inputs(device)
|
| 310 |
+
inputs["guess_mode"] = True
|
| 311 |
+
|
| 312 |
+
output = sd_pipe(**inputs)
|
| 313 |
+
image_slice = output.images[0, -3:, -3:, -1]
|
| 314 |
+
|
| 315 |
+
expected_slice = np.array([0.7335, 0.5866, 0.5623, 0.6242, 0.5751, 0.5999, 0.4091, 0.4590, 0.5054])
|
| 316 |
+
|
| 317 |
+
# make sure that it's equal
|
| 318 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-4
|
| 319 |
+
|
| 320 |
+
def test_controlnet_sdxl_lcm(self):
|
| 321 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 322 |
+
|
| 323 |
+
components = self.get_dummy_components(time_cond_proj_dim=256)
|
| 324 |
+
sd_pipe = StableDiffusionXLControlNetPipeline(**components)
|
| 325 |
+
sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
|
| 326 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 327 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 328 |
+
|
| 329 |
+
inputs = self.get_dummy_inputs(device)
|
| 330 |
+
output = sd_pipe(**inputs)
|
| 331 |
+
image = output.images
|
| 332 |
+
|
| 333 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 334 |
+
|
| 335 |
+
assert image.shape == (1, 64, 64, 3)
|
| 336 |
+
expected_slice = np.array([0.7820, 0.6195, 0.6193, 0.7045, 0.6706, 0.5837, 0.4147, 0.5232, 0.4868])
|
| 337 |
+
|
| 338 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 339 |
+
|
| 340 |
+
# Copied from test_stable_diffusion_xl.py:test_stable_diffusion_two_xl_mixture_of_denoiser_fast
|
| 341 |
+
# with `StableDiffusionXLControlNetPipeline` instead of `StableDiffusionXLPipeline`
|
| 342 |
+
def test_controlnet_sdxl_two_mixture_of_denoiser_fast(self):
|
| 343 |
+
components = self.get_dummy_components()
|
| 344 |
+
pipe_1 = StableDiffusionXLControlNetPipeline(**components).to(torch_device)
|
| 345 |
+
pipe_1.unet.set_default_attn_processor()
|
| 346 |
+
|
| 347 |
+
components_without_controlnet = {k: v for k, v in components.items() if k != "controlnet"}
|
| 348 |
+
pipe_2 = StableDiffusionXLImg2ImgPipeline(**components_without_controlnet).to(torch_device)
|
| 349 |
+
pipe_2.unet.set_default_attn_processor()
|
| 350 |
+
|
| 351 |
+
def assert_run_mixture(
|
| 352 |
+
num_steps,
|
| 353 |
+
split,
|
| 354 |
+
scheduler_cls_orig,
|
| 355 |
+
expected_tss,
|
| 356 |
+
num_train_timesteps=pipe_1.scheduler.config.num_train_timesteps,
|
| 357 |
+
):
|
| 358 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 359 |
+
inputs["num_inference_steps"] = num_steps
|
| 360 |
+
|
| 361 |
+
class scheduler_cls(scheduler_cls_orig):
|
| 362 |
+
pass
|
| 363 |
+
|
| 364 |
+
pipe_1.scheduler = scheduler_cls.from_config(pipe_1.scheduler.config)
|
| 365 |
+
pipe_2.scheduler = scheduler_cls.from_config(pipe_2.scheduler.config)
|
| 366 |
+
|
| 367 |
+
# Let's retrieve the number of timesteps we want to use
|
| 368 |
+
pipe_1.scheduler.set_timesteps(num_steps)
|
| 369 |
+
expected_steps = pipe_1.scheduler.timesteps.tolist()
|
| 370 |
+
|
| 371 |
+
if pipe_1.scheduler.order == 2:
|
| 372 |
+
expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
|
| 373 |
+
expected_steps_2 = expected_steps_1[-1:] + list(filter(lambda ts: ts < split, expected_tss))
|
| 374 |
+
expected_steps = expected_steps_1 + expected_steps_2
|
| 375 |
+
else:
|
| 376 |
+
expected_steps_1 = list(filter(lambda ts: ts >= split, expected_tss))
|
| 377 |
+
expected_steps_2 = list(filter(lambda ts: ts < split, expected_tss))
|
| 378 |
+
|
| 379 |
+
# now we monkey patch step `done_steps`
|
| 380 |
+
# list into the step function for testing
|
| 381 |
+
done_steps = []
|
| 382 |
+
old_step = copy.copy(scheduler_cls.step)
|
| 383 |
+
|
| 384 |
+
def new_step(self, *args, **kwargs):
|
| 385 |
+
done_steps.append(args[1].cpu().item()) # args[1] is always the passed `t`
|
| 386 |
+
return old_step(self, *args, **kwargs)
|
| 387 |
+
|
| 388 |
+
scheduler_cls.step = new_step
|
| 389 |
+
|
| 390 |
+
inputs_1 = {
|
| 391 |
+
**inputs,
|
| 392 |
+
**{
|
| 393 |
+
"denoising_end": 1.0 - (split / num_train_timesteps),
|
| 394 |
+
"output_type": "latent",
|
| 395 |
+
},
|
| 396 |
+
}
|
| 397 |
+
latents = pipe_1(**inputs_1).images[0]
|
| 398 |
+
|
| 399 |
+
assert expected_steps_1 == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
|
| 400 |
+
|
| 401 |
+
inputs_2 = {
|
| 402 |
+
**inputs,
|
| 403 |
+
**{
|
| 404 |
+
"denoising_start": 1.0 - (split / num_train_timesteps),
|
| 405 |
+
"image": latents,
|
| 406 |
+
},
|
| 407 |
+
}
|
| 408 |
+
pipe_2(**inputs_2).images[0]
|
| 409 |
+
|
| 410 |
+
assert expected_steps_2 == done_steps[len(expected_steps_1) :]
|
| 411 |
+
assert expected_steps == done_steps, f"Failure with {scheduler_cls.__name__} and {num_steps} and {split}"
|
| 412 |
+
|
| 413 |
+
steps = 10
|
| 414 |
+
for split in [300, 700]:
|
| 415 |
+
for scheduler_cls_timesteps in [
|
| 416 |
+
(EulerDiscreteScheduler, [901, 801, 701, 601, 501, 401, 301, 201, 101, 1]),
|
| 417 |
+
(
|
| 418 |
+
HeunDiscreteScheduler,
|
| 419 |
+
[
|
| 420 |
+
901.0,
|
| 421 |
+
801.0,
|
| 422 |
+
801.0,
|
| 423 |
+
701.0,
|
| 424 |
+
701.0,
|
| 425 |
+
601.0,
|
| 426 |
+
601.0,
|
| 427 |
+
501.0,
|
| 428 |
+
501.0,
|
| 429 |
+
401.0,
|
| 430 |
+
401.0,
|
| 431 |
+
301.0,
|
| 432 |
+
301.0,
|
| 433 |
+
201.0,
|
| 434 |
+
201.0,
|
| 435 |
+
101.0,
|
| 436 |
+
101.0,
|
| 437 |
+
1.0,
|
| 438 |
+
1.0,
|
| 439 |
+
],
|
| 440 |
+
),
|
| 441 |
+
]:
|
| 442 |
+
assert_run_mixture(steps, split, scheduler_cls_timesteps[0], scheduler_cls_timesteps[1])
|
| 443 |
+
|
| 444 |
+
|
| 445 |
+
class StableDiffusionXLMultiControlNetPipelineFastTests(
|
| 446 |
+
PipelineTesterMixin, PipelineKarrasSchedulerTesterMixin, unittest.TestCase
|
| 447 |
+
):
|
| 448 |
+
pipeline_class = StableDiffusionXLControlNetPipeline
|
| 449 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 450 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 451 |
+
image_params = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
|
| 452 |
+
|
| 453 |
+
supports_dduf = False
|
| 454 |
+
|
| 455 |
+
def get_dummy_components(self):
|
| 456 |
+
torch.manual_seed(0)
|
| 457 |
+
unet = UNet2DConditionModel(
|
| 458 |
+
block_out_channels=(32, 64),
|
| 459 |
+
layers_per_block=2,
|
| 460 |
+
sample_size=32,
|
| 461 |
+
in_channels=4,
|
| 462 |
+
out_channels=4,
|
| 463 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 464 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 465 |
+
# SD2-specific config below
|
| 466 |
+
attention_head_dim=(2, 4),
|
| 467 |
+
use_linear_projection=True,
|
| 468 |
+
addition_embed_type="text_time",
|
| 469 |
+
addition_time_embed_dim=8,
|
| 470 |
+
transformer_layers_per_block=(1, 2),
|
| 471 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 472 |
+
cross_attention_dim=64,
|
| 473 |
+
)
|
| 474 |
+
torch.manual_seed(0)
|
| 475 |
+
|
| 476 |
+
def init_weights(m):
|
| 477 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 478 |
+
torch.nn.init.normal_(m.weight)
|
| 479 |
+
m.bias.data.fill_(1.0)
|
| 480 |
+
|
| 481 |
+
controlnet1 = ControlNetModel(
|
| 482 |
+
block_out_channels=(32, 64),
|
| 483 |
+
layers_per_block=2,
|
| 484 |
+
in_channels=4,
|
| 485 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 486 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 487 |
+
# SD2-specific config below
|
| 488 |
+
attention_head_dim=(2, 4),
|
| 489 |
+
use_linear_projection=True,
|
| 490 |
+
addition_embed_type="text_time",
|
| 491 |
+
addition_time_embed_dim=8,
|
| 492 |
+
transformer_layers_per_block=(1, 2),
|
| 493 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 494 |
+
cross_attention_dim=64,
|
| 495 |
+
)
|
| 496 |
+
controlnet1.controlnet_down_blocks.apply(init_weights)
|
| 497 |
+
|
| 498 |
+
torch.manual_seed(0)
|
| 499 |
+
controlnet2 = ControlNetModel(
|
| 500 |
+
block_out_channels=(32, 64),
|
| 501 |
+
layers_per_block=2,
|
| 502 |
+
in_channels=4,
|
| 503 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 504 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 505 |
+
# SD2-specific config below
|
| 506 |
+
attention_head_dim=(2, 4),
|
| 507 |
+
use_linear_projection=True,
|
| 508 |
+
addition_embed_type="text_time",
|
| 509 |
+
addition_time_embed_dim=8,
|
| 510 |
+
transformer_layers_per_block=(1, 2),
|
| 511 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 512 |
+
cross_attention_dim=64,
|
| 513 |
+
)
|
| 514 |
+
controlnet2.controlnet_down_blocks.apply(init_weights)
|
| 515 |
+
|
| 516 |
+
torch.manual_seed(0)
|
| 517 |
+
scheduler = EulerDiscreteScheduler(
|
| 518 |
+
beta_start=0.00085,
|
| 519 |
+
beta_end=0.012,
|
| 520 |
+
steps_offset=1,
|
| 521 |
+
beta_schedule="scaled_linear",
|
| 522 |
+
timestep_spacing="leading",
|
| 523 |
+
)
|
| 524 |
+
torch.manual_seed(0)
|
| 525 |
+
vae = AutoencoderKL(
|
| 526 |
+
block_out_channels=[32, 64],
|
| 527 |
+
in_channels=3,
|
| 528 |
+
out_channels=3,
|
| 529 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 530 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 531 |
+
latent_channels=4,
|
| 532 |
+
)
|
| 533 |
+
torch.manual_seed(0)
|
| 534 |
+
text_encoder_config = CLIPTextConfig(
|
| 535 |
+
bos_token_id=0,
|
| 536 |
+
eos_token_id=2,
|
| 537 |
+
hidden_size=32,
|
| 538 |
+
intermediate_size=37,
|
| 539 |
+
layer_norm_eps=1e-05,
|
| 540 |
+
num_attention_heads=4,
|
| 541 |
+
num_hidden_layers=5,
|
| 542 |
+
pad_token_id=1,
|
| 543 |
+
vocab_size=1000,
|
| 544 |
+
# SD2-specific config below
|
| 545 |
+
hidden_act="gelu",
|
| 546 |
+
projection_dim=32,
|
| 547 |
+
)
|
| 548 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 549 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 550 |
+
|
| 551 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 552 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 553 |
+
|
| 554 |
+
controlnet = MultiControlNetModel([controlnet1, controlnet2])
|
| 555 |
+
|
| 556 |
+
components = {
|
| 557 |
+
"unet": unet,
|
| 558 |
+
"controlnet": controlnet,
|
| 559 |
+
"scheduler": scheduler,
|
| 560 |
+
"vae": vae,
|
| 561 |
+
"text_encoder": text_encoder,
|
| 562 |
+
"tokenizer": tokenizer,
|
| 563 |
+
"text_encoder_2": text_encoder_2,
|
| 564 |
+
"tokenizer_2": tokenizer_2,
|
| 565 |
+
"feature_extractor": None,
|
| 566 |
+
"image_encoder": None,
|
| 567 |
+
}
|
| 568 |
+
return components
|
| 569 |
+
|
| 570 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 571 |
+
if str(device).startswith("mps"):
|
| 572 |
+
generator = torch.manual_seed(seed)
|
| 573 |
+
else:
|
| 574 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 575 |
+
|
| 576 |
+
controlnet_embedder_scale_factor = 2
|
| 577 |
+
|
| 578 |
+
images = [
|
| 579 |
+
randn_tensor(
|
| 580 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 581 |
+
generator=generator,
|
| 582 |
+
device=torch.device(device),
|
| 583 |
+
),
|
| 584 |
+
randn_tensor(
|
| 585 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 586 |
+
generator=generator,
|
| 587 |
+
device=torch.device(device),
|
| 588 |
+
),
|
| 589 |
+
]
|
| 590 |
+
|
| 591 |
+
inputs = {
|
| 592 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 593 |
+
"generator": generator,
|
| 594 |
+
"num_inference_steps": 2,
|
| 595 |
+
"guidance_scale": 6.0,
|
| 596 |
+
"output_type": "np",
|
| 597 |
+
"image": images,
|
| 598 |
+
}
|
| 599 |
+
|
| 600 |
+
return inputs
|
| 601 |
+
|
| 602 |
+
def test_control_guidance_switch(self):
|
| 603 |
+
components = self.get_dummy_components()
|
| 604 |
+
pipe = self.pipeline_class(**components)
|
| 605 |
+
pipe.to(torch_device)
|
| 606 |
+
|
| 607 |
+
scale = 10.0
|
| 608 |
+
steps = 4
|
| 609 |
+
|
| 610 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 611 |
+
inputs["num_inference_steps"] = steps
|
| 612 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 613 |
+
output_1 = pipe(**inputs)[0]
|
| 614 |
+
|
| 615 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 616 |
+
inputs["num_inference_steps"] = steps
|
| 617 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 618 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 619 |
+
|
| 620 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 621 |
+
inputs["num_inference_steps"] = steps
|
| 622 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 623 |
+
output_3 = pipe(**inputs, control_guidance_start=[0.1, 0.3], control_guidance_end=[0.2, 0.7])[0]
|
| 624 |
+
|
| 625 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 626 |
+
inputs["num_inference_steps"] = steps
|
| 627 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 628 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5, 0.8])[0]
|
| 629 |
+
|
| 630 |
+
# make sure that all outputs are different
|
| 631 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 632 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 633 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 634 |
+
|
| 635 |
+
def test_attention_slicing_forward_pass(self):
|
| 636 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 637 |
+
|
| 638 |
+
@unittest.skipIf(
|
| 639 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 640 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 641 |
+
)
|
| 642 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 643 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 644 |
+
|
| 645 |
+
def test_inference_batch_single_identical(self):
|
| 646 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 647 |
+
|
| 648 |
+
@unittest.skip("We test this functionality elsewhere already.")
|
| 649 |
+
def test_save_load_optional_components(self):
|
| 650 |
+
pass
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
class StableDiffusionXLMultiControlNetOneModelPipelineFastTests(
|
| 654 |
+
PipelineKarrasSchedulerTesterMixin, PipelineTesterMixin, unittest.TestCase
|
| 655 |
+
):
|
| 656 |
+
pipeline_class = StableDiffusionXLControlNetPipeline
|
| 657 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 658 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 659 |
+
image_params = frozenset([]) # TO_DO: add image_params once refactored VaeImageProcessor.preprocess
|
| 660 |
+
|
| 661 |
+
supports_dduf = False
|
| 662 |
+
|
| 663 |
+
def get_dummy_components(self):
|
| 664 |
+
torch.manual_seed(0)
|
| 665 |
+
unet = UNet2DConditionModel(
|
| 666 |
+
block_out_channels=(32, 64),
|
| 667 |
+
layers_per_block=2,
|
| 668 |
+
sample_size=32,
|
| 669 |
+
in_channels=4,
|
| 670 |
+
out_channels=4,
|
| 671 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 672 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 673 |
+
# SD2-specific config below
|
| 674 |
+
attention_head_dim=(2, 4),
|
| 675 |
+
use_linear_projection=True,
|
| 676 |
+
addition_embed_type="text_time",
|
| 677 |
+
addition_time_embed_dim=8,
|
| 678 |
+
transformer_layers_per_block=(1, 2),
|
| 679 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 680 |
+
cross_attention_dim=64,
|
| 681 |
+
)
|
| 682 |
+
torch.manual_seed(0)
|
| 683 |
+
|
| 684 |
+
def init_weights(m):
|
| 685 |
+
if isinstance(m, torch.nn.Conv2d):
|
| 686 |
+
torch.nn.init.normal_(m.weight)
|
| 687 |
+
m.bias.data.fill_(1.0)
|
| 688 |
+
|
| 689 |
+
controlnet = ControlNetModel(
|
| 690 |
+
block_out_channels=(32, 64),
|
| 691 |
+
layers_per_block=2,
|
| 692 |
+
in_channels=4,
|
| 693 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 694 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 695 |
+
# SD2-specific config below
|
| 696 |
+
attention_head_dim=(2, 4),
|
| 697 |
+
use_linear_projection=True,
|
| 698 |
+
addition_embed_type="text_time",
|
| 699 |
+
addition_time_embed_dim=8,
|
| 700 |
+
transformer_layers_per_block=(1, 2),
|
| 701 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 702 |
+
cross_attention_dim=64,
|
| 703 |
+
)
|
| 704 |
+
controlnet.controlnet_down_blocks.apply(init_weights)
|
| 705 |
+
|
| 706 |
+
torch.manual_seed(0)
|
| 707 |
+
scheduler = EulerDiscreteScheduler(
|
| 708 |
+
beta_start=0.00085,
|
| 709 |
+
beta_end=0.012,
|
| 710 |
+
steps_offset=1,
|
| 711 |
+
beta_schedule="scaled_linear",
|
| 712 |
+
timestep_spacing="leading",
|
| 713 |
+
)
|
| 714 |
+
torch.manual_seed(0)
|
| 715 |
+
vae = AutoencoderKL(
|
| 716 |
+
block_out_channels=[32, 64],
|
| 717 |
+
in_channels=3,
|
| 718 |
+
out_channels=3,
|
| 719 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 720 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 721 |
+
latent_channels=4,
|
| 722 |
+
)
|
| 723 |
+
torch.manual_seed(0)
|
| 724 |
+
text_encoder_config = CLIPTextConfig(
|
| 725 |
+
bos_token_id=0,
|
| 726 |
+
eos_token_id=2,
|
| 727 |
+
hidden_size=32,
|
| 728 |
+
intermediate_size=37,
|
| 729 |
+
layer_norm_eps=1e-05,
|
| 730 |
+
num_attention_heads=4,
|
| 731 |
+
num_hidden_layers=5,
|
| 732 |
+
pad_token_id=1,
|
| 733 |
+
vocab_size=1000,
|
| 734 |
+
# SD2-specific config below
|
| 735 |
+
hidden_act="gelu",
|
| 736 |
+
projection_dim=32,
|
| 737 |
+
)
|
| 738 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 739 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 740 |
+
|
| 741 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 742 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 743 |
+
|
| 744 |
+
controlnet = MultiControlNetModel([controlnet])
|
| 745 |
+
|
| 746 |
+
components = {
|
| 747 |
+
"unet": unet,
|
| 748 |
+
"controlnet": controlnet,
|
| 749 |
+
"scheduler": scheduler,
|
| 750 |
+
"vae": vae,
|
| 751 |
+
"text_encoder": text_encoder,
|
| 752 |
+
"tokenizer": tokenizer,
|
| 753 |
+
"text_encoder_2": text_encoder_2,
|
| 754 |
+
"tokenizer_2": tokenizer_2,
|
| 755 |
+
"feature_extractor": None,
|
| 756 |
+
"image_encoder": None,
|
| 757 |
+
}
|
| 758 |
+
return components
|
| 759 |
+
|
| 760 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 761 |
+
if str(device).startswith("mps"):
|
| 762 |
+
generator = torch.manual_seed(seed)
|
| 763 |
+
else:
|
| 764 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 765 |
+
|
| 766 |
+
controlnet_embedder_scale_factor = 2
|
| 767 |
+
images = [
|
| 768 |
+
randn_tensor(
|
| 769 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 770 |
+
generator=generator,
|
| 771 |
+
device=torch.device(device),
|
| 772 |
+
),
|
| 773 |
+
]
|
| 774 |
+
|
| 775 |
+
inputs = {
|
| 776 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 777 |
+
"generator": generator,
|
| 778 |
+
"num_inference_steps": 2,
|
| 779 |
+
"guidance_scale": 6.0,
|
| 780 |
+
"output_type": "np",
|
| 781 |
+
"image": images,
|
| 782 |
+
}
|
| 783 |
+
|
| 784 |
+
return inputs
|
| 785 |
+
|
| 786 |
+
def test_control_guidance_switch(self):
|
| 787 |
+
components = self.get_dummy_components()
|
| 788 |
+
pipe = self.pipeline_class(**components)
|
| 789 |
+
pipe.to(torch_device)
|
| 790 |
+
|
| 791 |
+
scale = 10.0
|
| 792 |
+
steps = 4
|
| 793 |
+
|
| 794 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 795 |
+
inputs["num_inference_steps"] = steps
|
| 796 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 797 |
+
output_1 = pipe(**inputs)[0]
|
| 798 |
+
|
| 799 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 800 |
+
inputs["num_inference_steps"] = steps
|
| 801 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 802 |
+
output_2 = pipe(**inputs, control_guidance_start=0.1, control_guidance_end=0.2)[0]
|
| 803 |
+
|
| 804 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 805 |
+
inputs["num_inference_steps"] = steps
|
| 806 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 807 |
+
output_3 = pipe(
|
| 808 |
+
**inputs,
|
| 809 |
+
control_guidance_start=[0.1],
|
| 810 |
+
control_guidance_end=[0.2],
|
| 811 |
+
)[0]
|
| 812 |
+
|
| 813 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 814 |
+
inputs["num_inference_steps"] = steps
|
| 815 |
+
inputs["controlnet_conditioning_scale"] = scale
|
| 816 |
+
output_4 = pipe(**inputs, control_guidance_start=0.4, control_guidance_end=[0.5])[0]
|
| 817 |
+
|
| 818 |
+
# make sure that all outputs are different
|
| 819 |
+
assert np.sum(np.abs(output_1 - output_2)) > 1e-3
|
| 820 |
+
assert np.sum(np.abs(output_1 - output_3)) > 1e-3
|
| 821 |
+
assert np.sum(np.abs(output_1 - output_4)) > 1e-3
|
| 822 |
+
|
| 823 |
+
def test_attention_slicing_forward_pass(self):
|
| 824 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 825 |
+
|
| 826 |
+
@unittest.skip("We test this functionality elsewhere already.")
|
| 827 |
+
def test_save_load_optional_components(self):
|
| 828 |
+
pass
|
| 829 |
+
|
| 830 |
+
@unittest.skipIf(
|
| 831 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 832 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 833 |
+
)
|
| 834 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 835 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 836 |
+
|
| 837 |
+
def test_inference_batch_single_identical(self):
|
| 838 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 839 |
+
|
| 840 |
+
def test_negative_conditions(self):
|
| 841 |
+
components = self.get_dummy_components()
|
| 842 |
+
pipe = self.pipeline_class(**components)
|
| 843 |
+
pipe.to(torch_device)
|
| 844 |
+
|
| 845 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 846 |
+
image = pipe(**inputs).images
|
| 847 |
+
image_slice_without_neg_cond = image[0, -3:, -3:, -1]
|
| 848 |
+
|
| 849 |
+
image = pipe(
|
| 850 |
+
**inputs,
|
| 851 |
+
negative_original_size=(512, 512),
|
| 852 |
+
negative_crops_coords_top_left=(0, 0),
|
| 853 |
+
negative_target_size=(1024, 1024),
|
| 854 |
+
).images
|
| 855 |
+
image_slice_with_neg_cond = image[0, -3:, -3:, -1]
|
| 856 |
+
|
| 857 |
+
self.assertTrue(np.abs(image_slice_without_neg_cond - image_slice_with_neg_cond).max() > 1e-2)
|
| 858 |
+
|
| 859 |
+
|
| 860 |
+
@slow
|
| 861 |
+
@require_torch_accelerator
|
| 862 |
+
class ControlNetSDXLPipelineSlowTests(unittest.TestCase):
|
| 863 |
+
def setUp(self):
|
| 864 |
+
super().setUp()
|
| 865 |
+
gc.collect()
|
| 866 |
+
backend_empty_cache(torch_device)
|
| 867 |
+
|
| 868 |
+
def tearDown(self):
|
| 869 |
+
super().tearDown()
|
| 870 |
+
gc.collect()
|
| 871 |
+
backend_empty_cache(torch_device)
|
| 872 |
+
|
| 873 |
+
def test_canny(self):
|
| 874 |
+
controlnet = ControlNetModel.from_pretrained("diffusers/controlnet-canny-sdxl-1.0")
|
| 875 |
+
|
| 876 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 877 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet
|
| 878 |
+
)
|
| 879 |
+
pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 880 |
+
pipe.set_progress_bar_config(disable=None)
|
| 881 |
+
|
| 882 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 883 |
+
prompt = "bird"
|
| 884 |
+
image = load_image(
|
| 885 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 886 |
+
)
|
| 887 |
+
|
| 888 |
+
images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
|
| 889 |
+
|
| 890 |
+
assert images[0].shape == (768, 512, 3)
|
| 891 |
+
|
| 892 |
+
original_image = images[0, -3:, -3:, -1].flatten()
|
| 893 |
+
expected_image = np.array([0.4185, 0.4127, 0.4089, 0.4046, 0.4115, 0.4096, 0.4081, 0.4112, 0.3913])
|
| 894 |
+
assert np.allclose(original_image, expected_image, atol=1e-04)
|
| 895 |
+
|
| 896 |
+
def test_depth(self):
|
| 897 |
+
controlnet = ControlNetModel.from_pretrained("diffusers/controlnet-depth-sdxl-1.0")
|
| 898 |
+
|
| 899 |
+
pipe = StableDiffusionXLControlNetPipeline.from_pretrained(
|
| 900 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet
|
| 901 |
+
)
|
| 902 |
+
pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 903 |
+
pipe.set_progress_bar_config(disable=None)
|
| 904 |
+
|
| 905 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 906 |
+
prompt = "Stormtrooper's lecture"
|
| 907 |
+
image = load_image(
|
| 908 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/stormtrooper_depth.png"
|
| 909 |
+
)
|
| 910 |
+
|
| 911 |
+
images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
|
| 912 |
+
|
| 913 |
+
assert images[0].shape == (512, 512, 3)
|
| 914 |
+
|
| 915 |
+
original_image = images[0, -3:, -3:, -1].flatten()
|
| 916 |
+
expected_image = np.array([0.4399, 0.5112, 0.5478, 0.4314, 0.472, 0.4823, 0.4647, 0.4957, 0.4853])
|
| 917 |
+
assert np.allclose(original_image, expected_image, atol=1e-04)
|
| 918 |
+
|
| 919 |
+
|
| 920 |
+
class StableDiffusionSSD1BControlNetPipelineFastTests(StableDiffusionXLControlNetPipelineFastTests):
|
| 921 |
+
def test_controlnet_sdxl_guess(self):
|
| 922 |
+
device = "cpu"
|
| 923 |
+
|
| 924 |
+
components = self.get_dummy_components()
|
| 925 |
+
|
| 926 |
+
sd_pipe = self.pipeline_class(**components)
|
| 927 |
+
sd_pipe = sd_pipe.to(device)
|
| 928 |
+
|
| 929 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 930 |
+
|
| 931 |
+
inputs = self.get_dummy_inputs(device)
|
| 932 |
+
inputs["guess_mode"] = True
|
| 933 |
+
|
| 934 |
+
output = sd_pipe(**inputs)
|
| 935 |
+
image_slice = output.images[0, -3:, -3:, -1]
|
| 936 |
+
|
| 937 |
+
expected_slice = np.array([0.7212, 0.5890, 0.5491, 0.6425, 0.5970, 0.6091, 0.4418, 0.4556, 0.5032])
|
| 938 |
+
|
| 939 |
+
# make sure that it's equal
|
| 940 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-4
|
| 941 |
+
|
| 942 |
+
def test_ip_adapter(self):
|
| 943 |
+
expected_pipe_slice = None
|
| 944 |
+
if torch_device == "cpu":
|
| 945 |
+
expected_pipe_slice = np.array([0.7212, 0.5890, 0.5491, 0.6425, 0.5970, 0.6091, 0.4418, 0.4556, 0.5032])
|
| 946 |
+
|
| 947 |
+
return super().test_ip_adapter(from_ssd1b=True, expected_pipe_slice=expected_pipe_slice)
|
| 948 |
+
|
| 949 |
+
def test_controlnet_sdxl_lcm(self):
|
| 950 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 951 |
+
|
| 952 |
+
components = self.get_dummy_components(time_cond_proj_dim=256)
|
| 953 |
+
sd_pipe = StableDiffusionXLControlNetPipeline(**components)
|
| 954 |
+
sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
|
| 955 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 956 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 957 |
+
|
| 958 |
+
inputs = self.get_dummy_inputs(device)
|
| 959 |
+
output = sd_pipe(**inputs)
|
| 960 |
+
image = output.images
|
| 961 |
+
|
| 962 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 963 |
+
|
| 964 |
+
assert image.shape == (1, 64, 64, 3)
|
| 965 |
+
expected_slice = np.array([0.6787, 0.5117, 0.5558, 0.6963, 0.6571, 0.5928, 0.4121, 0.5468, 0.5057])
|
| 966 |
+
|
| 967 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 968 |
+
|
| 969 |
+
def test_conditioning_channels(self):
|
| 970 |
+
unet = UNet2DConditionModel(
|
| 971 |
+
block_out_channels=(32, 64),
|
| 972 |
+
layers_per_block=2,
|
| 973 |
+
sample_size=32,
|
| 974 |
+
in_channels=4,
|
| 975 |
+
out_channels=4,
|
| 976 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 977 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 978 |
+
mid_block_type="UNetMidBlock2D",
|
| 979 |
+
# SD2-specific config below
|
| 980 |
+
attention_head_dim=(2, 4),
|
| 981 |
+
use_linear_projection=True,
|
| 982 |
+
addition_embed_type="text_time",
|
| 983 |
+
addition_time_embed_dim=8,
|
| 984 |
+
transformer_layers_per_block=(1, 2),
|
| 985 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 986 |
+
cross_attention_dim=64,
|
| 987 |
+
time_cond_proj_dim=None,
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
controlnet = ControlNetModel.from_unet(unet, conditioning_channels=4)
|
| 991 |
+
assert type(controlnet.mid_block) is UNetMidBlock2D
|
| 992 |
+
assert controlnet.conditioning_channels == 4
|
| 993 |
+
|
| 994 |
+
def get_dummy_components(self, time_cond_proj_dim=None):
|
| 995 |
+
torch.manual_seed(0)
|
| 996 |
+
unet = UNet2DConditionModel(
|
| 997 |
+
block_out_channels=(32, 64),
|
| 998 |
+
layers_per_block=2,
|
| 999 |
+
sample_size=32,
|
| 1000 |
+
in_channels=4,
|
| 1001 |
+
out_channels=4,
|
| 1002 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 1003 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 1004 |
+
mid_block_type="UNetMidBlock2D",
|
| 1005 |
+
# SD2-specific config below
|
| 1006 |
+
attention_head_dim=(2, 4),
|
| 1007 |
+
use_linear_projection=True,
|
| 1008 |
+
addition_embed_type="text_time",
|
| 1009 |
+
addition_time_embed_dim=8,
|
| 1010 |
+
transformer_layers_per_block=(1, 2),
|
| 1011 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 1012 |
+
cross_attention_dim=64,
|
| 1013 |
+
time_cond_proj_dim=time_cond_proj_dim,
|
| 1014 |
+
)
|
| 1015 |
+
torch.manual_seed(0)
|
| 1016 |
+
controlnet = ControlNetModel(
|
| 1017 |
+
block_out_channels=(32, 64),
|
| 1018 |
+
layers_per_block=2,
|
| 1019 |
+
in_channels=4,
|
| 1020 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 1021 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 1022 |
+
mid_block_type="UNetMidBlock2D",
|
| 1023 |
+
# SD2-specific config below
|
| 1024 |
+
attention_head_dim=(2, 4),
|
| 1025 |
+
use_linear_projection=True,
|
| 1026 |
+
addition_embed_type="text_time",
|
| 1027 |
+
addition_time_embed_dim=8,
|
| 1028 |
+
transformer_layers_per_block=(1, 2),
|
| 1029 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 1030 |
+
cross_attention_dim=64,
|
| 1031 |
+
)
|
| 1032 |
+
torch.manual_seed(0)
|
| 1033 |
+
scheduler = EulerDiscreteScheduler(
|
| 1034 |
+
beta_start=0.00085,
|
| 1035 |
+
beta_end=0.012,
|
| 1036 |
+
steps_offset=1,
|
| 1037 |
+
beta_schedule="scaled_linear",
|
| 1038 |
+
timestep_spacing="leading",
|
| 1039 |
+
)
|
| 1040 |
+
torch.manual_seed(0)
|
| 1041 |
+
vae = AutoencoderKL(
|
| 1042 |
+
block_out_channels=[32, 64],
|
| 1043 |
+
in_channels=3,
|
| 1044 |
+
out_channels=3,
|
| 1045 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 1046 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 1047 |
+
latent_channels=4,
|
| 1048 |
+
)
|
| 1049 |
+
torch.manual_seed(0)
|
| 1050 |
+
text_encoder_config = CLIPTextConfig(
|
| 1051 |
+
bos_token_id=0,
|
| 1052 |
+
eos_token_id=2,
|
| 1053 |
+
hidden_size=32,
|
| 1054 |
+
intermediate_size=37,
|
| 1055 |
+
layer_norm_eps=1e-05,
|
| 1056 |
+
num_attention_heads=4,
|
| 1057 |
+
num_hidden_layers=5,
|
| 1058 |
+
pad_token_id=1,
|
| 1059 |
+
vocab_size=1000,
|
| 1060 |
+
# SD2-specific config below
|
| 1061 |
+
hidden_act="gelu",
|
| 1062 |
+
projection_dim=32,
|
| 1063 |
+
)
|
| 1064 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 1065 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 1066 |
+
|
| 1067 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 1068 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 1069 |
+
|
| 1070 |
+
components = {
|
| 1071 |
+
"unet": unet,
|
| 1072 |
+
"controlnet": controlnet,
|
| 1073 |
+
"scheduler": scheduler,
|
| 1074 |
+
"vae": vae,
|
| 1075 |
+
"text_encoder": text_encoder,
|
| 1076 |
+
"tokenizer": tokenizer,
|
| 1077 |
+
"text_encoder_2": text_encoder_2,
|
| 1078 |
+
"tokenizer_2": tokenizer_2,
|
| 1079 |
+
"feature_extractor": None,
|
| 1080 |
+
"image_encoder": None,
|
| 1081 |
+
}
|
| 1082 |
+
return components
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_controlnet_sdxl_img2img.py
ADDED
|
@@ -0,0 +1,329 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import random
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKL,
|
| 25 |
+
ControlNetModel,
|
| 26 |
+
EulerDiscreteScheduler,
|
| 27 |
+
StableDiffusionXLControlNetImg2ImgPipeline,
|
| 28 |
+
UNet2DConditionModel,
|
| 29 |
+
)
|
| 30 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 31 |
+
from diffusers.utils.testing_utils import (
|
| 32 |
+
enable_full_determinism,
|
| 33 |
+
floats_tensor,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
torch_device,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from ..pipeline_params import (
|
| 39 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 40 |
+
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
|
| 41 |
+
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
|
| 42 |
+
TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS,
|
| 43 |
+
)
|
| 44 |
+
from ..test_pipelines_common import (
|
| 45 |
+
IPAdapterTesterMixin,
|
| 46 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 47 |
+
PipelineLatentTesterMixin,
|
| 48 |
+
PipelineTesterMixin,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
enable_full_determinism()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class ControlNetPipelineSDXLImg2ImgFastTests(
|
| 56 |
+
IPAdapterTesterMixin,
|
| 57 |
+
PipelineLatentTesterMixin,
|
| 58 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 59 |
+
PipelineTesterMixin,
|
| 60 |
+
unittest.TestCase,
|
| 61 |
+
):
|
| 62 |
+
pipeline_class = StableDiffusionXLControlNetImg2ImgPipeline
|
| 63 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS
|
| 64 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 65 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
|
| 66 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 67 |
+
image_latents_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 68 |
+
callback_cfg_params = TEXT_TO_IMAGE_CALLBACK_CFG_PARAMS.union(
|
| 69 |
+
{"add_text_embeds", "add_time_ids", "add_neg_time_ids"}
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
def get_dummy_components(self, skip_first_text_encoder=False):
|
| 73 |
+
torch.manual_seed(0)
|
| 74 |
+
unet = UNet2DConditionModel(
|
| 75 |
+
block_out_channels=(32, 64),
|
| 76 |
+
layers_per_block=2,
|
| 77 |
+
sample_size=32,
|
| 78 |
+
in_channels=4,
|
| 79 |
+
out_channels=4,
|
| 80 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 81 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 82 |
+
# SD2-specific config below
|
| 83 |
+
attention_head_dim=(2, 4),
|
| 84 |
+
use_linear_projection=True,
|
| 85 |
+
addition_embed_type="text_time",
|
| 86 |
+
addition_time_embed_dim=8,
|
| 87 |
+
transformer_layers_per_block=(1, 2),
|
| 88 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 89 |
+
cross_attention_dim=64 if not skip_first_text_encoder else 32,
|
| 90 |
+
)
|
| 91 |
+
torch.manual_seed(0)
|
| 92 |
+
controlnet = ControlNetModel(
|
| 93 |
+
block_out_channels=(32, 64),
|
| 94 |
+
layers_per_block=2,
|
| 95 |
+
in_channels=4,
|
| 96 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 97 |
+
conditioning_embedding_out_channels=(16, 32),
|
| 98 |
+
# SD2-specific config below
|
| 99 |
+
attention_head_dim=(2, 4),
|
| 100 |
+
use_linear_projection=True,
|
| 101 |
+
addition_embed_type="text_time",
|
| 102 |
+
addition_time_embed_dim=8,
|
| 103 |
+
transformer_layers_per_block=(1, 2),
|
| 104 |
+
projection_class_embeddings_input_dim=80, # 6 * 8 + 32
|
| 105 |
+
cross_attention_dim=64,
|
| 106 |
+
)
|
| 107 |
+
torch.manual_seed(0)
|
| 108 |
+
scheduler = EulerDiscreteScheduler(
|
| 109 |
+
beta_start=0.00085,
|
| 110 |
+
beta_end=0.012,
|
| 111 |
+
steps_offset=1,
|
| 112 |
+
beta_schedule="scaled_linear",
|
| 113 |
+
timestep_spacing="leading",
|
| 114 |
+
)
|
| 115 |
+
torch.manual_seed(0)
|
| 116 |
+
vae = AutoencoderKL(
|
| 117 |
+
block_out_channels=[32, 64],
|
| 118 |
+
in_channels=3,
|
| 119 |
+
out_channels=3,
|
| 120 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 121 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 122 |
+
latent_channels=4,
|
| 123 |
+
)
|
| 124 |
+
torch.manual_seed(0)
|
| 125 |
+
text_encoder_config = CLIPTextConfig(
|
| 126 |
+
bos_token_id=0,
|
| 127 |
+
eos_token_id=2,
|
| 128 |
+
hidden_size=32,
|
| 129 |
+
intermediate_size=37,
|
| 130 |
+
layer_norm_eps=1e-05,
|
| 131 |
+
num_attention_heads=4,
|
| 132 |
+
num_hidden_layers=5,
|
| 133 |
+
pad_token_id=1,
|
| 134 |
+
vocab_size=1000,
|
| 135 |
+
# SD2-specific config below
|
| 136 |
+
hidden_act="gelu",
|
| 137 |
+
projection_dim=32,
|
| 138 |
+
)
|
| 139 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 140 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 141 |
+
|
| 142 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 143 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 144 |
+
|
| 145 |
+
components = {
|
| 146 |
+
"unet": unet,
|
| 147 |
+
"controlnet": controlnet,
|
| 148 |
+
"scheduler": scheduler,
|
| 149 |
+
"vae": vae,
|
| 150 |
+
"text_encoder": text_encoder if not skip_first_text_encoder else None,
|
| 151 |
+
"tokenizer": tokenizer if not skip_first_text_encoder else None,
|
| 152 |
+
"text_encoder_2": text_encoder_2,
|
| 153 |
+
"tokenizer_2": tokenizer_2,
|
| 154 |
+
"image_encoder": None,
|
| 155 |
+
"feature_extractor": None,
|
| 156 |
+
}
|
| 157 |
+
return components
|
| 158 |
+
|
| 159 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 160 |
+
controlnet_embedder_scale_factor = 2
|
| 161 |
+
image = floats_tensor(
|
| 162 |
+
(1, 3, 32 * controlnet_embedder_scale_factor, 32 * controlnet_embedder_scale_factor),
|
| 163 |
+
rng=random.Random(seed),
|
| 164 |
+
).to(device)
|
| 165 |
+
|
| 166 |
+
if str(device).startswith("mps"):
|
| 167 |
+
generator = torch.manual_seed(seed)
|
| 168 |
+
else:
|
| 169 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 170 |
+
|
| 171 |
+
inputs = {
|
| 172 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 173 |
+
"generator": generator,
|
| 174 |
+
"num_inference_steps": 2,
|
| 175 |
+
"guidance_scale": 6.0,
|
| 176 |
+
"output_type": "np",
|
| 177 |
+
"image": image,
|
| 178 |
+
"control_image": image,
|
| 179 |
+
}
|
| 180 |
+
|
| 181 |
+
return inputs
|
| 182 |
+
|
| 183 |
+
def test_ip_adapter(self):
|
| 184 |
+
expected_pipe_slice = None
|
| 185 |
+
if torch_device == "cpu":
|
| 186 |
+
expected_pipe_slice = np.array([0.6276, 0.5271, 0.5205, 0.5393, 0.5774, 0.5872, 0.5456, 0.5415, 0.5354])
|
| 187 |
+
# TODO: update after slices.p
|
| 188 |
+
return super().test_ip_adapter(expected_pipe_slice=expected_pipe_slice)
|
| 189 |
+
|
| 190 |
+
def test_stable_diffusion_xl_controlnet_img2img(self):
|
| 191 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 192 |
+
components = self.get_dummy_components()
|
| 193 |
+
sd_pipe = self.pipeline_class(**components)
|
| 194 |
+
sd_pipe = sd_pipe.to(device)
|
| 195 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 196 |
+
|
| 197 |
+
inputs = self.get_dummy_inputs(device)
|
| 198 |
+
image = sd_pipe(**inputs).images
|
| 199 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 200 |
+
assert image.shape == (1, 64, 64, 3)
|
| 201 |
+
|
| 202 |
+
expected_slice = np.array(
|
| 203 |
+
[0.5557202, 0.46418434, 0.46983826, 0.623529, 0.5557242, 0.49262643, 0.6070508, 0.5702978, 0.43777135]
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 207 |
+
|
| 208 |
+
def test_stable_diffusion_xl_controlnet_img2img_guess(self):
|
| 209 |
+
device = "cpu"
|
| 210 |
+
|
| 211 |
+
components = self.get_dummy_components()
|
| 212 |
+
|
| 213 |
+
sd_pipe = self.pipeline_class(**components)
|
| 214 |
+
sd_pipe = sd_pipe.to(device)
|
| 215 |
+
|
| 216 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 217 |
+
|
| 218 |
+
inputs = self.get_dummy_inputs(device)
|
| 219 |
+
inputs["guess_mode"] = True
|
| 220 |
+
|
| 221 |
+
output = sd_pipe(**inputs)
|
| 222 |
+
image_slice = output.images[0, -3:, -3:, -1]
|
| 223 |
+
assert output.images.shape == (1, 64, 64, 3)
|
| 224 |
+
|
| 225 |
+
expected_slice = np.array(
|
| 226 |
+
[0.5557202, 0.46418434, 0.46983826, 0.623529, 0.5557242, 0.49262643, 0.6070508, 0.5702978, 0.43777135]
|
| 227 |
+
)
|
| 228 |
+
|
| 229 |
+
# make sure that it's equal
|
| 230 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 231 |
+
|
| 232 |
+
def test_attention_slicing_forward_pass(self):
|
| 233 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 234 |
+
|
| 235 |
+
@unittest.skipIf(
|
| 236 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 237 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 238 |
+
)
|
| 239 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 240 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 241 |
+
|
| 242 |
+
def test_inference_batch_single_identical(self):
|
| 243 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 244 |
+
|
| 245 |
+
# TODO(Patrick, Sayak) - skip for now as this requires more refiner tests
|
| 246 |
+
def test_save_load_optional_components(self):
|
| 247 |
+
pass
|
| 248 |
+
|
| 249 |
+
@require_torch_accelerator
|
| 250 |
+
def test_stable_diffusion_xl_offloads(self):
|
| 251 |
+
pipes = []
|
| 252 |
+
components = self.get_dummy_components()
|
| 253 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 254 |
+
pipes.append(sd_pipe)
|
| 255 |
+
|
| 256 |
+
components = self.get_dummy_components()
|
| 257 |
+
sd_pipe = self.pipeline_class(**components)
|
| 258 |
+
sd_pipe.enable_model_cpu_offload(device=torch_device)
|
| 259 |
+
pipes.append(sd_pipe)
|
| 260 |
+
|
| 261 |
+
components = self.get_dummy_components()
|
| 262 |
+
sd_pipe = self.pipeline_class(**components)
|
| 263 |
+
sd_pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 264 |
+
pipes.append(sd_pipe)
|
| 265 |
+
|
| 266 |
+
image_slices = []
|
| 267 |
+
for pipe in pipes:
|
| 268 |
+
pipe.unet.set_default_attn_processor()
|
| 269 |
+
|
| 270 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 271 |
+
image = pipe(**inputs).images
|
| 272 |
+
|
| 273 |
+
image_slices.append(image[0, -3:, -3:, -1].flatten())
|
| 274 |
+
|
| 275 |
+
assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
|
| 276 |
+
assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
|
| 277 |
+
|
| 278 |
+
def test_stable_diffusion_xl_multi_prompts(self):
|
| 279 |
+
components = self.get_dummy_components()
|
| 280 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 281 |
+
|
| 282 |
+
# forward with single prompt
|
| 283 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 284 |
+
output = sd_pipe(**inputs)
|
| 285 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 286 |
+
|
| 287 |
+
# forward with same prompt duplicated
|
| 288 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 289 |
+
inputs["prompt_2"] = inputs["prompt"]
|
| 290 |
+
output = sd_pipe(**inputs)
|
| 291 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 292 |
+
|
| 293 |
+
# ensure the results are equal
|
| 294 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 295 |
+
|
| 296 |
+
# forward with different prompt
|
| 297 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 298 |
+
inputs["prompt_2"] = "different prompt"
|
| 299 |
+
output = sd_pipe(**inputs)
|
| 300 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 301 |
+
|
| 302 |
+
# ensure the results are not equal
|
| 303 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 304 |
+
|
| 305 |
+
# manually set a negative_prompt
|
| 306 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 307 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 308 |
+
output = sd_pipe(**inputs)
|
| 309 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 310 |
+
|
| 311 |
+
# forward with same negative_prompt duplicated
|
| 312 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 313 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 314 |
+
inputs["negative_prompt_2"] = inputs["negative_prompt"]
|
| 315 |
+
output = sd_pipe(**inputs)
|
| 316 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 317 |
+
|
| 318 |
+
# ensure the results are equal
|
| 319 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 320 |
+
|
| 321 |
+
# forward with different negative_prompt
|
| 322 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 323 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 324 |
+
inputs["negative_prompt_2"] = "different negative prompt"
|
| 325 |
+
output = sd_pipe(**inputs)
|
| 326 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 327 |
+
|
| 328 |
+
# ensure the results are not equal
|
| 329 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet/test_flax_controlnet.py
ADDED
|
@@ -0,0 +1,127 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
from diffusers import FlaxControlNetModel, FlaxStableDiffusionControlNetPipeline
|
| 20 |
+
from diffusers.utils import is_flax_available, load_image
|
| 21 |
+
from diffusers.utils.testing_utils import require_flax, slow
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
if is_flax_available():
|
| 25 |
+
import jax
|
| 26 |
+
import jax.numpy as jnp
|
| 27 |
+
from flax.jax_utils import replicate
|
| 28 |
+
from flax.training.common_utils import shard
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@slow
|
| 32 |
+
@require_flax
|
| 33 |
+
class FlaxControlNetPipelineIntegrationTests(unittest.TestCase):
|
| 34 |
+
def tearDown(self):
|
| 35 |
+
# clean up the VRAM after each test
|
| 36 |
+
super().tearDown()
|
| 37 |
+
gc.collect()
|
| 38 |
+
|
| 39 |
+
def test_canny(self):
|
| 40 |
+
controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
|
| 41 |
+
"lllyasviel/sd-controlnet-canny", from_pt=True, dtype=jnp.bfloat16
|
| 42 |
+
)
|
| 43 |
+
pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
|
| 44 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, from_pt=True, dtype=jnp.bfloat16
|
| 45 |
+
)
|
| 46 |
+
params["controlnet"] = controlnet_params
|
| 47 |
+
|
| 48 |
+
prompts = "bird"
|
| 49 |
+
num_samples = jax.device_count()
|
| 50 |
+
prompt_ids = pipe.prepare_text_inputs([prompts] * num_samples)
|
| 51 |
+
|
| 52 |
+
canny_image = load_image(
|
| 53 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 54 |
+
)
|
| 55 |
+
processed_image = pipe.prepare_image_inputs([canny_image] * num_samples)
|
| 56 |
+
|
| 57 |
+
rng = jax.random.PRNGKey(0)
|
| 58 |
+
rng = jax.random.split(rng, jax.device_count())
|
| 59 |
+
|
| 60 |
+
p_params = replicate(params)
|
| 61 |
+
prompt_ids = shard(prompt_ids)
|
| 62 |
+
processed_image = shard(processed_image)
|
| 63 |
+
|
| 64 |
+
images = pipe(
|
| 65 |
+
prompt_ids=prompt_ids,
|
| 66 |
+
image=processed_image,
|
| 67 |
+
params=p_params,
|
| 68 |
+
prng_seed=rng,
|
| 69 |
+
num_inference_steps=50,
|
| 70 |
+
jit=True,
|
| 71 |
+
).images
|
| 72 |
+
assert images.shape == (jax.device_count(), 1, 768, 512, 3)
|
| 73 |
+
|
| 74 |
+
images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
|
| 75 |
+
image_slice = images[0, 253:256, 253:256, -1]
|
| 76 |
+
|
| 77 |
+
output_slice = jnp.asarray(jax.device_get(image_slice.flatten()))
|
| 78 |
+
expected_slice = jnp.array(
|
| 79 |
+
[0.167969, 0.116699, 0.081543, 0.154297, 0.132812, 0.108887, 0.169922, 0.169922, 0.205078]
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
assert jnp.abs(output_slice - expected_slice).max() < 1e-2
|
| 83 |
+
|
| 84 |
+
def test_pose(self):
|
| 85 |
+
controlnet, controlnet_params = FlaxControlNetModel.from_pretrained(
|
| 86 |
+
"lllyasviel/sd-controlnet-openpose", from_pt=True, dtype=jnp.bfloat16
|
| 87 |
+
)
|
| 88 |
+
pipe, params = FlaxStableDiffusionControlNetPipeline.from_pretrained(
|
| 89 |
+
"stable-diffusion-v1-5/stable-diffusion-v1-5", controlnet=controlnet, from_pt=True, dtype=jnp.bfloat16
|
| 90 |
+
)
|
| 91 |
+
params["controlnet"] = controlnet_params
|
| 92 |
+
|
| 93 |
+
prompts = "Chef in the kitchen"
|
| 94 |
+
num_samples = jax.device_count()
|
| 95 |
+
prompt_ids = pipe.prepare_text_inputs([prompts] * num_samples)
|
| 96 |
+
|
| 97 |
+
pose_image = load_image(
|
| 98 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/pose.png"
|
| 99 |
+
)
|
| 100 |
+
processed_image = pipe.prepare_image_inputs([pose_image] * num_samples)
|
| 101 |
+
|
| 102 |
+
rng = jax.random.PRNGKey(0)
|
| 103 |
+
rng = jax.random.split(rng, jax.device_count())
|
| 104 |
+
|
| 105 |
+
p_params = replicate(params)
|
| 106 |
+
prompt_ids = shard(prompt_ids)
|
| 107 |
+
processed_image = shard(processed_image)
|
| 108 |
+
|
| 109 |
+
images = pipe(
|
| 110 |
+
prompt_ids=prompt_ids,
|
| 111 |
+
image=processed_image,
|
| 112 |
+
params=p_params,
|
| 113 |
+
prng_seed=rng,
|
| 114 |
+
num_inference_steps=50,
|
| 115 |
+
jit=True,
|
| 116 |
+
).images
|
| 117 |
+
assert images.shape == (jax.device_count(), 1, 768, 512, 3)
|
| 118 |
+
|
| 119 |
+
images = images.reshape((images.shape[0] * images.shape[1],) + images.shape[-3:])
|
| 120 |
+
image_slice = images[0, 253:256, 253:256, -1]
|
| 121 |
+
|
| 122 |
+
output_slice = jnp.asarray(jax.device_get(image_slice.flatten()))
|
| 123 |
+
expected_slice = jnp.array(
|
| 124 |
+
[[0.271484, 0.261719, 0.275391, 0.277344, 0.279297, 0.291016, 0.294922, 0.302734, 0.302734]]
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
assert jnp.abs(output_slice - expected_slice).max() < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc and The InstantX Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import pytest
|
| 21 |
+
import torch
|
| 22 |
+
from huggingface_hub import hf_hub_download
|
| 23 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
| 24 |
+
|
| 25 |
+
from diffusers import (
|
| 26 |
+
AutoencoderKL,
|
| 27 |
+
FlowMatchEulerDiscreteScheduler,
|
| 28 |
+
FluxControlNetPipeline,
|
| 29 |
+
FluxTransformer2DModel,
|
| 30 |
+
)
|
| 31 |
+
from diffusers.models import FluxControlNetModel
|
| 32 |
+
from diffusers.utils import load_image
|
| 33 |
+
from diffusers.utils.testing_utils import (
|
| 34 |
+
backend_empty_cache,
|
| 35 |
+
enable_full_determinism,
|
| 36 |
+
nightly,
|
| 37 |
+
numpy_cosine_similarity_distance,
|
| 38 |
+
require_big_accelerator,
|
| 39 |
+
torch_device,
|
| 40 |
+
)
|
| 41 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 42 |
+
|
| 43 |
+
from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
enable_full_determinism()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class FluxControlNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin, FluxIPAdapterTesterMixin):
|
| 50 |
+
pipeline_class = FluxControlNetPipeline
|
| 51 |
+
|
| 52 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 53 |
+
batch_params = frozenset(["prompt"])
|
| 54 |
+
test_layerwise_casting = True
|
| 55 |
+
test_group_offloading = True
|
| 56 |
+
|
| 57 |
+
def get_dummy_components(self):
|
| 58 |
+
torch.manual_seed(0)
|
| 59 |
+
transformer = FluxTransformer2DModel(
|
| 60 |
+
patch_size=1,
|
| 61 |
+
in_channels=16,
|
| 62 |
+
num_layers=1,
|
| 63 |
+
num_single_layers=1,
|
| 64 |
+
attention_head_dim=16,
|
| 65 |
+
num_attention_heads=2,
|
| 66 |
+
joint_attention_dim=32,
|
| 67 |
+
pooled_projection_dim=32,
|
| 68 |
+
axes_dims_rope=[4, 4, 8],
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
torch.manual_seed(0)
|
| 72 |
+
controlnet = FluxControlNetModel(
|
| 73 |
+
patch_size=1,
|
| 74 |
+
in_channels=16,
|
| 75 |
+
num_layers=1,
|
| 76 |
+
num_single_layers=1,
|
| 77 |
+
attention_head_dim=16,
|
| 78 |
+
num_attention_heads=2,
|
| 79 |
+
joint_attention_dim=32,
|
| 80 |
+
pooled_projection_dim=32,
|
| 81 |
+
axes_dims_rope=[4, 4, 8],
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 85 |
+
bos_token_id=0,
|
| 86 |
+
eos_token_id=2,
|
| 87 |
+
hidden_size=32,
|
| 88 |
+
intermediate_size=37,
|
| 89 |
+
layer_norm_eps=1e-05,
|
| 90 |
+
num_attention_heads=4,
|
| 91 |
+
num_hidden_layers=5,
|
| 92 |
+
pad_token_id=1,
|
| 93 |
+
vocab_size=1000,
|
| 94 |
+
hidden_act="gelu",
|
| 95 |
+
projection_dim=32,
|
| 96 |
+
)
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 99 |
+
|
| 100 |
+
torch.manual_seed(0)
|
| 101 |
+
text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 102 |
+
|
| 103 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 104 |
+
tokenizer_2 = T5TokenizerFast.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 105 |
+
|
| 106 |
+
torch.manual_seed(0)
|
| 107 |
+
vae = AutoencoderKL(
|
| 108 |
+
sample_size=32,
|
| 109 |
+
in_channels=3,
|
| 110 |
+
out_channels=3,
|
| 111 |
+
block_out_channels=(4,),
|
| 112 |
+
layers_per_block=1,
|
| 113 |
+
latent_channels=4,
|
| 114 |
+
norm_num_groups=1,
|
| 115 |
+
use_quant_conv=False,
|
| 116 |
+
use_post_quant_conv=False,
|
| 117 |
+
shift_factor=0.0609,
|
| 118 |
+
scaling_factor=1.5035,
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 122 |
+
|
| 123 |
+
return {
|
| 124 |
+
"scheduler": scheduler,
|
| 125 |
+
"text_encoder": text_encoder,
|
| 126 |
+
"text_encoder_2": text_encoder_2,
|
| 127 |
+
"tokenizer": tokenizer,
|
| 128 |
+
"tokenizer_2": tokenizer_2,
|
| 129 |
+
"transformer": transformer,
|
| 130 |
+
"vae": vae,
|
| 131 |
+
"controlnet": controlnet,
|
| 132 |
+
"image_encoder": None,
|
| 133 |
+
"feature_extractor": None,
|
| 134 |
+
}
|
| 135 |
+
|
| 136 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 137 |
+
if str(device).startswith("mps"):
|
| 138 |
+
generator = torch.manual_seed(seed)
|
| 139 |
+
else:
|
| 140 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 141 |
+
|
| 142 |
+
control_image = randn_tensor(
|
| 143 |
+
(1, 3, 32, 32),
|
| 144 |
+
generator=generator,
|
| 145 |
+
device=torch.device(device),
|
| 146 |
+
dtype=torch.float16,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
controlnet_conditioning_scale = 0.5
|
| 150 |
+
|
| 151 |
+
inputs = {
|
| 152 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 153 |
+
"generator": generator,
|
| 154 |
+
"num_inference_steps": 2,
|
| 155 |
+
"guidance_scale": 3.5,
|
| 156 |
+
"output_type": "np",
|
| 157 |
+
"control_image": control_image,
|
| 158 |
+
"controlnet_conditioning_scale": controlnet_conditioning_scale,
|
| 159 |
+
}
|
| 160 |
+
|
| 161 |
+
return inputs
|
| 162 |
+
|
| 163 |
+
def test_controlnet_flux(self):
|
| 164 |
+
components = self.get_dummy_components()
|
| 165 |
+
flux_pipe = FluxControlNetPipeline(**components)
|
| 166 |
+
flux_pipe = flux_pipe.to(torch_device, dtype=torch.float16)
|
| 167 |
+
flux_pipe.set_progress_bar_config(disable=None)
|
| 168 |
+
|
| 169 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 170 |
+
output = flux_pipe(**inputs)
|
| 171 |
+
image = output.images
|
| 172 |
+
|
| 173 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 174 |
+
|
| 175 |
+
assert image.shape == (1, 32, 32, 3)
|
| 176 |
+
|
| 177 |
+
expected_slice = np.array(
|
| 178 |
+
[0.47387695, 0.63134766, 0.5605469, 0.61621094, 0.7207031, 0.7089844, 0.70410156, 0.6113281, 0.64160156]
|
| 179 |
+
)
|
| 180 |
+
|
| 181 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
|
| 182 |
+
f"Expected: {expected_slice}, got: {image_slice.flatten()}"
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
@unittest.skip("xFormersAttnProcessor does not work with SD3 Joint Attention")
|
| 186 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 187 |
+
pass
|
| 188 |
+
|
| 189 |
+
def test_flux_image_output_shape(self):
|
| 190 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 191 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 192 |
+
|
| 193 |
+
height_width_pairs = [(32, 32), (72, 56)]
|
| 194 |
+
for height, width in height_width_pairs:
|
| 195 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 196 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 197 |
+
|
| 198 |
+
inputs.update(
|
| 199 |
+
{
|
| 200 |
+
"control_image": randn_tensor(
|
| 201 |
+
(1, 3, height, width),
|
| 202 |
+
device=torch_device,
|
| 203 |
+
dtype=torch.float16,
|
| 204 |
+
)
|
| 205 |
+
}
|
| 206 |
+
)
|
| 207 |
+
image = pipe(**inputs).images[0]
|
| 208 |
+
output_height, output_width, _ = image.shape
|
| 209 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
| 210 |
+
|
| 211 |
+
|
| 212 |
+
@nightly
|
| 213 |
+
@require_big_accelerator
|
| 214 |
+
@pytest.mark.big_accelerator
|
| 215 |
+
class FluxControlNetPipelineSlowTests(unittest.TestCase):
|
| 216 |
+
pipeline_class = FluxControlNetPipeline
|
| 217 |
+
|
| 218 |
+
def setUp(self):
|
| 219 |
+
super().setUp()
|
| 220 |
+
gc.collect()
|
| 221 |
+
backend_empty_cache(torch_device)
|
| 222 |
+
|
| 223 |
+
def tearDown(self):
|
| 224 |
+
super().tearDown()
|
| 225 |
+
gc.collect()
|
| 226 |
+
backend_empty_cache(torch_device)
|
| 227 |
+
|
| 228 |
+
def test_canny(self):
|
| 229 |
+
controlnet = FluxControlNetModel.from_pretrained(
|
| 230 |
+
"InstantX/FLUX.1-dev-Controlnet-Canny-alpha", torch_dtype=torch.bfloat16
|
| 231 |
+
)
|
| 232 |
+
pipe = FluxControlNetPipeline.from_pretrained(
|
| 233 |
+
"black-forest-labs/FLUX.1-dev",
|
| 234 |
+
text_encoder=None,
|
| 235 |
+
text_encoder_2=None,
|
| 236 |
+
controlnet=controlnet,
|
| 237 |
+
torch_dtype=torch.bfloat16,
|
| 238 |
+
).to(torch_device)
|
| 239 |
+
pipe.set_progress_bar_config(disable=None)
|
| 240 |
+
|
| 241 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 242 |
+
control_image = load_image(
|
| 243 |
+
"https://huggingface.co/InstantX/FLUX.1-dev-Controlnet-Canny-alpha/resolve/main/canny.jpg"
|
| 244 |
+
).resize((512, 512))
|
| 245 |
+
|
| 246 |
+
prompt_embeds = torch.load(
|
| 247 |
+
hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
|
| 248 |
+
).to(torch_device)
|
| 249 |
+
pooled_prompt_embeds = torch.load(
|
| 250 |
+
hf_hub_download(
|
| 251 |
+
repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
|
| 252 |
+
)
|
| 253 |
+
).to(torch_device)
|
| 254 |
+
|
| 255 |
+
output = pipe(
|
| 256 |
+
prompt_embeds=prompt_embeds,
|
| 257 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 258 |
+
control_image=control_image,
|
| 259 |
+
controlnet_conditioning_scale=0.6,
|
| 260 |
+
num_inference_steps=2,
|
| 261 |
+
guidance_scale=3.5,
|
| 262 |
+
max_sequence_length=256,
|
| 263 |
+
output_type="np",
|
| 264 |
+
height=512,
|
| 265 |
+
width=512,
|
| 266 |
+
generator=generator,
|
| 267 |
+
)
|
| 268 |
+
|
| 269 |
+
image = output.images[0]
|
| 270 |
+
|
| 271 |
+
assert image.shape == (512, 512, 3)
|
| 272 |
+
|
| 273 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 274 |
+
|
| 275 |
+
expected_image = np.array([0.2734, 0.2852, 0.2852, 0.2734, 0.2754, 0.2891, 0.2617, 0.2637, 0.2773])
|
| 276 |
+
|
| 277 |
+
assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux_img2img.py
ADDED
|
@@ -0,0 +1,225 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 6 |
+
|
| 7 |
+
from diffusers import (
|
| 8 |
+
AutoencoderKL,
|
| 9 |
+
FlowMatchEulerDiscreteScheduler,
|
| 10 |
+
FluxControlNetImg2ImgPipeline,
|
| 11 |
+
FluxControlNetModel,
|
| 12 |
+
FluxTransformer2DModel,
|
| 13 |
+
)
|
| 14 |
+
from diffusers.utils.testing_utils import (
|
| 15 |
+
torch_device,
|
| 16 |
+
)
|
| 17 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 18 |
+
|
| 19 |
+
from ..test_pipelines_common import (
|
| 20 |
+
PipelineTesterMixin,
|
| 21 |
+
check_qkv_fusion_matches_attn_procs_length,
|
| 22 |
+
check_qkv_fusion_processors_exist,
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class FluxControlNetImg2ImgPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 27 |
+
pipeline_class = FluxControlNetImg2ImgPipeline
|
| 28 |
+
params = frozenset(
|
| 29 |
+
[
|
| 30 |
+
"prompt",
|
| 31 |
+
"image",
|
| 32 |
+
"control_image",
|
| 33 |
+
"height",
|
| 34 |
+
"width",
|
| 35 |
+
"strength",
|
| 36 |
+
"guidance_scale",
|
| 37 |
+
"controlnet_conditioning_scale",
|
| 38 |
+
"prompt_embeds",
|
| 39 |
+
"pooled_prompt_embeds",
|
| 40 |
+
]
|
| 41 |
+
)
|
| 42 |
+
batch_params = frozenset(["prompt", "image", "control_image"])
|
| 43 |
+
|
| 44 |
+
test_xformers_attention = False
|
| 45 |
+
|
| 46 |
+
def get_dummy_components(self):
|
| 47 |
+
torch.manual_seed(0)
|
| 48 |
+
transformer = FluxTransformer2DModel(
|
| 49 |
+
patch_size=1,
|
| 50 |
+
in_channels=4,
|
| 51 |
+
num_layers=1,
|
| 52 |
+
num_single_layers=1,
|
| 53 |
+
attention_head_dim=16,
|
| 54 |
+
num_attention_heads=2,
|
| 55 |
+
joint_attention_dim=32,
|
| 56 |
+
pooled_projection_dim=32,
|
| 57 |
+
axes_dims_rope=[4, 4, 8],
|
| 58 |
+
)
|
| 59 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 60 |
+
bos_token_id=0,
|
| 61 |
+
eos_token_id=2,
|
| 62 |
+
hidden_size=32,
|
| 63 |
+
intermediate_size=37,
|
| 64 |
+
layer_norm_eps=1e-05,
|
| 65 |
+
num_attention_heads=4,
|
| 66 |
+
num_hidden_layers=5,
|
| 67 |
+
pad_token_id=1,
|
| 68 |
+
vocab_size=1000,
|
| 69 |
+
hidden_act="gelu",
|
| 70 |
+
projection_dim=32,
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
torch.manual_seed(0)
|
| 74 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 75 |
+
|
| 76 |
+
torch.manual_seed(0)
|
| 77 |
+
text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 78 |
+
|
| 79 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 80 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 81 |
+
|
| 82 |
+
torch.manual_seed(0)
|
| 83 |
+
vae = AutoencoderKL(
|
| 84 |
+
sample_size=32,
|
| 85 |
+
in_channels=3,
|
| 86 |
+
out_channels=3,
|
| 87 |
+
block_out_channels=(4,),
|
| 88 |
+
layers_per_block=1,
|
| 89 |
+
latent_channels=1,
|
| 90 |
+
norm_num_groups=1,
|
| 91 |
+
use_quant_conv=False,
|
| 92 |
+
use_post_quant_conv=False,
|
| 93 |
+
shift_factor=0.0609,
|
| 94 |
+
scaling_factor=1.5035,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
controlnet = FluxControlNetModel(
|
| 99 |
+
in_channels=4,
|
| 100 |
+
num_layers=1,
|
| 101 |
+
num_single_layers=1,
|
| 102 |
+
attention_head_dim=16,
|
| 103 |
+
num_attention_heads=2,
|
| 104 |
+
joint_attention_dim=32,
|
| 105 |
+
pooled_projection_dim=32,
|
| 106 |
+
axes_dims_rope=[4, 4, 8],
|
| 107 |
+
)
|
| 108 |
+
|
| 109 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 110 |
+
|
| 111 |
+
return {
|
| 112 |
+
"scheduler": scheduler,
|
| 113 |
+
"text_encoder": text_encoder,
|
| 114 |
+
"text_encoder_2": text_encoder_2,
|
| 115 |
+
"tokenizer": tokenizer,
|
| 116 |
+
"tokenizer_2": tokenizer_2,
|
| 117 |
+
"transformer": transformer,
|
| 118 |
+
"vae": vae,
|
| 119 |
+
"controlnet": controlnet,
|
| 120 |
+
}
|
| 121 |
+
|
| 122 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 123 |
+
if str(device).startswith("mps"):
|
| 124 |
+
generator = torch.manual_seed(seed)
|
| 125 |
+
else:
|
| 126 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 127 |
+
|
| 128 |
+
image = torch.randn(1, 3, 32, 32).to(device)
|
| 129 |
+
control_image = torch.randn(1, 3, 32, 32).to(device)
|
| 130 |
+
|
| 131 |
+
inputs = {
|
| 132 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 133 |
+
"image": image,
|
| 134 |
+
"control_image": control_image,
|
| 135 |
+
"generator": generator,
|
| 136 |
+
"num_inference_steps": 2,
|
| 137 |
+
"guidance_scale": 5.0,
|
| 138 |
+
"controlnet_conditioning_scale": 1.0,
|
| 139 |
+
"strength": 0.8,
|
| 140 |
+
"height": 32,
|
| 141 |
+
"width": 32,
|
| 142 |
+
"max_sequence_length": 48,
|
| 143 |
+
"output_type": "np",
|
| 144 |
+
}
|
| 145 |
+
return inputs
|
| 146 |
+
|
| 147 |
+
def test_flux_controlnet_different_prompts(self):
|
| 148 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 149 |
+
|
| 150 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 151 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 152 |
+
|
| 153 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 154 |
+
inputs["prompt_2"] = "a different prompt"
|
| 155 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 156 |
+
|
| 157 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 158 |
+
|
| 159 |
+
assert max_diff > 1e-6
|
| 160 |
+
|
| 161 |
+
def test_fused_qkv_projections(self):
|
| 162 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 163 |
+
components = self.get_dummy_components()
|
| 164 |
+
pipe = self.pipeline_class(**components)
|
| 165 |
+
pipe = pipe.to(device)
|
| 166 |
+
pipe.set_progress_bar_config(disable=None)
|
| 167 |
+
|
| 168 |
+
inputs = self.get_dummy_inputs(device)
|
| 169 |
+
image = pipe(**inputs).images
|
| 170 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 171 |
+
|
| 172 |
+
pipe.transformer.fuse_qkv_projections()
|
| 173 |
+
assert check_qkv_fusion_processors_exist(pipe.transformer), (
|
| 174 |
+
"Something wrong with the fused attention processors. Expected all the attention processors to be fused."
|
| 175 |
+
)
|
| 176 |
+
assert check_qkv_fusion_matches_attn_procs_length(
|
| 177 |
+
pipe.transformer, pipe.transformer.original_attn_processors
|
| 178 |
+
), "Something wrong with the attention processors concerning the fused QKV projections."
|
| 179 |
+
|
| 180 |
+
inputs = self.get_dummy_inputs(device)
|
| 181 |
+
image = pipe(**inputs).images
|
| 182 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 183 |
+
|
| 184 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 185 |
+
inputs = self.get_dummy_inputs(device)
|
| 186 |
+
image = pipe(**inputs).images
|
| 187 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 188 |
+
|
| 189 |
+
assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
|
| 190 |
+
"Fusion of QKV projections shouldn't affect the outputs."
|
| 191 |
+
)
|
| 192 |
+
assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
|
| 193 |
+
"Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
|
| 194 |
+
)
|
| 195 |
+
assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
|
| 196 |
+
"Original outputs should match when fused QKV projections are disabled."
|
| 197 |
+
)
|
| 198 |
+
|
| 199 |
+
def test_flux_image_output_shape(self):
|
| 200 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 201 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 202 |
+
|
| 203 |
+
height_width_pairs = [(32, 32), (72, 56)]
|
| 204 |
+
for height, width in height_width_pairs:
|
| 205 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 206 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 207 |
+
inputs.update(
|
| 208 |
+
{
|
| 209 |
+
"control_image": randn_tensor(
|
| 210 |
+
(1, 3, height, width),
|
| 211 |
+
device=torch_device,
|
| 212 |
+
dtype=torch.float16,
|
| 213 |
+
),
|
| 214 |
+
"image": randn_tensor(
|
| 215 |
+
(1, 3, height, width),
|
| 216 |
+
device=torch_device,
|
| 217 |
+
dtype=torch.float16,
|
| 218 |
+
),
|
| 219 |
+
"height": height,
|
| 220 |
+
"width": width,
|
| 221 |
+
}
|
| 222 |
+
)
|
| 223 |
+
image = pipe(**inputs).images[0]
|
| 224 |
+
output_height, output_width, _ = image.shape
|
| 225 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_flux/test_controlnet_flux_inpaint.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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device, # {{ edit_1 }} Removed unused import
|
| 8 |
+
from transformers import (
|
| 9 |
+
AutoTokenizer,
|
| 10 |
+
CLIPTextConfig,
|
| 11 |
+
CLIPTextModel,
|
| 12 |
+
CLIPTokenizer,
|
| 13 |
+
T5EncoderModel,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from diffusers import (
|
| 17 |
+
AutoencoderKL,
|
| 18 |
+
FlowMatchEulerDiscreteScheduler,
|
| 19 |
+
FluxControlNetInpaintPipeline,
|
| 20 |
+
FluxControlNetModel,
|
| 21 |
+
FluxTransformer2DModel,
|
| 22 |
+
)
|
| 23 |
+
from diffusers.utils.testing_utils import (
|
| 24 |
+
enable_full_determinism,
|
| 25 |
+
floats_tensor,
|
| 26 |
+
torch_device,
|
| 27 |
+
)
|
| 28 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 29 |
+
|
| 30 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
enable_full_determinism()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class FluxControlNetInpaintPipelineTests(unittest.TestCase, PipelineTesterMixin):
|
| 37 |
+
pipeline_class = FluxControlNetInpaintPipeline
|
| 38 |
+
params = frozenset(
|
| 39 |
+
[
|
| 40 |
+
"prompt",
|
| 41 |
+
"height",
|
| 42 |
+
"width",
|
| 43 |
+
"guidance_scale",
|
| 44 |
+
"prompt_embeds",
|
| 45 |
+
"pooled_prompt_embeds",
|
| 46 |
+
"image",
|
| 47 |
+
"mask_image",
|
| 48 |
+
"control_image",
|
| 49 |
+
"strength",
|
| 50 |
+
"num_inference_steps",
|
| 51 |
+
"controlnet_conditioning_scale",
|
| 52 |
+
]
|
| 53 |
+
)
|
| 54 |
+
batch_params = frozenset(["prompt", "image", "mask_image", "control_image"])
|
| 55 |
+
test_xformers_attention = False
|
| 56 |
+
|
| 57 |
+
def get_dummy_components(self):
|
| 58 |
+
torch.manual_seed(0)
|
| 59 |
+
transformer = FluxTransformer2DModel(
|
| 60 |
+
patch_size=1,
|
| 61 |
+
in_channels=8,
|
| 62 |
+
num_layers=1,
|
| 63 |
+
num_single_layers=1,
|
| 64 |
+
attention_head_dim=16,
|
| 65 |
+
num_attention_heads=2,
|
| 66 |
+
joint_attention_dim=32,
|
| 67 |
+
pooled_projection_dim=32,
|
| 68 |
+
axes_dims_rope=[4, 4, 8],
|
| 69 |
+
)
|
| 70 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 71 |
+
bos_token_id=0,
|
| 72 |
+
eos_token_id=2,
|
| 73 |
+
hidden_size=32,
|
| 74 |
+
intermediate_size=37,
|
| 75 |
+
layer_norm_eps=1e-05,
|
| 76 |
+
num_attention_heads=4,
|
| 77 |
+
num_hidden_layers=5,
|
| 78 |
+
pad_token_id=1,
|
| 79 |
+
vocab_size=1000,
|
| 80 |
+
hidden_act="gelu",
|
| 81 |
+
projection_dim=32,
|
| 82 |
+
)
|
| 83 |
+
|
| 84 |
+
torch.manual_seed(0)
|
| 85 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 86 |
+
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 89 |
+
|
| 90 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 91 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 92 |
+
|
| 93 |
+
torch.manual_seed(0)
|
| 94 |
+
vae = AutoencoderKL(
|
| 95 |
+
sample_size=32,
|
| 96 |
+
in_channels=3,
|
| 97 |
+
out_channels=3,
|
| 98 |
+
block_out_channels=(4,),
|
| 99 |
+
layers_per_block=1,
|
| 100 |
+
latent_channels=2,
|
| 101 |
+
norm_num_groups=1,
|
| 102 |
+
use_quant_conv=False,
|
| 103 |
+
use_post_quant_conv=False,
|
| 104 |
+
shift_factor=0.0609,
|
| 105 |
+
scaling_factor=1.5035,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
torch.manual_seed(0)
|
| 109 |
+
controlnet = FluxControlNetModel(
|
| 110 |
+
patch_size=1,
|
| 111 |
+
in_channels=8,
|
| 112 |
+
num_layers=1,
|
| 113 |
+
num_single_layers=1,
|
| 114 |
+
attention_head_dim=16,
|
| 115 |
+
num_attention_heads=2,
|
| 116 |
+
joint_attention_dim=32,
|
| 117 |
+
pooled_projection_dim=32,
|
| 118 |
+
axes_dims_rope=[4, 4, 8],
|
| 119 |
+
)
|
| 120 |
+
|
| 121 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 122 |
+
|
| 123 |
+
return {
|
| 124 |
+
"scheduler": scheduler,
|
| 125 |
+
"text_encoder": text_encoder,
|
| 126 |
+
"text_encoder_2": text_encoder_2,
|
| 127 |
+
"tokenizer": tokenizer,
|
| 128 |
+
"tokenizer_2": tokenizer_2,
|
| 129 |
+
"transformer": transformer,
|
| 130 |
+
"vae": vae,
|
| 131 |
+
"controlnet": controlnet,
|
| 132 |
+
}
|
| 133 |
+
|
| 134 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 135 |
+
if str(device).startswith("mps"):
|
| 136 |
+
generator = torch.manual_seed(seed)
|
| 137 |
+
else:
|
| 138 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 139 |
+
|
| 140 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 141 |
+
mask_image = torch.ones((1, 1, 32, 32)).to(device)
|
| 142 |
+
control_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 143 |
+
|
| 144 |
+
inputs = {
|
| 145 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 146 |
+
"image": image,
|
| 147 |
+
"mask_image": mask_image,
|
| 148 |
+
"control_image": control_image,
|
| 149 |
+
"generator": generator,
|
| 150 |
+
"num_inference_steps": 2,
|
| 151 |
+
"guidance_scale": 5.0,
|
| 152 |
+
"height": 32,
|
| 153 |
+
"width": 32,
|
| 154 |
+
"max_sequence_length": 48,
|
| 155 |
+
"strength": 0.8,
|
| 156 |
+
"output_type": "np",
|
| 157 |
+
}
|
| 158 |
+
return inputs
|
| 159 |
+
|
| 160 |
+
def test_flux_controlnet_inpaint_with_num_images_per_prompt(self):
|
| 161 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 162 |
+
components = self.get_dummy_components()
|
| 163 |
+
pipe = self.pipeline_class(**components)
|
| 164 |
+
pipe = pipe.to(device)
|
| 165 |
+
pipe.set_progress_bar_config(disable=None)
|
| 166 |
+
|
| 167 |
+
inputs = self.get_dummy_inputs(device)
|
| 168 |
+
inputs["num_images_per_prompt"] = 2
|
| 169 |
+
output = pipe(**inputs)
|
| 170 |
+
images = output.images
|
| 171 |
+
|
| 172 |
+
assert images.shape == (2, 32, 32, 3)
|
| 173 |
+
|
| 174 |
+
def test_flux_controlnet_inpaint_with_controlnet_conditioning_scale(self):
|
| 175 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 176 |
+
components = self.get_dummy_components()
|
| 177 |
+
pipe = self.pipeline_class(**components)
|
| 178 |
+
pipe = pipe.to(device)
|
| 179 |
+
pipe.set_progress_bar_config(disable=None)
|
| 180 |
+
|
| 181 |
+
inputs = self.get_dummy_inputs(device)
|
| 182 |
+
output_default = pipe(**inputs)
|
| 183 |
+
image_default = output_default.images
|
| 184 |
+
|
| 185 |
+
inputs["controlnet_conditioning_scale"] = 0.5
|
| 186 |
+
output_scaled = pipe(**inputs)
|
| 187 |
+
image_scaled = output_scaled.images
|
| 188 |
+
|
| 189 |
+
# Ensure that changing the controlnet_conditioning_scale produces a different output
|
| 190 |
+
assert not np.allclose(image_default, image_scaled, atol=0.01)
|
| 191 |
+
|
| 192 |
+
def test_attention_slicing_forward_pass(self):
|
| 193 |
+
super().test_attention_slicing_forward_pass(expected_max_diff=3e-3)
|
| 194 |
+
|
| 195 |
+
def test_inference_batch_single_identical(self):
|
| 196 |
+
super().test_inference_batch_single_identical(expected_max_diff=3e-3)
|
| 197 |
+
|
| 198 |
+
def test_flux_image_output_shape(self):
|
| 199 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 200 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 201 |
+
|
| 202 |
+
height_width_pairs = [(32, 32), (72, 56)]
|
| 203 |
+
for height, width in height_width_pairs:
|
| 204 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 205 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 206 |
+
|
| 207 |
+
inputs.update(
|
| 208 |
+
{
|
| 209 |
+
"control_image": randn_tensor(
|
| 210 |
+
(1, 3, height, width),
|
| 211 |
+
device=torch_device,
|
| 212 |
+
dtype=torch.float16,
|
| 213 |
+
),
|
| 214 |
+
"image": randn_tensor(
|
| 215 |
+
(1, 3, height, width),
|
| 216 |
+
device=torch_device,
|
| 217 |
+
dtype=torch.float16,
|
| 218 |
+
),
|
| 219 |
+
"mask_image": torch.ones((1, 1, height, width)).to(torch_device),
|
| 220 |
+
"height": height,
|
| 221 |
+
"width": width,
|
| 222 |
+
}
|
| 223 |
+
)
|
| 224 |
+
image = pipe(**inputs).images[0]
|
| 225 |
+
output_height, output_width, _ = image.shape
|
| 226 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_hunyuandit/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_hunyuandit/test_controlnet_hunyuandit.py
ADDED
|
@@ -0,0 +1,364 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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 2025 HuggingFace Inc and Tencent Hunyuan Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import AutoTokenizer, BertModel, T5EncoderModel
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKL,
|
| 25 |
+
DDPMScheduler,
|
| 26 |
+
HunyuanDiT2DModel,
|
| 27 |
+
HunyuanDiTControlNetPipeline,
|
| 28 |
+
)
|
| 29 |
+
from diffusers.models import HunyuanDiT2DControlNetModel, HunyuanDiT2DMultiControlNetModel
|
| 30 |
+
from diffusers.utils import load_image
|
| 31 |
+
from diffusers.utils.testing_utils import (
|
| 32 |
+
backend_empty_cache,
|
| 33 |
+
enable_full_determinism,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
slow,
|
| 36 |
+
torch_device,
|
| 37 |
+
)
|
| 38 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 39 |
+
|
| 40 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
enable_full_determinism()
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
class HunyuanDiTControlNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 47 |
+
pipeline_class = HunyuanDiTControlNetPipeline
|
| 48 |
+
params = frozenset(
|
| 49 |
+
[
|
| 50 |
+
"prompt",
|
| 51 |
+
"height",
|
| 52 |
+
"width",
|
| 53 |
+
"guidance_scale",
|
| 54 |
+
"negative_prompt",
|
| 55 |
+
"prompt_embeds",
|
| 56 |
+
"negative_prompt_embeds",
|
| 57 |
+
]
|
| 58 |
+
)
|
| 59 |
+
batch_params = frozenset(["prompt", "negative_prompt"])
|
| 60 |
+
test_layerwise_casting = True
|
| 61 |
+
|
| 62 |
+
def get_dummy_components(self):
|
| 63 |
+
torch.manual_seed(0)
|
| 64 |
+
transformer = HunyuanDiT2DModel(
|
| 65 |
+
sample_size=16,
|
| 66 |
+
num_layers=4,
|
| 67 |
+
patch_size=2,
|
| 68 |
+
attention_head_dim=8,
|
| 69 |
+
num_attention_heads=3,
|
| 70 |
+
in_channels=4,
|
| 71 |
+
cross_attention_dim=32,
|
| 72 |
+
cross_attention_dim_t5=32,
|
| 73 |
+
pooled_projection_dim=16,
|
| 74 |
+
hidden_size=24,
|
| 75 |
+
activation_fn="gelu-approximate",
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
controlnet = HunyuanDiT2DControlNetModel(
|
| 80 |
+
sample_size=16,
|
| 81 |
+
transformer_num_layers=4,
|
| 82 |
+
patch_size=2,
|
| 83 |
+
attention_head_dim=8,
|
| 84 |
+
num_attention_heads=3,
|
| 85 |
+
in_channels=4,
|
| 86 |
+
cross_attention_dim=32,
|
| 87 |
+
cross_attention_dim_t5=32,
|
| 88 |
+
pooled_projection_dim=16,
|
| 89 |
+
hidden_size=24,
|
| 90 |
+
activation_fn="gelu-approximate",
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
torch.manual_seed(0)
|
| 94 |
+
vae = AutoencoderKL()
|
| 95 |
+
|
| 96 |
+
scheduler = DDPMScheduler()
|
| 97 |
+
text_encoder = BertModel.from_pretrained("hf-internal-testing/tiny-random-BertModel")
|
| 98 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-BertModel")
|
| 99 |
+
text_encoder_2 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 100 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 101 |
+
|
| 102 |
+
components = {
|
| 103 |
+
"transformer": transformer.eval(),
|
| 104 |
+
"vae": vae.eval(),
|
| 105 |
+
"scheduler": scheduler,
|
| 106 |
+
"text_encoder": text_encoder,
|
| 107 |
+
"tokenizer": tokenizer,
|
| 108 |
+
"text_encoder_2": text_encoder_2,
|
| 109 |
+
"tokenizer_2": tokenizer_2,
|
| 110 |
+
"safety_checker": None,
|
| 111 |
+
"feature_extractor": None,
|
| 112 |
+
"controlnet": controlnet,
|
| 113 |
+
}
|
| 114 |
+
return components
|
| 115 |
+
|
| 116 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 117 |
+
if str(device).startswith("mps"):
|
| 118 |
+
generator = torch.manual_seed(seed)
|
| 119 |
+
else:
|
| 120 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 121 |
+
|
| 122 |
+
control_image = randn_tensor(
|
| 123 |
+
(1, 3, 16, 16),
|
| 124 |
+
generator=generator,
|
| 125 |
+
device=torch.device(device),
|
| 126 |
+
dtype=torch.float16,
|
| 127 |
+
)
|
| 128 |
+
|
| 129 |
+
controlnet_conditioning_scale = 0.5
|
| 130 |
+
|
| 131 |
+
inputs = {
|
| 132 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 133 |
+
"generator": generator,
|
| 134 |
+
"num_inference_steps": 2,
|
| 135 |
+
"guidance_scale": 5.0,
|
| 136 |
+
"output_type": "np",
|
| 137 |
+
"control_image": control_image,
|
| 138 |
+
"controlnet_conditioning_scale": controlnet_conditioning_scale,
|
| 139 |
+
}
|
| 140 |
+
|
| 141 |
+
return inputs
|
| 142 |
+
|
| 143 |
+
def test_controlnet_hunyuandit(self):
|
| 144 |
+
components = self.get_dummy_components()
|
| 145 |
+
pipe = HunyuanDiTControlNetPipeline(**components)
|
| 146 |
+
pipe = pipe.to(torch_device, dtype=torch.float16)
|
| 147 |
+
pipe.set_progress_bar_config(disable=None)
|
| 148 |
+
|
| 149 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 150 |
+
output = pipe(**inputs)
|
| 151 |
+
image = output.images
|
| 152 |
+
|
| 153 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 154 |
+
assert image.shape == (1, 16, 16, 3)
|
| 155 |
+
|
| 156 |
+
if torch_device == "xpu":
|
| 157 |
+
expected_slice = np.array(
|
| 158 |
+
[0.6376953, 0.84375, 0.58691406, 0.48046875, 0.43652344, 0.5517578, 0.54248047, 0.5644531, 0.48217773]
|
| 159 |
+
)
|
| 160 |
+
else:
|
| 161 |
+
expected_slice = np.array(
|
| 162 |
+
[0.6953125, 0.89208984, 0.59375, 0.5078125, 0.5786133, 0.6035156, 0.5839844, 0.53564453, 0.52246094]
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
|
| 166 |
+
f"Expected: {expected_slice}, got: {image_slice.flatten()}"
|
| 167 |
+
)
|
| 168 |
+
|
| 169 |
+
def test_inference_batch_single_identical(self):
|
| 170 |
+
self._test_inference_batch_single_identical(
|
| 171 |
+
expected_max_diff=1e-3,
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def test_sequential_cpu_offload_forward_pass(self):
|
| 175 |
+
# TODO(YiYi) need to fix later
|
| 176 |
+
pass
|
| 177 |
+
|
| 178 |
+
def test_sequential_offload_forward_pass_twice(self):
|
| 179 |
+
# TODO(YiYi) need to fix later
|
| 180 |
+
pass
|
| 181 |
+
|
| 182 |
+
def test_save_load_optional_components(self):
|
| 183 |
+
# TODO(YiYi) need to fix later
|
| 184 |
+
pass
|
| 185 |
+
|
| 186 |
+
@unittest.skip(
|
| 187 |
+
"Test not supported as `encode_prompt` is called two times separately which deivates from about 99% of the pipelines we have."
|
| 188 |
+
)
|
| 189 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@slow
|
| 194 |
+
@require_torch_accelerator
|
| 195 |
+
class HunyuanDiTControlNetPipelineSlowTests(unittest.TestCase):
|
| 196 |
+
pipeline_class = HunyuanDiTControlNetPipeline
|
| 197 |
+
|
| 198 |
+
def setUp(self):
|
| 199 |
+
super().setUp()
|
| 200 |
+
gc.collect()
|
| 201 |
+
backend_empty_cache(torch_device)
|
| 202 |
+
|
| 203 |
+
def tearDown(self):
|
| 204 |
+
super().tearDown()
|
| 205 |
+
gc.collect()
|
| 206 |
+
backend_empty_cache(torch_device)
|
| 207 |
+
|
| 208 |
+
def test_canny(self):
|
| 209 |
+
controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
|
| 210 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
|
| 211 |
+
)
|
| 212 |
+
pipe = HunyuanDiTControlNetPipeline.from_pretrained(
|
| 213 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 214 |
+
)
|
| 215 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 216 |
+
pipe.set_progress_bar_config(disable=None)
|
| 217 |
+
|
| 218 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 219 |
+
prompt = "At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
|
| 220 |
+
n_prompt = ""
|
| 221 |
+
control_image = load_image(
|
| 222 |
+
"https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
output = pipe(
|
| 226 |
+
prompt,
|
| 227 |
+
negative_prompt=n_prompt,
|
| 228 |
+
control_image=control_image,
|
| 229 |
+
controlnet_conditioning_scale=0.5,
|
| 230 |
+
guidance_scale=5.0,
|
| 231 |
+
num_inference_steps=2,
|
| 232 |
+
output_type="np",
|
| 233 |
+
generator=generator,
|
| 234 |
+
)
|
| 235 |
+
image = output.images[0]
|
| 236 |
+
|
| 237 |
+
assert image.shape == (1024, 1024, 3)
|
| 238 |
+
|
| 239 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 240 |
+
|
| 241 |
+
expected_image = np.array(
|
| 242 |
+
[0.43652344, 0.4399414, 0.44921875, 0.45043945, 0.45703125, 0.44873047, 0.43579102, 0.44018555, 0.42578125]
|
| 243 |
+
)
|
| 244 |
+
|
| 245 |
+
assert np.abs(original_image.flatten() - expected_image).max() < 1e-2
|
| 246 |
+
|
| 247 |
+
def test_pose(self):
|
| 248 |
+
controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
|
| 249 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Pose", torch_dtype=torch.float16
|
| 250 |
+
)
|
| 251 |
+
pipe = HunyuanDiTControlNetPipeline.from_pretrained(
|
| 252 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 253 |
+
)
|
| 254 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 255 |
+
pipe.set_progress_bar_config(disable=None)
|
| 256 |
+
|
| 257 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 258 |
+
prompt = "An Asian woman, dressed in a green top, wearing a purple headscarf and a purple scarf, stands in front of a blackboard. The background is the blackboard. The photo is presented in a close-up, eye-level, and centered composition, adopting a realistic photographic style"
|
| 259 |
+
n_prompt = ""
|
| 260 |
+
control_image = load_image(
|
| 261 |
+
"https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Pose/resolve/main/pose.jpg?download=true"
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
output = pipe(
|
| 265 |
+
prompt,
|
| 266 |
+
negative_prompt=n_prompt,
|
| 267 |
+
control_image=control_image,
|
| 268 |
+
controlnet_conditioning_scale=0.5,
|
| 269 |
+
guidance_scale=5.0,
|
| 270 |
+
num_inference_steps=2,
|
| 271 |
+
output_type="np",
|
| 272 |
+
generator=generator,
|
| 273 |
+
)
|
| 274 |
+
image = output.images[0]
|
| 275 |
+
|
| 276 |
+
assert image.shape == (1024, 1024, 3)
|
| 277 |
+
|
| 278 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 279 |
+
|
| 280 |
+
expected_image = np.array(
|
| 281 |
+
[0.4091797, 0.4177246, 0.39526367, 0.4194336, 0.40356445, 0.3857422, 0.39208984, 0.40429688, 0.37451172]
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
assert np.abs(original_image.flatten() - expected_image).max() < 1e-2
|
| 285 |
+
|
| 286 |
+
def test_depth(self):
|
| 287 |
+
controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
|
| 288 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Depth", torch_dtype=torch.float16
|
| 289 |
+
)
|
| 290 |
+
pipe = HunyuanDiTControlNetPipeline.from_pretrained(
|
| 291 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 292 |
+
)
|
| 293 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 294 |
+
pipe.set_progress_bar_config(disable=None)
|
| 295 |
+
|
| 296 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 297 |
+
prompt = "In the dense forest, a black and white panda sits quietly in green trees and red flowers, surrounded by mountains, rivers, and the ocean. The background is the forest in a bright environment."
|
| 298 |
+
n_prompt = ""
|
| 299 |
+
control_image = load_image(
|
| 300 |
+
"https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Depth/resolve/main/depth.jpg?download=true"
|
| 301 |
+
)
|
| 302 |
+
|
| 303 |
+
output = pipe(
|
| 304 |
+
prompt,
|
| 305 |
+
negative_prompt=n_prompt,
|
| 306 |
+
control_image=control_image,
|
| 307 |
+
controlnet_conditioning_scale=0.5,
|
| 308 |
+
guidance_scale=5.0,
|
| 309 |
+
num_inference_steps=2,
|
| 310 |
+
output_type="np",
|
| 311 |
+
generator=generator,
|
| 312 |
+
)
|
| 313 |
+
image = output.images[0]
|
| 314 |
+
|
| 315 |
+
assert image.shape == (1024, 1024, 3)
|
| 316 |
+
|
| 317 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 318 |
+
|
| 319 |
+
expected_image = np.array(
|
| 320 |
+
[0.31982422, 0.32177734, 0.30126953, 0.3190918, 0.3100586, 0.31396484, 0.3232422, 0.33544922, 0.30810547]
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
assert np.abs(original_image.flatten() - expected_image).max() < 1e-2
|
| 324 |
+
|
| 325 |
+
def test_multi_controlnet(self):
|
| 326 |
+
controlnet = HunyuanDiT2DControlNetModel.from_pretrained(
|
| 327 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny", torch_dtype=torch.float16
|
| 328 |
+
)
|
| 329 |
+
controlnet = HunyuanDiT2DMultiControlNetModel([controlnet, controlnet])
|
| 330 |
+
|
| 331 |
+
pipe = HunyuanDiTControlNetPipeline.from_pretrained(
|
| 332 |
+
"Tencent-Hunyuan/HunyuanDiT-v1.1-Diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 333 |
+
)
|
| 334 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 335 |
+
pipe.set_progress_bar_config(disable=None)
|
| 336 |
+
|
| 337 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 338 |
+
prompt = "At night, an ancient Chinese-style lion statue stands in front of the hotel, its eyes gleaming as if guarding the building. The background is the hotel entrance at night, with a close-up, eye-level, and centered composition. This photo presents a realistic photographic style, embodies Chinese sculpture culture, and reveals a mysterious atmosphere."
|
| 339 |
+
n_prompt = ""
|
| 340 |
+
control_image = load_image(
|
| 341 |
+
"https://huggingface.co/Tencent-Hunyuan/HunyuanDiT-v1.1-ControlNet-Diffusers-Canny/resolve/main/canny.jpg?download=true"
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
output = pipe(
|
| 345 |
+
prompt,
|
| 346 |
+
negative_prompt=n_prompt,
|
| 347 |
+
control_image=[control_image, control_image],
|
| 348 |
+
controlnet_conditioning_scale=[0.25, 0.25],
|
| 349 |
+
guidance_scale=5.0,
|
| 350 |
+
num_inference_steps=2,
|
| 351 |
+
output_type="np",
|
| 352 |
+
generator=generator,
|
| 353 |
+
)
|
| 354 |
+
image = output.images[0]
|
| 355 |
+
|
| 356 |
+
assert image.shape == (1024, 1024, 3)
|
| 357 |
+
|
| 358 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 359 |
+
|
| 360 |
+
expected_image = np.array(
|
| 361 |
+
[0.43652344, 0.44018555, 0.4494629, 0.44995117, 0.45654297, 0.44848633, 0.43603516, 0.4404297, 0.42626953]
|
| 362 |
+
)
|
| 363 |
+
|
| 364 |
+
assert np.abs(original_image.flatten() - expected_image).max() < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/test_controlnet_inpaint_sd3.py
ADDED
|
@@ -0,0 +1,203 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, T5EncoderModel
|
| 21 |
+
|
| 22 |
+
from diffusers import (
|
| 23 |
+
AutoencoderKL,
|
| 24 |
+
FlowMatchEulerDiscreteScheduler,
|
| 25 |
+
SD3Transformer2DModel,
|
| 26 |
+
StableDiffusion3ControlNetInpaintingPipeline,
|
| 27 |
+
)
|
| 28 |
+
from diffusers.models import SD3ControlNetModel
|
| 29 |
+
from diffusers.utils.testing_utils import (
|
| 30 |
+
enable_full_determinism,
|
| 31 |
+
torch_device,
|
| 32 |
+
)
|
| 33 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 34 |
+
|
| 35 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
enable_full_determinism()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class StableDiffusion3ControlInpaintNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 42 |
+
pipeline_class = StableDiffusion3ControlNetInpaintingPipeline
|
| 43 |
+
params = frozenset(
|
| 44 |
+
[
|
| 45 |
+
"prompt",
|
| 46 |
+
"height",
|
| 47 |
+
"width",
|
| 48 |
+
"guidance_scale",
|
| 49 |
+
"negative_prompt",
|
| 50 |
+
"prompt_embeds",
|
| 51 |
+
"negative_prompt_embeds",
|
| 52 |
+
]
|
| 53 |
+
)
|
| 54 |
+
batch_params = frozenset(["prompt", "negative_prompt"])
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
transformer = SD3Transformer2DModel(
|
| 59 |
+
sample_size=32,
|
| 60 |
+
patch_size=1,
|
| 61 |
+
in_channels=8,
|
| 62 |
+
num_layers=4,
|
| 63 |
+
attention_head_dim=8,
|
| 64 |
+
num_attention_heads=4,
|
| 65 |
+
joint_attention_dim=32,
|
| 66 |
+
caption_projection_dim=32,
|
| 67 |
+
pooled_projection_dim=64,
|
| 68 |
+
out_channels=8,
|
| 69 |
+
)
|
| 70 |
+
|
| 71 |
+
torch.manual_seed(0)
|
| 72 |
+
controlnet = SD3ControlNetModel(
|
| 73 |
+
sample_size=32,
|
| 74 |
+
patch_size=1,
|
| 75 |
+
in_channels=8,
|
| 76 |
+
num_layers=1,
|
| 77 |
+
attention_head_dim=8,
|
| 78 |
+
num_attention_heads=4,
|
| 79 |
+
joint_attention_dim=32,
|
| 80 |
+
caption_projection_dim=32,
|
| 81 |
+
pooled_projection_dim=64,
|
| 82 |
+
out_channels=8,
|
| 83 |
+
extra_conditioning_channels=1,
|
| 84 |
+
)
|
| 85 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 86 |
+
bos_token_id=0,
|
| 87 |
+
eos_token_id=2,
|
| 88 |
+
hidden_size=32,
|
| 89 |
+
intermediate_size=37,
|
| 90 |
+
layer_norm_eps=1e-05,
|
| 91 |
+
num_attention_heads=4,
|
| 92 |
+
num_hidden_layers=5,
|
| 93 |
+
pad_token_id=1,
|
| 94 |
+
vocab_size=1000,
|
| 95 |
+
hidden_act="gelu",
|
| 96 |
+
projection_dim=32,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
torch.manual_seed(0)
|
| 100 |
+
text_encoder = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 101 |
+
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
text_encoder_2 = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 104 |
+
|
| 105 |
+
torch.manual_seed(0)
|
| 106 |
+
text_encoder_3 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 107 |
+
|
| 108 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 109 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 110 |
+
tokenizer_3 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 111 |
+
|
| 112 |
+
torch.manual_seed(0)
|
| 113 |
+
vae = AutoencoderKL(
|
| 114 |
+
sample_size=32,
|
| 115 |
+
in_channels=3,
|
| 116 |
+
out_channels=3,
|
| 117 |
+
block_out_channels=(4,),
|
| 118 |
+
layers_per_block=1,
|
| 119 |
+
latent_channels=8,
|
| 120 |
+
norm_num_groups=1,
|
| 121 |
+
use_quant_conv=False,
|
| 122 |
+
use_post_quant_conv=False,
|
| 123 |
+
shift_factor=0.0609,
|
| 124 |
+
scaling_factor=1.5035,
|
| 125 |
+
)
|
| 126 |
+
|
| 127 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 128 |
+
|
| 129 |
+
return {
|
| 130 |
+
"scheduler": scheduler,
|
| 131 |
+
"text_encoder": text_encoder,
|
| 132 |
+
"text_encoder_2": text_encoder_2,
|
| 133 |
+
"text_encoder_3": text_encoder_3,
|
| 134 |
+
"tokenizer": tokenizer,
|
| 135 |
+
"tokenizer_2": tokenizer_2,
|
| 136 |
+
"tokenizer_3": tokenizer_3,
|
| 137 |
+
"transformer": transformer,
|
| 138 |
+
"vae": vae,
|
| 139 |
+
"controlnet": controlnet,
|
| 140 |
+
"image_encoder": None,
|
| 141 |
+
"feature_extractor": None,
|
| 142 |
+
}
|
| 143 |
+
|
| 144 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 145 |
+
if str(device).startswith("mps"):
|
| 146 |
+
generator = torch.manual_seed(seed)
|
| 147 |
+
else:
|
| 148 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 149 |
+
|
| 150 |
+
control_image = randn_tensor(
|
| 151 |
+
(1, 3, 32, 32),
|
| 152 |
+
generator=generator,
|
| 153 |
+
device=torch.device(device),
|
| 154 |
+
dtype=torch.float16,
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
control_mask = randn_tensor(
|
| 158 |
+
(1, 1, 32, 32),
|
| 159 |
+
generator=generator,
|
| 160 |
+
device=torch.device(device),
|
| 161 |
+
dtype=torch.float16,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
controlnet_conditioning_scale = 0.95
|
| 165 |
+
|
| 166 |
+
inputs = {
|
| 167 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 168 |
+
"generator": generator,
|
| 169 |
+
"num_inference_steps": 2,
|
| 170 |
+
"guidance_scale": 7.0,
|
| 171 |
+
"output_type": "np",
|
| 172 |
+
"control_image": control_image,
|
| 173 |
+
"control_mask": control_mask,
|
| 174 |
+
"controlnet_conditioning_scale": controlnet_conditioning_scale,
|
| 175 |
+
}
|
| 176 |
+
|
| 177 |
+
return inputs
|
| 178 |
+
|
| 179 |
+
def test_controlnet_inpaint_sd3(self):
|
| 180 |
+
components = self.get_dummy_components()
|
| 181 |
+
sd_pipe = StableDiffusion3ControlNetInpaintingPipeline(**components)
|
| 182 |
+
sd_pipe = sd_pipe.to(torch_device, dtype=torch.float16)
|
| 183 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 184 |
+
|
| 185 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 186 |
+
output = sd_pipe(**inputs)
|
| 187 |
+
image = output.images
|
| 188 |
+
|
| 189 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 190 |
+
|
| 191 |
+
assert image.shape == (1, 32, 32, 3)
|
| 192 |
+
|
| 193 |
+
expected_slice = np.array(
|
| 194 |
+
[0.51708984, 0.7421875, 0.4580078, 0.6435547, 0.65625, 0.43603516, 0.5151367, 0.65722656, 0.60839844]
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
|
| 198 |
+
f"Expected: {expected_slice}, got: {image_slice.flatten()}"
|
| 199 |
+
)
|
| 200 |
+
|
| 201 |
+
@unittest.skip("xFormersAttnProcessor does not work with SD3 Joint Attention")
|
| 202 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 203 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_sd3/test_controlnet_sd3.py
ADDED
|
@@ -0,0 +1,367 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc and The InstantX Team.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
import numpy as np
|
| 21 |
+
import pytest
|
| 22 |
+
import torch
|
| 23 |
+
from transformers import AutoTokenizer, CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer, T5EncoderModel
|
| 24 |
+
|
| 25 |
+
from diffusers import (
|
| 26 |
+
AutoencoderKL,
|
| 27 |
+
FlowMatchEulerDiscreteScheduler,
|
| 28 |
+
SD3Transformer2DModel,
|
| 29 |
+
StableDiffusion3ControlNetPipeline,
|
| 30 |
+
)
|
| 31 |
+
from diffusers.models import SD3ControlNetModel, SD3MultiControlNetModel
|
| 32 |
+
from diffusers.utils import load_image
|
| 33 |
+
from diffusers.utils.testing_utils import (
|
| 34 |
+
backend_empty_cache,
|
| 35 |
+
enable_full_determinism,
|
| 36 |
+
numpy_cosine_similarity_distance,
|
| 37 |
+
require_big_accelerator,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 40 |
+
)
|
| 41 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 42 |
+
|
| 43 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
enable_full_determinism()
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class StableDiffusion3ControlNetPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 50 |
+
pipeline_class = StableDiffusion3ControlNetPipeline
|
| 51 |
+
params = frozenset(
|
| 52 |
+
[
|
| 53 |
+
"prompt",
|
| 54 |
+
"height",
|
| 55 |
+
"width",
|
| 56 |
+
"guidance_scale",
|
| 57 |
+
"negative_prompt",
|
| 58 |
+
"prompt_embeds",
|
| 59 |
+
"negative_prompt_embeds",
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
batch_params = frozenset(["prompt", "negative_prompt"])
|
| 63 |
+
test_layerwise_casting = True
|
| 64 |
+
test_group_offloading = True
|
| 65 |
+
|
| 66 |
+
def get_dummy_components(
|
| 67 |
+
self, num_controlnet_layers: int = 3, qk_norm: Optional[str] = "rms_norm", use_dual_attention=False
|
| 68 |
+
):
|
| 69 |
+
torch.manual_seed(0)
|
| 70 |
+
transformer = SD3Transformer2DModel(
|
| 71 |
+
sample_size=32,
|
| 72 |
+
patch_size=1,
|
| 73 |
+
in_channels=8,
|
| 74 |
+
num_layers=4,
|
| 75 |
+
attention_head_dim=8,
|
| 76 |
+
num_attention_heads=4,
|
| 77 |
+
joint_attention_dim=32,
|
| 78 |
+
caption_projection_dim=32,
|
| 79 |
+
pooled_projection_dim=64,
|
| 80 |
+
out_channels=8,
|
| 81 |
+
qk_norm=qk_norm,
|
| 82 |
+
dual_attention_layers=() if not use_dual_attention else (0, 1),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
torch.manual_seed(0)
|
| 86 |
+
controlnet = SD3ControlNetModel(
|
| 87 |
+
sample_size=32,
|
| 88 |
+
patch_size=1,
|
| 89 |
+
in_channels=8,
|
| 90 |
+
num_layers=num_controlnet_layers,
|
| 91 |
+
attention_head_dim=8,
|
| 92 |
+
num_attention_heads=4,
|
| 93 |
+
joint_attention_dim=32,
|
| 94 |
+
caption_projection_dim=32,
|
| 95 |
+
pooled_projection_dim=64,
|
| 96 |
+
out_channels=8,
|
| 97 |
+
qk_norm=qk_norm,
|
| 98 |
+
dual_attention_layers=() if not use_dual_attention else (0,),
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 102 |
+
bos_token_id=0,
|
| 103 |
+
eos_token_id=2,
|
| 104 |
+
hidden_size=32,
|
| 105 |
+
intermediate_size=37,
|
| 106 |
+
layer_norm_eps=1e-05,
|
| 107 |
+
num_attention_heads=4,
|
| 108 |
+
num_hidden_layers=5,
|
| 109 |
+
pad_token_id=1,
|
| 110 |
+
vocab_size=1000,
|
| 111 |
+
hidden_act="gelu",
|
| 112 |
+
projection_dim=32,
|
| 113 |
+
)
|
| 114 |
+
|
| 115 |
+
torch.manual_seed(0)
|
| 116 |
+
text_encoder = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 117 |
+
|
| 118 |
+
torch.manual_seed(0)
|
| 119 |
+
text_encoder_2 = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 120 |
+
|
| 121 |
+
torch.manual_seed(0)
|
| 122 |
+
text_encoder_3 = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 123 |
+
|
| 124 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 125 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 126 |
+
tokenizer_3 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 127 |
+
|
| 128 |
+
torch.manual_seed(0)
|
| 129 |
+
vae = AutoencoderKL(
|
| 130 |
+
sample_size=32,
|
| 131 |
+
in_channels=3,
|
| 132 |
+
out_channels=3,
|
| 133 |
+
block_out_channels=(4,),
|
| 134 |
+
layers_per_block=1,
|
| 135 |
+
latent_channels=8,
|
| 136 |
+
norm_num_groups=1,
|
| 137 |
+
use_quant_conv=False,
|
| 138 |
+
use_post_quant_conv=False,
|
| 139 |
+
shift_factor=0.0609,
|
| 140 |
+
scaling_factor=1.5035,
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 144 |
+
|
| 145 |
+
return {
|
| 146 |
+
"scheduler": scheduler,
|
| 147 |
+
"text_encoder": text_encoder,
|
| 148 |
+
"text_encoder_2": text_encoder_2,
|
| 149 |
+
"text_encoder_3": text_encoder_3,
|
| 150 |
+
"tokenizer": tokenizer,
|
| 151 |
+
"tokenizer_2": tokenizer_2,
|
| 152 |
+
"tokenizer_3": tokenizer_3,
|
| 153 |
+
"transformer": transformer,
|
| 154 |
+
"vae": vae,
|
| 155 |
+
"controlnet": controlnet,
|
| 156 |
+
"image_encoder": None,
|
| 157 |
+
"feature_extractor": None,
|
| 158 |
+
}
|
| 159 |
+
|
| 160 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 161 |
+
if str(device).startswith("mps"):
|
| 162 |
+
generator = torch.manual_seed(seed)
|
| 163 |
+
else:
|
| 164 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 165 |
+
|
| 166 |
+
control_image = randn_tensor(
|
| 167 |
+
(1, 3, 32, 32),
|
| 168 |
+
generator=generator,
|
| 169 |
+
device=torch.device(device),
|
| 170 |
+
dtype=torch.float16,
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
controlnet_conditioning_scale = 0.5
|
| 174 |
+
|
| 175 |
+
inputs = {
|
| 176 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 177 |
+
"generator": generator,
|
| 178 |
+
"num_inference_steps": 2,
|
| 179 |
+
"guidance_scale": 5.0,
|
| 180 |
+
"output_type": "np",
|
| 181 |
+
"control_image": control_image,
|
| 182 |
+
"controlnet_conditioning_scale": controlnet_conditioning_scale,
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
return inputs
|
| 186 |
+
|
| 187 |
+
def run_pipe(self, components, use_sd35=False):
|
| 188 |
+
sd_pipe = StableDiffusion3ControlNetPipeline(**components)
|
| 189 |
+
sd_pipe = sd_pipe.to(torch_device, dtype=torch.float16)
|
| 190 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 191 |
+
|
| 192 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 193 |
+
output = sd_pipe(**inputs)
|
| 194 |
+
image = output.images
|
| 195 |
+
|
| 196 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 197 |
+
|
| 198 |
+
assert image.shape == (1, 32, 32, 3)
|
| 199 |
+
|
| 200 |
+
if not use_sd35:
|
| 201 |
+
expected_slice = np.array([0.5767, 0.7100, 0.5981, 0.5674, 0.5952, 0.4102, 0.5093, 0.5044, 0.6030])
|
| 202 |
+
else:
|
| 203 |
+
expected_slice = np.array([1.0000, 0.9072, 0.4209, 0.2744, 0.5737, 0.3840, 0.6113, 0.6250, 0.6328])
|
| 204 |
+
|
| 205 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2, (
|
| 206 |
+
f"Expected: {expected_slice}, got: {image_slice.flatten()}"
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def test_controlnet_sd3(self):
|
| 210 |
+
components = self.get_dummy_components()
|
| 211 |
+
self.run_pipe(components)
|
| 212 |
+
|
| 213 |
+
def test_controlnet_sd35(self):
|
| 214 |
+
components = self.get_dummy_components(num_controlnet_layers=1, qk_norm="rms_norm", use_dual_attention=True)
|
| 215 |
+
self.run_pipe(components, use_sd35=True)
|
| 216 |
+
|
| 217 |
+
@unittest.skip("xFormersAttnProcessor does not work with SD3 Joint Attention")
|
| 218 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 219 |
+
pass
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@slow
|
| 223 |
+
@require_big_accelerator
|
| 224 |
+
@pytest.mark.big_accelerator
|
| 225 |
+
class StableDiffusion3ControlNetPipelineSlowTests(unittest.TestCase):
|
| 226 |
+
pipeline_class = StableDiffusion3ControlNetPipeline
|
| 227 |
+
|
| 228 |
+
def setUp(self):
|
| 229 |
+
super().setUp()
|
| 230 |
+
gc.collect()
|
| 231 |
+
backend_empty_cache(torch_device)
|
| 232 |
+
|
| 233 |
+
def tearDown(self):
|
| 234 |
+
super().tearDown()
|
| 235 |
+
gc.collect()
|
| 236 |
+
backend_empty_cache(torch_device)
|
| 237 |
+
|
| 238 |
+
def test_canny(self):
|
| 239 |
+
controlnet = SD3ControlNetModel.from_pretrained("InstantX/SD3-Controlnet-Canny", torch_dtype=torch.float16)
|
| 240 |
+
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
|
| 241 |
+
"stabilityai/stable-diffusion-3-medium-diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 242 |
+
)
|
| 243 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 244 |
+
pipe.set_progress_bar_config(disable=None)
|
| 245 |
+
|
| 246 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 247 |
+
prompt = "Anime style illustration of a girl wearing a suit. A moon in sky. In the background we see a big rain approaching. text 'InstantX' on image"
|
| 248 |
+
n_prompt = "NSFW, nude, naked, porn, ugly"
|
| 249 |
+
control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
|
| 250 |
+
|
| 251 |
+
output = pipe(
|
| 252 |
+
prompt,
|
| 253 |
+
negative_prompt=n_prompt,
|
| 254 |
+
control_image=control_image,
|
| 255 |
+
controlnet_conditioning_scale=0.5,
|
| 256 |
+
guidance_scale=5.0,
|
| 257 |
+
num_inference_steps=2,
|
| 258 |
+
output_type="np",
|
| 259 |
+
generator=generator,
|
| 260 |
+
)
|
| 261 |
+
image = output.images[0]
|
| 262 |
+
|
| 263 |
+
assert image.shape == (1024, 1024, 3)
|
| 264 |
+
|
| 265 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 266 |
+
|
| 267 |
+
expected_image = np.array([0.7314, 0.7075, 0.6611, 0.7539, 0.7563, 0.6650, 0.6123, 0.7275, 0.7222])
|
| 268 |
+
|
| 269 |
+
assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
|
| 270 |
+
|
| 271 |
+
def test_pose(self):
|
| 272 |
+
controlnet = SD3ControlNetModel.from_pretrained("InstantX/SD3-Controlnet-Pose", torch_dtype=torch.float16)
|
| 273 |
+
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
|
| 274 |
+
"stabilityai/stable-diffusion-3-medium-diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 275 |
+
)
|
| 276 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 277 |
+
pipe.set_progress_bar_config(disable=None)
|
| 278 |
+
|
| 279 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 280 |
+
prompt = 'Anime style illustration of a girl wearing a suit. A moon in sky. In the background we see a big rain approaching. text "InstantX" on image'
|
| 281 |
+
n_prompt = "NSFW, nude, naked, porn, ugly"
|
| 282 |
+
control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Pose/resolve/main/pose.jpg")
|
| 283 |
+
|
| 284 |
+
output = pipe(
|
| 285 |
+
prompt,
|
| 286 |
+
negative_prompt=n_prompt,
|
| 287 |
+
control_image=control_image,
|
| 288 |
+
controlnet_conditioning_scale=0.5,
|
| 289 |
+
guidance_scale=5.0,
|
| 290 |
+
num_inference_steps=2,
|
| 291 |
+
output_type="np",
|
| 292 |
+
generator=generator,
|
| 293 |
+
)
|
| 294 |
+
image = output.images[0]
|
| 295 |
+
|
| 296 |
+
assert image.shape == (1024, 1024, 3)
|
| 297 |
+
|
| 298 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 299 |
+
expected_image = np.array([0.9048, 0.8740, 0.8936, 0.8516, 0.8799, 0.9360, 0.8379, 0.8408, 0.8652])
|
| 300 |
+
|
| 301 |
+
assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
|
| 302 |
+
|
| 303 |
+
def test_tile(self):
|
| 304 |
+
controlnet = SD3ControlNetModel.from_pretrained("InstantX/SD3-Controlnet-Tile", torch_dtype=torch.float16)
|
| 305 |
+
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
|
| 306 |
+
"stabilityai/stable-diffusion-3-medium-diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 307 |
+
)
|
| 308 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 309 |
+
pipe.set_progress_bar_config(disable=None)
|
| 310 |
+
|
| 311 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 312 |
+
prompt = 'Anime style illustration of a girl wearing a suit. A moon in sky. In the background we see a big rain approaching. text "InstantX" on image'
|
| 313 |
+
n_prompt = "NSFW, nude, naked, porn, ugly"
|
| 314 |
+
control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Tile/resolve/main/tile.jpg")
|
| 315 |
+
|
| 316 |
+
output = pipe(
|
| 317 |
+
prompt,
|
| 318 |
+
negative_prompt=n_prompt,
|
| 319 |
+
control_image=control_image,
|
| 320 |
+
controlnet_conditioning_scale=0.5,
|
| 321 |
+
guidance_scale=5.0,
|
| 322 |
+
num_inference_steps=2,
|
| 323 |
+
output_type="np",
|
| 324 |
+
generator=generator,
|
| 325 |
+
)
|
| 326 |
+
image = output.images[0]
|
| 327 |
+
|
| 328 |
+
assert image.shape == (1024, 1024, 3)
|
| 329 |
+
|
| 330 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 331 |
+
expected_image = np.array([0.6699, 0.6836, 0.6226, 0.6572, 0.7310, 0.6646, 0.6650, 0.6694, 0.6011])
|
| 332 |
+
|
| 333 |
+
assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
|
| 334 |
+
|
| 335 |
+
def test_multi_controlnet(self):
|
| 336 |
+
controlnet = SD3ControlNetModel.from_pretrained("InstantX/SD3-Controlnet-Canny", torch_dtype=torch.float16)
|
| 337 |
+
controlnet = SD3MultiControlNetModel([controlnet, controlnet])
|
| 338 |
+
|
| 339 |
+
pipe = StableDiffusion3ControlNetPipeline.from_pretrained(
|
| 340 |
+
"stabilityai/stable-diffusion-3-medium-diffusers", controlnet=controlnet, torch_dtype=torch.float16
|
| 341 |
+
)
|
| 342 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 343 |
+
pipe.set_progress_bar_config(disable=None)
|
| 344 |
+
|
| 345 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 346 |
+
prompt = "Anime style illustration of a girl wearing a suit. A moon in sky. In the background we see a big rain approaching. text 'InstantX' on image"
|
| 347 |
+
n_prompt = "NSFW, nude, naked, porn, ugly"
|
| 348 |
+
control_image = load_image("https://huggingface.co/InstantX/SD3-Controlnet-Canny/resolve/main/canny.jpg")
|
| 349 |
+
|
| 350 |
+
output = pipe(
|
| 351 |
+
prompt,
|
| 352 |
+
negative_prompt=n_prompt,
|
| 353 |
+
control_image=[control_image, control_image],
|
| 354 |
+
controlnet_conditioning_scale=[0.25, 0.25],
|
| 355 |
+
guidance_scale=5.0,
|
| 356 |
+
num_inference_steps=2,
|
| 357 |
+
output_type="np",
|
| 358 |
+
generator=generator,
|
| 359 |
+
)
|
| 360 |
+
image = output.images[0]
|
| 361 |
+
|
| 362 |
+
assert image.shape == (1024, 1024, 3)
|
| 363 |
+
|
| 364 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 365 |
+
expected_image = np.array([0.7207, 0.7041, 0.6543, 0.7500, 0.7490, 0.6592, 0.6001, 0.7168, 0.7231])
|
| 366 |
+
|
| 367 |
+
assert numpy_cosine_similarity_distance(original_image.flatten(), expected_image) < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_xs/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/controlnet_xs/test_controlnetxs.py
ADDED
|
@@ -0,0 +1,352 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AsymmetricAutoencoderKL,
|
| 25 |
+
AutoencoderKL,
|
| 26 |
+
AutoencoderTiny,
|
| 27 |
+
ConsistencyDecoderVAE,
|
| 28 |
+
ControlNetXSAdapter,
|
| 29 |
+
DDIMScheduler,
|
| 30 |
+
LCMScheduler,
|
| 31 |
+
StableDiffusionControlNetXSPipeline,
|
| 32 |
+
UNet2DConditionModel,
|
| 33 |
+
)
|
| 34 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 35 |
+
from diffusers.utils.testing_utils import (
|
| 36 |
+
backend_empty_cache,
|
| 37 |
+
enable_full_determinism,
|
| 38 |
+
load_image,
|
| 39 |
+
require_accelerator,
|
| 40 |
+
require_torch_accelerator,
|
| 41 |
+
slow,
|
| 42 |
+
torch_device,
|
| 43 |
+
)
|
| 44 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 45 |
+
|
| 46 |
+
from ...models.autoencoders.vae import (
|
| 47 |
+
get_asym_autoencoder_kl_config,
|
| 48 |
+
get_autoencoder_kl_config,
|
| 49 |
+
get_autoencoder_tiny_config,
|
| 50 |
+
get_consistency_vae_config,
|
| 51 |
+
)
|
| 52 |
+
from ..pipeline_params import (
|
| 53 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 54 |
+
TEXT_TO_IMAGE_BATCH_PARAMS,
|
| 55 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 56 |
+
TEXT_TO_IMAGE_PARAMS,
|
| 57 |
+
)
|
| 58 |
+
from ..test_pipelines_common import (
|
| 59 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 60 |
+
PipelineLatentTesterMixin,
|
| 61 |
+
PipelineTesterMixin,
|
| 62 |
+
SDFunctionTesterMixin,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
enable_full_determinism()
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
def to_np(tensor):
|
| 70 |
+
if isinstance(tensor, torch.Tensor):
|
| 71 |
+
tensor = tensor.detach().cpu().numpy()
|
| 72 |
+
|
| 73 |
+
return tensor
|
| 74 |
+
|
| 75 |
+
|
| 76 |
+
class ControlNetXSPipelineFastTests(
|
| 77 |
+
PipelineLatentTesterMixin,
|
| 78 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 79 |
+
PipelineTesterMixin,
|
| 80 |
+
SDFunctionTesterMixin,
|
| 81 |
+
unittest.TestCase,
|
| 82 |
+
):
|
| 83 |
+
pipeline_class = StableDiffusionControlNetXSPipeline
|
| 84 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 85 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 86 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 87 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 88 |
+
|
| 89 |
+
test_attention_slicing = False
|
| 90 |
+
test_layerwise_casting = True
|
| 91 |
+
test_group_offloading = True
|
| 92 |
+
|
| 93 |
+
def get_dummy_components(self, time_cond_proj_dim=None):
|
| 94 |
+
torch.manual_seed(0)
|
| 95 |
+
unet = UNet2DConditionModel(
|
| 96 |
+
block_out_channels=(4, 8),
|
| 97 |
+
layers_per_block=2,
|
| 98 |
+
sample_size=16,
|
| 99 |
+
in_channels=4,
|
| 100 |
+
out_channels=4,
|
| 101 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 102 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 103 |
+
cross_attention_dim=8,
|
| 104 |
+
norm_num_groups=4,
|
| 105 |
+
time_cond_proj_dim=time_cond_proj_dim,
|
| 106 |
+
use_linear_projection=True,
|
| 107 |
+
)
|
| 108 |
+
torch.manual_seed(0)
|
| 109 |
+
controlnet = ControlNetXSAdapter.from_unet(
|
| 110 |
+
unet=unet,
|
| 111 |
+
size_ratio=1,
|
| 112 |
+
learn_time_embedding=True,
|
| 113 |
+
conditioning_embedding_out_channels=(2, 2),
|
| 114 |
+
)
|
| 115 |
+
torch.manual_seed(0)
|
| 116 |
+
scheduler = DDIMScheduler(
|
| 117 |
+
beta_start=0.00085,
|
| 118 |
+
beta_end=0.012,
|
| 119 |
+
beta_schedule="scaled_linear",
|
| 120 |
+
clip_sample=False,
|
| 121 |
+
set_alpha_to_one=False,
|
| 122 |
+
)
|
| 123 |
+
torch.manual_seed(0)
|
| 124 |
+
vae = AutoencoderKL(
|
| 125 |
+
block_out_channels=[4, 8],
|
| 126 |
+
in_channels=3,
|
| 127 |
+
out_channels=3,
|
| 128 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 129 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 130 |
+
latent_channels=4,
|
| 131 |
+
norm_num_groups=2,
|
| 132 |
+
)
|
| 133 |
+
torch.manual_seed(0)
|
| 134 |
+
text_encoder_config = CLIPTextConfig(
|
| 135 |
+
bos_token_id=0,
|
| 136 |
+
eos_token_id=2,
|
| 137 |
+
hidden_size=8,
|
| 138 |
+
intermediate_size=37,
|
| 139 |
+
layer_norm_eps=1e-05,
|
| 140 |
+
num_attention_heads=4,
|
| 141 |
+
num_hidden_layers=5,
|
| 142 |
+
pad_token_id=1,
|
| 143 |
+
vocab_size=1000,
|
| 144 |
+
)
|
| 145 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 146 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 147 |
+
|
| 148 |
+
components = {
|
| 149 |
+
"unet": unet,
|
| 150 |
+
"controlnet": controlnet,
|
| 151 |
+
"scheduler": scheduler,
|
| 152 |
+
"vae": vae,
|
| 153 |
+
"text_encoder": text_encoder,
|
| 154 |
+
"tokenizer": tokenizer,
|
| 155 |
+
"safety_checker": None,
|
| 156 |
+
"feature_extractor": None,
|
| 157 |
+
}
|
| 158 |
+
return components
|
| 159 |
+
|
| 160 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 161 |
+
if str(device).startswith("mps"):
|
| 162 |
+
generator = torch.manual_seed(seed)
|
| 163 |
+
else:
|
| 164 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 165 |
+
|
| 166 |
+
controlnet_embedder_scale_factor = 2
|
| 167 |
+
image = randn_tensor(
|
| 168 |
+
(1, 3, 8 * controlnet_embedder_scale_factor, 8 * controlnet_embedder_scale_factor),
|
| 169 |
+
generator=generator,
|
| 170 |
+
device=torch.device(device),
|
| 171 |
+
)
|
| 172 |
+
|
| 173 |
+
inputs = {
|
| 174 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 175 |
+
"generator": generator,
|
| 176 |
+
"num_inference_steps": 2,
|
| 177 |
+
"guidance_scale": 6.0,
|
| 178 |
+
"output_type": "numpy",
|
| 179 |
+
"image": image,
|
| 180 |
+
}
|
| 181 |
+
|
| 182 |
+
return inputs
|
| 183 |
+
|
| 184 |
+
@unittest.skipIf(
|
| 185 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 186 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 187 |
+
)
|
| 188 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 189 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 190 |
+
|
| 191 |
+
def test_inference_batch_single_identical(self):
|
| 192 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 193 |
+
|
| 194 |
+
def test_controlnet_lcm(self):
|
| 195 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 196 |
+
|
| 197 |
+
components = self.get_dummy_components(time_cond_proj_dim=8)
|
| 198 |
+
sd_pipe = StableDiffusionControlNetXSPipeline(**components)
|
| 199 |
+
sd_pipe.scheduler = LCMScheduler.from_config(sd_pipe.scheduler.config)
|
| 200 |
+
sd_pipe = sd_pipe.to(torch_device)
|
| 201 |
+
sd_pipe.set_progress_bar_config(disable=None)
|
| 202 |
+
|
| 203 |
+
inputs = self.get_dummy_inputs(device)
|
| 204 |
+
output = sd_pipe(**inputs)
|
| 205 |
+
image = output.images
|
| 206 |
+
|
| 207 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 208 |
+
|
| 209 |
+
assert image.shape == (1, 16, 16, 3)
|
| 210 |
+
expected_slice = np.array([0.745, 0.753, 0.767, 0.543, 0.523, 0.502, 0.314, 0.521, 0.478])
|
| 211 |
+
|
| 212 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 213 |
+
|
| 214 |
+
def test_to_dtype(self):
|
| 215 |
+
components = self.get_dummy_components()
|
| 216 |
+
pipe = self.pipeline_class(**components)
|
| 217 |
+
pipe.set_progress_bar_config(disable=None)
|
| 218 |
+
|
| 219 |
+
# pipeline creates a new UNetControlNetXSModel under the hood. So we need to check the dtype from pipe.components
|
| 220 |
+
model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
|
| 221 |
+
self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
|
| 222 |
+
|
| 223 |
+
pipe.to(dtype=torch.float16)
|
| 224 |
+
model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
|
| 225 |
+
self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
|
| 226 |
+
|
| 227 |
+
def test_multi_vae(self):
|
| 228 |
+
components = self.get_dummy_components()
|
| 229 |
+
pipe = self.pipeline_class(**components)
|
| 230 |
+
pipe = pipe.to(torch_device)
|
| 231 |
+
pipe.set_progress_bar_config(disable=None)
|
| 232 |
+
|
| 233 |
+
block_out_channels = pipe.vae.config.block_out_channels
|
| 234 |
+
norm_num_groups = pipe.vae.config.norm_num_groups
|
| 235 |
+
|
| 236 |
+
vae_classes = [AutoencoderKL, AsymmetricAutoencoderKL, ConsistencyDecoderVAE, AutoencoderTiny]
|
| 237 |
+
configs = [
|
| 238 |
+
get_autoencoder_kl_config(block_out_channels, norm_num_groups),
|
| 239 |
+
get_asym_autoencoder_kl_config(block_out_channels, norm_num_groups),
|
| 240 |
+
get_consistency_vae_config(block_out_channels, norm_num_groups),
|
| 241 |
+
get_autoencoder_tiny_config(block_out_channels),
|
| 242 |
+
]
|
| 243 |
+
|
| 244 |
+
out_np = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]
|
| 245 |
+
|
| 246 |
+
for vae_cls, config in zip(vae_classes, configs):
|
| 247 |
+
vae = vae_cls(**config)
|
| 248 |
+
vae = vae.to(torch_device)
|
| 249 |
+
components["vae"] = vae
|
| 250 |
+
vae_pipe = self.pipeline_class(**components)
|
| 251 |
+
|
| 252 |
+
# pipeline creates a new UNetControlNetXSModel under the hood, which aren't on device.
|
| 253 |
+
# So we need to move the new pipe to device.
|
| 254 |
+
vae_pipe.to(torch_device)
|
| 255 |
+
vae_pipe.set_progress_bar_config(disable=None)
|
| 256 |
+
|
| 257 |
+
out_vae_np = vae_pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]
|
| 258 |
+
|
| 259 |
+
assert out_vae_np.shape == out_np.shape
|
| 260 |
+
|
| 261 |
+
@require_accelerator
|
| 262 |
+
def test_to_device(self):
|
| 263 |
+
components = self.get_dummy_components()
|
| 264 |
+
pipe = self.pipeline_class(**components)
|
| 265 |
+
pipe.set_progress_bar_config(disable=None)
|
| 266 |
+
|
| 267 |
+
pipe.to("cpu")
|
| 268 |
+
# pipeline creates a new UNetControlNetXSModel under the hood. So we need to check the device from pipe.components
|
| 269 |
+
model_devices = [
|
| 270 |
+
component.device.type for component in pipe.components.values() if hasattr(component, "device")
|
| 271 |
+
]
|
| 272 |
+
self.assertTrue(all(device == "cpu" for device in model_devices))
|
| 273 |
+
|
| 274 |
+
output_cpu = pipe(**self.get_dummy_inputs("cpu"))[0]
|
| 275 |
+
self.assertTrue(np.isnan(output_cpu).sum() == 0)
|
| 276 |
+
|
| 277 |
+
pipe.to(torch_device)
|
| 278 |
+
model_devices = [
|
| 279 |
+
component.device.type for component in pipe.components.values() if hasattr(component, "device")
|
| 280 |
+
]
|
| 281 |
+
self.assertTrue(all(device == torch_device for device in model_devices))
|
| 282 |
+
|
| 283 |
+
output_device = pipe(**self.get_dummy_inputs(torch_device))[0]
|
| 284 |
+
self.assertTrue(np.isnan(to_np(output_device)).sum() == 0)
|
| 285 |
+
|
| 286 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 287 |
+
extra_required_param_value_dict = {
|
| 288 |
+
"device": torch.device(torch_device).type,
|
| 289 |
+
"do_classifier_free_guidance": self.get_dummy_inputs(device=torch_device).get("guidance_scale", 1.0) > 1.0,
|
| 290 |
+
}
|
| 291 |
+
return super().test_encode_prompt_works_in_isolation(extra_required_param_value_dict)
|
| 292 |
+
|
| 293 |
+
|
| 294 |
+
@slow
|
| 295 |
+
@require_torch_accelerator
|
| 296 |
+
class ControlNetXSPipelineSlowTests(unittest.TestCase):
|
| 297 |
+
def tearDown(self):
|
| 298 |
+
super().tearDown()
|
| 299 |
+
gc.collect()
|
| 300 |
+
backend_empty_cache(torch_device)
|
| 301 |
+
|
| 302 |
+
def test_canny(self):
|
| 303 |
+
controlnet = ControlNetXSAdapter.from_pretrained(
|
| 304 |
+
"UmerHA/Testing-ConrolNetXS-SD2.1-canny", torch_dtype=torch.float16
|
| 305 |
+
)
|
| 306 |
+
pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
|
| 307 |
+
"stabilityai/stable-diffusion-2-1-base", controlnet=controlnet, torch_dtype=torch.float16
|
| 308 |
+
)
|
| 309 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 310 |
+
pipe.set_progress_bar_config(disable=None)
|
| 311 |
+
|
| 312 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 313 |
+
prompt = "bird"
|
| 314 |
+
image = load_image(
|
| 315 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 316 |
+
)
|
| 317 |
+
|
| 318 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 319 |
+
|
| 320 |
+
image = output.images[0]
|
| 321 |
+
|
| 322 |
+
assert image.shape == (768, 512, 3)
|
| 323 |
+
|
| 324 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 325 |
+
expected_image = np.array([0.1963, 0.229, 0.2659, 0.2109, 0.2332, 0.2827, 0.2534, 0.2422, 0.2808])
|
| 326 |
+
assert np.allclose(original_image, expected_image, atol=1e-04)
|
| 327 |
+
|
| 328 |
+
def test_depth(self):
|
| 329 |
+
controlnet = ControlNetXSAdapter.from_pretrained(
|
| 330 |
+
"UmerHA/Testing-ConrolNetXS-SD2.1-depth", torch_dtype=torch.float16
|
| 331 |
+
)
|
| 332 |
+
pipe = StableDiffusionControlNetXSPipeline.from_pretrained(
|
| 333 |
+
"stabilityai/stable-diffusion-2-1-base", controlnet=controlnet, torch_dtype=torch.float16
|
| 334 |
+
)
|
| 335 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 336 |
+
pipe.set_progress_bar_config(disable=None)
|
| 337 |
+
|
| 338 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 339 |
+
prompt = "Stormtrooper's lecture"
|
| 340 |
+
image = load_image(
|
| 341 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/stormtrooper_depth.png"
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
output = pipe(prompt, image, generator=generator, output_type="np", num_inference_steps=3)
|
| 345 |
+
|
| 346 |
+
image = output.images[0]
|
| 347 |
+
|
| 348 |
+
assert image.shape == (512, 512, 3)
|
| 349 |
+
|
| 350 |
+
original_image = image[-3:, -3:, -1].flatten()
|
| 351 |
+
expected_image = np.array([0.4844, 0.4937, 0.4956, 0.4663, 0.5039, 0.5044, 0.4565, 0.4883, 0.4941])
|
| 352 |
+
assert np.allclose(original_image,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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2023 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTextModelWithProjection, CLIPTokenizer
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AsymmetricAutoencoderKL,
|
| 25 |
+
AutoencoderKL,
|
| 26 |
+
AutoencoderTiny,
|
| 27 |
+
ConsistencyDecoderVAE,
|
| 28 |
+
ControlNetXSAdapter,
|
| 29 |
+
EulerDiscreteScheduler,
|
| 30 |
+
StableDiffusionXLControlNetXSPipeline,
|
| 31 |
+
UNet2DConditionModel,
|
| 32 |
+
)
|
| 33 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 34 |
+
from diffusers.utils.testing_utils import (
|
| 35 |
+
backend_empty_cache,
|
| 36 |
+
enable_full_determinism,
|
| 37 |
+
load_image,
|
| 38 |
+
require_torch_accelerator,
|
| 39 |
+
slow,
|
| 40 |
+
torch_device,
|
| 41 |
+
)
|
| 42 |
+
from diffusers.utils.torch_utils import randn_tensor
|
| 43 |
+
|
| 44 |
+
from ...models.autoencoders.vae import (
|
| 45 |
+
get_asym_autoencoder_kl_config,
|
| 46 |
+
get_autoencoder_kl_config,
|
| 47 |
+
get_autoencoder_tiny_config,
|
| 48 |
+
get_consistency_vae_config,
|
| 49 |
+
)
|
| 50 |
+
from ..pipeline_params import (
|
| 51 |
+
IMAGE_TO_IMAGE_IMAGE_PARAMS,
|
| 52 |
+
TEXT_TO_IMAGE_BATCH_PARAMS,
|
| 53 |
+
TEXT_TO_IMAGE_IMAGE_PARAMS,
|
| 54 |
+
TEXT_TO_IMAGE_PARAMS,
|
| 55 |
+
)
|
| 56 |
+
from ..test_pipelines_common import (
|
| 57 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 58 |
+
PipelineLatentTesterMixin,
|
| 59 |
+
PipelineTesterMixin,
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
enable_full_determinism()
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
class StableDiffusionXLControlNetXSPipelineFastTests(
|
| 67 |
+
PipelineLatentTesterMixin,
|
| 68 |
+
PipelineKarrasSchedulerTesterMixin,
|
| 69 |
+
PipelineTesterMixin,
|
| 70 |
+
unittest.TestCase,
|
| 71 |
+
):
|
| 72 |
+
pipeline_class = StableDiffusionXLControlNetXSPipeline
|
| 73 |
+
params = TEXT_TO_IMAGE_PARAMS
|
| 74 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 75 |
+
image_params = IMAGE_TO_IMAGE_IMAGE_PARAMS
|
| 76 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 77 |
+
|
| 78 |
+
test_attention_slicing = False
|
| 79 |
+
test_layerwise_casting = True
|
| 80 |
+
test_group_offloading = True
|
| 81 |
+
|
| 82 |
+
def get_dummy_components(self):
|
| 83 |
+
torch.manual_seed(0)
|
| 84 |
+
unet = UNet2DConditionModel(
|
| 85 |
+
block_out_channels=(4, 8),
|
| 86 |
+
layers_per_block=2,
|
| 87 |
+
sample_size=16,
|
| 88 |
+
in_channels=4,
|
| 89 |
+
out_channels=4,
|
| 90 |
+
down_block_types=("DownBlock2D", "CrossAttnDownBlock2D"),
|
| 91 |
+
up_block_types=("CrossAttnUpBlock2D", "UpBlock2D"),
|
| 92 |
+
use_linear_projection=True,
|
| 93 |
+
norm_num_groups=4,
|
| 94 |
+
# SD2-specific config below
|
| 95 |
+
attention_head_dim=(2, 4),
|
| 96 |
+
addition_embed_type="text_time",
|
| 97 |
+
addition_time_embed_dim=8,
|
| 98 |
+
transformer_layers_per_block=(1, 2),
|
| 99 |
+
projection_class_embeddings_input_dim=56, # 6 * 8 (addition_time_embed_dim) + 8 (cross_attention_dim)
|
| 100 |
+
cross_attention_dim=8,
|
| 101 |
+
)
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
controlnet = ControlNetXSAdapter.from_unet(
|
| 104 |
+
unet=unet,
|
| 105 |
+
size_ratio=0.5,
|
| 106 |
+
learn_time_embedding=True,
|
| 107 |
+
conditioning_embedding_out_channels=(2, 2),
|
| 108 |
+
)
|
| 109 |
+
torch.manual_seed(0)
|
| 110 |
+
scheduler = EulerDiscreteScheduler(
|
| 111 |
+
beta_start=0.00085,
|
| 112 |
+
beta_end=0.012,
|
| 113 |
+
steps_offset=1,
|
| 114 |
+
beta_schedule="scaled_linear",
|
| 115 |
+
timestep_spacing="leading",
|
| 116 |
+
)
|
| 117 |
+
torch.manual_seed(0)
|
| 118 |
+
vae = AutoencoderKL(
|
| 119 |
+
block_out_channels=[4, 8],
|
| 120 |
+
in_channels=3,
|
| 121 |
+
out_channels=3,
|
| 122 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 123 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 124 |
+
latent_channels=4,
|
| 125 |
+
norm_num_groups=2,
|
| 126 |
+
)
|
| 127 |
+
torch.manual_seed(0)
|
| 128 |
+
text_encoder_config = CLIPTextConfig(
|
| 129 |
+
bos_token_id=0,
|
| 130 |
+
eos_token_id=2,
|
| 131 |
+
hidden_size=4,
|
| 132 |
+
intermediate_size=37,
|
| 133 |
+
layer_norm_eps=1e-05,
|
| 134 |
+
num_attention_heads=4,
|
| 135 |
+
num_hidden_layers=5,
|
| 136 |
+
pad_token_id=1,
|
| 137 |
+
vocab_size=1000,
|
| 138 |
+
# SD2-specific config below
|
| 139 |
+
hidden_act="gelu",
|
| 140 |
+
projection_dim=8,
|
| 141 |
+
)
|
| 142 |
+
text_encoder = CLIPTextModel(text_encoder_config)
|
| 143 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 144 |
+
|
| 145 |
+
text_encoder_2 = CLIPTextModelWithProjection(text_encoder_config)
|
| 146 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 147 |
+
|
| 148 |
+
components = {
|
| 149 |
+
"unet": unet,
|
| 150 |
+
"controlnet": controlnet,
|
| 151 |
+
"scheduler": scheduler,
|
| 152 |
+
"vae": vae,
|
| 153 |
+
"text_encoder": text_encoder,
|
| 154 |
+
"tokenizer": tokenizer,
|
| 155 |
+
"text_encoder_2": text_encoder_2,
|
| 156 |
+
"tokenizer_2": tokenizer_2,
|
| 157 |
+
"feature_extractor": None,
|
| 158 |
+
}
|
| 159 |
+
return components
|
| 160 |
+
|
| 161 |
+
# Copied from test_controlnet_sdxl.py
|
| 162 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 163 |
+
if str(device).startswith("mps"):
|
| 164 |
+
generator = torch.manual_seed(seed)
|
| 165 |
+
else:
|
| 166 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 167 |
+
|
| 168 |
+
controlnet_embedder_scale_factor = 2
|
| 169 |
+
image = randn_tensor(
|
| 170 |
+
(1, 3, 8 * controlnet_embedder_scale_factor, 8 * controlnet_embedder_scale_factor),
|
| 171 |
+
generator=generator,
|
| 172 |
+
device=torch.device(device),
|
| 173 |
+
)
|
| 174 |
+
|
| 175 |
+
inputs = {
|
| 176 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 177 |
+
"generator": generator,
|
| 178 |
+
"num_inference_steps": 2,
|
| 179 |
+
"guidance_scale": 6.0,
|
| 180 |
+
"output_type": "np",
|
| 181 |
+
"image": image,
|
| 182 |
+
}
|
| 183 |
+
|
| 184 |
+
return inputs
|
| 185 |
+
|
| 186 |
+
# Copied from test_controlnet_sdxl.py
|
| 187 |
+
def test_attention_slicing_forward_pass(self):
|
| 188 |
+
return self._test_attention_slicing_forward_pass(expected_max_diff=2e-3)
|
| 189 |
+
|
| 190 |
+
@unittest.skipIf(
|
| 191 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 192 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 193 |
+
)
|
| 194 |
+
# Copied from test_controlnet_sdxl.py
|
| 195 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 196 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=2e-3)
|
| 197 |
+
|
| 198 |
+
# Copied from test_controlnet_sdxl.py
|
| 199 |
+
def test_inference_batch_single_identical(self):
|
| 200 |
+
self._test_inference_batch_single_identical(expected_max_diff=2e-3)
|
| 201 |
+
|
| 202 |
+
@unittest.skip("We test this functionality elsewhere already.")
|
| 203 |
+
def test_save_load_optional_components(self):
|
| 204 |
+
pass
|
| 205 |
+
|
| 206 |
+
@require_torch_accelerator
|
| 207 |
+
# Copied from test_controlnet_sdxl.py
|
| 208 |
+
def test_stable_diffusion_xl_offloads(self):
|
| 209 |
+
pipes = []
|
| 210 |
+
components = self.get_dummy_components()
|
| 211 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 212 |
+
pipes.append(sd_pipe)
|
| 213 |
+
|
| 214 |
+
components = self.get_dummy_components()
|
| 215 |
+
sd_pipe = self.pipeline_class(**components)
|
| 216 |
+
sd_pipe.enable_model_cpu_offload(device=torch_device)
|
| 217 |
+
pipes.append(sd_pipe)
|
| 218 |
+
|
| 219 |
+
components = self.get_dummy_components()
|
| 220 |
+
sd_pipe = self.pipeline_class(**components)
|
| 221 |
+
sd_pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 222 |
+
pipes.append(sd_pipe)
|
| 223 |
+
|
| 224 |
+
image_slices = []
|
| 225 |
+
for pipe in pipes:
|
| 226 |
+
pipe.unet.set_default_attn_processor()
|
| 227 |
+
|
| 228 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 229 |
+
image = pipe(**inputs).images
|
| 230 |
+
|
| 231 |
+
image_slices.append(image[0, -3:, -3:, -1].flatten())
|
| 232 |
+
|
| 233 |
+
assert np.abs(image_slices[0] - image_slices[1]).max() < 1e-3
|
| 234 |
+
assert np.abs(image_slices[0] - image_slices[2]).max() < 1e-3
|
| 235 |
+
|
| 236 |
+
# Copied from test_controlnet_sdxl.py
|
| 237 |
+
def test_stable_diffusion_xl_multi_prompts(self):
|
| 238 |
+
components = self.get_dummy_components()
|
| 239 |
+
sd_pipe = self.pipeline_class(**components).to(torch_device)
|
| 240 |
+
|
| 241 |
+
# forward with single prompt
|
| 242 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 243 |
+
output = sd_pipe(**inputs)
|
| 244 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 245 |
+
|
| 246 |
+
# forward with same prompt duplicated
|
| 247 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 248 |
+
inputs["prompt_2"] = inputs["prompt"]
|
| 249 |
+
output = sd_pipe(**inputs)
|
| 250 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 251 |
+
|
| 252 |
+
# ensure the results are equal
|
| 253 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 254 |
+
|
| 255 |
+
# forward with different prompt
|
| 256 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 257 |
+
inputs["prompt_2"] = "different prompt"
|
| 258 |
+
output = sd_pipe(**inputs)
|
| 259 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 260 |
+
|
| 261 |
+
# ensure the results are not equal
|
| 262 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 263 |
+
|
| 264 |
+
# manually set a negative_prompt
|
| 265 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 266 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 267 |
+
output = sd_pipe(**inputs)
|
| 268 |
+
image_slice_1 = output.images[0, -3:, -3:, -1]
|
| 269 |
+
|
| 270 |
+
# forward with same negative_prompt duplicated
|
| 271 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 272 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 273 |
+
inputs["negative_prompt_2"] = inputs["negative_prompt"]
|
| 274 |
+
output = sd_pipe(**inputs)
|
| 275 |
+
image_slice_2 = output.images[0, -3:, -3:, -1]
|
| 276 |
+
|
| 277 |
+
# ensure the results are equal
|
| 278 |
+
assert np.abs(image_slice_1.flatten() - image_slice_2.flatten()).max() < 1e-4
|
| 279 |
+
|
| 280 |
+
# forward with different negative_prompt
|
| 281 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 282 |
+
inputs["negative_prompt"] = "negative prompt"
|
| 283 |
+
inputs["negative_prompt_2"] = "different negative prompt"
|
| 284 |
+
output = sd_pipe(**inputs)
|
| 285 |
+
image_slice_3 = output.images[0, -3:, -3:, -1]
|
| 286 |
+
|
| 287 |
+
# ensure the results are not equal
|
| 288 |
+
assert np.abs(image_slice_1.flatten() - image_slice_3.flatten()).max() > 1e-4
|
| 289 |
+
|
| 290 |
+
# Copied from test_controlnetxs.py
|
| 291 |
+
def test_to_dtype(self):
|
| 292 |
+
components = self.get_dummy_components()
|
| 293 |
+
pipe = self.pipeline_class(**components)
|
| 294 |
+
pipe.set_progress_bar_config(disable=None)
|
| 295 |
+
|
| 296 |
+
# pipeline creates a new UNetControlNetXSModel under the hood. So we need to check the dtype from pipe.components
|
| 297 |
+
model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
|
| 298 |
+
self.assertTrue(all(dtype == torch.float32 for dtype in model_dtypes))
|
| 299 |
+
|
| 300 |
+
pipe.to(dtype=torch.float16)
|
| 301 |
+
model_dtypes = [component.dtype for component in pipe.components.values() if hasattr(component, "dtype")]
|
| 302 |
+
self.assertTrue(all(dtype == torch.float16 for dtype in model_dtypes))
|
| 303 |
+
|
| 304 |
+
def test_multi_vae(self):
|
| 305 |
+
components = self.get_dummy_components()
|
| 306 |
+
pipe = self.pipeline_class(**components)
|
| 307 |
+
pipe = pipe.to(torch_device)
|
| 308 |
+
pipe.set_progress_bar_config(disable=None)
|
| 309 |
+
|
| 310 |
+
block_out_channels = pipe.vae.config.block_out_channels
|
| 311 |
+
norm_num_groups = pipe.vae.config.norm_num_groups
|
| 312 |
+
|
| 313 |
+
vae_classes = [AutoencoderKL, AsymmetricAutoencoderKL, ConsistencyDecoderVAE, AutoencoderTiny]
|
| 314 |
+
configs = [
|
| 315 |
+
get_autoencoder_kl_config(block_out_channels, norm_num_groups),
|
| 316 |
+
get_asym_autoencoder_kl_config(block_out_channels, norm_num_groups),
|
| 317 |
+
get_consistency_vae_config(block_out_channels, norm_num_groups),
|
| 318 |
+
get_autoencoder_tiny_config(block_out_channels),
|
| 319 |
+
]
|
| 320 |
+
|
| 321 |
+
out_np = pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]
|
| 322 |
+
|
| 323 |
+
for vae_cls, config in zip(vae_classes, configs):
|
| 324 |
+
vae = vae_cls(**config)
|
| 325 |
+
vae = vae.to(torch_device)
|
| 326 |
+
components["vae"] = vae
|
| 327 |
+
vae_pipe = self.pipeline_class(**components)
|
| 328 |
+
|
| 329 |
+
# pipeline creates a new UNetControlNetXSModel under the hood, which aren't on device.
|
| 330 |
+
# So we need to move the new pipe to device.
|
| 331 |
+
vae_pipe.to(torch_device)
|
| 332 |
+
vae_pipe.set_progress_bar_config(disable=None)
|
| 333 |
+
|
| 334 |
+
out_vae_np = vae_pipe(**self.get_dummy_inputs_by_type(torch_device, input_image_type="np"))[0]
|
| 335 |
+
|
| 336 |
+
assert out_vae_np.shape == out_np.shape
|
| 337 |
+
|
| 338 |
+
|
| 339 |
+
@slow
|
| 340 |
+
@require_torch_accelerator
|
| 341 |
+
class StableDiffusionXLControlNetXSPipelineSlowTests(unittest.TestCase):
|
| 342 |
+
def tearDown(self):
|
| 343 |
+
super().tearDown()
|
| 344 |
+
gc.collect()
|
| 345 |
+
backend_empty_cache(torch_device)
|
| 346 |
+
|
| 347 |
+
def test_canny(self):
|
| 348 |
+
controlnet = ControlNetXSAdapter.from_pretrained(
|
| 349 |
+
"UmerHA/Testing-ConrolNetXS-SDXL-canny", torch_dtype=torch.float16
|
| 350 |
+
)
|
| 351 |
+
pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
|
| 352 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
|
| 353 |
+
)
|
| 354 |
+
pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 355 |
+
pipe.set_progress_bar_config(disable=None)
|
| 356 |
+
|
| 357 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 358 |
+
prompt = "bird"
|
| 359 |
+
image = load_image(
|
| 360 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/bird_canny.png"
|
| 361 |
+
)
|
| 362 |
+
|
| 363 |
+
images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
|
| 364 |
+
|
| 365 |
+
assert images[0].shape == (768, 512, 3)
|
| 366 |
+
|
| 367 |
+
original_image = images[0, -3:, -3:, -1].flatten()
|
| 368 |
+
expected_image = np.array([0.3202, 0.3151, 0.3328, 0.3172, 0.337, 0.3381, 0.3378, 0.3389, 0.3224])
|
| 369 |
+
assert np.allclose(original_image, expected_image, atol=1e-04)
|
| 370 |
+
|
| 371 |
+
def test_depth(self):
|
| 372 |
+
controlnet = ControlNetXSAdapter.from_pretrained(
|
| 373 |
+
"UmerHA/Testing-ConrolNetXS-SDXL-depth", torch_dtype=torch.float16
|
| 374 |
+
)
|
| 375 |
+
pipe = StableDiffusionXLControlNetXSPipeline.from_pretrained(
|
| 376 |
+
"stabilityai/stable-diffusion-xl-base-1.0", controlnet=controlnet, torch_dtype=torch.float16
|
| 377 |
+
)
|
| 378 |
+
pipe.enable_sequential_cpu_offload(device=torch_device)
|
| 379 |
+
pipe.set_progress_bar_config(disable=None)
|
| 380 |
+
|
| 381 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 382 |
+
prompt = "Stormtrooper's lecture"
|
| 383 |
+
image = load_image(
|
| 384 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/sd_controlnet/stormtrooper_depth.png"
|
| 385 |
+
)
|
| 386 |
+
|
| 387 |
+
images = pipe(prompt, image=image, generator=generator, output_type="np", num_inference_steps=3).images
|
| 388 |
+
|
| 389 |
+
assert images[0].shape == (512, 512, 3)
|
| 390 |
+
|
| 391 |
+
original_image = images[0, -3:, -3:, -1].flatten()
|
| 392 |
+
expected_image = np.array([0.5448, 0.5437, 0.5426, 0.5543, 0.553, 0.5475, 0.5595, 0.5602, 0.5529])
|
| 393 |
+
assert np.allclose(original_image, expected_image, atol=1e-04)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/cosmos_guardrail.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
# ===== This file is an implementation of a dummy guardrail for the fast tests =====
|
| 16 |
+
|
| 17 |
+
from typing import Union
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers.configuration_utils import ConfigMixin
|
| 23 |
+
from diffusers.models.modeling_utils import ModelMixin
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class DummyCosmosSafetyChecker(ModelMixin, ConfigMixin):
|
| 27 |
+
def __init__(self) -> None:
|
| 28 |
+
super().__init__()
|
| 29 |
+
|
| 30 |
+
self._dtype = torch.float32
|
| 31 |
+
|
| 32 |
+
def check_text_safety(self, prompt: str) -> bool:
|
| 33 |
+
return True
|
| 34 |
+
|
| 35 |
+
def check_video_safety(self, frames: np.ndarray) -> np.ndarray:
|
| 36 |
+
return frames
|
| 37 |
+
|
| 38 |
+
def to(self, device: Union[str, torch.device] = None, dtype: torch.dtype = None) -> None:
|
| 39 |
+
self._dtype = dtype
|
| 40 |
+
|
| 41 |
+
@property
|
| 42 |
+
def device(self) -> torch.device:
|
| 43 |
+
return None
|
| 44 |
+
|
| 45 |
+
@property
|
| 46 |
+
def dtype(self) -> torch.dtype:
|
| 47 |
+
return self._dtype
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos.py
ADDED
|
@@ -0,0 +1,350 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 24 |
+
|
| 25 |
+
from diffusers import AutoencoderKLCosmos, CosmosTextToWorldPipeline, CosmosTransformer3DModel, EDMEulerScheduler
|
| 26 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 27 |
+
|
| 28 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 29 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 30 |
+
from .cosmos_guardrail import DummyCosmosSafetyChecker
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
enable_full_determinism()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
class CosmosTextToWorldPipelineWrapper(CosmosTextToWorldPipeline):
|
| 37 |
+
@staticmethod
|
| 38 |
+
def from_pretrained(*args, **kwargs):
|
| 39 |
+
kwargs["safety_checker"] = DummyCosmosSafetyChecker()
|
| 40 |
+
return CosmosTextToWorldPipeline.from_pretrained(*args, **kwargs)
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class CosmosTextToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 44 |
+
pipeline_class = CosmosTextToWorldPipelineWrapper
|
| 45 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 46 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 47 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 48 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 49 |
+
required_optional_params = frozenset(
|
| 50 |
+
[
|
| 51 |
+
"num_inference_steps",
|
| 52 |
+
"generator",
|
| 53 |
+
"latents",
|
| 54 |
+
"return_dict",
|
| 55 |
+
"callback_on_step_end",
|
| 56 |
+
"callback_on_step_end_tensor_inputs",
|
| 57 |
+
]
|
| 58 |
+
)
|
| 59 |
+
supports_dduf = False
|
| 60 |
+
test_xformers_attention = False
|
| 61 |
+
test_layerwise_casting = True
|
| 62 |
+
test_group_offloading = True
|
| 63 |
+
|
| 64 |
+
def get_dummy_components(self):
|
| 65 |
+
torch.manual_seed(0)
|
| 66 |
+
transformer = CosmosTransformer3DModel(
|
| 67 |
+
in_channels=4,
|
| 68 |
+
out_channels=4,
|
| 69 |
+
num_attention_heads=2,
|
| 70 |
+
attention_head_dim=16,
|
| 71 |
+
num_layers=2,
|
| 72 |
+
mlp_ratio=2,
|
| 73 |
+
text_embed_dim=32,
|
| 74 |
+
adaln_lora_dim=4,
|
| 75 |
+
max_size=(4, 32, 32),
|
| 76 |
+
patch_size=(1, 2, 2),
|
| 77 |
+
rope_scale=(2.0, 1.0, 1.0),
|
| 78 |
+
concat_padding_mask=True,
|
| 79 |
+
extra_pos_embed_type="learnable",
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
torch.manual_seed(0)
|
| 83 |
+
vae = AutoencoderKLCosmos(
|
| 84 |
+
in_channels=3,
|
| 85 |
+
out_channels=3,
|
| 86 |
+
latent_channels=4,
|
| 87 |
+
encoder_block_out_channels=(8, 8, 8, 8),
|
| 88 |
+
decode_block_out_channels=(8, 8, 8, 8),
|
| 89 |
+
attention_resolutions=(8,),
|
| 90 |
+
resolution=64,
|
| 91 |
+
num_layers=2,
|
| 92 |
+
patch_size=4,
|
| 93 |
+
patch_type="haar",
|
| 94 |
+
scaling_factor=1.0,
|
| 95 |
+
spatial_compression_ratio=4,
|
| 96 |
+
temporal_compression_ratio=4,
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
torch.manual_seed(0)
|
| 100 |
+
scheduler = EDMEulerScheduler(
|
| 101 |
+
sigma_min=0.002,
|
| 102 |
+
sigma_max=80,
|
| 103 |
+
sigma_data=0.5,
|
| 104 |
+
sigma_schedule="karras",
|
| 105 |
+
num_train_timesteps=1000,
|
| 106 |
+
prediction_type="epsilon",
|
| 107 |
+
rho=7.0,
|
| 108 |
+
final_sigmas_type="sigma_min",
|
| 109 |
+
)
|
| 110 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 111 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 112 |
+
|
| 113 |
+
components = {
|
| 114 |
+
"transformer": transformer,
|
| 115 |
+
"vae": vae,
|
| 116 |
+
"scheduler": scheduler,
|
| 117 |
+
"text_encoder": text_encoder,
|
| 118 |
+
"tokenizer": tokenizer,
|
| 119 |
+
# We cannot run the Cosmos Guardrail for fast tests due to the large model size
|
| 120 |
+
"safety_checker": DummyCosmosSafetyChecker(),
|
| 121 |
+
}
|
| 122 |
+
return components
|
| 123 |
+
|
| 124 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 125 |
+
if str(device).startswith("mps"):
|
| 126 |
+
generator = torch.manual_seed(seed)
|
| 127 |
+
else:
|
| 128 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 129 |
+
|
| 130 |
+
inputs = {
|
| 131 |
+
"prompt": "dance monkey",
|
| 132 |
+
"negative_prompt": "bad quality",
|
| 133 |
+
"generator": generator,
|
| 134 |
+
"num_inference_steps": 2,
|
| 135 |
+
"guidance_scale": 3.0,
|
| 136 |
+
"height": 32,
|
| 137 |
+
"width": 32,
|
| 138 |
+
"num_frames": 9,
|
| 139 |
+
"max_sequence_length": 16,
|
| 140 |
+
"output_type": "pt",
|
| 141 |
+
}
|
| 142 |
+
|
| 143 |
+
return inputs
|
| 144 |
+
|
| 145 |
+
def test_inference(self):
|
| 146 |
+
device = "cpu"
|
| 147 |
+
|
| 148 |
+
components = self.get_dummy_components()
|
| 149 |
+
pipe = self.pipeline_class(**components)
|
| 150 |
+
pipe.to(device)
|
| 151 |
+
pipe.set_progress_bar_config(disable=None)
|
| 152 |
+
|
| 153 |
+
inputs = self.get_dummy_inputs(device)
|
| 154 |
+
video = pipe(**inputs).frames
|
| 155 |
+
generated_video = video[0]
|
| 156 |
+
|
| 157 |
+
self.assertEqual(generated_video.shape, (9, 3, 32, 32))
|
| 158 |
+
expected_video = torch.randn(9, 3, 32, 32)
|
| 159 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 160 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 161 |
+
|
| 162 |
+
def test_callback_inputs(self):
|
| 163 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 164 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 165 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 166 |
+
|
| 167 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 168 |
+
return
|
| 169 |
+
|
| 170 |
+
components = self.get_dummy_components()
|
| 171 |
+
pipe = self.pipeline_class(**components)
|
| 172 |
+
pipe = pipe.to(torch_device)
|
| 173 |
+
pipe.set_progress_bar_config(disable=None)
|
| 174 |
+
self.assertTrue(
|
| 175 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 176 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 177 |
+
)
|
| 178 |
+
|
| 179 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 180 |
+
# iterate over callback args
|
| 181 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 182 |
+
# check that we're only passing in allowed tensor inputs
|
| 183 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 184 |
+
|
| 185 |
+
return callback_kwargs
|
| 186 |
+
|
| 187 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 188 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 189 |
+
assert tensor_name in callback_kwargs
|
| 190 |
+
|
| 191 |
+
# iterate over callback args
|
| 192 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 193 |
+
# check that we're only passing in allowed tensor inputs
|
| 194 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 195 |
+
|
| 196 |
+
return callback_kwargs
|
| 197 |
+
|
| 198 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 199 |
+
|
| 200 |
+
# Test passing in a subset
|
| 201 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 202 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 203 |
+
output = pipe(**inputs)[0]
|
| 204 |
+
|
| 205 |
+
# Test passing in a everything
|
| 206 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 207 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 208 |
+
output = pipe(**inputs)[0]
|
| 209 |
+
|
| 210 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 211 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 212 |
+
if is_last:
|
| 213 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 214 |
+
return callback_kwargs
|
| 215 |
+
|
| 216 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 217 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 218 |
+
output = pipe(**inputs)[0]
|
| 219 |
+
assert output.abs().sum() < 1e10
|
| 220 |
+
|
| 221 |
+
def test_inference_batch_single_identical(self):
|
| 222 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
|
| 223 |
+
|
| 224 |
+
def test_attention_slicing_forward_pass(
|
| 225 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 226 |
+
):
|
| 227 |
+
if not self.test_attention_slicing:
|
| 228 |
+
return
|
| 229 |
+
|
| 230 |
+
components = self.get_dummy_components()
|
| 231 |
+
pipe = self.pipeline_class(**components)
|
| 232 |
+
for component in pipe.components.values():
|
| 233 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 234 |
+
component.set_default_attn_processor()
|
| 235 |
+
pipe.to(torch_device)
|
| 236 |
+
pipe.set_progress_bar_config(disable=None)
|
| 237 |
+
|
| 238 |
+
generator_device = "cpu"
|
| 239 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 240 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 241 |
+
|
| 242 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 243 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 244 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 245 |
+
|
| 246 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 247 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 248 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 249 |
+
|
| 250 |
+
if test_max_difference:
|
| 251 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 252 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 253 |
+
self.assertLess(
|
| 254 |
+
max(max_diff1, max_diff2),
|
| 255 |
+
expected_max_diff,
|
| 256 |
+
"Attention slicing should not affect the inference results",
|
| 257 |
+
)
|
| 258 |
+
|
| 259 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 260 |
+
generator_device = "cpu"
|
| 261 |
+
components = self.get_dummy_components()
|
| 262 |
+
|
| 263 |
+
pipe = self.pipeline_class(**components)
|
| 264 |
+
pipe.to("cpu")
|
| 265 |
+
pipe.set_progress_bar_config(disable=None)
|
| 266 |
+
|
| 267 |
+
# Without tiling
|
| 268 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 269 |
+
inputs["height"] = inputs["width"] = 128
|
| 270 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 271 |
+
|
| 272 |
+
# With tiling
|
| 273 |
+
pipe.vae.enable_tiling(
|
| 274 |
+
tile_sample_min_height=96,
|
| 275 |
+
tile_sample_min_width=96,
|
| 276 |
+
tile_sample_stride_height=64,
|
| 277 |
+
tile_sample_stride_width=64,
|
| 278 |
+
)
|
| 279 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 280 |
+
inputs["height"] = inputs["width"] = 128
|
| 281 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 282 |
+
|
| 283 |
+
self.assertLess(
|
| 284 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 285 |
+
expected_diff_max,
|
| 286 |
+
"VAE tiling should not affect the inference results",
|
| 287 |
+
)
|
| 288 |
+
|
| 289 |
+
def test_save_load_optional_components(self, expected_max_difference=1e-4):
|
| 290 |
+
self.pipeline_class._optional_components.remove("safety_checker")
|
| 291 |
+
super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
|
| 292 |
+
self.pipeline_class._optional_components.append("safety_checker")
|
| 293 |
+
|
| 294 |
+
def test_serialization_with_variants(self):
|
| 295 |
+
components = self.get_dummy_components()
|
| 296 |
+
pipe = self.pipeline_class(**components)
|
| 297 |
+
model_components = [
|
| 298 |
+
component_name
|
| 299 |
+
for component_name, component in pipe.components.items()
|
| 300 |
+
if isinstance(component, torch.nn.Module)
|
| 301 |
+
]
|
| 302 |
+
model_components.remove("safety_checker")
|
| 303 |
+
variant = "fp16"
|
| 304 |
+
|
| 305 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 306 |
+
pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
|
| 307 |
+
|
| 308 |
+
with open(f"{tmpdir}/model_index.json", "r") as f:
|
| 309 |
+
config = json.load(f)
|
| 310 |
+
|
| 311 |
+
for subfolder in os.listdir(tmpdir):
|
| 312 |
+
if not os.path.isfile(subfolder) and subfolder in model_components:
|
| 313 |
+
folder_path = os.path.join(tmpdir, subfolder)
|
| 314 |
+
is_folder = os.path.isdir(folder_path) and subfolder in config
|
| 315 |
+
assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
|
| 316 |
+
|
| 317 |
+
def test_torch_dtype_dict(self):
|
| 318 |
+
components = self.get_dummy_components()
|
| 319 |
+
if not components:
|
| 320 |
+
self.skipTest("No dummy components defined.")
|
| 321 |
+
|
| 322 |
+
pipe = self.pipeline_class(**components)
|
| 323 |
+
|
| 324 |
+
specified_key = next(iter(components.keys()))
|
| 325 |
+
|
| 326 |
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
|
| 327 |
+
pipe.save_pretrained(tmpdirname, safe_serialization=False)
|
| 328 |
+
torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
|
| 329 |
+
loaded_pipe = self.pipeline_class.from_pretrained(
|
| 330 |
+
tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
|
| 331 |
+
)
|
| 332 |
+
|
| 333 |
+
for name, component in loaded_pipe.components.items():
|
| 334 |
+
if name == "safety_checker":
|
| 335 |
+
continue
|
| 336 |
+
if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
|
| 337 |
+
expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
|
| 338 |
+
self.assertEqual(
|
| 339 |
+
component.dtype,
|
| 340 |
+
expected_dtype,
|
| 341 |
+
f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
|
| 342 |
+
)
|
| 343 |
+
|
| 344 |
+
@unittest.skip(
|
| 345 |
+
"The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
|
| 346 |
+
"a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
|
| 347 |
+
"too large and slow to run on CI."
|
| 348 |
+
)
|
| 349 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 350 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos2_text2image.py
ADDED
|
@@ -0,0 +1,337 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import torch
|
| 23 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 24 |
+
|
| 25 |
+
from diffusers import (
|
| 26 |
+
AutoencoderKLWan,
|
| 27 |
+
Cosmos2TextToImagePipeline,
|
| 28 |
+
CosmosTransformer3DModel,
|
| 29 |
+
FlowMatchEulerDiscreteScheduler,
|
| 30 |
+
)
|
| 31 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 32 |
+
|
| 33 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 34 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 35 |
+
from .cosmos_guardrail import DummyCosmosSafetyChecker
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
enable_full_determinism()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class Cosmos2TextToImagePipelineWrapper(Cosmos2TextToImagePipeline):
|
| 42 |
+
@staticmethod
|
| 43 |
+
def from_pretrained(*args, **kwargs):
|
| 44 |
+
kwargs["safety_checker"] = DummyCosmosSafetyChecker()
|
| 45 |
+
return Cosmos2TextToImagePipeline.from_pretrained(*args, **kwargs)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
class Cosmos2TextToImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 49 |
+
pipeline_class = Cosmos2TextToImagePipelineWrapper
|
| 50 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 51 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 52 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 53 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 54 |
+
required_optional_params = frozenset(
|
| 55 |
+
[
|
| 56 |
+
"num_inference_steps",
|
| 57 |
+
"generator",
|
| 58 |
+
"latents",
|
| 59 |
+
"return_dict",
|
| 60 |
+
"callback_on_step_end",
|
| 61 |
+
"callback_on_step_end_tensor_inputs",
|
| 62 |
+
]
|
| 63 |
+
)
|
| 64 |
+
supports_dduf = False
|
| 65 |
+
test_xformers_attention = False
|
| 66 |
+
test_layerwise_casting = True
|
| 67 |
+
test_group_offloading = True
|
| 68 |
+
|
| 69 |
+
def get_dummy_components(self):
|
| 70 |
+
torch.manual_seed(0)
|
| 71 |
+
transformer = CosmosTransformer3DModel(
|
| 72 |
+
in_channels=16,
|
| 73 |
+
out_channels=16,
|
| 74 |
+
num_attention_heads=2,
|
| 75 |
+
attention_head_dim=16,
|
| 76 |
+
num_layers=2,
|
| 77 |
+
mlp_ratio=2,
|
| 78 |
+
text_embed_dim=32,
|
| 79 |
+
adaln_lora_dim=4,
|
| 80 |
+
max_size=(4, 32, 32),
|
| 81 |
+
patch_size=(1, 2, 2),
|
| 82 |
+
rope_scale=(2.0, 1.0, 1.0),
|
| 83 |
+
concat_padding_mask=True,
|
| 84 |
+
extra_pos_embed_type="learnable",
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
vae = AutoencoderKLWan(
|
| 89 |
+
base_dim=3,
|
| 90 |
+
z_dim=16,
|
| 91 |
+
dim_mult=[1, 1, 1, 1],
|
| 92 |
+
num_res_blocks=1,
|
| 93 |
+
temperal_downsample=[False, True, True],
|
| 94 |
+
)
|
| 95 |
+
|
| 96 |
+
torch.manual_seed(0)
|
| 97 |
+
scheduler = FlowMatchEulerDiscreteScheduler(use_karras_sigmas=True)
|
| 98 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 99 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 100 |
+
|
| 101 |
+
components = {
|
| 102 |
+
"transformer": transformer,
|
| 103 |
+
"vae": vae,
|
| 104 |
+
"scheduler": scheduler,
|
| 105 |
+
"text_encoder": text_encoder,
|
| 106 |
+
"tokenizer": tokenizer,
|
| 107 |
+
# We cannot run the Cosmos Guardrail for fast tests due to the large model size
|
| 108 |
+
"safety_checker": DummyCosmosSafetyChecker(),
|
| 109 |
+
}
|
| 110 |
+
return components
|
| 111 |
+
|
| 112 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 113 |
+
if str(device).startswith("mps"):
|
| 114 |
+
generator = torch.manual_seed(seed)
|
| 115 |
+
else:
|
| 116 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 117 |
+
|
| 118 |
+
inputs = {
|
| 119 |
+
"prompt": "dance monkey",
|
| 120 |
+
"negative_prompt": "bad quality",
|
| 121 |
+
"generator": generator,
|
| 122 |
+
"num_inference_steps": 2,
|
| 123 |
+
"guidance_scale": 3.0,
|
| 124 |
+
"height": 32,
|
| 125 |
+
"width": 32,
|
| 126 |
+
"max_sequence_length": 16,
|
| 127 |
+
"output_type": "pt",
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
return inputs
|
| 131 |
+
|
| 132 |
+
def test_inference(self):
|
| 133 |
+
device = "cpu"
|
| 134 |
+
|
| 135 |
+
components = self.get_dummy_components()
|
| 136 |
+
pipe = self.pipeline_class(**components)
|
| 137 |
+
pipe.to(device)
|
| 138 |
+
pipe.set_progress_bar_config(disable=None)
|
| 139 |
+
|
| 140 |
+
inputs = self.get_dummy_inputs(device)
|
| 141 |
+
image = pipe(**inputs).images
|
| 142 |
+
generated_image = image[0]
|
| 143 |
+
|
| 144 |
+
self.assertEqual(generated_image.shape, (3, 32, 32))
|
| 145 |
+
expected_video = torch.randn(3, 32, 32)
|
| 146 |
+
max_diff = np.abs(generated_image - expected_video).max()
|
| 147 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 148 |
+
|
| 149 |
+
def test_callback_inputs(self):
|
| 150 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 151 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 152 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 153 |
+
|
| 154 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 155 |
+
return
|
| 156 |
+
|
| 157 |
+
components = self.get_dummy_components()
|
| 158 |
+
pipe = self.pipeline_class(**components)
|
| 159 |
+
pipe = pipe.to(torch_device)
|
| 160 |
+
pipe.set_progress_bar_config(disable=None)
|
| 161 |
+
self.assertTrue(
|
| 162 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 163 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 164 |
+
)
|
| 165 |
+
|
| 166 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 167 |
+
# iterate over callback args
|
| 168 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 169 |
+
# check that we're only passing in allowed tensor inputs
|
| 170 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 171 |
+
|
| 172 |
+
return callback_kwargs
|
| 173 |
+
|
| 174 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 175 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 176 |
+
assert tensor_name in callback_kwargs
|
| 177 |
+
|
| 178 |
+
# iterate over callback args
|
| 179 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 180 |
+
# check that we're only passing in allowed tensor inputs
|
| 181 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 182 |
+
|
| 183 |
+
return callback_kwargs
|
| 184 |
+
|
| 185 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 186 |
+
|
| 187 |
+
# Test passing in a subset
|
| 188 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 189 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 190 |
+
output = pipe(**inputs)[0]
|
| 191 |
+
|
| 192 |
+
# Test passing in a everything
|
| 193 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 194 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 195 |
+
output = pipe(**inputs)[0]
|
| 196 |
+
|
| 197 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 198 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 199 |
+
if is_last:
|
| 200 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 201 |
+
return callback_kwargs
|
| 202 |
+
|
| 203 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 204 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 205 |
+
output = pipe(**inputs)[0]
|
| 206 |
+
assert output.abs().sum() < 1e10
|
| 207 |
+
|
| 208 |
+
def test_inference_batch_single_identical(self):
|
| 209 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
|
| 210 |
+
|
| 211 |
+
def test_attention_slicing_forward_pass(
|
| 212 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 213 |
+
):
|
| 214 |
+
if not self.test_attention_slicing:
|
| 215 |
+
return
|
| 216 |
+
|
| 217 |
+
components = self.get_dummy_components()
|
| 218 |
+
pipe = self.pipeline_class(**components)
|
| 219 |
+
for component in pipe.components.values():
|
| 220 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 221 |
+
component.set_default_attn_processor()
|
| 222 |
+
pipe.to(torch_device)
|
| 223 |
+
pipe.set_progress_bar_config(disable=None)
|
| 224 |
+
|
| 225 |
+
generator_device = "cpu"
|
| 226 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 227 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 228 |
+
|
| 229 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 230 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 231 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 232 |
+
|
| 233 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 234 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 235 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 236 |
+
|
| 237 |
+
if test_max_difference:
|
| 238 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 239 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 240 |
+
self.assertLess(
|
| 241 |
+
max(max_diff1, max_diff2),
|
| 242 |
+
expected_max_diff,
|
| 243 |
+
"Attention slicing should not affect the inference results",
|
| 244 |
+
)
|
| 245 |
+
|
| 246 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 247 |
+
generator_device = "cpu"
|
| 248 |
+
components = self.get_dummy_components()
|
| 249 |
+
|
| 250 |
+
pipe = self.pipeline_class(**components)
|
| 251 |
+
pipe.to("cpu")
|
| 252 |
+
pipe.set_progress_bar_config(disable=None)
|
| 253 |
+
|
| 254 |
+
# Without tiling
|
| 255 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 256 |
+
inputs["height"] = inputs["width"] = 128
|
| 257 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 258 |
+
|
| 259 |
+
# With tiling
|
| 260 |
+
pipe.vae.enable_tiling(
|
| 261 |
+
tile_sample_min_height=96,
|
| 262 |
+
tile_sample_min_width=96,
|
| 263 |
+
tile_sample_stride_height=64,
|
| 264 |
+
tile_sample_stride_width=64,
|
| 265 |
+
)
|
| 266 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 267 |
+
inputs["height"] = inputs["width"] = 128
|
| 268 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 269 |
+
|
| 270 |
+
self.assertLess(
|
| 271 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 272 |
+
expected_diff_max,
|
| 273 |
+
"VAE tiling should not affect the inference results",
|
| 274 |
+
)
|
| 275 |
+
|
| 276 |
+
def test_save_load_optional_components(self, expected_max_difference=1e-4):
|
| 277 |
+
self.pipeline_class._optional_components.remove("safety_checker")
|
| 278 |
+
super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
|
| 279 |
+
self.pipeline_class._optional_components.append("safety_checker")
|
| 280 |
+
|
| 281 |
+
def test_serialization_with_variants(self):
|
| 282 |
+
components = self.get_dummy_components()
|
| 283 |
+
pipe = self.pipeline_class(**components)
|
| 284 |
+
model_components = [
|
| 285 |
+
component_name
|
| 286 |
+
for component_name, component in pipe.components.items()
|
| 287 |
+
if isinstance(component, torch.nn.Module)
|
| 288 |
+
]
|
| 289 |
+
model_components.remove("safety_checker")
|
| 290 |
+
variant = "fp16"
|
| 291 |
+
|
| 292 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 293 |
+
pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
|
| 294 |
+
|
| 295 |
+
with open(f"{tmpdir}/model_index.json", "r") as f:
|
| 296 |
+
config = json.load(f)
|
| 297 |
+
|
| 298 |
+
for subfolder in os.listdir(tmpdir):
|
| 299 |
+
if not os.path.isfile(subfolder) and subfolder in model_components:
|
| 300 |
+
folder_path = os.path.join(tmpdir, subfolder)
|
| 301 |
+
is_folder = os.path.isdir(folder_path) and subfolder in config
|
| 302 |
+
assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
|
| 303 |
+
|
| 304 |
+
def test_torch_dtype_dict(self):
|
| 305 |
+
components = self.get_dummy_components()
|
| 306 |
+
if not components:
|
| 307 |
+
self.skipTest("No dummy components defined.")
|
| 308 |
+
|
| 309 |
+
pipe = self.pipeline_class(**components)
|
| 310 |
+
|
| 311 |
+
specified_key = next(iter(components.keys()))
|
| 312 |
+
|
| 313 |
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
|
| 314 |
+
pipe.save_pretrained(tmpdirname, safe_serialization=False)
|
| 315 |
+
torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
|
| 316 |
+
loaded_pipe = self.pipeline_class.from_pretrained(
|
| 317 |
+
tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
|
| 318 |
+
)
|
| 319 |
+
|
| 320 |
+
for name, component in loaded_pipe.components.items():
|
| 321 |
+
if name == "safety_checker":
|
| 322 |
+
continue
|
| 323 |
+
if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
|
| 324 |
+
expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
|
| 325 |
+
self.assertEqual(
|
| 326 |
+
component.dtype,
|
| 327 |
+
expected_dtype,
|
| 328 |
+
f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
|
| 329 |
+
)
|
| 330 |
+
|
| 331 |
+
@unittest.skip(
|
| 332 |
+
"The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
|
| 333 |
+
"a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
|
| 334 |
+
"too large and slow to run on CI."
|
| 335 |
+
)
|
| 336 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 337 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos2_video2world.py
ADDED
|
@@ -0,0 +1,351 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import PIL.Image
|
| 23 |
+
import torch
|
| 24 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers import (
|
| 27 |
+
AutoencoderKLWan,
|
| 28 |
+
Cosmos2VideoToWorldPipeline,
|
| 29 |
+
CosmosTransformer3DModel,
|
| 30 |
+
FlowMatchEulerDiscreteScheduler,
|
| 31 |
+
)
|
| 32 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 33 |
+
|
| 34 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 35 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 36 |
+
from .cosmos_guardrail import DummyCosmosSafetyChecker
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
enable_full_determinism()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class Cosmos2VideoToWorldPipelineWrapper(Cosmos2VideoToWorldPipeline):
|
| 43 |
+
@staticmethod
|
| 44 |
+
def from_pretrained(*args, **kwargs):
|
| 45 |
+
kwargs["safety_checker"] = DummyCosmosSafetyChecker()
|
| 46 |
+
return Cosmos2VideoToWorldPipeline.from_pretrained(*args, **kwargs)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class Cosmos2VideoToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 50 |
+
pipeline_class = Cosmos2VideoToWorldPipelineWrapper
|
| 51 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 52 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image", "video"})
|
| 53 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 54 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 55 |
+
required_optional_params = frozenset(
|
| 56 |
+
[
|
| 57 |
+
"num_inference_steps",
|
| 58 |
+
"generator",
|
| 59 |
+
"latents",
|
| 60 |
+
"return_dict",
|
| 61 |
+
"callback_on_step_end",
|
| 62 |
+
"callback_on_step_end_tensor_inputs",
|
| 63 |
+
]
|
| 64 |
+
)
|
| 65 |
+
supports_dduf = False
|
| 66 |
+
test_xformers_attention = False
|
| 67 |
+
test_layerwise_casting = True
|
| 68 |
+
test_group_offloading = True
|
| 69 |
+
|
| 70 |
+
def get_dummy_components(self):
|
| 71 |
+
torch.manual_seed(0)
|
| 72 |
+
transformer = CosmosTransformer3DModel(
|
| 73 |
+
in_channels=16 + 1,
|
| 74 |
+
out_channels=16,
|
| 75 |
+
num_attention_heads=2,
|
| 76 |
+
attention_head_dim=16,
|
| 77 |
+
num_layers=2,
|
| 78 |
+
mlp_ratio=2,
|
| 79 |
+
text_embed_dim=32,
|
| 80 |
+
adaln_lora_dim=4,
|
| 81 |
+
max_size=(4, 32, 32),
|
| 82 |
+
patch_size=(1, 2, 2),
|
| 83 |
+
rope_scale=(2.0, 1.0, 1.0),
|
| 84 |
+
concat_padding_mask=True,
|
| 85 |
+
extra_pos_embed_type="learnable",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
torch.manual_seed(0)
|
| 89 |
+
vae = AutoencoderKLWan(
|
| 90 |
+
base_dim=3,
|
| 91 |
+
z_dim=16,
|
| 92 |
+
dim_mult=[1, 1, 1, 1],
|
| 93 |
+
num_res_blocks=1,
|
| 94 |
+
temperal_downsample=[False, True, True],
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
scheduler = FlowMatchEulerDiscreteScheduler(use_karras_sigmas=True)
|
| 99 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 100 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 101 |
+
|
| 102 |
+
components = {
|
| 103 |
+
"transformer": transformer,
|
| 104 |
+
"vae": vae,
|
| 105 |
+
"scheduler": scheduler,
|
| 106 |
+
"text_encoder": text_encoder,
|
| 107 |
+
"tokenizer": tokenizer,
|
| 108 |
+
# We cannot run the Cosmos Guardrail for fast tests due to the large model size
|
| 109 |
+
"safety_checker": DummyCosmosSafetyChecker(),
|
| 110 |
+
}
|
| 111 |
+
return components
|
| 112 |
+
|
| 113 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 114 |
+
if str(device).startswith("mps"):
|
| 115 |
+
generator = torch.manual_seed(seed)
|
| 116 |
+
else:
|
| 117 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 118 |
+
|
| 119 |
+
image_height = 32
|
| 120 |
+
image_width = 32
|
| 121 |
+
image = PIL.Image.new("RGB", (image_width, image_height))
|
| 122 |
+
|
| 123 |
+
inputs = {
|
| 124 |
+
"image": image,
|
| 125 |
+
"prompt": "dance monkey",
|
| 126 |
+
"negative_prompt": "bad quality",
|
| 127 |
+
"generator": generator,
|
| 128 |
+
"num_inference_steps": 2,
|
| 129 |
+
"guidance_scale": 3.0,
|
| 130 |
+
"height": image_height,
|
| 131 |
+
"width": image_width,
|
| 132 |
+
"num_frames": 9,
|
| 133 |
+
"max_sequence_length": 16,
|
| 134 |
+
"output_type": "pt",
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
return inputs
|
| 138 |
+
|
| 139 |
+
def test_inference(self):
|
| 140 |
+
device = "cpu"
|
| 141 |
+
|
| 142 |
+
components = self.get_dummy_components()
|
| 143 |
+
pipe = self.pipeline_class(**components)
|
| 144 |
+
pipe.to(device)
|
| 145 |
+
pipe.set_progress_bar_config(disable=None)
|
| 146 |
+
|
| 147 |
+
inputs = self.get_dummy_inputs(device)
|
| 148 |
+
video = pipe(**inputs).frames
|
| 149 |
+
generated_video = video[0]
|
| 150 |
+
|
| 151 |
+
self.assertEqual(generated_video.shape, (9, 3, 32, 32))
|
| 152 |
+
expected_video = torch.randn(9, 3, 32, 32)
|
| 153 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 154 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 155 |
+
|
| 156 |
+
def test_components_function(self):
|
| 157 |
+
init_components = self.get_dummy_components()
|
| 158 |
+
init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
|
| 159 |
+
pipe = self.pipeline_class(**init_components)
|
| 160 |
+
self.assertTrue(hasattr(pipe, "components"))
|
| 161 |
+
self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
|
| 162 |
+
|
| 163 |
+
def test_callback_inputs(self):
|
| 164 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 165 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 166 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 167 |
+
|
| 168 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 169 |
+
return
|
| 170 |
+
|
| 171 |
+
components = self.get_dummy_components()
|
| 172 |
+
pipe = self.pipeline_class(**components)
|
| 173 |
+
pipe = pipe.to(torch_device)
|
| 174 |
+
pipe.set_progress_bar_config(disable=None)
|
| 175 |
+
self.assertTrue(
|
| 176 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 177 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 178 |
+
)
|
| 179 |
+
|
| 180 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 181 |
+
# iterate over callback args
|
| 182 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 183 |
+
# check that we're only passing in allowed tensor inputs
|
| 184 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 185 |
+
|
| 186 |
+
return callback_kwargs
|
| 187 |
+
|
| 188 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 189 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 190 |
+
assert tensor_name in callback_kwargs
|
| 191 |
+
|
| 192 |
+
# iterate over callback args
|
| 193 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 194 |
+
# check that we're only passing in allowed tensor inputs
|
| 195 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 196 |
+
|
| 197 |
+
return callback_kwargs
|
| 198 |
+
|
| 199 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 200 |
+
|
| 201 |
+
# Test passing in a subset
|
| 202 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 203 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 204 |
+
output = pipe(**inputs)[0]
|
| 205 |
+
|
| 206 |
+
# Test passing in a everything
|
| 207 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 208 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 209 |
+
output = pipe(**inputs)[0]
|
| 210 |
+
|
| 211 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 212 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 213 |
+
if is_last:
|
| 214 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 215 |
+
return callback_kwargs
|
| 216 |
+
|
| 217 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 218 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 219 |
+
output = pipe(**inputs)[0]
|
| 220 |
+
assert output.abs().sum() < 1e10
|
| 221 |
+
|
| 222 |
+
def test_inference_batch_single_identical(self):
|
| 223 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
|
| 224 |
+
|
| 225 |
+
def test_attention_slicing_forward_pass(
|
| 226 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 227 |
+
):
|
| 228 |
+
if not self.test_attention_slicing:
|
| 229 |
+
return
|
| 230 |
+
|
| 231 |
+
components = self.get_dummy_components()
|
| 232 |
+
pipe = self.pipeline_class(**components)
|
| 233 |
+
for component in pipe.components.values():
|
| 234 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 235 |
+
component.set_default_attn_processor()
|
| 236 |
+
pipe.to(torch_device)
|
| 237 |
+
pipe.set_progress_bar_config(disable=None)
|
| 238 |
+
|
| 239 |
+
generator_device = "cpu"
|
| 240 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 241 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 242 |
+
|
| 243 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 244 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 245 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 246 |
+
|
| 247 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 248 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 249 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 250 |
+
|
| 251 |
+
if test_max_difference:
|
| 252 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 253 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 254 |
+
self.assertLess(
|
| 255 |
+
max(max_diff1, max_diff2),
|
| 256 |
+
expected_max_diff,
|
| 257 |
+
"Attention slicing should not affect the inference results",
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 261 |
+
generator_device = "cpu"
|
| 262 |
+
components = self.get_dummy_components()
|
| 263 |
+
|
| 264 |
+
pipe = self.pipeline_class(**components)
|
| 265 |
+
pipe.to("cpu")
|
| 266 |
+
pipe.set_progress_bar_config(disable=None)
|
| 267 |
+
|
| 268 |
+
# Without tiling
|
| 269 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 270 |
+
inputs["height"] = inputs["width"] = 128
|
| 271 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 272 |
+
|
| 273 |
+
# With tiling
|
| 274 |
+
pipe.vae.enable_tiling(
|
| 275 |
+
tile_sample_min_height=96,
|
| 276 |
+
tile_sample_min_width=96,
|
| 277 |
+
tile_sample_stride_height=64,
|
| 278 |
+
tile_sample_stride_width=64,
|
| 279 |
+
)
|
| 280 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 281 |
+
inputs["height"] = inputs["width"] = 128
|
| 282 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 283 |
+
|
| 284 |
+
self.assertLess(
|
| 285 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 286 |
+
expected_diff_max,
|
| 287 |
+
"VAE tiling should not affect the inference results",
|
| 288 |
+
)
|
| 289 |
+
|
| 290 |
+
def test_save_load_optional_components(self, expected_max_difference=1e-4):
|
| 291 |
+
self.pipeline_class._optional_components.remove("safety_checker")
|
| 292 |
+
super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
|
| 293 |
+
self.pipeline_class._optional_components.append("safety_checker")
|
| 294 |
+
|
| 295 |
+
def test_serialization_with_variants(self):
|
| 296 |
+
components = self.get_dummy_components()
|
| 297 |
+
pipe = self.pipeline_class(**components)
|
| 298 |
+
model_components = [
|
| 299 |
+
component_name
|
| 300 |
+
for component_name, component in pipe.components.items()
|
| 301 |
+
if isinstance(component, torch.nn.Module)
|
| 302 |
+
]
|
| 303 |
+
model_components.remove("safety_checker")
|
| 304 |
+
variant = "fp16"
|
| 305 |
+
|
| 306 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 307 |
+
pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
|
| 308 |
+
|
| 309 |
+
with open(f"{tmpdir}/model_index.json", "r") as f:
|
| 310 |
+
config = json.load(f)
|
| 311 |
+
|
| 312 |
+
for subfolder in os.listdir(tmpdir):
|
| 313 |
+
if not os.path.isfile(subfolder) and subfolder in model_components:
|
| 314 |
+
folder_path = os.path.join(tmpdir, subfolder)
|
| 315 |
+
is_folder = os.path.isdir(folder_path) and subfolder in config
|
| 316 |
+
assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
|
| 317 |
+
|
| 318 |
+
def test_torch_dtype_dict(self):
|
| 319 |
+
components = self.get_dummy_components()
|
| 320 |
+
if not components:
|
| 321 |
+
self.skipTest("No dummy components defined.")
|
| 322 |
+
|
| 323 |
+
pipe = self.pipeline_class(**components)
|
| 324 |
+
|
| 325 |
+
specified_key = next(iter(components.keys()))
|
| 326 |
+
|
| 327 |
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
|
| 328 |
+
pipe.save_pretrained(tmpdirname, safe_serialization=False)
|
| 329 |
+
torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
|
| 330 |
+
loaded_pipe = self.pipeline_class.from_pretrained(
|
| 331 |
+
tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
for name, component in loaded_pipe.components.items():
|
| 335 |
+
if name == "safety_checker":
|
| 336 |
+
continue
|
| 337 |
+
if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
|
| 338 |
+
expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
|
| 339 |
+
self.assertEqual(
|
| 340 |
+
component.dtype,
|
| 341 |
+
expected_dtype,
|
| 342 |
+
f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
@unittest.skip(
|
| 346 |
+
"The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
|
| 347 |
+
"a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
|
| 348 |
+
"too large and slow to run on CI."
|
| 349 |
+
)
|
| 350 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 351 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/cosmos/test_cosmos_video2world.py
ADDED
|
@@ -0,0 +1,363 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import inspect
|
| 16 |
+
import json
|
| 17 |
+
import os
|
| 18 |
+
import tempfile
|
| 19 |
+
import unittest
|
| 20 |
+
|
| 21 |
+
import numpy as np
|
| 22 |
+
import PIL.Image
|
| 23 |
+
import torch
|
| 24 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 25 |
+
|
| 26 |
+
from diffusers import AutoencoderKLCosmos, CosmosTransformer3DModel, CosmosVideoToWorldPipeline, EDMEulerScheduler
|
| 27 |
+
from diffusers.utils.testing_utils import enable_full_determinism, torch_device
|
| 28 |
+
|
| 29 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 30 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 31 |
+
from .cosmos_guardrail import DummyCosmosSafetyChecker
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
enable_full_determinism()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class CosmosVideoToWorldPipelineWrapper(CosmosVideoToWorldPipeline):
|
| 38 |
+
@staticmethod
|
| 39 |
+
def from_pretrained(*args, **kwargs):
|
| 40 |
+
kwargs["safety_checker"] = DummyCosmosSafetyChecker()
|
| 41 |
+
return CosmosVideoToWorldPipeline.from_pretrained(*args, **kwargs)
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class CosmosVideoToWorldPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 45 |
+
pipeline_class = CosmosVideoToWorldPipelineWrapper
|
| 46 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 47 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS.union({"image", "video"})
|
| 48 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 49 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 50 |
+
required_optional_params = frozenset(
|
| 51 |
+
[
|
| 52 |
+
"num_inference_steps",
|
| 53 |
+
"generator",
|
| 54 |
+
"latents",
|
| 55 |
+
"return_dict",
|
| 56 |
+
"callback_on_step_end",
|
| 57 |
+
"callback_on_step_end_tensor_inputs",
|
| 58 |
+
]
|
| 59 |
+
)
|
| 60 |
+
supports_dduf = False
|
| 61 |
+
test_xformers_attention = False
|
| 62 |
+
test_layerwise_casting = True
|
| 63 |
+
test_group_offloading = True
|
| 64 |
+
|
| 65 |
+
def get_dummy_components(self):
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
transformer = CosmosTransformer3DModel(
|
| 68 |
+
in_channels=4 + 1,
|
| 69 |
+
out_channels=4,
|
| 70 |
+
num_attention_heads=2,
|
| 71 |
+
attention_head_dim=16,
|
| 72 |
+
num_layers=2,
|
| 73 |
+
mlp_ratio=2,
|
| 74 |
+
text_embed_dim=32,
|
| 75 |
+
adaln_lora_dim=4,
|
| 76 |
+
max_size=(4, 32, 32),
|
| 77 |
+
patch_size=(1, 2, 2),
|
| 78 |
+
rope_scale=(2.0, 1.0, 1.0),
|
| 79 |
+
concat_padding_mask=True,
|
| 80 |
+
extra_pos_embed_type="learnable",
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
torch.manual_seed(0)
|
| 84 |
+
vae = AutoencoderKLCosmos(
|
| 85 |
+
in_channels=3,
|
| 86 |
+
out_channels=3,
|
| 87 |
+
latent_channels=4,
|
| 88 |
+
encoder_block_out_channels=(8, 8, 8, 8),
|
| 89 |
+
decode_block_out_channels=(8, 8, 8, 8),
|
| 90 |
+
attention_resolutions=(8,),
|
| 91 |
+
resolution=64,
|
| 92 |
+
num_layers=2,
|
| 93 |
+
patch_size=4,
|
| 94 |
+
patch_type="haar",
|
| 95 |
+
scaling_factor=1.0,
|
| 96 |
+
spatial_compression_ratio=4,
|
| 97 |
+
temporal_compression_ratio=4,
|
| 98 |
+
)
|
| 99 |
+
|
| 100 |
+
torch.manual_seed(0)
|
| 101 |
+
scheduler = EDMEulerScheduler(
|
| 102 |
+
sigma_min=0.002,
|
| 103 |
+
sigma_max=80,
|
| 104 |
+
sigma_data=0.5,
|
| 105 |
+
sigma_schedule="karras",
|
| 106 |
+
num_train_timesteps=1000,
|
| 107 |
+
prediction_type="epsilon",
|
| 108 |
+
rho=7.0,
|
| 109 |
+
final_sigmas_type="sigma_min",
|
| 110 |
+
)
|
| 111 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 112 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 113 |
+
|
| 114 |
+
components = {
|
| 115 |
+
"transformer": transformer,
|
| 116 |
+
"vae": vae,
|
| 117 |
+
"scheduler": scheduler,
|
| 118 |
+
"text_encoder": text_encoder,
|
| 119 |
+
"tokenizer": tokenizer,
|
| 120 |
+
# We cannot run the Cosmos Guardrail for fast tests due to the large model size
|
| 121 |
+
"safety_checker": DummyCosmosSafetyChecker(),
|
| 122 |
+
}
|
| 123 |
+
return components
|
| 124 |
+
|
| 125 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 126 |
+
if str(device).startswith("mps"):
|
| 127 |
+
generator = torch.manual_seed(seed)
|
| 128 |
+
else:
|
| 129 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 130 |
+
|
| 131 |
+
image_height = 32
|
| 132 |
+
image_width = 32
|
| 133 |
+
image = PIL.Image.new("RGB", (image_width, image_height))
|
| 134 |
+
|
| 135 |
+
inputs = {
|
| 136 |
+
"image": image,
|
| 137 |
+
"prompt": "dance monkey",
|
| 138 |
+
"negative_prompt": "bad quality",
|
| 139 |
+
"generator": generator,
|
| 140 |
+
"num_inference_steps": 2,
|
| 141 |
+
"guidance_scale": 3.0,
|
| 142 |
+
"height": image_height,
|
| 143 |
+
"width": image_width,
|
| 144 |
+
"num_frames": 9,
|
| 145 |
+
"max_sequence_length": 16,
|
| 146 |
+
"output_type": "pt",
|
| 147 |
+
}
|
| 148 |
+
|
| 149 |
+
return inputs
|
| 150 |
+
|
| 151 |
+
def test_inference(self):
|
| 152 |
+
device = "cpu"
|
| 153 |
+
|
| 154 |
+
components = self.get_dummy_components()
|
| 155 |
+
pipe = self.pipeline_class(**components)
|
| 156 |
+
pipe.to(device)
|
| 157 |
+
pipe.set_progress_bar_config(disable=None)
|
| 158 |
+
|
| 159 |
+
inputs = self.get_dummy_inputs(device)
|
| 160 |
+
video = pipe(**inputs).frames
|
| 161 |
+
generated_video = video[0]
|
| 162 |
+
|
| 163 |
+
self.assertEqual(generated_video.shape, (9, 3, 32, 32))
|
| 164 |
+
expected_video = torch.randn(9, 3, 32, 32)
|
| 165 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 166 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 167 |
+
|
| 168 |
+
def test_components_function(self):
|
| 169 |
+
init_components = self.get_dummy_components()
|
| 170 |
+
init_components = {k: v for k, v in init_components.items() if not isinstance(v, (str, int, float))}
|
| 171 |
+
pipe = self.pipeline_class(**init_components)
|
| 172 |
+
self.assertTrue(hasattr(pipe, "components"))
|
| 173 |
+
self.assertTrue(set(pipe.components.keys()) == set(init_components.keys()))
|
| 174 |
+
|
| 175 |
+
def test_callback_inputs(self):
|
| 176 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 177 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 178 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 179 |
+
|
| 180 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 181 |
+
return
|
| 182 |
+
|
| 183 |
+
components = self.get_dummy_components()
|
| 184 |
+
pipe = self.pipeline_class(**components)
|
| 185 |
+
pipe = pipe.to(torch_device)
|
| 186 |
+
pipe.set_progress_bar_config(disable=None)
|
| 187 |
+
self.assertTrue(
|
| 188 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 189 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 193 |
+
# iterate over callback args
|
| 194 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 195 |
+
# check that we're only passing in allowed tensor inputs
|
| 196 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 197 |
+
|
| 198 |
+
return callback_kwargs
|
| 199 |
+
|
| 200 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 201 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 202 |
+
assert tensor_name in callback_kwargs
|
| 203 |
+
|
| 204 |
+
# iterate over callback args
|
| 205 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 206 |
+
# check that we're only passing in allowed tensor inputs
|
| 207 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 208 |
+
|
| 209 |
+
return callback_kwargs
|
| 210 |
+
|
| 211 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 212 |
+
|
| 213 |
+
# Test passing in a subset
|
| 214 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 215 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 216 |
+
output = pipe(**inputs)[0]
|
| 217 |
+
|
| 218 |
+
# Test passing in a everything
|
| 219 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 220 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 221 |
+
output = pipe(**inputs)[0]
|
| 222 |
+
|
| 223 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 224 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 225 |
+
if is_last:
|
| 226 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 227 |
+
return callback_kwargs
|
| 228 |
+
|
| 229 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 230 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 231 |
+
output = pipe(**inputs)[0]
|
| 232 |
+
assert output.abs().sum() < 1e10
|
| 233 |
+
|
| 234 |
+
def test_inference_batch_single_identical(self):
|
| 235 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-2)
|
| 236 |
+
|
| 237 |
+
def test_attention_slicing_forward_pass(
|
| 238 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 239 |
+
):
|
| 240 |
+
if not self.test_attention_slicing:
|
| 241 |
+
return
|
| 242 |
+
|
| 243 |
+
components = self.get_dummy_components()
|
| 244 |
+
pipe = self.pipeline_class(**components)
|
| 245 |
+
for component in pipe.components.values():
|
| 246 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 247 |
+
component.set_default_attn_processor()
|
| 248 |
+
pipe.to(torch_device)
|
| 249 |
+
pipe.set_progress_bar_config(disable=None)
|
| 250 |
+
|
| 251 |
+
generator_device = "cpu"
|
| 252 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 253 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 254 |
+
|
| 255 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 256 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 257 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 258 |
+
|
| 259 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 260 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 261 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 262 |
+
|
| 263 |
+
if test_max_difference:
|
| 264 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 265 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 266 |
+
self.assertLess(
|
| 267 |
+
max(max_diff1, max_diff2),
|
| 268 |
+
expected_max_diff,
|
| 269 |
+
"Attention slicing should not affect the inference results",
|
| 270 |
+
)
|
| 271 |
+
|
| 272 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 273 |
+
generator_device = "cpu"
|
| 274 |
+
components = self.get_dummy_components()
|
| 275 |
+
|
| 276 |
+
pipe = self.pipeline_class(**components)
|
| 277 |
+
pipe.to("cpu")
|
| 278 |
+
pipe.set_progress_bar_config(disable=None)
|
| 279 |
+
|
| 280 |
+
# Without tiling
|
| 281 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 282 |
+
inputs["height"] = inputs["width"] = 128
|
| 283 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 284 |
+
|
| 285 |
+
# With tiling
|
| 286 |
+
pipe.vae.enable_tiling(
|
| 287 |
+
tile_sample_min_height=96,
|
| 288 |
+
tile_sample_min_width=96,
|
| 289 |
+
tile_sample_stride_height=64,
|
| 290 |
+
tile_sample_stride_width=64,
|
| 291 |
+
)
|
| 292 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 293 |
+
inputs["height"] = inputs["width"] = 128
|
| 294 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 295 |
+
|
| 296 |
+
self.assertLess(
|
| 297 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 298 |
+
expected_diff_max,
|
| 299 |
+
"VAE tiling should not affect the inference results",
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
def test_save_load_optional_components(self, expected_max_difference=1e-4):
|
| 303 |
+
self.pipeline_class._optional_components.remove("safety_checker")
|
| 304 |
+
super().test_save_load_optional_components(expected_max_difference=expected_max_difference)
|
| 305 |
+
self.pipeline_class._optional_components.append("safety_checker")
|
| 306 |
+
|
| 307 |
+
def test_serialization_with_variants(self):
|
| 308 |
+
components = self.get_dummy_components()
|
| 309 |
+
pipe = self.pipeline_class(**components)
|
| 310 |
+
model_components = [
|
| 311 |
+
component_name
|
| 312 |
+
for component_name, component in pipe.components.items()
|
| 313 |
+
if isinstance(component, torch.nn.Module)
|
| 314 |
+
]
|
| 315 |
+
model_components.remove("safety_checker")
|
| 316 |
+
variant = "fp16"
|
| 317 |
+
|
| 318 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 319 |
+
pipe.save_pretrained(tmpdir, variant=variant, safe_serialization=False)
|
| 320 |
+
|
| 321 |
+
with open(f"{tmpdir}/model_index.json", "r") as f:
|
| 322 |
+
config = json.load(f)
|
| 323 |
+
|
| 324 |
+
for subfolder in os.listdir(tmpdir):
|
| 325 |
+
if not os.path.isfile(subfolder) and subfolder in model_components:
|
| 326 |
+
folder_path = os.path.join(tmpdir, subfolder)
|
| 327 |
+
is_folder = os.path.isdir(folder_path) and subfolder in config
|
| 328 |
+
assert is_folder and any(p.split(".")[1].startswith(variant) for p in os.listdir(folder_path))
|
| 329 |
+
|
| 330 |
+
def test_torch_dtype_dict(self):
|
| 331 |
+
components = self.get_dummy_components()
|
| 332 |
+
if not components:
|
| 333 |
+
self.skipTest("No dummy components defined.")
|
| 334 |
+
|
| 335 |
+
pipe = self.pipeline_class(**components)
|
| 336 |
+
|
| 337 |
+
specified_key = next(iter(components.keys()))
|
| 338 |
+
|
| 339 |
+
with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as tmpdirname:
|
| 340 |
+
pipe.save_pretrained(tmpdirname, safe_serialization=False)
|
| 341 |
+
torch_dtype_dict = {specified_key: torch.bfloat16, "default": torch.float16}
|
| 342 |
+
loaded_pipe = self.pipeline_class.from_pretrained(
|
| 343 |
+
tmpdirname, safety_checker=DummyCosmosSafetyChecker(), torch_dtype=torch_dtype_dict
|
| 344 |
+
)
|
| 345 |
+
|
| 346 |
+
for name, component in loaded_pipe.components.items():
|
| 347 |
+
if name == "safety_checker":
|
| 348 |
+
continue
|
| 349 |
+
if isinstance(component, torch.nn.Module) and hasattr(component, "dtype"):
|
| 350 |
+
expected_dtype = torch_dtype_dict.get(name, torch_dtype_dict.get("default", torch.float32))
|
| 351 |
+
self.assertEqual(
|
| 352 |
+
component.dtype,
|
| 353 |
+
expected_dtype,
|
| 354 |
+
f"Component '{name}' has dtype {component.dtype} but expected {expected_dtype}",
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
@unittest.skip(
|
| 358 |
+
"The pipeline should not be runnable without a safety checker. The test creates a pipeline without passing in "
|
| 359 |
+
"a safety checker, which makes the pipeline default to the actual Cosmos Guardrail. The Cosmos Guardrail is "
|
| 360 |
+
"too large and slow to run on CI."
|
| 361 |
+
)
|
| 362 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 363 |
+
pass
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dance_diffusion/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/dance_diffusion/test_dance_diffusion.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import DanceDiffusionPipeline, IPNDMScheduler, UNet1DModel
|
| 23 |
+
from diffusers.utils.testing_utils import (
|
| 24 |
+
backend_empty_cache,
|
| 25 |
+
enable_full_determinism,
|
| 26 |
+
nightly,
|
| 27 |
+
require_torch_accelerator,
|
| 28 |
+
skip_mps,
|
| 29 |
+
torch_device,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from ..pipeline_params import UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS, UNCONDITIONAL_AUDIO_GENERATION_PARAMS
|
| 33 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
enable_full_determinism()
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class DanceDiffusionPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 40 |
+
pipeline_class = DanceDiffusionPipeline
|
| 41 |
+
params = UNCONDITIONAL_AUDIO_GENERATION_PARAMS
|
| 42 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {
|
| 43 |
+
"callback",
|
| 44 |
+
"latents",
|
| 45 |
+
"callback_steps",
|
| 46 |
+
"output_type",
|
| 47 |
+
"num_images_per_prompt",
|
| 48 |
+
}
|
| 49 |
+
batch_params = UNCONDITIONAL_AUDIO_GENERATION_BATCH_PARAMS
|
| 50 |
+
test_attention_slicing = False
|
| 51 |
+
|
| 52 |
+
def get_dummy_components(self):
|
| 53 |
+
torch.manual_seed(0)
|
| 54 |
+
unet = UNet1DModel(
|
| 55 |
+
block_out_channels=(32, 32, 64),
|
| 56 |
+
extra_in_channels=16,
|
| 57 |
+
sample_size=512,
|
| 58 |
+
sample_rate=16_000,
|
| 59 |
+
in_channels=2,
|
| 60 |
+
out_channels=2,
|
| 61 |
+
flip_sin_to_cos=True,
|
| 62 |
+
use_timestep_embedding=False,
|
| 63 |
+
time_embedding_type="fourier",
|
| 64 |
+
mid_block_type="UNetMidBlock1D",
|
| 65 |
+
down_block_types=("DownBlock1DNoSkip", "DownBlock1D", "AttnDownBlock1D"),
|
| 66 |
+
up_block_types=("AttnUpBlock1D", "UpBlock1D", "UpBlock1DNoSkip"),
|
| 67 |
+
)
|
| 68 |
+
scheduler = IPNDMScheduler()
|
| 69 |
+
|
| 70 |
+
components = {
|
| 71 |
+
"unet": unet,
|
| 72 |
+
"scheduler": scheduler,
|
| 73 |
+
}
|
| 74 |
+
return components
|
| 75 |
+
|
| 76 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 77 |
+
if str(device).startswith("mps"):
|
| 78 |
+
generator = torch.manual_seed(seed)
|
| 79 |
+
else:
|
| 80 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 81 |
+
inputs = {
|
| 82 |
+
"batch_size": 1,
|
| 83 |
+
"generator": generator,
|
| 84 |
+
"num_inference_steps": 4,
|
| 85 |
+
}
|
| 86 |
+
return inputs
|
| 87 |
+
|
| 88 |
+
def test_dance_diffusion(self):
|
| 89 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 90 |
+
components = self.get_dummy_components()
|
| 91 |
+
pipe = DanceDiffusionPipeline(**components)
|
| 92 |
+
pipe = pipe.to(device)
|
| 93 |
+
pipe.set_progress_bar_config(disable=None)
|
| 94 |
+
|
| 95 |
+
inputs = self.get_dummy_inputs(device)
|
| 96 |
+
output = pipe(**inputs)
|
| 97 |
+
audio = output.audios
|
| 98 |
+
|
| 99 |
+
audio_slice = audio[0, -3:, -3:]
|
| 100 |
+
|
| 101 |
+
assert audio.shape == (1, 2, components["unet"].sample_size)
|
| 102 |
+
expected_slice = np.array([-0.7265, 1.0000, -0.8388, 0.1175, 0.9498, -1.0000])
|
| 103 |
+
assert np.abs(audio_slice.flatten() - expected_slice).max() < 1e-2
|
| 104 |
+
|
| 105 |
+
@skip_mps
|
| 106 |
+
def test_save_load_local(self):
|
| 107 |
+
return super().test_save_load_local()
|
| 108 |
+
|
| 109 |
+
@skip_mps
|
| 110 |
+
def test_dict_tuple_outputs_equivalent(self):
|
| 111 |
+
return super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3)
|
| 112 |
+
|
| 113 |
+
@skip_mps
|
| 114 |
+
def test_save_load_optional_components(self):
|
| 115 |
+
return super().test_save_load_optional_components()
|
| 116 |
+
|
| 117 |
+
@skip_mps
|
| 118 |
+
def test_attention_slicing_forward_pass(self):
|
| 119 |
+
return super().test_attention_slicing_forward_pass()
|
| 120 |
+
|
| 121 |
+
def test_inference_batch_single_identical(self):
|
| 122 |
+
super().test_inference_batch_single_identical(expected_max_diff=3e-3)
|
| 123 |
+
|
| 124 |
+
|
| 125 |
+
@nightly
|
| 126 |
+
@require_torch_accelerator
|
| 127 |
+
class PipelineIntegrationTests(unittest.TestCase):
|
| 128 |
+
def setUp(self):
|
| 129 |
+
# clean up the VRAM before each test
|
| 130 |
+
super().setUp()
|
| 131 |
+
gc.collect()
|
| 132 |
+
backend_empty_cache(torch_device)
|
| 133 |
+
|
| 134 |
+
def tearDown(self):
|
| 135 |
+
# clean up the VRAM after each test
|
| 136 |
+
super().tearDown()
|
| 137 |
+
gc.collect()
|
| 138 |
+
backend_empty_cache(torch_device)
|
| 139 |
+
|
| 140 |
+
def test_dance_diffusion(self):
|
| 141 |
+
device = torch_device
|
| 142 |
+
|
| 143 |
+
pipe = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k")
|
| 144 |
+
pipe = pipe.to(device)
|
| 145 |
+
pipe.set_progress_bar_config(disable=None)
|
| 146 |
+
|
| 147 |
+
generator = torch.manual_seed(0)
|
| 148 |
+
output = pipe(generator=generator, num_inference_steps=100, audio_length_in_s=4.096)
|
| 149 |
+
audio = output.audios
|
| 150 |
+
|
| 151 |
+
audio_slice = audio[0, -3:, -3:]
|
| 152 |
+
|
| 153 |
+
assert audio.shape == (1, 2, pipe.unet.config.sample_size)
|
| 154 |
+
expected_slice = np.array([-0.0192, -0.0231, -0.0318, -0.0059, 0.0002, -0.0020])
|
| 155 |
+
|
| 156 |
+
assert np.abs(audio_slice.flatten() - expected_slice).max() < 1e-2
|
| 157 |
+
|
| 158 |
+
def test_dance_diffusion_fp16(self):
|
| 159 |
+
device = torch_device
|
| 160 |
+
|
| 161 |
+
pipe = DanceDiffusionPipeline.from_pretrained("harmonai/maestro-150k", torch_dtype=torch.float16)
|
| 162 |
+
pipe = pipe.to(device)
|
| 163 |
+
pipe.set_progress_bar_config(disable=None)
|
| 164 |
+
|
| 165 |
+
generator = torch.manual_seed(0)
|
| 166 |
+
output = pipe(generator=generator, num_inference_steps=100, audio_length_in_s=4.096)
|
| 167 |
+
audio = output.audios
|
| 168 |
+
|
| 169 |
+
audio_slice = audio[0, -3:, -3:]
|
| 170 |
+
|
| 171 |
+
assert audio.shape == (1, 2, pipe.unet.config.sample_size)
|
| 172 |
+
expected_slice = np.array([-0.0367, -0.0488, -0.0771, -0.0525, -0.0444, -0.0341])
|
| 173 |
+
|
| 174 |
+
assert np.abs(audio_slice.flatten() - expected_slice).max() < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddim/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddim/test_ddim.py
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from diffusers import DDIMPipeline, DDIMScheduler, UNet2DModel
|
| 22 |
+
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
|
| 23 |
+
|
| 24 |
+
from ..pipeline_params import UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS, UNCONDITIONAL_IMAGE_GENERATION_PARAMS
|
| 25 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
enable_full_determinism()
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
class DDIMPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 32 |
+
pipeline_class = DDIMPipeline
|
| 33 |
+
params = UNCONDITIONAL_IMAGE_GENERATION_PARAMS
|
| 34 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {
|
| 35 |
+
"num_images_per_prompt",
|
| 36 |
+
"latents",
|
| 37 |
+
"callback",
|
| 38 |
+
"callback_steps",
|
| 39 |
+
}
|
| 40 |
+
batch_params = UNCONDITIONAL_IMAGE_GENERATION_BATCH_PARAMS
|
| 41 |
+
|
| 42 |
+
def get_dummy_components(self):
|
| 43 |
+
torch.manual_seed(0)
|
| 44 |
+
unet = UNet2DModel(
|
| 45 |
+
block_out_channels=(4, 8),
|
| 46 |
+
layers_per_block=1,
|
| 47 |
+
norm_num_groups=4,
|
| 48 |
+
sample_size=8,
|
| 49 |
+
in_channels=3,
|
| 50 |
+
out_channels=3,
|
| 51 |
+
down_block_types=("DownBlock2D", "AttnDownBlock2D"),
|
| 52 |
+
up_block_types=("AttnUpBlock2D", "UpBlock2D"),
|
| 53 |
+
)
|
| 54 |
+
scheduler = DDIMScheduler()
|
| 55 |
+
components = {"unet": unet, "scheduler": scheduler}
|
| 56 |
+
return components
|
| 57 |
+
|
| 58 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 59 |
+
if str(device).startswith("mps"):
|
| 60 |
+
generator = torch.manual_seed(seed)
|
| 61 |
+
else:
|
| 62 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 63 |
+
inputs = {
|
| 64 |
+
"batch_size": 1,
|
| 65 |
+
"generator": generator,
|
| 66 |
+
"num_inference_steps": 2,
|
| 67 |
+
"output_type": "np",
|
| 68 |
+
}
|
| 69 |
+
return inputs
|
| 70 |
+
|
| 71 |
+
def test_inference(self):
|
| 72 |
+
device = "cpu"
|
| 73 |
+
|
| 74 |
+
components = self.get_dummy_components()
|
| 75 |
+
pipe = self.pipeline_class(**components)
|
| 76 |
+
pipe.to(device)
|
| 77 |
+
pipe.set_progress_bar_config(disable=None)
|
| 78 |
+
|
| 79 |
+
inputs = self.get_dummy_inputs(device)
|
| 80 |
+
image = pipe(**inputs).images
|
| 81 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 82 |
+
|
| 83 |
+
self.assertEqual(image.shape, (1, 8, 8, 3))
|
| 84 |
+
expected_slice = np.array([0.0, 9.979e-01, 0.0, 9.999e-01, 9.986e-01, 9.991e-01, 7.106e-04, 0.0, 0.0])
|
| 85 |
+
max_diff = np.abs(image_slice.flatten() - expected_slice).max()
|
| 86 |
+
self.assertLessEqual(max_diff, 1e-3)
|
| 87 |
+
|
| 88 |
+
def test_dict_tuple_outputs_equivalent(self):
|
| 89 |
+
super().test_dict_tuple_outputs_equivalent(expected_max_difference=3e-3)
|
| 90 |
+
|
| 91 |
+
def test_save_load_local(self):
|
| 92 |
+
super().test_save_load_local(expected_max_difference=3e-3)
|
| 93 |
+
|
| 94 |
+
def test_save_load_optional_components(self):
|
| 95 |
+
super().test_save_load_optional_components(expected_max_difference=3e-3)
|
| 96 |
+
|
| 97 |
+
def test_inference_batch_single_identical(self):
|
| 98 |
+
super().test_inference_batch_single_identical(expected_max_diff=3e-3)
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
@slow
|
| 102 |
+
@require_torch_accelerator
|
| 103 |
+
class DDIMPipelineIntegrationTests(unittest.TestCase):
|
| 104 |
+
def test_inference_cifar10(self):
|
| 105 |
+
model_id = "google/ddpm-cifar10-32"
|
| 106 |
+
|
| 107 |
+
unet = UNet2DModel.from_pretrained(model_id)
|
| 108 |
+
scheduler = DDIMScheduler()
|
| 109 |
+
|
| 110 |
+
ddim = DDIMPipeline(unet=unet, scheduler=scheduler)
|
| 111 |
+
ddim.to(torch_device)
|
| 112 |
+
ddim.set_progress_bar_config(disable=None)
|
| 113 |
+
|
| 114 |
+
generator = torch.manual_seed(0)
|
| 115 |
+
image = ddim(generator=generator, eta=0.0, output_type="np").images
|
| 116 |
+
|
| 117 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 118 |
+
|
| 119 |
+
assert image.shape == (1, 32, 32, 3)
|
| 120 |
+
expected_slice = np.array([0.1723, 0.1617, 0.1600, 0.1626, 0.1497, 0.1513, 0.1505, 0.1442, 0.1453])
|
| 121 |
+
|
| 122 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 123 |
+
|
| 124 |
+
def test_inference_ema_bedroom(self):
|
| 125 |
+
model_id = "google/ddpm-ema-bedroom-256"
|
| 126 |
+
|
| 127 |
+
unet = UNet2DModel.from_pretrained(model_id)
|
| 128 |
+
scheduler = DDIMScheduler.from_pretrained(model_id)
|
| 129 |
+
|
| 130 |
+
ddpm = DDIMPipeline(unet=unet, scheduler=scheduler)
|
| 131 |
+
ddpm.to(torch_device)
|
| 132 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 133 |
+
|
| 134 |
+
generator = torch.manual_seed(0)
|
| 135 |
+
image = ddpm(generator=generator, output_type="np").images
|
| 136 |
+
|
| 137 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 138 |
+
|
| 139 |
+
assert image.shape == (1, 256, 256, 3)
|
| 140 |
+
expected_slice = np.array([0.0060, 0.0201, 0.0344, 0.0024, 0.0018, 0.0002, 0.0022, 0.0000, 0.0069])
|
| 141 |
+
|
| 142 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddpm/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/ddpm/test_ddpm.py
ADDED
|
@@ -0,0 +1,110 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import unittest
|
| 17 |
+
|
| 18 |
+
import numpy as np
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from diffusers import DDPMPipeline, DDPMScheduler, UNet2DModel
|
| 22 |
+
from diffusers.utils.testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
enable_full_determinism()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
class DDPMPipelineFastTests(unittest.TestCase):
|
| 29 |
+
@property
|
| 30 |
+
def dummy_uncond_unet(self):
|
| 31 |
+
torch.manual_seed(0)
|
| 32 |
+
model = UNet2DModel(
|
| 33 |
+
block_out_channels=(4, 8),
|
| 34 |
+
layers_per_block=1,
|
| 35 |
+
norm_num_groups=4,
|
| 36 |
+
sample_size=8,
|
| 37 |
+
in_channels=3,
|
| 38 |
+
out_channels=3,
|
| 39 |
+
down_block_types=("DownBlock2D", "AttnDownBlock2D"),
|
| 40 |
+
up_block_types=("AttnUpBlock2D", "UpBlock2D"),
|
| 41 |
+
)
|
| 42 |
+
return model
|
| 43 |
+
|
| 44 |
+
def test_fast_inference(self):
|
| 45 |
+
device = "cpu"
|
| 46 |
+
unet = self.dummy_uncond_unet
|
| 47 |
+
scheduler = DDPMScheduler()
|
| 48 |
+
|
| 49 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 50 |
+
ddpm.to(device)
|
| 51 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 52 |
+
|
| 53 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 54 |
+
image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
|
| 55 |
+
|
| 56 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 57 |
+
image_from_tuple = ddpm(generator=generator, num_inference_steps=2, output_type="np", return_dict=False)[0]
|
| 58 |
+
|
| 59 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 60 |
+
image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
|
| 61 |
+
|
| 62 |
+
assert image.shape == (1, 8, 8, 3)
|
| 63 |
+
expected_slice = np.array([0.0, 0.9996672, 0.00329116, 1.0, 0.9995991, 1.0, 0.0060907, 0.00115037, 0.0])
|
| 64 |
+
|
| 65 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 66 |
+
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
|
| 67 |
+
|
| 68 |
+
def test_inference_predict_sample(self):
|
| 69 |
+
unet = self.dummy_uncond_unet
|
| 70 |
+
scheduler = DDPMScheduler(prediction_type="sample")
|
| 71 |
+
|
| 72 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 73 |
+
ddpm.to(torch_device)
|
| 74 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 75 |
+
|
| 76 |
+
generator = torch.manual_seed(0)
|
| 77 |
+
image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
|
| 78 |
+
|
| 79 |
+
generator = torch.manual_seed(0)
|
| 80 |
+
image_eps = ddpm(generator=generator, num_inference_steps=2, output_type="np")[0]
|
| 81 |
+
|
| 82 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 83 |
+
image_eps_slice = image_eps[0, -3:, -3:, -1]
|
| 84 |
+
|
| 85 |
+
assert image.shape == (1, 8, 8, 3)
|
| 86 |
+
tolerance = 1e-2 if torch_device != "mps" else 3e-2
|
| 87 |
+
assert np.abs(image_slice.flatten() - image_eps_slice.flatten()).max() < tolerance
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@slow
|
| 91 |
+
@require_torch_accelerator
|
| 92 |
+
class DDPMPipelineIntegrationTests(unittest.TestCase):
|
| 93 |
+
def test_inference_cifar10(self):
|
| 94 |
+
model_id = "google/ddpm-cifar10-32"
|
| 95 |
+
|
| 96 |
+
unet = UNet2DModel.from_pretrained(model_id)
|
| 97 |
+
scheduler = DDPMScheduler.from_pretrained(model_id)
|
| 98 |
+
|
| 99 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 100 |
+
ddpm.to(torch_device)
|
| 101 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 102 |
+
|
| 103 |
+
generator = torch.manual_seed(0)
|
| 104 |
+
image = ddpm(generator=generator, output_type="np").images
|
| 105 |
+
|
| 106 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 107 |
+
|
| 108 |
+
assert image.shape == (1, 32, 32, 3)
|
| 109 |
+
expected_slice = np.array([0.4200, 0.3588, 0.1939, 0.3847, 0.3382, 0.2647, 0.4155, 0.3582, 0.3385])
|
| 110 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipel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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoTokenizer, T5EncoderModel
|
| 6 |
+
|
| 7 |
+
from diffusers import DDPMScheduler, UNet2DConditionModel
|
| 8 |
+
from diffusers.models.attention_processor import AttnAddedKVProcessor
|
| 9 |
+
from diffusers.pipelines.deepfloyd_if import IFWatermarker
|
| 10 |
+
from diffusers.utils.testing_utils import torch_device
|
| 11 |
+
|
| 12 |
+
from ..test_pipelines_common import to_np
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
# WARN: the hf-internal-testing/tiny-random-t5 text encoder has some non-determinism in the `save_load` tests.
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class IFPipelineTesterMixin:
|
| 19 |
+
def _get_dummy_components(self):
|
| 20 |
+
torch.manual_seed(0)
|
| 21 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 22 |
+
|
| 23 |
+
torch.manual_seed(0)
|
| 24 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 25 |
+
|
| 26 |
+
torch.manual_seed(0)
|
| 27 |
+
unet = UNet2DConditionModel(
|
| 28 |
+
sample_size=32,
|
| 29 |
+
layers_per_block=1,
|
| 30 |
+
block_out_channels=[32, 64],
|
| 31 |
+
down_block_types=[
|
| 32 |
+
"ResnetDownsampleBlock2D",
|
| 33 |
+
"SimpleCrossAttnDownBlock2D",
|
| 34 |
+
],
|
| 35 |
+
mid_block_type="UNetMidBlock2DSimpleCrossAttn",
|
| 36 |
+
up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"],
|
| 37 |
+
in_channels=3,
|
| 38 |
+
out_channels=6,
|
| 39 |
+
cross_attention_dim=32,
|
| 40 |
+
encoder_hid_dim=32,
|
| 41 |
+
attention_head_dim=8,
|
| 42 |
+
addition_embed_type="text",
|
| 43 |
+
addition_embed_type_num_heads=2,
|
| 44 |
+
cross_attention_norm="group_norm",
|
| 45 |
+
resnet_time_scale_shift="scale_shift",
|
| 46 |
+
act_fn="gelu",
|
| 47 |
+
)
|
| 48 |
+
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 49 |
+
|
| 50 |
+
torch.manual_seed(0)
|
| 51 |
+
scheduler = DDPMScheduler(
|
| 52 |
+
num_train_timesteps=1000,
|
| 53 |
+
beta_schedule="squaredcos_cap_v2",
|
| 54 |
+
beta_start=0.0001,
|
| 55 |
+
beta_end=0.02,
|
| 56 |
+
thresholding=True,
|
| 57 |
+
dynamic_thresholding_ratio=0.95,
|
| 58 |
+
sample_max_value=1.0,
|
| 59 |
+
prediction_type="epsilon",
|
| 60 |
+
variance_type="learned_range",
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
torch.manual_seed(0)
|
| 64 |
+
watermarker = IFWatermarker()
|
| 65 |
+
|
| 66 |
+
return {
|
| 67 |
+
"text_encoder": text_encoder,
|
| 68 |
+
"tokenizer": tokenizer,
|
| 69 |
+
"unet": unet,
|
| 70 |
+
"scheduler": scheduler,
|
| 71 |
+
"watermarker": watermarker,
|
| 72 |
+
"safety_checker": None,
|
| 73 |
+
"feature_extractor": None,
|
| 74 |
+
}
|
| 75 |
+
|
| 76 |
+
def _get_superresolution_dummy_components(self):
|
| 77 |
+
torch.manual_seed(0)
|
| 78 |
+
text_encoder = T5EncoderModel.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 79 |
+
|
| 80 |
+
torch.manual_seed(0)
|
| 81 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 82 |
+
|
| 83 |
+
torch.manual_seed(0)
|
| 84 |
+
unet = UNet2DConditionModel(
|
| 85 |
+
sample_size=32,
|
| 86 |
+
layers_per_block=[1, 2],
|
| 87 |
+
block_out_channels=[32, 64],
|
| 88 |
+
down_block_types=[
|
| 89 |
+
"ResnetDownsampleBlock2D",
|
| 90 |
+
"SimpleCrossAttnDownBlock2D",
|
| 91 |
+
],
|
| 92 |
+
mid_block_type="UNetMidBlock2DSimpleCrossAttn",
|
| 93 |
+
up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"],
|
| 94 |
+
in_channels=6,
|
| 95 |
+
out_channels=6,
|
| 96 |
+
cross_attention_dim=32,
|
| 97 |
+
encoder_hid_dim=32,
|
| 98 |
+
attention_head_dim=8,
|
| 99 |
+
addition_embed_type="text",
|
| 100 |
+
addition_embed_type_num_heads=2,
|
| 101 |
+
cross_attention_norm="group_norm",
|
| 102 |
+
resnet_time_scale_shift="scale_shift",
|
| 103 |
+
act_fn="gelu",
|
| 104 |
+
class_embed_type="timestep",
|
| 105 |
+
mid_block_scale_factor=1.414,
|
| 106 |
+
time_embedding_act_fn="gelu",
|
| 107 |
+
time_embedding_dim=32,
|
| 108 |
+
)
|
| 109 |
+
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 110 |
+
|
| 111 |
+
torch.manual_seed(0)
|
| 112 |
+
scheduler = DDPMScheduler(
|
| 113 |
+
num_train_timesteps=1000,
|
| 114 |
+
beta_schedule="squaredcos_cap_v2",
|
| 115 |
+
beta_start=0.0001,
|
| 116 |
+
beta_end=0.02,
|
| 117 |
+
thresholding=True,
|
| 118 |
+
dynamic_thresholding_ratio=0.95,
|
| 119 |
+
sample_max_value=1.0,
|
| 120 |
+
prediction_type="epsilon",
|
| 121 |
+
variance_type="learned_range",
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
torch.manual_seed(0)
|
| 125 |
+
image_noising_scheduler = DDPMScheduler(
|
| 126 |
+
num_train_timesteps=1000,
|
| 127 |
+
beta_schedule="squaredcos_cap_v2",
|
| 128 |
+
beta_start=0.0001,
|
| 129 |
+
beta_end=0.02,
|
| 130 |
+
)
|
| 131 |
+
|
| 132 |
+
torch.manual_seed(0)
|
| 133 |
+
watermarker = IFWatermarker()
|
| 134 |
+
|
| 135 |
+
return {
|
| 136 |
+
"text_encoder": text_encoder,
|
| 137 |
+
"tokenizer": tokenizer,
|
| 138 |
+
"unet": unet,
|
| 139 |
+
"scheduler": scheduler,
|
| 140 |
+
"image_noising_scheduler": image_noising_scheduler,
|
| 141 |
+
"watermarker": watermarker,
|
| 142 |
+
"safety_checker": None,
|
| 143 |
+
"feature_extractor": None,
|
| 144 |
+
}
|
| 145 |
+
|
| 146 |
+
# this test is modified from the base class because if pipelines set the text encoder
|
| 147 |
+
# as optional with the intention that the user is allowed to encode the prompt once
|
| 148 |
+
# and then pass the embeddings directly to the pipeline. The base class test uses
|
| 149 |
+
# the unmodified arguments from `self.get_dummy_inputs` which will pass the unencoded
|
| 150 |
+
# prompt to the pipeline when the text encoder is set to None, throwing an error.
|
| 151 |
+
# So we make the test reflect the intended usage of setting the text encoder to None.
|
| 152 |
+
def _test_save_load_optional_components(self):
|
| 153 |
+
components = self.get_dummy_components()
|
| 154 |
+
pipe = self.pipeline_class(**components)
|
| 155 |
+
pipe.to(torch_device)
|
| 156 |
+
pipe.set_progress_bar_config(disable=None)
|
| 157 |
+
|
| 158 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 159 |
+
|
| 160 |
+
prompt = inputs["prompt"]
|
| 161 |
+
generator = inputs["generator"]
|
| 162 |
+
num_inference_steps = inputs["num_inference_steps"]
|
| 163 |
+
output_type = inputs["output_type"]
|
| 164 |
+
|
| 165 |
+
if "image" in inputs:
|
| 166 |
+
image = inputs["image"]
|
| 167 |
+
else:
|
| 168 |
+
image = None
|
| 169 |
+
|
| 170 |
+
if "mask_image" in inputs:
|
| 171 |
+
mask_image = inputs["mask_image"]
|
| 172 |
+
else:
|
| 173 |
+
mask_image = None
|
| 174 |
+
|
| 175 |
+
if "original_image" in inputs:
|
| 176 |
+
original_image = inputs["original_image"]
|
| 177 |
+
else:
|
| 178 |
+
original_image = None
|
| 179 |
+
|
| 180 |
+
prompt_embeds, negative_prompt_embeds = pipe.encode_prompt(prompt)
|
| 181 |
+
|
| 182 |
+
# inputs with prompt converted to embeddings
|
| 183 |
+
inputs = {
|
| 184 |
+
"prompt_embeds": prompt_embeds,
|
| 185 |
+
"negative_prompt_embeds": negative_prompt_embeds,
|
| 186 |
+
"generator": generator,
|
| 187 |
+
"num_inference_steps": num_inference_steps,
|
| 188 |
+
"output_type": output_type,
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
if image is not None:
|
| 192 |
+
inputs["image"] = image
|
| 193 |
+
|
| 194 |
+
if mask_image is not None:
|
| 195 |
+
inputs["mask_image"] = mask_image
|
| 196 |
+
|
| 197 |
+
if original_image is not None:
|
| 198 |
+
inputs["original_image"] = original_image
|
| 199 |
+
|
| 200 |
+
# set all optional components to None
|
| 201 |
+
for optional_component in pipe._optional_components:
|
| 202 |
+
setattr(pipe, optional_component, None)
|
| 203 |
+
|
| 204 |
+
output = pipe(**inputs)[0]
|
| 205 |
+
|
| 206 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 207 |
+
pipe.save_pretrained(tmpdir)
|
| 208 |
+
pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
|
| 209 |
+
pipe_loaded.to(torch_device)
|
| 210 |
+
pipe_loaded.set_progress_bar_config(disable=None)
|
| 211 |
+
|
| 212 |
+
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 213 |
+
|
| 214 |
+
for optional_component in pipe._optional_components:
|
| 215 |
+
self.assertTrue(
|
| 216 |
+
getattr(pipe_loaded, optional_component) is None,
|
| 217 |
+
f"`{optional_component}` did not stay set to None after loading.",
|
| 218 |
+
)
|
| 219 |
+
|
| 220 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 221 |
+
|
| 222 |
+
generator = inputs["generator"]
|
| 223 |
+
num_inference_steps = inputs["num_inference_steps"]
|
| 224 |
+
output_type = inputs["output_type"]
|
| 225 |
+
|
| 226 |
+
# inputs with prompt converted to embeddings
|
| 227 |
+
inputs = {
|
| 228 |
+
"prompt_embeds": prompt_embeds,
|
| 229 |
+
"negative_prompt_embeds": negative_prompt_embeds,
|
| 230 |
+
"generator": generator,
|
| 231 |
+
"num_inference_steps": num_inference_steps,
|
| 232 |
+
"output_type": output_type,
|
| 233 |
+
}
|
| 234 |
+
|
| 235 |
+
if image is not None:
|
| 236 |
+
inputs["image"] = image
|
| 237 |
+
|
| 238 |
+
if mask_image is not None:
|
| 239 |
+
inputs["mask_image"] = mask_image
|
| 240 |
+
|
| 241 |
+
if original_image is not None:
|
| 242 |
+
inputs["original_image"] = original_image
|
| 243 |
+
|
| 244 |
+
output_loaded = pipe_loaded(**inputs)[0]
|
| 245 |
+
|
| 246 |
+
max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
|
| 247 |
+
self.assertLess(max_diff, 1e-4)
|
| 248 |
+
|
| 249 |
+
# Modified from `PipelineTesterMixin` to set the attn processor as it's not serialized.
|
| 250 |
+
# This should be handled in the base test and then this method can be removed.
|
| 251 |
+
def _test_save_load_local(self):
|
| 252 |
+
components = self.get_dummy_components()
|
| 253 |
+
pipe = self.pipeline_class(**components)
|
| 254 |
+
pipe.to(torch_device)
|
| 255 |
+
pipe.set_progress_bar_config(disable=None)
|
| 256 |
+
|
| 257 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 258 |
+
output = pipe(**inputs)[0]
|
| 259 |
+
|
| 260 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 261 |
+
pipe.save_pretrained(tmpdir)
|
| 262 |
+
pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
|
| 263 |
+
pipe_loaded.to(torch_device)
|
| 264 |
+
pipe_loaded.set_progress_bar_config(disable=None)
|
| 265 |
+
|
| 266 |
+
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 267 |
+
|
| 268 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 269 |
+
output_loaded = pipe_loaded(**inputs)[0]
|
| 270 |
+
|
| 271 |
+
max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
|
| 272 |
+
self.assertLess(max_diff, 1e-4)
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if.py
ADDED
|
@@ -0,0 +1,146 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import torch
|
| 20 |
+
|
| 21 |
+
from diffusers import (
|
| 22 |
+
IFPipeline,
|
| 23 |
+
)
|
| 24 |
+
from diffusers.models.attention_processor import AttnAddedKVProcessor
|
| 25 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 26 |
+
from diffusers.utils.testing_utils import (
|
| 27 |
+
backend_empty_cache,
|
| 28 |
+
backend_max_memory_allocated,
|
| 29 |
+
backend_reset_max_memory_allocated,
|
| 30 |
+
backend_reset_peak_memory_stats,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 42 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 43 |
+
from . import IFPipelineTesterMixin
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@skip_mps
|
| 47 |
+
class IFPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 48 |
+
pipeline_class = IFPipeline
|
| 49 |
+
params = TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
|
| 50 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 51 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 52 |
+
|
| 53 |
+
def get_dummy_components(self):
|
| 54 |
+
return self._get_dummy_components()
|
| 55 |
+
|
| 56 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 57 |
+
if str(device).startswith("mps"):
|
| 58 |
+
generator = torch.manual_seed(seed)
|
| 59 |
+
else:
|
| 60 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 61 |
+
|
| 62 |
+
inputs = {
|
| 63 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 64 |
+
"generator": generator,
|
| 65 |
+
"num_inference_steps": 2,
|
| 66 |
+
"output_type": "np",
|
| 67 |
+
}
|
| 68 |
+
|
| 69 |
+
return inputs
|
| 70 |
+
|
| 71 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 72 |
+
@require_accelerator
|
| 73 |
+
def test_save_load_float16(self):
|
| 74 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 75 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 76 |
+
|
| 77 |
+
def test_attention_slicing_forward_pass(self):
|
| 78 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 79 |
+
|
| 80 |
+
def test_save_load_local(self):
|
| 81 |
+
self._test_save_load_local()
|
| 82 |
+
|
| 83 |
+
def test_inference_batch_single_identical(self):
|
| 84 |
+
self._test_inference_batch_single_identical(
|
| 85 |
+
expected_max_diff=1e-2,
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
@unittest.skipIf(
|
| 89 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 90 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 91 |
+
)
|
| 92 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 93 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 94 |
+
|
| 95 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 96 |
+
@require_transformers_version_greater("4.47.1")
|
| 97 |
+
def test_save_load_dduf(self):
|
| 98 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 99 |
+
|
| 100 |
+
@unittest.skip("Functionality is tested elsewhere.")
|
| 101 |
+
def test_save_load_optional_components(self):
|
| 102 |
+
pass
|
| 103 |
+
|
| 104 |
+
|
| 105 |
+
@slow
|
| 106 |
+
@require_torch_accelerator
|
| 107 |
+
class IFPipelineSlowTests(unittest.TestCase):
|
| 108 |
+
def setUp(self):
|
| 109 |
+
# clean up the VRAM before each test
|
| 110 |
+
super().setUp()
|
| 111 |
+
gc.collect()
|
| 112 |
+
backend_empty_cache(torch_device)
|
| 113 |
+
|
| 114 |
+
def tearDown(self):
|
| 115 |
+
# clean up the VRAM after each test
|
| 116 |
+
super().tearDown()
|
| 117 |
+
gc.collect()
|
| 118 |
+
backend_empty_cache(torch_device)
|
| 119 |
+
|
| 120 |
+
def test_if_text_to_image(self):
|
| 121 |
+
pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
|
| 122 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 123 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 124 |
+
|
| 125 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 126 |
+
backend_empty_cache(torch_device)
|
| 127 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 128 |
+
|
| 129 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 130 |
+
output = pipe(
|
| 131 |
+
prompt="anime turtle",
|
| 132 |
+
num_inference_steps=2,
|
| 133 |
+
generator=generator,
|
| 134 |
+
output_type="np",
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
image = output.images[0]
|
| 138 |
+
|
| 139 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 140 |
+
assert mem_bytes < 12 * 10**9
|
| 141 |
+
|
| 142 |
+
expected_image = load_numpy(
|
| 143 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"
|
| 144 |
+
)
|
| 145 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 146 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
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
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import random
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import IFImg2ImgPipeline
|
| 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 |
+
backend_empty_cache,
|
| 27 |
+
backend_max_memory_allocated,
|
| 28 |
+
backend_reset_max_memory_allocated,
|
| 29 |
+
backend_reset_peak_memory_stats,
|
| 30 |
+
floats_tensor,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import (
|
| 42 |
+
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
|
| 43 |
+
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
|
| 44 |
+
)
|
| 45 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 46 |
+
from . import IFPipelineTesterMixin
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@skip_mps
|
| 50 |
+
class IFImg2ImgPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 51 |
+
pipeline_class = IFImg2ImgPipeline
|
| 52 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
|
| 53 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
|
| 54 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
return self._get_dummy_components()
|
| 58 |
+
|
| 59 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 60 |
+
if str(device).startswith("mps"):
|
| 61 |
+
generator = torch.manual_seed(seed)
|
| 62 |
+
else:
|
| 63 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 64 |
+
|
| 65 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 66 |
+
|
| 67 |
+
inputs = {
|
| 68 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 69 |
+
"image": image,
|
| 70 |
+
"generator": generator,
|
| 71 |
+
"num_inference_steps": 2,
|
| 72 |
+
"output_type": "np",
|
| 73 |
+
}
|
| 74 |
+
|
| 75 |
+
return inputs
|
| 76 |
+
|
| 77 |
+
@unittest.skipIf(
|
| 78 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 79 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 80 |
+
)
|
| 81 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 82 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 83 |
+
|
| 84 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 85 |
+
@require_accelerator
|
| 86 |
+
def test_save_load_float16(self):
|
| 87 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 88 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 89 |
+
|
| 90 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 91 |
+
@require_accelerator
|
| 92 |
+
def test_float16_inference(self):
|
| 93 |
+
super().test_float16_inference(expected_max_diff=1e-1)
|
| 94 |
+
|
| 95 |
+
def test_attention_slicing_forward_pass(self):
|
| 96 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 97 |
+
|
| 98 |
+
def test_save_load_local(self):
|
| 99 |
+
self._test_save_load_local()
|
| 100 |
+
|
| 101 |
+
def test_inference_batch_single_identical(self):
|
| 102 |
+
self._test_inference_batch_single_identical(
|
| 103 |
+
expected_max_diff=1e-2,
|
| 104 |
+
)
|
| 105 |
+
|
| 106 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 107 |
+
@require_transformers_version_greater("4.47.1")
|
| 108 |
+
def test_save_load_dduf(self):
|
| 109 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 110 |
+
|
| 111 |
+
@unittest.skip("Functionality is tested elsewhere.")
|
| 112 |
+
def test_save_load_optional_components(self):
|
| 113 |
+
pass
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
@slow
|
| 117 |
+
@require_torch_accelerator
|
| 118 |
+
class IFImg2ImgPipelineSlowTests(unittest.TestCase):
|
| 119 |
+
def setUp(self):
|
| 120 |
+
# clean up the VRAM before each test
|
| 121 |
+
super().setUp()
|
| 122 |
+
gc.collect()
|
| 123 |
+
backend_empty_cache(torch_device)
|
| 124 |
+
|
| 125 |
+
def tearDown(self):
|
| 126 |
+
# clean up the VRAM after each test
|
| 127 |
+
super().tearDown()
|
| 128 |
+
gc.collect()
|
| 129 |
+
backend_empty_cache(torch_device)
|
| 130 |
+
|
| 131 |
+
def test_if_img2img(self):
|
| 132 |
+
pipe = IFImg2ImgPipeline.from_pretrained(
|
| 133 |
+
"DeepFloyd/IF-I-L-v1.0",
|
| 134 |
+
variant="fp16",
|
| 135 |
+
torch_dtype=torch.float16,
|
| 136 |
+
)
|
| 137 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 138 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 139 |
+
|
| 140 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 141 |
+
backend_empty_cache(torch_device)
|
| 142 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 143 |
+
|
| 144 |
+
image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
|
| 145 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 146 |
+
output = pipe(
|
| 147 |
+
prompt="anime turtle",
|
| 148 |
+
image=image,
|
| 149 |
+
num_inference_steps=2,
|
| 150 |
+
generator=generator,
|
| 151 |
+
output_type="np",
|
| 152 |
+
)
|
| 153 |
+
image = output.images[0]
|
| 154 |
+
|
| 155 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 156 |
+
assert mem_bytes < 12 * 10**9
|
| 157 |
+
|
| 158 |
+
expected_image = load_numpy(
|
| 159 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img.npy"
|
| 160 |
+
)
|
| 161 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 162 |
+
|
| 163 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img_superresolution.py
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import random
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import IFImg2ImgSuperResolutionPipeline
|
| 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 |
+
backend_empty_cache,
|
| 27 |
+
backend_max_memory_allocated,
|
| 28 |
+
backend_reset_max_memory_allocated,
|
| 29 |
+
backend_reset_peak_memory_stats,
|
| 30 |
+
floats_tensor,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import (
|
| 42 |
+
TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS,
|
| 43 |
+
TEXT_GUIDED_IMAGE_VARIATION_PARAMS,
|
| 44 |
+
)
|
| 45 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 46 |
+
from . import IFPipelineTesterMixin
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@skip_mps
|
| 50 |
+
class IFImg2ImgSuperResolutionPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 51 |
+
pipeline_class = IFImg2ImgSuperResolutionPipeline
|
| 52 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
|
| 53 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS.union({"original_image"})
|
| 54 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
return self._get_superresolution_dummy_components()
|
| 58 |
+
|
| 59 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 60 |
+
if str(device).startswith("mps"):
|
| 61 |
+
generator = torch.manual_seed(seed)
|
| 62 |
+
else:
|
| 63 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 64 |
+
|
| 65 |
+
original_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 66 |
+
image = floats_tensor((1, 3, 16, 16), rng=random.Random(seed)).to(device)
|
| 67 |
+
|
| 68 |
+
inputs = {
|
| 69 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 70 |
+
"image": image,
|
| 71 |
+
"original_image": original_image,
|
| 72 |
+
"generator": generator,
|
| 73 |
+
"num_inference_steps": 2,
|
| 74 |
+
"output_type": "np",
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return inputs
|
| 78 |
+
|
| 79 |
+
@unittest.skipIf(
|
| 80 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 81 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 82 |
+
)
|
| 83 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 84 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 85 |
+
|
| 86 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 87 |
+
@require_accelerator
|
| 88 |
+
def test_save_load_float16(self):
|
| 89 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 90 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 91 |
+
|
| 92 |
+
def test_attention_slicing_forward_pass(self):
|
| 93 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 94 |
+
|
| 95 |
+
def test_save_load_local(self):
|
| 96 |
+
self._test_save_load_local()
|
| 97 |
+
|
| 98 |
+
def test_inference_batch_single_identical(self):
|
| 99 |
+
self._test_inference_batch_single_identical(
|
| 100 |
+
expected_max_diff=1e-2,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 104 |
+
@require_transformers_version_greater("4.47.1")
|
| 105 |
+
def test_save_load_dduf(self):
|
| 106 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 107 |
+
|
| 108 |
+
@unittest.skip("Functionality is tested elsewhere.")
|
| 109 |
+
def test_save_load_optional_components(self):
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@slow
|
| 114 |
+
@require_torch_accelerator
|
| 115 |
+
class IFImg2ImgSuperResolutionPipelineSlowTests(unittest.TestCase):
|
| 116 |
+
def setUp(self):
|
| 117 |
+
# clean up the VRAM before each test
|
| 118 |
+
super().setUp()
|
| 119 |
+
gc.collect()
|
| 120 |
+
backend_empty_cache(torch_device)
|
| 121 |
+
|
| 122 |
+
def tearDown(self):
|
| 123 |
+
# clean up the VRAM after each test
|
| 124 |
+
super().tearDown()
|
| 125 |
+
gc.collect()
|
| 126 |
+
backend_empty_cache(torch_device)
|
| 127 |
+
|
| 128 |
+
def test_if_img2img_superresolution(self):
|
| 129 |
+
pipe = IFImg2ImgSuperResolutionPipeline.from_pretrained(
|
| 130 |
+
"DeepFloyd/IF-II-L-v1.0",
|
| 131 |
+
variant="fp16",
|
| 132 |
+
torch_dtype=torch.float16,
|
| 133 |
+
)
|
| 134 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 135 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 136 |
+
|
| 137 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 138 |
+
backend_empty_cache(torch_device)
|
| 139 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 140 |
+
|
| 141 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 142 |
+
|
| 143 |
+
original_image = floats_tensor((1, 3, 256, 256), rng=random.Random(0)).to(torch_device)
|
| 144 |
+
image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
|
| 145 |
+
|
| 146 |
+
output = pipe(
|
| 147 |
+
prompt="anime turtle",
|
| 148 |
+
image=image,
|
| 149 |
+
original_image=original_image,
|
| 150 |
+
generator=generator,
|
| 151 |
+
num_inference_steps=2,
|
| 152 |
+
output_type="np",
|
| 153 |
+
)
|
| 154 |
+
|
| 155 |
+
image = output.images[0]
|
| 156 |
+
|
| 157 |
+
assert image.shape == (256, 256, 3)
|
| 158 |
+
|
| 159 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 160 |
+
|
| 161 |
+
assert mem_bytes < 12 * 10**9
|
| 162 |
+
|
| 163 |
+
expected_image = load_numpy(
|
| 164 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_img2img_superresolution_stage_II.npy"
|
| 165 |
+
)
|
| 166 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 167 |
+
|
| 168 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting.py
ADDED
|
@@ -0,0 +1,160 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import random
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
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 |
+
backend_empty_cache,
|
| 27 |
+
backend_max_memory_allocated,
|
| 28 |
+
backend_reset_max_memory_allocated,
|
| 29 |
+
backend_reset_peak_memory_stats,
|
| 30 |
+
floats_tensor,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import (
|
| 42 |
+
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
|
| 43 |
+
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
|
| 44 |
+
)
|
| 45 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 46 |
+
from . import IFPipelineTesterMixin
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@skip_mps
|
| 50 |
+
class IFInpaintingPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 51 |
+
pipeline_class = IFInpaintingPipeline
|
| 52 |
+
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"}
|
| 53 |
+
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS
|
| 54 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
return self._get_dummy_components()
|
| 58 |
+
|
| 59 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 60 |
+
if str(device).startswith("mps"):
|
| 61 |
+
generator = torch.manual_seed(seed)
|
| 62 |
+
else:
|
| 63 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 64 |
+
|
| 65 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 66 |
+
mask_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 67 |
+
|
| 68 |
+
inputs = {
|
| 69 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 70 |
+
"image": image,
|
| 71 |
+
"mask_image": mask_image,
|
| 72 |
+
"generator": generator,
|
| 73 |
+
"num_inference_steps": 2,
|
| 74 |
+
"output_type": "np",
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
return inputs
|
| 78 |
+
|
| 79 |
+
@unittest.skipIf(
|
| 80 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 81 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 82 |
+
)
|
| 83 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 84 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 85 |
+
|
| 86 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 87 |
+
@require_accelerator
|
| 88 |
+
def test_save_load_float16(self):
|
| 89 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 90 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 91 |
+
|
| 92 |
+
def test_attention_slicing_forward_pass(self):
|
| 93 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 94 |
+
|
| 95 |
+
def test_save_load_local(self):
|
| 96 |
+
self._test_save_load_local()
|
| 97 |
+
|
| 98 |
+
def test_inference_batch_single_identical(self):
|
| 99 |
+
self._test_inference_batch_single_identical(
|
| 100 |
+
expected_max_diff=1e-2,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 104 |
+
@require_transformers_version_greater("4.47.1")
|
| 105 |
+
def test_save_load_dduf(self):
|
| 106 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 107 |
+
|
| 108 |
+
@unittest.skip("Test done elsewhere.")
|
| 109 |
+
def test_save_load_optional_components(self, expected_max_difference=0.0001):
|
| 110 |
+
pass
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
@slow
|
| 114 |
+
@require_torch_accelerator
|
| 115 |
+
class IFInpaintingPipelineSlowTests(unittest.TestCase):
|
| 116 |
+
def setUp(self):
|
| 117 |
+
# clean up the VRAM before each test
|
| 118 |
+
super().setUp()
|
| 119 |
+
gc.collect()
|
| 120 |
+
backend_empty_cache(torch_device)
|
| 121 |
+
|
| 122 |
+
def tearDown(self):
|
| 123 |
+
# clean up the VRAM after each test
|
| 124 |
+
super().tearDown()
|
| 125 |
+
gc.collect()
|
| 126 |
+
backend_empty_cache(torch_device)
|
| 127 |
+
|
| 128 |
+
def test_if_inpainting(self):
|
| 129 |
+
pipe = IFInpaintingPipeline.from_pretrained(
|
| 130 |
+
"DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16
|
| 131 |
+
)
|
| 132 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 133 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 134 |
+
|
| 135 |
+
backend_empty_cache(torch_device)
|
| 136 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 137 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 138 |
+
|
| 139 |
+
image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
|
| 140 |
+
mask_image = floats_tensor((1, 3, 64, 64), rng=random.Random(1)).to(torch_device)
|
| 141 |
+
|
| 142 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 143 |
+
output = pipe(
|
| 144 |
+
prompt="anime prompts",
|
| 145 |
+
image=image,
|
| 146 |
+
mask_image=mask_image,
|
| 147 |
+
num_inference_steps=2,
|
| 148 |
+
generator=generator,
|
| 149 |
+
output_type="np",
|
| 150 |
+
)
|
| 151 |
+
image = output.images[0]
|
| 152 |
+
|
| 153 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 154 |
+
assert mem_bytes < 12 * 10**9
|
| 155 |
+
|
| 156 |
+
expected_image = load_numpy(
|
| 157 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting.npy"
|
| 158 |
+
)
|
| 159 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 160 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting_superresolution.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import random
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import IFInpaintingSuperResolutionPipeline
|
| 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 |
+
backend_empty_cache,
|
| 27 |
+
backend_max_memory_allocated,
|
| 28 |
+
backend_reset_max_memory_allocated,
|
| 29 |
+
backend_reset_peak_memory_stats,
|
| 30 |
+
floats_tensor,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import (
|
| 42 |
+
TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS,
|
| 43 |
+
TEXT_GUIDED_IMAGE_INPAINTING_PARAMS,
|
| 44 |
+
)
|
| 45 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 46 |
+
from . import IFPipelineTesterMixin
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
@skip_mps
|
| 50 |
+
class IFInpaintingSuperResolutionPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 51 |
+
pipeline_class = IFInpaintingSuperResolutionPipeline
|
| 52 |
+
params = TEXT_GUIDED_IMAGE_INPAINTING_PARAMS - {"width", "height"}
|
| 53 |
+
batch_params = TEXT_GUIDED_IMAGE_INPAINTING_BATCH_PARAMS.union({"original_image"})
|
| 54 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
return self._get_superresolution_dummy_components()
|
| 58 |
+
|
| 59 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 60 |
+
if str(device).startswith("mps"):
|
| 61 |
+
generator = torch.manual_seed(seed)
|
| 62 |
+
else:
|
| 63 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 64 |
+
|
| 65 |
+
image = floats_tensor((1, 3, 16, 16), rng=random.Random(seed)).to(device)
|
| 66 |
+
original_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 67 |
+
mask_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 68 |
+
|
| 69 |
+
inputs = {
|
| 70 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 71 |
+
"image": image,
|
| 72 |
+
"original_image": original_image,
|
| 73 |
+
"mask_image": mask_image,
|
| 74 |
+
"generator": generator,
|
| 75 |
+
"num_inference_steps": 2,
|
| 76 |
+
"output_type": "np",
|
| 77 |
+
}
|
| 78 |
+
|
| 79 |
+
return inputs
|
| 80 |
+
|
| 81 |
+
@unittest.skipIf(
|
| 82 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 83 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 84 |
+
)
|
| 85 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 86 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 87 |
+
|
| 88 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 89 |
+
@require_accelerator
|
| 90 |
+
def test_save_load_float16(self):
|
| 91 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 92 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 93 |
+
|
| 94 |
+
def test_attention_slicing_forward_pass(self):
|
| 95 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 96 |
+
|
| 97 |
+
def test_save_load_local(self):
|
| 98 |
+
self._test_save_load_local()
|
| 99 |
+
|
| 100 |
+
def test_inference_batch_single_identical(self):
|
| 101 |
+
self._test_inference_batch_single_identical(
|
| 102 |
+
expected_max_diff=1e-2,
|
| 103 |
+
)
|
| 104 |
+
|
| 105 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 106 |
+
@require_transformers_version_greater("4.47.1")
|
| 107 |
+
def test_save_load_dduf(self):
|
| 108 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 109 |
+
|
| 110 |
+
@unittest.skip("Test done elsewhere.")
|
| 111 |
+
def test_save_load_optional_components(self, expected_max_difference=0.0001):
|
| 112 |
+
pass
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
@slow
|
| 116 |
+
@require_torch_accelerator
|
| 117 |
+
class IFInpaintingSuperResolutionPipelineSlowTests(unittest.TestCase):
|
| 118 |
+
def setUp(self):
|
| 119 |
+
# clean up the VRAM before each test
|
| 120 |
+
super().setUp()
|
| 121 |
+
gc.collect()
|
| 122 |
+
backend_empty_cache(torch_device)
|
| 123 |
+
|
| 124 |
+
def tearDown(self):
|
| 125 |
+
# clean up the VRAM after each test
|
| 126 |
+
super().tearDown()
|
| 127 |
+
gc.collect()
|
| 128 |
+
backend_empty_cache(torch_device)
|
| 129 |
+
|
| 130 |
+
def test_if_inpainting_superresolution(self):
|
| 131 |
+
pipe = IFInpaintingSuperResolutionPipeline.from_pretrained(
|
| 132 |
+
"DeepFloyd/IF-II-L-v1.0", variant="fp16", torch_dtype=torch.float16
|
| 133 |
+
)
|
| 134 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 135 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 136 |
+
|
| 137 |
+
# Super resolution test
|
| 138 |
+
backend_empty_cache(torch_device)
|
| 139 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 140 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 141 |
+
|
| 142 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 143 |
+
|
| 144 |
+
image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
|
| 145 |
+
original_image = floats_tensor((1, 3, 256, 256), rng=random.Random(0)).to(torch_device)
|
| 146 |
+
mask_image = floats_tensor((1, 3, 256, 256), rng=random.Random(1)).to(torch_device)
|
| 147 |
+
|
| 148 |
+
output = pipe(
|
| 149 |
+
prompt="anime turtle",
|
| 150 |
+
image=image,
|
| 151 |
+
original_image=original_image,
|
| 152 |
+
mask_image=mask_image,
|
| 153 |
+
generator=generator,
|
| 154 |
+
num_inference_steps=2,
|
| 155 |
+
output_type="np",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
image = output.images[0]
|
| 159 |
+
|
| 160 |
+
assert image.shape == (256, 256, 3)
|
| 161 |
+
|
| 162 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 163 |
+
assert mem_bytes < 12 * 10**9
|
| 164 |
+
|
| 165 |
+
expected_image = load_numpy(
|
| 166 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_inpainting_superresolution_stage_II.npy"
|
| 167 |
+
)
|
| 168 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 169 |
+
|
| 170 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/deepfloyd_if/test_if_superresolution.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import random
|
| 18 |
+
import unittest
|
| 19 |
+
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import IFSuperResolutionPipeline
|
| 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 |
+
backend_empty_cache,
|
| 27 |
+
backend_max_memory_allocated,
|
| 28 |
+
backend_reset_max_memory_allocated,
|
| 29 |
+
backend_reset_peak_memory_stats,
|
| 30 |
+
floats_tensor,
|
| 31 |
+
load_numpy,
|
| 32 |
+
require_accelerator,
|
| 33 |
+
require_hf_hub_version_greater,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
require_transformers_version_greater,
|
| 36 |
+
skip_mps,
|
| 37 |
+
slow,
|
| 38 |
+
torch_device,
|
| 39 |
+
)
|
| 40 |
+
|
| 41 |
+
from ..pipeline_params import TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS, TEXT_GUIDED_IMAGE_VARIATION_PARAMS
|
| 42 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 43 |
+
from . import IFPipelineTesterMixin
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
@skip_mps
|
| 47 |
+
class IFSuperResolutionPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 48 |
+
pipeline_class = IFSuperResolutionPipeline
|
| 49 |
+
params = TEXT_GUIDED_IMAGE_VARIATION_PARAMS - {"width", "height"}
|
| 50 |
+
batch_params = TEXT_GUIDED_IMAGE_VARIATION_BATCH_PARAMS
|
| 51 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 52 |
+
|
| 53 |
+
def get_dummy_components(self):
|
| 54 |
+
return self._get_superresolution_dummy_components()
|
| 55 |
+
|
| 56 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 57 |
+
if str(device).startswith("mps"):
|
| 58 |
+
generator = torch.manual_seed(seed)
|
| 59 |
+
else:
|
| 60 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 61 |
+
|
| 62 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 63 |
+
|
| 64 |
+
inputs = {
|
| 65 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 66 |
+
"image": image,
|
| 67 |
+
"generator": generator,
|
| 68 |
+
"num_inference_steps": 2,
|
| 69 |
+
"output_type": "np",
|
| 70 |
+
}
|
| 71 |
+
|
| 72 |
+
return inputs
|
| 73 |
+
|
| 74 |
+
@unittest.skipIf(
|
| 75 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 76 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 77 |
+
)
|
| 78 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 79 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 80 |
+
|
| 81 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 82 |
+
@require_accelerator
|
| 83 |
+
def test_save_load_float16(self):
|
| 84 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 85 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 86 |
+
|
| 87 |
+
def test_attention_slicing_forward_pass(self):
|
| 88 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 89 |
+
|
| 90 |
+
def test_save_load_local(self):
|
| 91 |
+
self._test_save_load_local()
|
| 92 |
+
|
| 93 |
+
def test_inference_batch_single_identical(self):
|
| 94 |
+
self._test_inference_batch_single_identical(
|
| 95 |
+
expected_max_diff=1e-2,
|
| 96 |
+
)
|
| 97 |
+
|
| 98 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 99 |
+
@require_transformers_version_greater("4.47.1")
|
| 100 |
+
def test_save_load_dduf(self):
|
| 101 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 102 |
+
|
| 103 |
+
@unittest.skip("Test done elsewhere.")
|
| 104 |
+
def test_save_load_optional_components(self, expected_max_difference=0.0001):
|
| 105 |
+
pass
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
@slow
|
| 109 |
+
@require_torch_accelerator
|
| 110 |
+
class IFSuperResolutionPipelineSlowTests(unittest.TestCase):
|
| 111 |
+
def setUp(self):
|
| 112 |
+
# clean up the VRAM before each test
|
| 113 |
+
super().setUp()
|
| 114 |
+
gc.collect()
|
| 115 |
+
backend_empty_cache(torch_device)
|
| 116 |
+
|
| 117 |
+
def tearDown(self):
|
| 118 |
+
# clean up the VRAM after each test
|
| 119 |
+
super().tearDown()
|
| 120 |
+
gc.collect()
|
| 121 |
+
backend_empty_cache(torch_device)
|
| 122 |
+
|
| 123 |
+
def test_if_superresolution(self):
|
| 124 |
+
pipe = IFSuperResolutionPipeline.from_pretrained(
|
| 125 |
+
"DeepFloyd/IF-II-L-v1.0", variant="fp16", torch_dtype=torch.float16
|
| 126 |
+
)
|
| 127 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 128 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 129 |
+
|
| 130 |
+
# Super resolution test
|
| 131 |
+
backend_empty_cache(torch_device)
|
| 132 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 133 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 134 |
+
|
| 135 |
+
image = floats_tensor((1, 3, 64, 64), rng=random.Random(0)).to(torch_device)
|
| 136 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 137 |
+
output = pipe(
|
| 138 |
+
prompt="anime turtle",
|
| 139 |
+
image=image,
|
| 140 |
+
generator=generator,
|
| 141 |
+
num_inference_steps=2,
|
| 142 |
+
output_type="np",
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
image = output.images[0]
|
| 146 |
+
|
| 147 |
+
assert image.shape == (256, 256, 3)
|
| 148 |
+
|
| 149 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 150 |
+
assert mem_bytes < 12 * 10**9
|
| 151 |
+
|
| 152 |
+
expected_image = load_numpy(
|
| 153 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if_superresolution_stage_II.npy"
|
| 154 |
+
)
|
| 155 |
+
assert_mean_pixel_difference(image, expected_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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# coding=utf-8
|
| 2 |
+
# Copyright 2025 HuggingFace Inc.
|
| 3 |
+
#
|
| 4 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 5 |
+
# you may not use this file except in compliance with the License.
|
| 6 |
+
# You may obtain a copy of the License at
|
| 7 |
+
#
|
| 8 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 9 |
+
#
|
| 10 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 11 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 12 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 13 |
+
# See the License for the specific language governing permissions and
|
| 14 |
+
# limitations under the License.
|
| 15 |
+
|
| 16 |
+
import gc
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
|
| 22 |
+
from diffusers import AutoencoderKL, DDIMScheduler, DiTPipeline, DiTTransformer2DModel, DPMSolverMultistepScheduler
|
| 23 |
+
from diffusers.utils import is_xformers_available
|
| 24 |
+
from diffusers.utils.testing_utils import (
|
| 25 |
+
backend_empty_cache,
|
| 26 |
+
enable_full_determinism,
|
| 27 |
+
load_numpy,
|
| 28 |
+
nightly,
|
| 29 |
+
numpy_cosine_similarity_distance,
|
| 30 |
+
require_torch_accelerator,
|
| 31 |
+
torch_device,
|
| 32 |
+
)
|
| 33 |
+
|
| 34 |
+
from ..pipeline_params import (
|
| 35 |
+
CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS,
|
| 36 |
+
CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS,
|
| 37 |
+
)
|
| 38 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
enable_full_determinism()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class DiTPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 45 |
+
pipeline_class = DiTPipeline
|
| 46 |
+
params = CLASS_CONDITIONED_IMAGE_GENERATION_PARAMS
|
| 47 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {
|
| 48 |
+
"latents",
|
| 49 |
+
"num_images_per_prompt",
|
| 50 |
+
"callback",
|
| 51 |
+
"callback_steps",
|
| 52 |
+
}
|
| 53 |
+
batch_params = CLASS_CONDITIONED_IMAGE_GENERATION_BATCH_PARAMS
|
| 54 |
+
|
| 55 |
+
def get_dummy_components(self):
|
| 56 |
+
torch.manual_seed(0)
|
| 57 |
+
transformer = DiTTransformer2DModel(
|
| 58 |
+
sample_size=16,
|
| 59 |
+
num_layers=2,
|
| 60 |
+
patch_size=4,
|
| 61 |
+
attention_head_dim=8,
|
| 62 |
+
num_attention_heads=2,
|
| 63 |
+
in_channels=4,
|
| 64 |
+
out_channels=8,
|
| 65 |
+
attention_bias=True,
|
| 66 |
+
activation_fn="gelu-approximate",
|
| 67 |
+
num_embeds_ada_norm=1000,
|
| 68 |
+
norm_type="ada_norm_zero",
|
| 69 |
+
norm_elementwise_affine=False,
|
| 70 |
+
)
|
| 71 |
+
vae = AutoencoderKL()
|
| 72 |
+
scheduler = DDIMScheduler()
|
| 73 |
+
components = {"transformer": transformer.eval(), "vae": vae.eval(), "scheduler": scheduler}
|
| 74 |
+
return components
|
| 75 |
+
|
| 76 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 77 |
+
if str(device).startswith("mps"):
|
| 78 |
+
generator = torch.manual_seed(seed)
|
| 79 |
+
else:
|
| 80 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 81 |
+
inputs = {
|
| 82 |
+
"class_labels": [1],
|
| 83 |
+
"generator": generator,
|
| 84 |
+
"num_inference_steps": 2,
|
| 85 |
+
"output_type": "np",
|
| 86 |
+
}
|
| 87 |
+
return inputs
|
| 88 |
+
|
| 89 |
+
def test_inference(self):
|
| 90 |
+
device = "cpu"
|
| 91 |
+
|
| 92 |
+
components = self.get_dummy_components()
|
| 93 |
+
pipe = self.pipeline_class(**components)
|
| 94 |
+
pipe.to(device)
|
| 95 |
+
pipe.set_progress_bar_config(disable=None)
|
| 96 |
+
|
| 97 |
+
inputs = self.get_dummy_inputs(device)
|
| 98 |
+
image = pipe(**inputs).images
|
| 99 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 100 |
+
|
| 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])
|
| 103 |
+
max_diff = np.abs(image_slice.flatten() - expected_slice).max()
|
| 104 |
+
self.assertLessEqual(max_diff, 1e-3)
|
| 105 |
+
|
| 106 |
+
def test_inference_batch_single_identical(self):
|
| 107 |
+
self._test_inference_batch_single_identical(expected_max_diff=1e-3)
|
| 108 |
+
|
| 109 |
+
@unittest.skipIf(
|
| 110 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 111 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 112 |
+
)
|
| 113 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 114 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@nightly
|
| 118 |
+
@require_torch_accelerator
|
| 119 |
+
class DiTPipelineIntegrationTests(unittest.TestCase):
|
| 120 |
+
def setUp(self):
|
| 121 |
+
super().setUp()
|
| 122 |
+
gc.collect()
|
| 123 |
+
backend_empty_cache(torch_device)
|
| 124 |
+
|
| 125 |
+
def tearDown(self):
|
| 126 |
+
super().tearDown()
|
| 127 |
+
gc.collect()
|
| 128 |
+
backend_empty_cache(torch_device)
|
| 129 |
+
|
| 130 |
+
def test_dit_256(self):
|
| 131 |
+
generator = torch.manual_seed(0)
|
| 132 |
+
|
| 133 |
+
pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-256")
|
| 134 |
+
pipe.to(torch_device)
|
| 135 |
+
|
| 136 |
+
words = ["vase", "umbrella", "white shark", "white wolf"]
|
| 137 |
+
ids = pipe.get_label_ids(words)
|
| 138 |
+
|
| 139 |
+
images = pipe(ids, generator=generator, num_inference_steps=40, output_type="np").images
|
| 140 |
+
|
| 141 |
+
for word, image in zip(words, images):
|
| 142 |
+
expected_image = load_numpy(
|
| 143 |
+
f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}.npy"
|
| 144 |
+
)
|
| 145 |
+
assert np.abs((expected_image - image).max()) < 1e-2
|
| 146 |
+
|
| 147 |
+
def test_dit_512(self):
|
| 148 |
+
pipe = DiTPipeline.from_pretrained("facebook/DiT-XL-2-512")
|
| 149 |
+
pipe.scheduler = DPMSolverMultistepScheduler.from_config(pipe.scheduler.config)
|
| 150 |
+
pipe.to(torch_device)
|
| 151 |
+
|
| 152 |
+
words = ["vase", "umbrella"]
|
| 153 |
+
ids = pipe.get_label_ids(words)
|
| 154 |
+
|
| 155 |
+
generator = torch.manual_seed(0)
|
| 156 |
+
images = pipe(ids, generator=generator, num_inference_steps=25, output_type="np").images
|
| 157 |
+
|
| 158 |
+
for word, image in zip(words, images):
|
| 159 |
+
expected_image = load_numpy(
|
| 160 |
+
f"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/dit/{word}_512.npy"
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
expected_slice = expected_image.flatten()
|
| 164 |
+
output_slice = image.flatten()
|
| 165 |
+
|
| 166 |
+
assert numpy_cosine_similarity_distance(expected_slice, output_slice) < 1e-2
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/easyanimate/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/easyan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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
| 2 |
+
#
|
| 3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
| 4 |
+
# you may not use this file except in compliance with the License.
|
| 5 |
+
# You may obtain a copy of the License at
|
| 6 |
+
#
|
| 7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
| 8 |
+
#
|
| 9 |
+
# Unless required by applicable law or agreed to in writing, software
|
| 10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
| 11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
| 12 |
+
# See the License for the specific language governing permissions and
|
| 13 |
+
# limitations under the License.
|
| 14 |
+
|
| 15 |
+
import gc
|
| 16 |
+
import inspect
|
| 17 |
+
import unittest
|
| 18 |
+
|
| 19 |
+
import numpy as np
|
| 20 |
+
import torch
|
| 21 |
+
from transformers import Qwen2Tokenizer, Qwen2VLForConditionalGeneration
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKLMagvit,
|
| 25 |
+
EasyAnimatePipeline,
|
| 26 |
+
EasyAnimateTransformer3DModel,
|
| 27 |
+
FlowMatchEulerDiscreteScheduler,
|
| 28 |
+
)
|
| 29 |
+
from diffusers.utils.testing_utils import (
|
| 30 |
+
backend_empty_cache,
|
| 31 |
+
enable_full_determinism,
|
| 32 |
+
numpy_cosine_similarity_distance,
|
| 33 |
+
require_torch_accelerator,
|
| 34 |
+
slow,
|
| 35 |
+
torch_device,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 39 |
+
from ..test_pipelines_common import PipelineTesterMixin, to_np
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
enable_full_determinism()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class EasyAnimatePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 46 |
+
pipeline_class = EasyAnimatePipeline
|
| 47 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 48 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 49 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 50 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 51 |
+
required_optional_params = frozenset(
|
| 52 |
+
[
|
| 53 |
+
"num_inference_steps",
|
| 54 |
+
"generator",
|
| 55 |
+
"latents",
|
| 56 |
+
"return_dict",
|
| 57 |
+
"callback_on_step_end",
|
| 58 |
+
"callback_on_step_end_tensor_inputs",
|
| 59 |
+
]
|
| 60 |
+
)
|
| 61 |
+
|
| 62 |
+
supports_dduf = False
|
| 63 |
+
|
| 64 |
+
def get_dummy_components(self):
|
| 65 |
+
torch.manual_seed(0)
|
| 66 |
+
transformer = EasyAnimateTransformer3DModel(
|
| 67 |
+
num_attention_heads=2,
|
| 68 |
+
attention_head_dim=16,
|
| 69 |
+
in_channels=4,
|
| 70 |
+
out_channels=4,
|
| 71 |
+
time_embed_dim=2,
|
| 72 |
+
text_embed_dim=16, # Must match with tiny-random-t5
|
| 73 |
+
num_layers=1,
|
| 74 |
+
sample_width=16, # latent width: 2 -> final width: 16
|
| 75 |
+
sample_height=16, # latent height: 2 -> final height: 16
|
| 76 |
+
patch_size=2,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
torch.manual_seed(0)
|
| 80 |
+
vae = AutoencoderKLMagvit(
|
| 81 |
+
in_channels=3,
|
| 82 |
+
out_channels=3,
|
| 83 |
+
down_block_types=(
|
| 84 |
+
"SpatialDownBlock3D",
|
| 85 |
+
"SpatialTemporalDownBlock3D",
|
| 86 |
+
"SpatialTemporalDownBlock3D",
|
| 87 |
+
"SpatialTemporalDownBlock3D",
|
| 88 |
+
),
|
| 89 |
+
up_block_types=(
|
| 90 |
+
"SpatialUpBlock3D",
|
| 91 |
+
"SpatialTemporalUpBlock3D",
|
| 92 |
+
"SpatialTemporalUpBlock3D",
|
| 93 |
+
"SpatialTemporalUpBlock3D",
|
| 94 |
+
),
|
| 95 |
+
block_out_channels=(8, 8, 8, 8),
|
| 96 |
+
latent_channels=4,
|
| 97 |
+
layers_per_block=1,
|
| 98 |
+
norm_num_groups=2,
|
| 99 |
+
spatial_group_norm=False,
|
| 100 |
+
)
|
| 101 |
+
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 104 |
+
text_encoder = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 105 |
+
"hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"
|
| 106 |
+
)
|
| 107 |
+
tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 108 |
+
|
| 109 |
+
components = {
|
| 110 |
+
"transformer": transformer,
|
| 111 |
+
"vae": vae,
|
| 112 |
+
"scheduler": scheduler,
|
| 113 |
+
"text_encoder": text_encoder,
|
| 114 |
+
"tokenizer": tokenizer,
|
| 115 |
+
}
|
| 116 |
+
return components
|
| 117 |
+
|
| 118 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 119 |
+
if str(device).startswith("mps"):
|
| 120 |
+
generator = torch.manual_seed(seed)
|
| 121 |
+
else:
|
| 122 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 123 |
+
inputs = {
|
| 124 |
+
"prompt": "dance monkey",
|
| 125 |
+
"negative_prompt": "",
|
| 126 |
+
"generator": generator,
|
| 127 |
+
"num_inference_steps": 2,
|
| 128 |
+
"guidance_scale": 6.0,
|
| 129 |
+
"height": 16,
|
| 130 |
+
"width": 16,
|
| 131 |
+
"num_frames": 5,
|
| 132 |
+
"output_type": "pt",
|
| 133 |
+
}
|
| 134 |
+
return inputs
|
| 135 |
+
|
| 136 |
+
def test_inference(self):
|
| 137 |
+
device = "cpu"
|
| 138 |
+
|
| 139 |
+
components = self.get_dummy_components()
|
| 140 |
+
pipe = self.pipeline_class(**components)
|
| 141 |
+
pipe.to(device)
|
| 142 |
+
pipe.set_progress_bar_config(disable=None)
|
| 143 |
+
|
| 144 |
+
inputs = self.get_dummy_inputs(device)
|
| 145 |
+
video = pipe(**inputs).frames
|
| 146 |
+
generated_video = video[0]
|
| 147 |
+
|
| 148 |
+
self.assertEqual(generated_video.shape, (5, 3, 16, 16))
|
| 149 |
+
expected_video = torch.randn(5, 3, 16, 16)
|
| 150 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 151 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 152 |
+
|
| 153 |
+
def test_callback_inputs(self):
|
| 154 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 155 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 156 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 157 |
+
|
| 158 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 159 |
+
return
|
| 160 |
+
|
| 161 |
+
components = self.get_dummy_components()
|
| 162 |
+
pipe = self.pipeline_class(**components)
|
| 163 |
+
pipe = pipe.to(torch_device)
|
| 164 |
+
pipe.set_progress_bar_config(disable=None)
|
| 165 |
+
self.assertTrue(
|
| 166 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 167 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 168 |
+
)
|
| 169 |
+
|
| 170 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 171 |
+
# iterate over callback args
|
| 172 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 173 |
+
# check that we're only passing in allowed tensor inputs
|
| 174 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 175 |
+
|
| 176 |
+
return callback_kwargs
|
| 177 |
+
|
| 178 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 179 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 180 |
+
assert tensor_name in callback_kwargs
|
| 181 |
+
|
| 182 |
+
# iterate over callback args
|
| 183 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 184 |
+
# check that we're only passing in allowed tensor inputs
|
| 185 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 186 |
+
|
| 187 |
+
return callback_kwargs
|
| 188 |
+
|
| 189 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 190 |
+
|
| 191 |
+
# Test passing in a subset
|
| 192 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 193 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 194 |
+
output = pipe(**inputs)[0]
|
| 195 |
+
|
| 196 |
+
# Test passing in a everything
|
| 197 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 198 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 199 |
+
output = pipe(**inputs)[0]
|
| 200 |
+
|
| 201 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 202 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 203 |
+
if is_last:
|
| 204 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 205 |
+
return callback_kwargs
|
| 206 |
+
|
| 207 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 208 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 209 |
+
output = pipe(**inputs)[0]
|
| 210 |
+
assert output.abs().sum() < 1e10
|
| 211 |
+
|
| 212 |
+
def test_inference_batch_single_identical(self):
|
| 213 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
|
| 214 |
+
|
| 215 |
+
def test_attention_slicing_forward_pass(
|
| 216 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 217 |
+
):
|
| 218 |
+
if not self.test_attention_slicing:
|
| 219 |
+
return
|
| 220 |
+
|
| 221 |
+
components = self.get_dummy_components()
|
| 222 |
+
pipe = self.pipeline_class(**components)
|
| 223 |
+
for component in pipe.components.values():
|
| 224 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 225 |
+
component.set_default_attn_processor()
|
| 226 |
+
pipe.to(torch_device)
|
| 227 |
+
pipe.set_progress_bar_config(disable=None)
|
| 228 |
+
|
| 229 |
+
generator_device = "cpu"
|
| 230 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 231 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 232 |
+
|
| 233 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 234 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 235 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 236 |
+
|
| 237 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 238 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 239 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 240 |
+
|
| 241 |
+
if test_max_difference:
|
| 242 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 243 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 244 |
+
self.assertLess(
|
| 245 |
+
max(max_diff1, max_diff2),
|
| 246 |
+
expected_max_diff,
|
| 247 |
+
"Attention slicing should not affect the inference results",
|
| 248 |
+
)
|
| 249 |
+
|
| 250 |
+
def test_dict_tuple_outputs_equivalent(self, expected_slice=None, expected_max_difference=0.001):
|
| 251 |
+
# Seems to need a higher tolerance
|
| 252 |
+
return super().test_dict_tuple_outputs_equivalent(expected_slice, expected_max_difference)
|
| 253 |
+
|
| 254 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 255 |
+
# Seems to need a higher tolerance
|
| 256 |
+
return super().test_encode_prompt_works_in_isolation(atol=1e-3, rtol=1e-3)
|
| 257 |
+
|
| 258 |
+
|
| 259 |
+
@slow
|
| 260 |
+
@require_torch_accelerator
|
| 261 |
+
class EasyAnimatePipelineIntegrationTests(unittest.TestCase):
|
| 262 |
+
prompt = "A painting of a squirrel eating a burger."
|
| 263 |
+
|
| 264 |
+
def setUp(self):
|
| 265 |
+
super().setUp()
|
| 266 |
+
gc.collect()
|
| 267 |
+
backend_empty_cache(torch_device)
|
| 268 |
+
|
| 269 |
+
def tearDown(self):
|
| 270 |
+
super().tearDown()
|
| 271 |
+
gc.collect()
|
| 272 |
+
backend_empty_cache(torch_device)
|
| 273 |
+
|
| 274 |
+
def test_EasyAnimate(self):
|
| 275 |
+
generator = torch.Generator("cpu").manual_seed(0)
|
| 276 |
+
|
| 277 |
+
pipe = EasyAnimatePipeline.from_pretrained("alibaba-pai/EasyAnimateV5.1-12b-zh", torch_dtype=torch.float16)
|
| 278 |
+
pipe.enable_model_cpu_offload()
|
| 279 |
+
prompt = self.prompt
|
| 280 |
+
|
| 281 |
+
videos = pipe(
|
| 282 |
+
prompt=prompt,
|
| 283 |
+
height=480,
|
| 284 |
+
width=720,
|
| 285 |
+
num_frames=5,
|
| 286 |
+
generator=generator,
|
| 287 |
+
num_inference_steps=2,
|
| 288 |
+
output_type="pt",
|
| 289 |
+
).frames
|
| 290 |
+
|
| 291 |
+
video = videos[0]
|
| 292 |
+
expected_video = torch.randn(1, 5, 480, 720, 3).numpy()
|
| 293 |
+
|
| 294 |
+
max_diff = numpy_cosine_similarity_distance(video, expected_video)
|
| 295 |
+
assert max_diff < 1e-3, f"Max diff is too high. got {video}"
|
tasks/tasksmith-9ca70b8463d4/tests/source/tests/pipelines/flux/__init__.py
ADDED
|
File without changes
|