Stage Harbor release files 99001-99500
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddim/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddim/test_ddim.py +142 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddpm/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddpm/test_ddpm.py +111 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/__init__.py +277 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if.py +144 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img.py +163 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img_superresolution.py +168 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting.py +160 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_inpainting_superresolution.py +170 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_superresolution.py +157 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dit/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dit/test_dit.py +166 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/test_pipeline_dreamlite.py +360 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/test_pipeline_dreamlite_mobile.py +354 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/easyanimate/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/easyanimate/test_easyanimate.py +296 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux.py +378 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control.py +176 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control_img2img.py +145 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control_inpaint.py +170 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_fill.py +147 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_img2img.py +170 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_inpaint.py +144 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_kontext.py +178 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_kontext_inpaint.py +191 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_redux.py +150 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2.py +190 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein.py +283 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein_inpaint.py +199 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein_kv.py +174 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/glm_image/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/glm_image/test_glm_image.py +397 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/helios/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/helios/test_helios.py +172 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hidream_image/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hidream_image/test_pipeline_hidream.py +162 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_image_21/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_image_21/test_hunyuanimage.py +286 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/__init__.py +0 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_image2video.py +390 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_skyreels_image2video.py +345 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_video.py +358 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_video_framepack.py +404 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video1_5/__init__.py +1 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video1_5/test_hunyuan_1_5.py +195 -0
- tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuandit/__init__.py +0 -0
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddim/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/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 |
+
|
| 23 |
+
from ...testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
|
| 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-ee553a5e62c1/tests/source/tests/pipelines/ddpm/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/ddpm/test_ddpm.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 23 |
+
from ...testing_utils import enable_full_determinism, require_torch_accelerator, slow, torch_device
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
enable_full_determinism()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class DDPMPipelineFastTests(unittest.TestCase):
|
| 30 |
+
@property
|
| 31 |
+
def dummy_uncond_unet(self):
|
| 32 |
+
torch.manual_seed(0)
|
| 33 |
+
model = UNet2DModel(
|
| 34 |
+
block_out_channels=(4, 8),
|
| 35 |
+
layers_per_block=1,
|
| 36 |
+
norm_num_groups=4,
|
| 37 |
+
sample_size=8,
|
| 38 |
+
in_channels=3,
|
| 39 |
+
out_channels=3,
|
| 40 |
+
down_block_types=("DownBlock2D", "AttnDownBlock2D"),
|
| 41 |
+
up_block_types=("AttnUpBlock2D", "UpBlock2D"),
|
| 42 |
+
)
|
| 43 |
+
return model
|
| 44 |
+
|
| 45 |
+
def test_fast_inference(self):
|
| 46 |
+
device = "cpu"
|
| 47 |
+
unet = self.dummy_uncond_unet
|
| 48 |
+
scheduler = DDPMScheduler()
|
| 49 |
+
|
| 50 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 51 |
+
ddpm.to(device)
|
| 52 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 53 |
+
|
| 54 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 55 |
+
image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
|
| 56 |
+
|
| 57 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 58 |
+
image_from_tuple = ddpm(generator=generator, num_inference_steps=2, output_type="np", return_dict=False)[0]
|
| 59 |
+
|
| 60 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 61 |
+
image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]
|
| 62 |
+
|
| 63 |
+
assert image.shape == (1, 8, 8, 3)
|
| 64 |
+
expected_slice = np.array([0.0, 0.9996672, 0.00329116, 1.0, 0.9995991, 1.0, 0.0060907, 0.00115037, 0.0])
|
| 65 |
+
|
| 66 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
| 67 |
+
assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2
|
| 68 |
+
|
| 69 |
+
def test_inference_predict_sample(self):
|
| 70 |
+
unet = self.dummy_uncond_unet
|
| 71 |
+
scheduler = DDPMScheduler(prediction_type="sample")
|
| 72 |
+
|
| 73 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 74 |
+
ddpm.to(torch_device)
|
| 75 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 76 |
+
|
| 77 |
+
generator = torch.manual_seed(0)
|
| 78 |
+
image = ddpm(generator=generator, num_inference_steps=2, output_type="np").images
|
| 79 |
+
|
| 80 |
+
generator = torch.manual_seed(0)
|
| 81 |
+
image_eps = ddpm(generator=generator, num_inference_steps=2, output_type="np")[0]
|
| 82 |
+
|
| 83 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 84 |
+
image_eps_slice = image_eps[0, -3:, -3:, -1]
|
| 85 |
+
|
| 86 |
+
assert image.shape == (1, 8, 8, 3)
|
| 87 |
+
tolerance = 1e-2 if torch_device != "mps" else 3e-2
|
| 88 |
+
assert np.abs(image_slice.flatten() - image_eps_slice.flatten()).max() < tolerance
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
@slow
|
| 92 |
+
@require_torch_accelerator
|
| 93 |
+
class DDPMPipelineIntegrationTests(unittest.TestCase):
|
| 94 |
+
def test_inference_cifar10(self):
|
| 95 |
+
model_id = "google/ddpm-cifar10-32"
|
| 96 |
+
|
| 97 |
+
unet = UNet2DModel.from_pretrained(model_id)
|
| 98 |
+
scheduler = DDPMScheduler.from_pretrained(model_id)
|
| 99 |
+
|
| 100 |
+
ddpm = DDPMPipeline(unet=unet, scheduler=scheduler)
|
| 101 |
+
ddpm.to(torch_device)
|
| 102 |
+
ddpm.set_progress_bar_config(disable=None)
|
| 103 |
+
|
| 104 |
+
generator = torch.manual_seed(0)
|
| 105 |
+
image = ddpm(generator=generator, output_type="np").images
|
| 106 |
+
|
| 107 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 108 |
+
|
| 109 |
+
assert image.shape == (1, 32, 32, 3)
|
| 110 |
+
expected_slice = np.array([0.4200, 0.3588, 0.1939, 0.3847, 0.3382, 0.2647, 0.4155, 0.3582, 0.3385])
|
| 111 |
+
assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/__init__.py
ADDED
|
@@ -0,0 +1,277 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import tempfile
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoConfig, 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 |
+
|
| 11 |
+
from ...testing_utils import torch_device
|
| 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 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 22 |
+
text_encoder = T5EncoderModel(config)
|
| 23 |
+
|
| 24 |
+
torch.manual_seed(0)
|
| 25 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 26 |
+
|
| 27 |
+
torch.manual_seed(0)
|
| 28 |
+
unet = UNet2DConditionModel(
|
| 29 |
+
sample_size=32,
|
| 30 |
+
layers_per_block=1,
|
| 31 |
+
block_out_channels=[32, 64],
|
| 32 |
+
down_block_types=[
|
| 33 |
+
"ResnetDownsampleBlock2D",
|
| 34 |
+
"SimpleCrossAttnDownBlock2D",
|
| 35 |
+
],
|
| 36 |
+
mid_block_type="UNetMidBlock2DSimpleCrossAttn",
|
| 37 |
+
up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"],
|
| 38 |
+
in_channels=3,
|
| 39 |
+
out_channels=6,
|
| 40 |
+
cross_attention_dim=32,
|
| 41 |
+
encoder_hid_dim=32,
|
| 42 |
+
attention_head_dim=8,
|
| 43 |
+
addition_embed_type="text",
|
| 44 |
+
addition_embed_type_num_heads=2,
|
| 45 |
+
cross_attention_norm="group_norm",
|
| 46 |
+
resnet_time_scale_shift="scale_shift",
|
| 47 |
+
act_fn="gelu",
|
| 48 |
+
)
|
| 49 |
+
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 50 |
+
|
| 51 |
+
torch.manual_seed(0)
|
| 52 |
+
scheduler = DDPMScheduler(
|
| 53 |
+
num_train_timesteps=1000,
|
| 54 |
+
beta_schedule="squaredcos_cap_v2",
|
| 55 |
+
beta_start=0.0001,
|
| 56 |
+
beta_end=0.02,
|
| 57 |
+
thresholding=True,
|
| 58 |
+
dynamic_thresholding_ratio=0.95,
|
| 59 |
+
sample_max_value=1.0,
|
| 60 |
+
prediction_type="epsilon",
|
| 61 |
+
variance_type="learned_range",
|
| 62 |
+
)
|
| 63 |
+
|
| 64 |
+
torch.manual_seed(0)
|
| 65 |
+
watermarker = IFWatermarker()
|
| 66 |
+
|
| 67 |
+
return {
|
| 68 |
+
"text_encoder": text_encoder,
|
| 69 |
+
"tokenizer": tokenizer,
|
| 70 |
+
"unet": unet,
|
| 71 |
+
"scheduler": scheduler,
|
| 72 |
+
"watermarker": watermarker,
|
| 73 |
+
"safety_checker": None,
|
| 74 |
+
"feature_extractor": None,
|
| 75 |
+
}
|
| 76 |
+
|
| 77 |
+
def _get_superresolution_dummy_components(self):
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 80 |
+
text_encoder = T5EncoderModel(config)
|
| 81 |
+
|
| 82 |
+
torch.manual_seed(0)
|
| 83 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 84 |
+
|
| 85 |
+
torch.manual_seed(0)
|
| 86 |
+
unet = UNet2DConditionModel(
|
| 87 |
+
sample_size=32,
|
| 88 |
+
layers_per_block=[1, 2],
|
| 89 |
+
block_out_channels=[32, 64],
|
| 90 |
+
down_block_types=[
|
| 91 |
+
"ResnetDownsampleBlock2D",
|
| 92 |
+
"SimpleCrossAttnDownBlock2D",
|
| 93 |
+
],
|
| 94 |
+
mid_block_type="UNetMidBlock2DSimpleCrossAttn",
|
| 95 |
+
up_block_types=["SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"],
|
| 96 |
+
in_channels=6,
|
| 97 |
+
out_channels=6,
|
| 98 |
+
cross_attention_dim=32,
|
| 99 |
+
encoder_hid_dim=32,
|
| 100 |
+
attention_head_dim=8,
|
| 101 |
+
addition_embed_type="text",
|
| 102 |
+
addition_embed_type_num_heads=2,
|
| 103 |
+
cross_attention_norm="group_norm",
|
| 104 |
+
resnet_time_scale_shift="scale_shift",
|
| 105 |
+
act_fn="gelu",
|
| 106 |
+
class_embed_type="timestep",
|
| 107 |
+
mid_block_scale_factor=1.414,
|
| 108 |
+
time_embedding_act_fn="gelu",
|
| 109 |
+
time_embedding_dim=32,
|
| 110 |
+
)
|
| 111 |
+
unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 112 |
+
|
| 113 |
+
torch.manual_seed(0)
|
| 114 |
+
scheduler = DDPMScheduler(
|
| 115 |
+
num_train_timesteps=1000,
|
| 116 |
+
beta_schedule="squaredcos_cap_v2",
|
| 117 |
+
beta_start=0.0001,
|
| 118 |
+
beta_end=0.02,
|
| 119 |
+
thresholding=True,
|
| 120 |
+
dynamic_thresholding_ratio=0.95,
|
| 121 |
+
sample_max_value=1.0,
|
| 122 |
+
prediction_type="epsilon",
|
| 123 |
+
variance_type="learned_range",
|
| 124 |
+
)
|
| 125 |
+
|
| 126 |
+
torch.manual_seed(0)
|
| 127 |
+
image_noising_scheduler = DDPMScheduler(
|
| 128 |
+
num_train_timesteps=1000,
|
| 129 |
+
beta_schedule="squaredcos_cap_v2",
|
| 130 |
+
beta_start=0.0001,
|
| 131 |
+
beta_end=0.02,
|
| 132 |
+
)
|
| 133 |
+
|
| 134 |
+
torch.manual_seed(0)
|
| 135 |
+
watermarker = IFWatermarker()
|
| 136 |
+
|
| 137 |
+
return {
|
| 138 |
+
"text_encoder": text_encoder,
|
| 139 |
+
"tokenizer": tokenizer,
|
| 140 |
+
"unet": unet,
|
| 141 |
+
"scheduler": scheduler,
|
| 142 |
+
"image_noising_scheduler": image_noising_scheduler,
|
| 143 |
+
"watermarker": watermarker,
|
| 144 |
+
"safety_checker": None,
|
| 145 |
+
"feature_extractor": None,
|
| 146 |
+
}
|
| 147 |
+
|
| 148 |
+
# this test is modified from the base class because if pipelines set the text encoder
|
| 149 |
+
# as optional with the intention that the user is allowed to encode the prompt once
|
| 150 |
+
# and then pass the embeddings directly to the pipeline. The base class test uses
|
| 151 |
+
# the unmodified arguments from `self.get_dummy_inputs` which will pass the unencoded
|
| 152 |
+
# prompt to the pipeline when the text encoder is set to None, throwing an error.
|
| 153 |
+
# So we make the test reflect the intended usage of setting the text encoder to None.
|
| 154 |
+
def _test_save_load_optional_components(self):
|
| 155 |
+
components = self.get_dummy_components()
|
| 156 |
+
pipe = self.pipeline_class(**components)
|
| 157 |
+
pipe.to(torch_device)
|
| 158 |
+
pipe.set_progress_bar_config(disable=None)
|
| 159 |
+
|
| 160 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 161 |
+
|
| 162 |
+
prompt = inputs["prompt"]
|
| 163 |
+
generator = inputs["generator"]
|
| 164 |
+
num_inference_steps = inputs["num_inference_steps"]
|
| 165 |
+
output_type = inputs["output_type"]
|
| 166 |
+
|
| 167 |
+
if "image" in inputs:
|
| 168 |
+
image = inputs["image"]
|
| 169 |
+
else:
|
| 170 |
+
image = None
|
| 171 |
+
|
| 172 |
+
if "mask_image" in inputs:
|
| 173 |
+
mask_image = inputs["mask_image"]
|
| 174 |
+
else:
|
| 175 |
+
mask_image = None
|
| 176 |
+
|
| 177 |
+
if "original_image" in inputs:
|
| 178 |
+
original_image = inputs["original_image"]
|
| 179 |
+
else:
|
| 180 |
+
original_image = None
|
| 181 |
+
|
| 182 |
+
prompt_embeds, negative_prompt_embeds = pipe.encode_prompt(prompt)
|
| 183 |
+
|
| 184 |
+
# inputs with prompt converted to embeddings
|
| 185 |
+
inputs = {
|
| 186 |
+
"prompt_embeds": prompt_embeds,
|
| 187 |
+
"negative_prompt_embeds": negative_prompt_embeds,
|
| 188 |
+
"generator": generator,
|
| 189 |
+
"num_inference_steps": num_inference_steps,
|
| 190 |
+
"output_type": output_type,
|
| 191 |
+
}
|
| 192 |
+
|
| 193 |
+
if image is not None:
|
| 194 |
+
inputs["image"] = image
|
| 195 |
+
|
| 196 |
+
if mask_image is not None:
|
| 197 |
+
inputs["mask_image"] = mask_image
|
| 198 |
+
|
| 199 |
+
if original_image is not None:
|
| 200 |
+
inputs["original_image"] = original_image
|
| 201 |
+
|
| 202 |
+
# set all optional components to None
|
| 203 |
+
for optional_component in pipe._optional_components:
|
| 204 |
+
setattr(pipe, optional_component, None)
|
| 205 |
+
|
| 206 |
+
output = pipe(**inputs)[0]
|
| 207 |
+
|
| 208 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 209 |
+
pipe.save_pretrained(tmpdir)
|
| 210 |
+
pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
|
| 211 |
+
pipe_loaded.to(torch_device)
|
| 212 |
+
pipe_loaded.set_progress_bar_config(disable=None)
|
| 213 |
+
|
| 214 |
+
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 215 |
+
|
| 216 |
+
for optional_component in pipe._optional_components:
|
| 217 |
+
self.assertTrue(
|
| 218 |
+
getattr(pipe_loaded, optional_component) is None,
|
| 219 |
+
f"`{optional_component}` did not stay set to None after loading.",
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 223 |
+
|
| 224 |
+
generator = inputs["generator"]
|
| 225 |
+
num_inference_steps = inputs["num_inference_steps"]
|
| 226 |
+
output_type = inputs["output_type"]
|
| 227 |
+
|
| 228 |
+
# inputs with prompt converted to embeddings
|
| 229 |
+
inputs = {
|
| 230 |
+
"prompt_embeds": prompt_embeds,
|
| 231 |
+
"negative_prompt_embeds": negative_prompt_embeds,
|
| 232 |
+
"generator": generator,
|
| 233 |
+
"num_inference_steps": num_inference_steps,
|
| 234 |
+
"output_type": output_type,
|
| 235 |
+
}
|
| 236 |
+
|
| 237 |
+
if image is not None:
|
| 238 |
+
inputs["image"] = image
|
| 239 |
+
|
| 240 |
+
if mask_image is not None:
|
| 241 |
+
inputs["mask_image"] = mask_image
|
| 242 |
+
|
| 243 |
+
if original_image is not None:
|
| 244 |
+
inputs["original_image"] = original_image
|
| 245 |
+
|
| 246 |
+
output_loaded = pipe_loaded(**inputs)[0]
|
| 247 |
+
|
| 248 |
+
max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
|
| 249 |
+
self.assertLess(max_diff, 1e-4)
|
| 250 |
+
|
| 251 |
+
# Modified from `PipelineTesterMixin` to set the attn processor as it's not serialized.
|
| 252 |
+
# This should be handled in the base test and then this method can be removed.
|
| 253 |
+
def _test_save_load_local(self):
|
| 254 |
+
components = self.get_dummy_components()
|
| 255 |
+
for key in components:
|
| 256 |
+
if "text_encoder" in key and hasattr(components[key], "eval"):
|
| 257 |
+
components[key].eval()
|
| 258 |
+
pipe = self.pipeline_class(**components)
|
| 259 |
+
pipe.to(torch_device)
|
| 260 |
+
pipe.set_progress_bar_config(disable=None)
|
| 261 |
+
|
| 262 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 263 |
+
output = pipe(**inputs)[0]
|
| 264 |
+
|
| 265 |
+
with tempfile.TemporaryDirectory() as tmpdir:
|
| 266 |
+
pipe.save_pretrained(tmpdir)
|
| 267 |
+
pipe_loaded = self.pipeline_class.from_pretrained(tmpdir)
|
| 268 |
+
pipe_loaded.to(torch_device)
|
| 269 |
+
pipe_loaded.set_progress_bar_config(disable=None)
|
| 270 |
+
|
| 271 |
+
pipe_loaded.unet.set_attn_processor(AttnAddedKVProcessor()) # For reproducibility tests
|
| 272 |
+
|
| 273 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 274 |
+
output_loaded = pipe_loaded(**inputs)[0]
|
| 275 |
+
|
| 276 |
+
max_diff = np.abs(to_np(output) - to_np(output_loaded)).max()
|
| 277 |
+
self.assertLess(max_diff, 1e-4)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 IFPipeline
|
| 22 |
+
from diffusers.models.attention_processor import AttnAddedKVProcessor
|
| 23 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 24 |
+
|
| 25 |
+
from ...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 |
+
load_numpy,
|
| 31 |
+
require_accelerator,
|
| 32 |
+
require_hf_hub_version_greater,
|
| 33 |
+
require_torch_accelerator,
|
| 34 |
+
require_transformers_version_greater,
|
| 35 |
+
skip_mps,
|
| 36 |
+
slow,
|
| 37 |
+
torch_device,
|
| 38 |
+
)
|
| 39 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 40 |
+
from ..test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference
|
| 41 |
+
from . import IFPipelineTesterMixin
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
@skip_mps
|
| 45 |
+
class IFPipelineFastTests(PipelineTesterMixin, IFPipelineTesterMixin, unittest.TestCase):
|
| 46 |
+
pipeline_class = IFPipeline
|
| 47 |
+
params = TEXT_TO_IMAGE_PARAMS - {"width", "height", "latents"}
|
| 48 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 49 |
+
required_optional_params = PipelineTesterMixin.required_optional_params - {"latents"}
|
| 50 |
+
|
| 51 |
+
def get_dummy_components(self):
|
| 52 |
+
return self._get_dummy_components()
|
| 53 |
+
|
| 54 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 55 |
+
if str(device).startswith("mps"):
|
| 56 |
+
generator = torch.manual_seed(seed)
|
| 57 |
+
else:
|
| 58 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 59 |
+
|
| 60 |
+
inputs = {
|
| 61 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 62 |
+
"generator": generator,
|
| 63 |
+
"num_inference_steps": 2,
|
| 64 |
+
"output_type": "np",
|
| 65 |
+
}
|
| 66 |
+
|
| 67 |
+
return inputs
|
| 68 |
+
|
| 69 |
+
@unittest.skipIf(torch_device not in ["cuda", "xpu"], reason="float16 requires CUDA or XPU")
|
| 70 |
+
@require_accelerator
|
| 71 |
+
def test_save_load_float16(self):
|
| 72 |
+
# Due to non-determinism in save load of the hf-internal-testing/tiny-random-t5 text encoder
|
| 73 |
+
super().test_save_load_float16(expected_max_diff=1e-1)
|
| 74 |
+
|
| 75 |
+
def test_attention_slicing_forward_pass(self):
|
| 76 |
+
self._test_attention_slicing_forward_pass(expected_max_diff=1e-2)
|
| 77 |
+
|
| 78 |
+
def test_save_load_local(self):
|
| 79 |
+
self._test_save_load_local()
|
| 80 |
+
|
| 81 |
+
def test_inference_batch_single_identical(self):
|
| 82 |
+
self._test_inference_batch_single_identical(
|
| 83 |
+
expected_max_diff=1e-2,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
@unittest.skipIf(
|
| 87 |
+
torch_device != "cuda" or not is_xformers_available(),
|
| 88 |
+
reason="XFormers attention is only available with CUDA and `xformers` installed",
|
| 89 |
+
)
|
| 90 |
+
def test_xformers_attention_forwardGenerator_pass(self):
|
| 91 |
+
self._test_xformers_attention_forwardGenerator_pass(expected_max_diff=1e-3)
|
| 92 |
+
|
| 93 |
+
@require_hf_hub_version_greater("0.26.5")
|
| 94 |
+
@require_transformers_version_greater("4.47.1")
|
| 95 |
+
def test_save_load_dduf(self):
|
| 96 |
+
super().test_save_load_dduf(atol=1e-2, rtol=1e-2)
|
| 97 |
+
|
| 98 |
+
@unittest.skip("Functionality is tested elsewhere.")
|
| 99 |
+
def test_save_load_optional_components(self):
|
| 100 |
+
pass
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@slow
|
| 104 |
+
@require_torch_accelerator
|
| 105 |
+
class IFPipelineSlowTests(unittest.TestCase):
|
| 106 |
+
def setUp(self):
|
| 107 |
+
# clean up the VRAM before each test
|
| 108 |
+
super().setUp()
|
| 109 |
+
gc.collect()
|
| 110 |
+
backend_empty_cache(torch_device)
|
| 111 |
+
|
| 112 |
+
def tearDown(self):
|
| 113 |
+
# clean up the VRAM after each test
|
| 114 |
+
super().tearDown()
|
| 115 |
+
gc.collect()
|
| 116 |
+
backend_empty_cache(torch_device)
|
| 117 |
+
|
| 118 |
+
def test_if_text_to_image(self):
|
| 119 |
+
pipe = IFPipeline.from_pretrained("DeepFloyd/IF-I-XL-v1.0", variant="fp16", torch_dtype=torch.float16)
|
| 120 |
+
pipe.unet.set_attn_processor(AttnAddedKVProcessor())
|
| 121 |
+
pipe.enable_model_cpu_offload(device=torch_device)
|
| 122 |
+
|
| 123 |
+
backend_reset_max_memory_allocated(torch_device)
|
| 124 |
+
backend_empty_cache(torch_device)
|
| 125 |
+
backend_reset_peak_memory_stats(torch_device)
|
| 126 |
+
|
| 127 |
+
generator = torch.Generator(device="cpu").manual_seed(0)
|
| 128 |
+
output = pipe(
|
| 129 |
+
prompt="anime turtle",
|
| 130 |
+
num_inference_steps=2,
|
| 131 |
+
generator=generator,
|
| 132 |
+
output_type="np",
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
image = output.images[0]
|
| 136 |
+
|
| 137 |
+
mem_bytes = backend_max_memory_allocated(torch_device)
|
| 138 |
+
assert mem_bytes < 12 * 10**9
|
| 139 |
+
|
| 140 |
+
expected_image = load_numpy(
|
| 141 |
+
"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/if/test_if.npy"
|
| 142 |
+
)
|
| 143 |
+
assert_mean_pixel_difference(image, expected_image)
|
| 144 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/deepfloyd_if/test_if_img2img.py
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 IFImg2ImgPipeline
|
| 23 |
+
from diffusers.models.attention_processor import AttnAddedKVProcessor
|
| 24 |
+
from diffusers.utils.import_utils import is_xformers_available
|
| 25 |
+
|
| 26 |
+
from ...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 |
+
floats_tensor,
|
| 32 |
+
load_numpy,
|
| 33 |
+
require_accelerator,
|
| 34 |
+
require_hf_hub_version_greater,
|
| 35 |
+
require_torch_accelerator,
|
| 36 |
+
require_transformers_version_greater,
|
| 37 |
+
skip_mps,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 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-ee553a5e62c1/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 |
+
|
| 26 |
+
from ...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 |
+
floats_tensor,
|
| 32 |
+
load_numpy,
|
| 33 |
+
require_accelerator,
|
| 34 |
+
require_hf_hub_version_greater,
|
| 35 |
+
require_torch_accelerator,
|
| 36 |
+
require_transformers_version_greater,
|
| 37 |
+
skip_mps,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 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-ee553a5e62c1/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 |
+
|
| 26 |
+
from ...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 |
+
floats_tensor,
|
| 32 |
+
load_numpy,
|
| 33 |
+
require_accelerator,
|
| 34 |
+
require_hf_hub_version_greater,
|
| 35 |
+
require_torch_accelerator,
|
| 36 |
+
require_transformers_version_greater,
|
| 37 |
+
skip_mps,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 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-ee553a5e62c1/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 |
+
|
| 26 |
+
from ...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 |
+
floats_tensor,
|
| 32 |
+
load_numpy,
|
| 33 |
+
require_accelerator,
|
| 34 |
+
require_hf_hub_version_greater,
|
| 35 |
+
require_torch_accelerator,
|
| 36 |
+
require_transformers_version_greater,
|
| 37 |
+
skip_mps,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 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-ee553a5e62c1/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 |
+
|
| 26 |
+
from ...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 |
+
floats_tensor,
|
| 32 |
+
load_numpy,
|
| 33 |
+
require_accelerator,
|
| 34 |
+
require_hf_hub_version_greater,
|
| 35 |
+
require_torch_accelerator,
|
| 36 |
+
require_transformers_version_greater,
|
| 37 |
+
skip_mps,
|
| 38 |
+
slow,
|
| 39 |
+
torch_device,
|
| 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_image)
|
| 156 |
+
|
| 157 |
+
pipe.remove_all_hooks()
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dit/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dit/test_dit.py
ADDED
|
@@ -0,0 +1,166 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 25 |
+
from ...testing_utils import (
|
| 26 |
+
backend_empty_cache,
|
| 27 |
+
enable_full_determinism,
|
| 28 |
+
load_numpy,
|
| 29 |
+
nightly,
|
| 30 |
+
numpy_cosine_similarity_distance,
|
| 31 |
+
require_torch_accelerator,
|
| 32 |
+
torch_device,
|
| 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-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/test_pipeline_dreamlite.py
ADDED
|
@@ -0,0 +1,360 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
|
| 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 |
+
"""Tests for ``DreamLitePipeline``.
|
| 15 |
+
|
| 16 |
+
Test design
|
| 17 |
+
-----------
|
| 18 |
+
``DreamLitePipeline`` depends on Qwen3-VL as its text/image encoder. For the
|
| 19 |
+
fast tests we instantiate a real ``Qwen3VLForConditionalGeneration`` from a
|
| 20 |
+
tiny config (mirroring the NucleusMoE-Image fast tests), and load the matching
|
| 21 |
+
processor / tokenizer from the public ``hf-internal-testing`` mirror, so that
|
| 22 |
+
the standard ``PipelineTesterMixin`` save/load and dtype/device tests work
|
| 23 |
+
out of the box.
|
| 24 |
+
|
| 25 |
+
For end-to-end verification against the original repo, see the
|
| 26 |
+
``parity_run_*.py`` scripts shipped with the integration.
|
| 27 |
+
"""
|
| 28 |
+
|
| 29 |
+
import gc
|
| 30 |
+
import os
|
| 31 |
+
import unittest
|
| 32 |
+
|
| 33 |
+
import numpy as np
|
| 34 |
+
import torch
|
| 35 |
+
from PIL import Image
|
| 36 |
+
from transformers import AutoTokenizer, Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLProcessor
|
| 37 |
+
|
| 38 |
+
from diffusers import (
|
| 39 |
+
AutoencoderTiny,
|
| 40 |
+
DreamLitePipeline,
|
| 41 |
+
DreamLiteUNetModel,
|
| 42 |
+
FlowMatchEulerDiscreteScheduler,
|
| 43 |
+
)
|
| 44 |
+
from diffusers.utils.testing_utils import (
|
| 45 |
+
enable_full_determinism,
|
| 46 |
+
nightly,
|
| 47 |
+
require_torch_gpu,
|
| 48 |
+
torch_device,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
from ..test_pipelines_common import (
|
| 52 |
+
PipelineTesterMixin,
|
| 53 |
+
to_np,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
enable_full_determinism()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
# Match the tiny text encoder hidden size below; the UNet's cross-attention
|
| 61 |
+
# dimension must match what ``encode_prompt`` returns.
|
| 62 |
+
_CROSS_ATTN_DIM = 16
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _build_tiny_text_encoder() -> Qwen3VLForConditionalGeneration:
|
| 66 |
+
"""Build a tiny but functional Qwen3-VL model for the fast test fixture.
|
| 67 |
+
|
| 68 |
+
Mirrors the recipe used by ``tests/pipelines/nucleusmoe_image``: small text
|
| 69 |
+
+ vision configs that still go through the real Qwen3-VL forward path, so
|
| 70 |
+
DreamLite's ``encode_prompt`` (chat template + tokenizer + multimodal
|
| 71 |
+
processor) is exercised for real.
|
| 72 |
+
"""
|
| 73 |
+
config = Qwen3VLConfig(
|
| 74 |
+
text_config={
|
| 75 |
+
"hidden_size": _CROSS_ATTN_DIM,
|
| 76 |
+
"intermediate_size": _CROSS_ATTN_DIM,
|
| 77 |
+
"num_hidden_layers": 2,
|
| 78 |
+
"num_attention_heads": 2,
|
| 79 |
+
"num_key_value_heads": 2,
|
| 80 |
+
"rope_scaling": {
|
| 81 |
+
"mrope_section": [1, 1, 2],
|
| 82 |
+
"rope_type": "default",
|
| 83 |
+
"type": "default",
|
| 84 |
+
},
|
| 85 |
+
"rope_theta": 1000000.0,
|
| 86 |
+
"vocab_size": 151936,
|
| 87 |
+
"head_dim": 8,
|
| 88 |
+
},
|
| 89 |
+
vision_config={
|
| 90 |
+
"depth": 2,
|
| 91 |
+
"hidden_size": _CROSS_ATTN_DIM,
|
| 92 |
+
"intermediate_size": _CROSS_ATTN_DIM,
|
| 93 |
+
"num_heads": 2,
|
| 94 |
+
"out_channels": _CROSS_ATTN_DIM,
|
| 95 |
+
# ``out_hidden_size`` is the dim that vision tokens are projected to before
|
| 96 |
+
# being merged into the text stream; it must match ``text_config.hidden_size``.
|
| 97 |
+
"out_hidden_size": _CROSS_ATTN_DIM,
|
| 98 |
+
# Match the cached ``hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration``
|
| 99 |
+
# image processor (``patch_size=14``); otherwise the pixel_values
|
| 100 |
+
# produced by the processor cannot be reshaped to the model's
|
| 101 |
+
# vision patch embed.
|
| 102 |
+
"patch_size": 14,
|
| 103 |
+
},
|
| 104 |
+
)
|
| 105 |
+
return Qwen3VLForConditionalGeneration(config).eval()
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
class DreamLitePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 109 |
+
pipeline_class = DreamLitePipeline
|
| 110 |
+
params = frozenset(
|
| 111 |
+
[
|
| 112 |
+
"prompt",
|
| 113 |
+
"height",
|
| 114 |
+
"width",
|
| 115 |
+
"guidance_scale",
|
| 116 |
+
"negative_prompt",
|
| 117 |
+
"num_inference_steps",
|
| 118 |
+
]
|
| 119 |
+
)
|
| 120 |
+
batch_params = frozenset(["prompt", "negative_prompt"])
|
| 121 |
+
required_optional_params = frozenset(
|
| 122 |
+
[
|
| 123 |
+
"num_inference_steps",
|
| 124 |
+
"generator",
|
| 125 |
+
"output_type",
|
| 126 |
+
"return_dict",
|
| 127 |
+
]
|
| 128 |
+
)
|
| 129 |
+
test_xformers_attention = False
|
| 130 |
+
test_attention_slicing = False
|
| 131 |
+
test_layerwise_casting = False
|
| 132 |
+
test_group_offloading = False
|
| 133 |
+
|
| 134 |
+
def get_dummy_components(self):
|
| 135 |
+
torch.manual_seed(0)
|
| 136 |
+
unet = DreamLiteUNetModel(
|
| 137 |
+
sample_size=8,
|
| 138 |
+
in_channels=4,
|
| 139 |
+
out_channels=4,
|
| 140 |
+
down_block_types=(
|
| 141 |
+
"DreamLiteCrossAttnNoSelfAttnDownBlock2D",
|
| 142 |
+
"DreamLiteCrossAttnDownBlock2D",
|
| 143 |
+
),
|
| 144 |
+
up_block_types=("DreamLiteCrossAttnUpBlock2D", "DreamLiteUpBlock2D"),
|
| 145 |
+
block_out_channels=(32, 64),
|
| 146 |
+
cross_attention_dim=_CROSS_ATTN_DIM,
|
| 147 |
+
attention_head_dim=8,
|
| 148 |
+
layers_per_block=1,
|
| 149 |
+
norm_num_groups=8,
|
| 150 |
+
transformer_layers_per_block=1,
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
torch.manual_seed(0)
|
| 154 |
+
vae = AutoencoderTiny(
|
| 155 |
+
in_channels=3,
|
| 156 |
+
out_channels=3,
|
| 157 |
+
encoder_block_out_channels=(32, 32),
|
| 158 |
+
decoder_block_out_channels=(32, 32),
|
| 159 |
+
num_encoder_blocks=(1, 1),
|
| 160 |
+
num_decoder_blocks=(1, 1),
|
| 161 |
+
latent_channels=4,
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000)
|
| 165 |
+
|
| 166 |
+
torch.manual_seed(0)
|
| 167 |
+
text_encoder = _build_tiny_text_encoder()
|
| 168 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 169 |
+
processor = Qwen3VLProcessor.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 170 |
+
|
| 171 |
+
return {
|
| 172 |
+
"text_encoder": text_encoder,
|
| 173 |
+
"tokenizer": tokenizer,
|
| 174 |
+
"processor": processor,
|
| 175 |
+
"vae": vae,
|
| 176 |
+
"unet": unet,
|
| 177 |
+
"scheduler": scheduler,
|
| 178 |
+
}
|
| 179 |
+
|
| 180 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 181 |
+
if str(device).startswith("mps"):
|
| 182 |
+
generator = torch.manual_seed(seed)
|
| 183 |
+
else:
|
| 184 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 185 |
+
return {
|
| 186 |
+
"prompt": "a small dog",
|
| 187 |
+
"negative_prompt": "",
|
| 188 |
+
"generator": generator,
|
| 189 |
+
"num_inference_steps": 2,
|
| 190 |
+
"guidance_scale": 3.5,
|
| 191 |
+
"height": 64,
|
| 192 |
+
"width": 64,
|
| 193 |
+
"max_sequence_length": 16,
|
| 194 |
+
"output_type": "np",
|
| 195 |
+
}
|
| 196 |
+
|
| 197 |
+
def get_dummy_i2i_inputs(self, device, seed=0):
|
| 198 |
+
inputs = self.get_dummy_inputs(device, seed)
|
| 199 |
+
# 64x64 RGB image -- will be processed by VaeImageProcessor.
|
| 200 |
+
inputs["image"] = Image.fromarray((np.random.RandomState(seed).rand(64, 64, 3) * 255).astype(np.uint8))
|
| 201 |
+
inputs["image_guidance_scale"] = 1.5
|
| 202 |
+
return inputs
|
| 203 |
+
|
| 204 |
+
# ---- skips for mixin tests that genuinely don't apply ----------------
|
| 205 |
+
# The remaining skips reflect intrinsic design choices of the DreamLite pipeline:
|
| 206 |
+
# * ``encode_prompt`` returns a ``(prompt_embeds, prompt_embeds_mask)``
|
| 207 |
+
# tuple, while the mixin's ``test_encode_prompt_works_in_isolation``
|
| 208 |
+
# assumes a single tensor return value;
|
| 209 |
+
# * the pipeline forces ``batch_size = 1`` internally, so the mixin's
|
| 210 |
+
# batch sweep cannot apply.
|
| 211 |
+
@unittest.skip(
|
| 212 |
+
"DreamLite intentionally limits ``batch_size`` to 1 (CFG memory blow-up); "
|
| 213 |
+
"only ``num_images_per_prompt > 1`` is supported."
|
| 214 |
+
)
|
| 215 |
+
def test_num_images_per_prompt(self):
|
| 216 |
+
pass
|
| 217 |
+
|
| 218 |
+
@unittest.skip(
|
| 219 |
+
"DreamLite encode_prompt returns (embeds, mask) tuple, not a single tensor; "
|
| 220 |
+
"the mixin's test_encode_prompt_works_in_isolation assumes single tensor return."
|
| 221 |
+
)
|
| 222 |
+
def test_encode_prompt_works_in_isolation(self, extra_required_param_value_dict=None, atol=1e-4, rtol=1e-4):
|
| 223 |
+
pass
|
| 224 |
+
|
| 225 |
+
@unittest.skip(
|
| 226 |
+
"Qwen3VLProcessor save_pretrained does not currently round-trip through DDUF "
|
| 227 |
+
"(image_processor sub-config is dropped); orthogonal to DreamLite."
|
| 228 |
+
)
|
| 229 |
+
def test_save_load_dduf(self, atol=1e-4, rtol=1e-4):
|
| 230 |
+
pass
|
| 231 |
+
|
| 232 |
+
@unittest.skip("DreamLite forces batch_size=1 internally.")
|
| 233 |
+
def test_inference_batch_consistent(self):
|
| 234 |
+
pass
|
| 235 |
+
|
| 236 |
+
@unittest.skip("DreamLite forces batch_size=1 internally.")
|
| 237 |
+
def test_inference_batch_single_identical(self):
|
| 238 |
+
pass
|
| 239 |
+
|
| 240 |
+
# ---- actual tests ------------------------------------------------------
|
| 241 |
+
def test_dreamlite_t2i_default_case(self):
|
| 242 |
+
device = torch_device
|
| 243 |
+
components = self.get_dummy_components()
|
| 244 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 245 |
+
pipe.set_progress_bar_config(disable=None)
|
| 246 |
+
|
| 247 |
+
inputs = self.get_dummy_inputs(device)
|
| 248 |
+
out = pipe(**inputs).images
|
| 249 |
+
out_np = to_np(out)
|
| 250 |
+
|
| 251 |
+
# shape: (B=1, H, W, C=3)
|
| 252 |
+
self.assertEqual(out_np.shape, (1, 64, 64, 3))
|
| 253 |
+
self.assertFalse(np.isnan(out_np).any())
|
| 254 |
+
|
| 255 |
+
def test_dreamlite_i2i_default_case(self):
|
| 256 |
+
device = torch_device
|
| 257 |
+
components = self.get_dummy_components()
|
| 258 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 259 |
+
pipe.set_progress_bar_config(disable=None)
|
| 260 |
+
|
| 261 |
+
inputs = self.get_dummy_i2i_inputs(device)
|
| 262 |
+
out = pipe(**inputs).images
|
| 263 |
+
out_np = to_np(out)
|
| 264 |
+
|
| 265 |
+
self.assertEqual(out_np.shape, (1, 64, 64, 3))
|
| 266 |
+
self.assertFalse(np.isnan(out_np).any())
|
| 267 |
+
|
| 268 |
+
def test_dreamlite_cfg_branch_count(self):
|
| 269 |
+
"""In edit mode the pipeline must run a 3-way CFG concat (uncond/img/text)."""
|
| 270 |
+
device = torch_device
|
| 271 |
+
components = self.get_dummy_components()
|
| 272 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 273 |
+
pipe.set_progress_bar_config(disable=None)
|
| 274 |
+
|
| 275 |
+
original_forward = pipe.unet.forward
|
| 276 |
+
seen_batches = []
|
| 277 |
+
|
| 278 |
+
def spy_forward(*args, **kwargs):
|
| 279 |
+
x = args[0] if args else kwargs["sample"]
|
| 280 |
+
seen_batches.append(x.shape[0])
|
| 281 |
+
return original_forward(*args, **kwargs)
|
| 282 |
+
|
| 283 |
+
pipe.unet.forward = spy_forward
|
| 284 |
+
inputs = self.get_dummy_i2i_inputs(device)
|
| 285 |
+
inputs["num_inference_steps"] = 1
|
| 286 |
+
pipe(**inputs)
|
| 287 |
+
|
| 288 |
+
self.assertTrue(all(b == 3 for b in seen_batches), f"expected all 3-way, got {seen_batches}")
|
| 289 |
+
|
| 290 |
+
|
| 291 |
+
@nightly
|
| 292 |
+
@require_torch_gpu
|
| 293 |
+
class DreamLitePipelineSlowTests(unittest.TestCase):
|
| 294 |
+
"""End-to-end test against the real DreamLite-base checkpoint on the Hub.
|
| 295 |
+
|
| 296 |
+
By default this loads ``carlofkl/DreamLite-base`` (``diffusers`` branch)
|
| 297 |
+
from the HF Hub. To run against a local copy during development, set the
|
| 298 |
+
``DREAMLITE_BASE_PATH`` env var to that path.
|
| 299 |
+
"""
|
| 300 |
+
|
| 301 |
+
repo_id = "carlofkl/DreamLite-base"
|
| 302 |
+
revision = "diffusers"
|
| 303 |
+
|
| 304 |
+
def setUp(self):
|
| 305 |
+
super().setUp()
|
| 306 |
+
gc.collect()
|
| 307 |
+
torch.cuda.empty_cache()
|
| 308 |
+
|
| 309 |
+
def tearDown(self):
|
| 310 |
+
super().tearDown()
|
| 311 |
+
gc.collect()
|
| 312 |
+
torch.cuda.empty_cache()
|
| 313 |
+
|
| 314 |
+
def _from_pretrained_kwargs(self):
|
| 315 |
+
local = os.getenv("DREAMLITE_BASE_PATH")
|
| 316 |
+
if local:
|
| 317 |
+
return {"pretrained_model_name_or_path": local}
|
| 318 |
+
return {"pretrained_model_name_or_path": self.repo_id, "revision": self.revision}
|
| 319 |
+
|
| 320 |
+
def test_dreamlite_t2i_real_checkpoint(self):
|
| 321 |
+
pipe = DreamLitePipeline.from_pretrained(**self._from_pretrained_kwargs(), torch_dtype=torch.bfloat16).to(
|
| 322 |
+
"cuda"
|
| 323 |
+
)
|
| 324 |
+
out = pipe(
|
| 325 |
+
prompt="a dog running on the grass",
|
| 326 |
+
num_inference_steps=2,
|
| 327 |
+
guidance_scale=3.5,
|
| 328 |
+
height=1024,
|
| 329 |
+
width=1024,
|
| 330 |
+
generator=torch.Generator("cpu").manual_seed(0),
|
| 331 |
+
output_type="np",
|
| 332 |
+
).images
|
| 333 |
+
|
| 334 |
+
self.assertEqual(out.shape, (1, 1024, 1024, 3))
|
| 335 |
+
self.assertFalse(np.isnan(out).any())
|
| 336 |
+
|
| 337 |
+
def test_dreamlite_i2i_real_checkpoint(self):
|
| 338 |
+
pipe = DreamLitePipeline.from_pretrained(**self._from_pretrained_kwargs(), torch_dtype=torch.bfloat16).to(
|
| 339 |
+
"cuda"
|
| 340 |
+
)
|
| 341 |
+
|
| 342 |
+
src = Image.fromarray((np.random.RandomState(0).rand(1024, 1024, 3) * 255).astype(np.uint8))
|
| 343 |
+
out = pipe(
|
| 344 |
+
prompt="make it look like a painting",
|
| 345 |
+
image=src,
|
| 346 |
+
num_inference_steps=2,
|
| 347 |
+
guidance_scale=3.5,
|
| 348 |
+
image_guidance_scale=1.5,
|
| 349 |
+
height=1024,
|
| 350 |
+
width=1024,
|
| 351 |
+
generator=torch.Generator("cpu").manual_seed(0),
|
| 352 |
+
output_type="np",
|
| 353 |
+
).images
|
| 354 |
+
|
| 355 |
+
self.assertEqual(out.shape, (1, 1024, 1024, 3))
|
| 356 |
+
self.assertFalse(np.isnan(out).any())
|
| 357 |
+
|
| 358 |
+
|
| 359 |
+
if __name__ == "__main__":
|
| 360 |
+
unittest.main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/dreamlite/test_pipeline_dreamlite_mobile.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Copyright (c) 2026 ByteDance Ltd. and/or its affiliates.
|
| 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 |
+
"""Tests for ``DreamLiteMobilePipeline``.
|
| 15 |
+
|
| 16 |
+
The mobile pipeline is a distilled, no-CFG sibling of ``DreamLitePipeline``.
|
| 17 |
+
It runs a single UNet forward per step (no 3-way concat) and ignores
|
| 18 |
+
``guidance_scale`` / ``image_guidance_scale``. Test layout mirrors
|
| 19 |
+
``test_pipeline_dreamlite.py``; see that file for the rationale behind the
|
| 20 |
+
tiny Qwen3-VL test fixture.
|
| 21 |
+
"""
|
| 22 |
+
|
| 23 |
+
import gc
|
| 24 |
+
import os
|
| 25 |
+
import unittest
|
| 26 |
+
|
| 27 |
+
import numpy as np
|
| 28 |
+
import torch
|
| 29 |
+
from PIL import Image
|
| 30 |
+
from transformers import AutoTokenizer, Qwen3VLConfig, Qwen3VLForConditionalGeneration, Qwen3VLProcessor
|
| 31 |
+
|
| 32 |
+
from diffusers import (
|
| 33 |
+
AutoencoderTiny,
|
| 34 |
+
DreamLiteMobilePipeline,
|
| 35 |
+
DreamLiteUNetModel,
|
| 36 |
+
FlowMatchEulerDiscreteScheduler,
|
| 37 |
+
)
|
| 38 |
+
from diffusers.utils.testing_utils import (
|
| 39 |
+
enable_full_determinism,
|
| 40 |
+
nightly,
|
| 41 |
+
require_torch_gpu,
|
| 42 |
+
torch_device,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
from ..test_pipelines_common import (
|
| 46 |
+
PipelineTesterMixin,
|
| 47 |
+
to_np,
|
| 48 |
+
)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
enable_full_determinism()
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
# Match the tiny text encoder hidden size below; the UNet's cross-attention
|
| 55 |
+
# dimension must match what ``encode_prompt`` returns.
|
| 56 |
+
_CROSS_ATTN_DIM = 16
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
def _build_tiny_text_encoder() -> Qwen3VLForConditionalGeneration:
|
| 60 |
+
"""Build a tiny but functional Qwen3-VL model for the fast test fixture.
|
| 61 |
+
|
| 62 |
+
Mirrors the recipe used by ``tests/pipelines/nucleusmoe_image``: small text
|
| 63 |
+
+ vision configs that still go through the real Qwen3-VL forward path, so
|
| 64 |
+
DreamLite's ``encode_prompt`` (chat template + tokenizer + multimodal
|
| 65 |
+
processor) is exercised for real.
|
| 66 |
+
"""
|
| 67 |
+
config = Qwen3VLConfig(
|
| 68 |
+
text_config={
|
| 69 |
+
"hidden_size": _CROSS_ATTN_DIM,
|
| 70 |
+
"intermediate_size": _CROSS_ATTN_DIM,
|
| 71 |
+
"num_hidden_layers": 2,
|
| 72 |
+
"num_attention_heads": 2,
|
| 73 |
+
"num_key_value_heads": 2,
|
| 74 |
+
"rope_scaling": {
|
| 75 |
+
"mrope_section": [1, 1, 2],
|
| 76 |
+
"rope_type": "default",
|
| 77 |
+
"type": "default",
|
| 78 |
+
},
|
| 79 |
+
"rope_theta": 1000000.0,
|
| 80 |
+
"vocab_size": 151936,
|
| 81 |
+
"head_dim": 8,
|
| 82 |
+
},
|
| 83 |
+
vision_config={
|
| 84 |
+
"depth": 2,
|
| 85 |
+
"hidden_size": _CROSS_ATTN_DIM,
|
| 86 |
+
"intermediate_size": _CROSS_ATTN_DIM,
|
| 87 |
+
"num_heads": 2,
|
| 88 |
+
"out_channels": _CROSS_ATTN_DIM,
|
| 89 |
+
# ``out_hidden_size`` is the dim that vision tokens are projected to before
|
| 90 |
+
# being merged into the text stream; it must match ``text_config.hidden_size``.
|
| 91 |
+
"out_hidden_size": _CROSS_ATTN_DIM,
|
| 92 |
+
# Match the cached ``hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration``
|
| 93 |
+
# image processor (``patch_size=14``); otherwise the pixel_values
|
| 94 |
+
# produced by the processor cannot be reshaped to the model's
|
| 95 |
+
# vision patch embed.
|
| 96 |
+
"patch_size": 14,
|
| 97 |
+
},
|
| 98 |
+
)
|
| 99 |
+
return Qwen3VLForConditionalGeneration(config).eval()
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
class DreamLiteMobilePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 103 |
+
pipeline_class = DreamLiteMobilePipeline
|
| 104 |
+
params = frozenset(
|
| 105 |
+
[
|
| 106 |
+
"prompt",
|
| 107 |
+
"height",
|
| 108 |
+
"width",
|
| 109 |
+
"num_inference_steps",
|
| 110 |
+
]
|
| 111 |
+
)
|
| 112 |
+
batch_params = frozenset(["prompt"])
|
| 113 |
+
required_optional_params = frozenset(
|
| 114 |
+
[
|
| 115 |
+
"num_inference_steps",
|
| 116 |
+
"generator",
|
| 117 |
+
"output_type",
|
| 118 |
+
"return_dict",
|
| 119 |
+
]
|
| 120 |
+
)
|
| 121 |
+
test_xformers_attention = False
|
| 122 |
+
test_attention_slicing = False
|
| 123 |
+
test_layerwise_casting = False
|
| 124 |
+
test_group_offloading = False
|
| 125 |
+
|
| 126 |
+
def get_dummy_components(self):
|
| 127 |
+
torch.manual_seed(0)
|
| 128 |
+
unet = DreamLiteUNetModel(
|
| 129 |
+
sample_size=8,
|
| 130 |
+
in_channels=4,
|
| 131 |
+
out_channels=4,
|
| 132 |
+
down_block_types=(
|
| 133 |
+
"DreamLiteCrossAttnNoSelfAttnDownBlock2D",
|
| 134 |
+
"DreamLiteCrossAttnDownBlock2D",
|
| 135 |
+
),
|
| 136 |
+
up_block_types=("DreamLiteCrossAttnUpBlock2D", "DreamLiteUpBlock2D"),
|
| 137 |
+
block_out_channels=(32, 64),
|
| 138 |
+
cross_attention_dim=_CROSS_ATTN_DIM,
|
| 139 |
+
attention_head_dim=8,
|
| 140 |
+
layers_per_block=1,
|
| 141 |
+
norm_num_groups=8,
|
| 142 |
+
transformer_layers_per_block=1,
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
torch.manual_seed(0)
|
| 146 |
+
vae = AutoencoderTiny(
|
| 147 |
+
in_channels=3,
|
| 148 |
+
out_channels=3,
|
| 149 |
+
encoder_block_out_channels=(32, 32),
|
| 150 |
+
decoder_block_out_channels=(32, 32),
|
| 151 |
+
num_encoder_blocks=(1, 1),
|
| 152 |
+
num_decoder_blocks=(1, 1),
|
| 153 |
+
latent_channels=4,
|
| 154 |
+
)
|
| 155 |
+
|
| 156 |
+
scheduler = FlowMatchEulerDiscreteScheduler(num_train_timesteps=1000)
|
| 157 |
+
|
| 158 |
+
torch.manual_seed(0)
|
| 159 |
+
text_encoder = _build_tiny_text_encoder()
|
| 160 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 161 |
+
processor = Qwen3VLProcessor.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 162 |
+
|
| 163 |
+
return {
|
| 164 |
+
"text_encoder": text_encoder,
|
| 165 |
+
"tokenizer": tokenizer,
|
| 166 |
+
"processor": processor,
|
| 167 |
+
"vae": vae,
|
| 168 |
+
"unet": unet,
|
| 169 |
+
"scheduler": scheduler,
|
| 170 |
+
}
|
| 171 |
+
|
| 172 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 173 |
+
if str(device).startswith("mps"):
|
| 174 |
+
generator = torch.manual_seed(seed)
|
| 175 |
+
else:
|
| 176 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 177 |
+
return {
|
| 178 |
+
"prompt": "a small dog",
|
| 179 |
+
"generator": generator,
|
| 180 |
+
"num_inference_steps": 2,
|
| 181 |
+
"height": 64,
|
| 182 |
+
"width": 64,
|
| 183 |
+
"max_sequence_length": 16,
|
| 184 |
+
"output_type": "np",
|
| 185 |
+
}
|
| 186 |
+
|
| 187 |
+
def get_dummy_i2i_inputs(self, device, seed=0):
|
| 188 |
+
inputs = self.get_dummy_inputs(device, seed)
|
| 189 |
+
inputs["image"] = Image.fromarray((np.random.RandomState(seed).rand(64, 64, 3) * 255).astype(np.uint8))
|
| 190 |
+
return inputs
|
| 191 |
+
|
| 192 |
+
# ---- skips for mixin tests that genuinely don't apply ----------------
|
| 193 |
+
# The remaining skips are intrinsic to the mobile pipeline's design:
|
| 194 |
+
# * ``encode_prompt`` returns ``(prompt_embeds, prompt_embeds_mask)``;
|
| 195 |
+
# * the pipeline forces ``batch_size = 1`` internally.
|
| 196 |
+
@unittest.skip(
|
| 197 |
+
"DreamLiteMobile encode_prompt returns (embeds, mask) tuple, not a single tensor; "
|
| 198 |
+
"the mixin's test_encode_prompt_works_in_isolation assumes single tensor return."
|
| 199 |
+
)
|
| 200 |
+
def test_encode_prompt_works_in_isolation(self, extra_required_param_value_dict=None, atol=1e-4, rtol=1e-4):
|
| 201 |
+
pass
|
| 202 |
+
|
| 203 |
+
@unittest.skip(
|
| 204 |
+
"DreamLiteMobile intentionally limits ``batch_size`` to 1; only ``num_images_per_prompt > 1`` is supported."
|
| 205 |
+
)
|
| 206 |
+
def test_num_images_per_prompt(self):
|
| 207 |
+
pass
|
| 208 |
+
|
| 209 |
+
@unittest.skip(
|
| 210 |
+
"Qwen3VLProcessor save_pretrained does not currently round-trip through DDUF "
|
| 211 |
+
"(image_processor sub-config is dropped); orthogonal to DreamLiteMobile."
|
| 212 |
+
)
|
| 213 |
+
def test_save_load_dduf(self, atol=1e-4, rtol=1e-4):
|
| 214 |
+
pass
|
| 215 |
+
|
| 216 |
+
@unittest.skip("DreamLiteMobile forces batch_size=1 internally.")
|
| 217 |
+
def test_inference_batch_consistent(self):
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
@unittest.skip("DreamLiteMobile forces batch_size=1 internally.")
|
| 221 |
+
def test_inference_batch_single_identical(self):
|
| 222 |
+
pass
|
| 223 |
+
|
| 224 |
+
# ---- actual tests ------------------------------------------------------
|
| 225 |
+
def test_mobile_t2i_default_case(self):
|
| 226 |
+
device = torch_device
|
| 227 |
+
components = self.get_dummy_components()
|
| 228 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 229 |
+
pipe.set_progress_bar_config(disable=None)
|
| 230 |
+
|
| 231 |
+
inputs = self.get_dummy_inputs(device)
|
| 232 |
+
out = pipe(**inputs).images
|
| 233 |
+
out_np = to_np(out)
|
| 234 |
+
|
| 235 |
+
self.assertEqual(out_np.shape, (1, 64, 64, 3))
|
| 236 |
+
self.assertFalse(np.isnan(out_np).any())
|
| 237 |
+
|
| 238 |
+
def test_mobile_i2i_default_case(self):
|
| 239 |
+
device = torch_device
|
| 240 |
+
components = self.get_dummy_components()
|
| 241 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 242 |
+
pipe.set_progress_bar_config(disable=None)
|
| 243 |
+
|
| 244 |
+
inputs = self.get_dummy_i2i_inputs(device)
|
| 245 |
+
out = pipe(**inputs).images
|
| 246 |
+
out_np = to_np(out)
|
| 247 |
+
|
| 248 |
+
self.assertEqual(out_np.shape, (1, 64, 64, 3))
|
| 249 |
+
self.assertFalse(np.isnan(out_np).any())
|
| 250 |
+
|
| 251 |
+
def test_mobile_single_forward_per_step(self):
|
| 252 |
+
"""Mobile pipeline must run exactly ONE UNet forward per step (no CFG concat)."""
|
| 253 |
+
device = torch_device
|
| 254 |
+
components = self.get_dummy_components()
|
| 255 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 256 |
+
pipe.set_progress_bar_config(disable=None)
|
| 257 |
+
|
| 258 |
+
original_forward = pipe.unet.forward
|
| 259 |
+
seen_batches = []
|
| 260 |
+
|
| 261 |
+
def spy_forward(*args, **kwargs):
|
| 262 |
+
x = args[0] if args else kwargs["sample"]
|
| 263 |
+
seen_batches.append(x.shape[0])
|
| 264 |
+
return original_forward(*args, **kwargs)
|
| 265 |
+
|
| 266 |
+
pipe.unet.forward = spy_forward
|
| 267 |
+
inputs = self.get_dummy_i2i_inputs(device)
|
| 268 |
+
inputs["num_inference_steps"] = 2
|
| 269 |
+
pipe(**inputs)
|
| 270 |
+
|
| 271 |
+
self.assertTrue(all(b == 1 for b in seen_batches), f"expected all 1-way, got {seen_batches}")
|
| 272 |
+
self.assertEqual(len(seen_batches), 2, "expected exactly 2 unet calls (1 per step)")
|
| 273 |
+
|
| 274 |
+
def test_mobile_guidance_scale_ignored(self):
|
| 275 |
+
"""Passing guidance_scale to the mobile pipeline should be accepted but ignored (with warning)."""
|
| 276 |
+
device = torch_device
|
| 277 |
+
components = self.get_dummy_components()
|
| 278 |
+
pipe = self.pipeline_class(**components).to(device)
|
| 279 |
+
pipe.set_progress_bar_config(disable=None)
|
| 280 |
+
|
| 281 |
+
inputs = self.get_dummy_inputs(device)
|
| 282 |
+
inputs["guidance_scale"] = 7.5 # should not raise
|
| 283 |
+
inputs["image_guidance_scale"] = 1.5 # should not raise
|
| 284 |
+
out = pipe(**inputs).images
|
| 285 |
+
self.assertEqual(to_np(out).shape, (1, 64, 64, 3))
|
| 286 |
+
|
| 287 |
+
|
| 288 |
+
@nightly
|
| 289 |
+
@require_torch_gpu
|
| 290 |
+
class DreamLiteMobilePipelineSlowTests(unittest.TestCase):
|
| 291 |
+
"""End-to-end test against the real DreamLite-mobile checkpoint on the Hub.
|
| 292 |
+
|
| 293 |
+
By default this loads ``carlofkl/DreamLite-mobile`` (``diffusers`` branch)
|
| 294 |
+
from the HF Hub. To run against a local copy during development, set the
|
| 295 |
+
``DREAMLITE_MOBILE_PATH`` env var to that path.
|
| 296 |
+
"""
|
| 297 |
+
|
| 298 |
+
repo_id = "carlofkl/DreamLite-mobile"
|
| 299 |
+
revision = "diffusers"
|
| 300 |
+
|
| 301 |
+
def setUp(self):
|
| 302 |
+
super().setUp()
|
| 303 |
+
gc.collect()
|
| 304 |
+
torch.cuda.empty_cache()
|
| 305 |
+
|
| 306 |
+
def tearDown(self):
|
| 307 |
+
super().tearDown()
|
| 308 |
+
gc.collect()
|
| 309 |
+
torch.cuda.empty_cache()
|
| 310 |
+
|
| 311 |
+
def _from_pretrained_kwargs(self):
|
| 312 |
+
local = os.getenv("DREAMLITE_MOBILE_PATH")
|
| 313 |
+
if local:
|
| 314 |
+
return {"pretrained_model_name_or_path": local}
|
| 315 |
+
return {"pretrained_model_name_or_path": self.repo_id, "revision": self.revision}
|
| 316 |
+
|
| 317 |
+
def test_mobile_t2i_real_checkpoint(self):
|
| 318 |
+
pipe = DreamLiteMobilePipeline.from_pretrained(
|
| 319 |
+
**self._from_pretrained_kwargs(), torch_dtype=torch.bfloat16
|
| 320 |
+
).to("cuda")
|
| 321 |
+
out = pipe(
|
| 322 |
+
prompt="a dog running on the grass",
|
| 323 |
+
num_inference_steps=4,
|
| 324 |
+
height=1024,
|
| 325 |
+
width=1024,
|
| 326 |
+
generator=torch.Generator("cpu").manual_seed(0),
|
| 327 |
+
output_type="np",
|
| 328 |
+
).images
|
| 329 |
+
|
| 330 |
+
self.assertEqual(out.shape, (1, 1024, 1024, 3))
|
| 331 |
+
self.assertFalse(np.isnan(out).any())
|
| 332 |
+
|
| 333 |
+
def test_mobile_i2i_real_checkpoint(self):
|
| 334 |
+
pipe = DreamLiteMobilePipeline.from_pretrained(
|
| 335 |
+
**self._from_pretrained_kwargs(), torch_dtype=torch.bfloat16
|
| 336 |
+
).to("cuda")
|
| 337 |
+
|
| 338 |
+
src = Image.fromarray((np.random.RandomState(0).rand(1024, 1024, 3) * 255).astype(np.uint8))
|
| 339 |
+
out = pipe(
|
| 340 |
+
prompt="make it look like a painting",
|
| 341 |
+
image=src,
|
| 342 |
+
num_inference_steps=4,
|
| 343 |
+
height=1024,
|
| 344 |
+
width=1024,
|
| 345 |
+
generator=torch.Generator("cpu").manual_seed(0),
|
| 346 |
+
output_type="np",
|
| 347 |
+
).images
|
| 348 |
+
|
| 349 |
+
self.assertEqual(out.shape, (1, 1024, 1024, 3))
|
| 350 |
+
self.assertFalse(np.isnan(out).any())
|
| 351 |
+
|
| 352 |
+
|
| 353 |
+
if __name__ == "__main__":
|
| 354 |
+
unittest.main()
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/easyanimate/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/easyanimate/test_easyanimate.py
ADDED
|
@@ -0,0 +1,296 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 30 |
+
from ...testing_utils import (
|
| 31 |
+
backend_empty_cache,
|
| 32 |
+
enable_full_determinism,
|
| 33 |
+
numpy_cosine_similarity_distance,
|
| 34 |
+
require_torch_accelerator,
|
| 35 |
+
slow,
|
| 36 |
+
torch_device,
|
| 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 |
+
test_xformers_attention = False
|
| 52 |
+
required_optional_params = frozenset(
|
| 53 |
+
[
|
| 54 |
+
"num_inference_steps",
|
| 55 |
+
"generator",
|
| 56 |
+
"latents",
|
| 57 |
+
"return_dict",
|
| 58 |
+
"callback_on_step_end",
|
| 59 |
+
"callback_on_step_end_tensor_inputs",
|
| 60 |
+
]
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
supports_dduf = False
|
| 64 |
+
|
| 65 |
+
def get_dummy_components(self):
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
transformer = EasyAnimateTransformer3DModel(
|
| 68 |
+
num_attention_heads=2,
|
| 69 |
+
attention_head_dim=16,
|
| 70 |
+
in_channels=4,
|
| 71 |
+
out_channels=4,
|
| 72 |
+
time_embed_dim=2,
|
| 73 |
+
text_embed_dim=16, # Must match with tiny-random-t5
|
| 74 |
+
num_layers=1,
|
| 75 |
+
sample_width=16, # latent width: 2 -> final width: 16
|
| 76 |
+
sample_height=16, # latent height: 2 -> final height: 16
|
| 77 |
+
patch_size=2,
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
torch.manual_seed(0)
|
| 81 |
+
vae = AutoencoderKLMagvit(
|
| 82 |
+
in_channels=3,
|
| 83 |
+
out_channels=3,
|
| 84 |
+
down_block_types=(
|
| 85 |
+
"SpatialDownBlock3D",
|
| 86 |
+
"SpatialTemporalDownBlock3D",
|
| 87 |
+
"SpatialTemporalDownBlock3D",
|
| 88 |
+
"SpatialTemporalDownBlock3D",
|
| 89 |
+
),
|
| 90 |
+
up_block_types=(
|
| 91 |
+
"SpatialUpBlock3D",
|
| 92 |
+
"SpatialTemporalUpBlock3D",
|
| 93 |
+
"SpatialTemporalUpBlock3D",
|
| 94 |
+
"SpatialTemporalUpBlock3D",
|
| 95 |
+
),
|
| 96 |
+
block_out_channels=(8, 8, 8, 8),
|
| 97 |
+
latent_channels=4,
|
| 98 |
+
layers_per_block=1,
|
| 99 |
+
norm_num_groups=2,
|
| 100 |
+
spatial_group_norm=False,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
torch.manual_seed(0)
|
| 104 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 105 |
+
text_encoder = Qwen2VLForConditionalGeneration.from_pretrained(
|
| 106 |
+
"hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"
|
| 107 |
+
)
|
| 108 |
+
tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 109 |
+
|
| 110 |
+
components = {
|
| 111 |
+
"transformer": transformer,
|
| 112 |
+
"vae": vae,
|
| 113 |
+
"scheduler": scheduler,
|
| 114 |
+
"text_encoder": text_encoder,
|
| 115 |
+
"tokenizer": tokenizer,
|
| 116 |
+
}
|
| 117 |
+
return components
|
| 118 |
+
|
| 119 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 120 |
+
if str(device).startswith("mps"):
|
| 121 |
+
generator = torch.manual_seed(seed)
|
| 122 |
+
else:
|
| 123 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 124 |
+
inputs = {
|
| 125 |
+
"prompt": "dance monkey",
|
| 126 |
+
"negative_prompt": "",
|
| 127 |
+
"generator": generator,
|
| 128 |
+
"num_inference_steps": 2,
|
| 129 |
+
"guidance_scale": 6.0,
|
| 130 |
+
"height": 16,
|
| 131 |
+
"width": 16,
|
| 132 |
+
"num_frames": 5,
|
| 133 |
+
"output_type": "pt",
|
| 134 |
+
}
|
| 135 |
+
return inputs
|
| 136 |
+
|
| 137 |
+
def test_inference(self):
|
| 138 |
+
device = "cpu"
|
| 139 |
+
|
| 140 |
+
components = self.get_dummy_components()
|
| 141 |
+
pipe = self.pipeline_class(**components)
|
| 142 |
+
pipe.to(device)
|
| 143 |
+
pipe.set_progress_bar_config(disable=None)
|
| 144 |
+
|
| 145 |
+
inputs = self.get_dummy_inputs(device)
|
| 146 |
+
video = pipe(**inputs).frames
|
| 147 |
+
generated_video = video[0]
|
| 148 |
+
|
| 149 |
+
self.assertEqual(generated_video.shape, (5, 3, 16, 16))
|
| 150 |
+
expected_video = torch.randn(5, 3, 16, 16)
|
| 151 |
+
max_diff = np.abs(generated_video - expected_video).max()
|
| 152 |
+
self.assertLessEqual(max_diff, 1e10)
|
| 153 |
+
|
| 154 |
+
def test_callback_inputs(self):
|
| 155 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 156 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 157 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 158 |
+
|
| 159 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 160 |
+
return
|
| 161 |
+
|
| 162 |
+
components = self.get_dummy_components()
|
| 163 |
+
pipe = self.pipeline_class(**components)
|
| 164 |
+
pipe = pipe.to(torch_device)
|
| 165 |
+
pipe.set_progress_bar_config(disable=None)
|
| 166 |
+
self.assertTrue(
|
| 167 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 168 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 172 |
+
# iterate over callback args
|
| 173 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 174 |
+
# check that we're only passing in allowed tensor inputs
|
| 175 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 176 |
+
|
| 177 |
+
return callback_kwargs
|
| 178 |
+
|
| 179 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 180 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 181 |
+
assert tensor_name in callback_kwargs
|
| 182 |
+
|
| 183 |
+
# iterate over callback args
|
| 184 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 185 |
+
# check that we're only passing in allowed tensor inputs
|
| 186 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 187 |
+
|
| 188 |
+
return callback_kwargs
|
| 189 |
+
|
| 190 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 191 |
+
|
| 192 |
+
# Test passing in a subset
|
| 193 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 194 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 195 |
+
output = pipe(**inputs)[0]
|
| 196 |
+
|
| 197 |
+
# Test passing in a everything
|
| 198 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 199 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 200 |
+
output = pipe(**inputs)[0]
|
| 201 |
+
|
| 202 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 203 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 204 |
+
if is_last:
|
| 205 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 206 |
+
return callback_kwargs
|
| 207 |
+
|
| 208 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 209 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 210 |
+
output = pipe(**inputs)[0]
|
| 211 |
+
assert output.abs().sum() < 1e10
|
| 212 |
+
|
| 213 |
+
def test_inference_batch_single_identical(self):
|
| 214 |
+
self._test_inference_batch_single_identical(batch_size=3, expected_max_diff=1e-3)
|
| 215 |
+
|
| 216 |
+
def test_attention_slicing_forward_pass(
|
| 217 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 218 |
+
):
|
| 219 |
+
if not self.test_attention_slicing:
|
| 220 |
+
return
|
| 221 |
+
|
| 222 |
+
components = self.get_dummy_components()
|
| 223 |
+
pipe = self.pipeline_class(**components)
|
| 224 |
+
for component in pipe.components.values():
|
| 225 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 226 |
+
component.set_default_attn_processor()
|
| 227 |
+
pipe.to(torch_device)
|
| 228 |
+
pipe.set_progress_bar_config(disable=None)
|
| 229 |
+
|
| 230 |
+
generator_device = "cpu"
|
| 231 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 232 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 233 |
+
|
| 234 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 235 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 236 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 237 |
+
|
| 238 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 239 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 240 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 241 |
+
|
| 242 |
+
if test_max_difference:
|
| 243 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 244 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 245 |
+
self.assertLess(
|
| 246 |
+
max(max_diff1, max_diff2),
|
| 247 |
+
expected_max_diff,
|
| 248 |
+
"Attention slicing should not affect the inference results",
|
| 249 |
+
)
|
| 250 |
+
|
| 251 |
+
def test_dict_tuple_outputs_equivalent(self, expected_slice=None, expected_max_difference=0.001):
|
| 252 |
+
# Seems to need a higher tolerance
|
| 253 |
+
return super().test_dict_tuple_outputs_equivalent(expected_slice, expected_max_difference)
|
| 254 |
+
|
| 255 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 256 |
+
# Seems to need a higher tolerance
|
| 257 |
+
return super().test_encode_prompt_works_in_isolation(atol=1e-3, rtol=1e-3)
|
| 258 |
+
|
| 259 |
+
|
| 260 |
+
@slow
|
| 261 |
+
@require_torch_accelerator
|
| 262 |
+
class EasyAnimatePipelineIntegrationTests(unittest.TestCase):
|
| 263 |
+
prompt = "A painting of a squirrel eating a burger."
|
| 264 |
+
|
| 265 |
+
def setUp(self):
|
| 266 |
+
super().setUp()
|
| 267 |
+
gc.collect()
|
| 268 |
+
backend_empty_cache(torch_device)
|
| 269 |
+
|
| 270 |
+
def tearDown(self):
|
| 271 |
+
super().tearDown()
|
| 272 |
+
gc.collect()
|
| 273 |
+
backend_empty_cache(torch_device)
|
| 274 |
+
|
| 275 |
+
def test_EasyAnimate(self):
|
| 276 |
+
generator = torch.Generator("cpu").manual_seed(0)
|
| 277 |
+
|
| 278 |
+
pipe = EasyAnimatePipeline.from_pretrained("alibaba-pai/EasyAnimateV5.1-12b-zh", torch_dtype=torch.float16)
|
| 279 |
+
pipe.enable_model_cpu_offload()
|
| 280 |
+
prompt = self.prompt
|
| 281 |
+
|
| 282 |
+
videos = pipe(
|
| 283 |
+
prompt=prompt,
|
| 284 |
+
height=480,
|
| 285 |
+
width=720,
|
| 286 |
+
num_frames=5,
|
| 287 |
+
generator=generator,
|
| 288 |
+
num_inference_steps=2,
|
| 289 |
+
output_type="pt",
|
| 290 |
+
).frames
|
| 291 |
+
|
| 292 |
+
video = videos[0]
|
| 293 |
+
expected_video = torch.randn(1, 5, 480, 720, 3).numpy()
|
| 294 |
+
|
| 295 |
+
max_diff = numpy_cosine_similarity_distance(video, expected_video)
|
| 296 |
+
assert max_diff < 1e-3, f"Max diff is too high. got {video}"
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux.py
ADDED
|
@@ -0,0 +1,378 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from huggingface_hub import hf_hub_download
|
| 7 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 8 |
+
|
| 9 |
+
from diffusers import (
|
| 10 |
+
AutoencoderKL,
|
| 11 |
+
FasterCacheConfig,
|
| 12 |
+
FlowMatchEulerDiscreteScheduler,
|
| 13 |
+
FluxPipeline,
|
| 14 |
+
FluxTransformer2DModel,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from ...testing_utils import (
|
| 18 |
+
Expectations,
|
| 19 |
+
backend_empty_cache,
|
| 20 |
+
nightly,
|
| 21 |
+
numpy_cosine_similarity_distance,
|
| 22 |
+
require_big_accelerator,
|
| 23 |
+
slow,
|
| 24 |
+
torch_device,
|
| 25 |
+
)
|
| 26 |
+
from ..test_pipelines_common import (
|
| 27 |
+
FasterCacheTesterMixin,
|
| 28 |
+
FirstBlockCacheTesterMixin,
|
| 29 |
+
FluxIPAdapterTesterMixin,
|
| 30 |
+
MagCacheTesterMixin,
|
| 31 |
+
PipelineTesterMixin,
|
| 32 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 33 |
+
TaylorSeerCacheTesterMixin,
|
| 34 |
+
check_qkv_fused_layers_exist,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
class FluxPipelineFastTests(
|
| 39 |
+
PipelineTesterMixin,
|
| 40 |
+
FluxIPAdapterTesterMixin,
|
| 41 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 42 |
+
FasterCacheTesterMixin,
|
| 43 |
+
FirstBlockCacheTesterMixin,
|
| 44 |
+
TaylorSeerCacheTesterMixin,
|
| 45 |
+
MagCacheTesterMixin,
|
| 46 |
+
unittest.TestCase,
|
| 47 |
+
):
|
| 48 |
+
pipeline_class = FluxPipeline
|
| 49 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 50 |
+
batch_params = frozenset(["prompt"])
|
| 51 |
+
|
| 52 |
+
# there is no xformers processor for Flux
|
| 53 |
+
test_xformers_attention = False
|
| 54 |
+
test_layerwise_casting = True
|
| 55 |
+
test_group_offloading = True
|
| 56 |
+
|
| 57 |
+
faster_cache_config = FasterCacheConfig(
|
| 58 |
+
spatial_attention_block_skip_range=2,
|
| 59 |
+
spatial_attention_timestep_skip_range=(-1, 901),
|
| 60 |
+
unconditional_batch_skip_range=2,
|
| 61 |
+
attention_weight_callback=lambda _: 0.5,
|
| 62 |
+
is_guidance_distilled=True,
|
| 63 |
+
)
|
| 64 |
+
|
| 65 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
transformer = FluxTransformer2DModel(
|
| 68 |
+
patch_size=1,
|
| 69 |
+
in_channels=4,
|
| 70 |
+
num_layers=num_layers,
|
| 71 |
+
num_single_layers=num_single_layers,
|
| 72 |
+
attention_head_dim=16,
|
| 73 |
+
num_attention_heads=2,
|
| 74 |
+
joint_attention_dim=32,
|
| 75 |
+
pooled_projection_dim=32,
|
| 76 |
+
axes_dims_rope=[4, 4, 8],
|
| 77 |
+
)
|
| 78 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 79 |
+
bos_token_id=0,
|
| 80 |
+
eos_token_id=2,
|
| 81 |
+
hidden_size=32,
|
| 82 |
+
intermediate_size=37,
|
| 83 |
+
layer_norm_eps=1e-05,
|
| 84 |
+
num_attention_heads=4,
|
| 85 |
+
num_hidden_layers=5,
|
| 86 |
+
pad_token_id=1,
|
| 87 |
+
vocab_size=1000,
|
| 88 |
+
hidden_act="gelu",
|
| 89 |
+
projection_dim=32,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
torch.manual_seed(0)
|
| 93 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 94 |
+
|
| 95 |
+
torch.manual_seed(0)
|
| 96 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 97 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 98 |
+
|
| 99 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 100 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 101 |
+
|
| 102 |
+
torch.manual_seed(0)
|
| 103 |
+
vae = AutoencoderKL(
|
| 104 |
+
sample_size=32,
|
| 105 |
+
in_channels=3,
|
| 106 |
+
out_channels=3,
|
| 107 |
+
block_out_channels=(4,),
|
| 108 |
+
layers_per_block=1,
|
| 109 |
+
latent_channels=1,
|
| 110 |
+
norm_num_groups=1,
|
| 111 |
+
use_quant_conv=False,
|
| 112 |
+
use_post_quant_conv=False,
|
| 113 |
+
shift_factor=0.0609,
|
| 114 |
+
scaling_factor=1.5035,
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 118 |
+
|
| 119 |
+
return {
|
| 120 |
+
"scheduler": scheduler,
|
| 121 |
+
"text_encoder": text_encoder,
|
| 122 |
+
"text_encoder_2": text_encoder_2,
|
| 123 |
+
"tokenizer": tokenizer,
|
| 124 |
+
"tokenizer_2": tokenizer_2,
|
| 125 |
+
"transformer": transformer,
|
| 126 |
+
"vae": vae,
|
| 127 |
+
"image_encoder": None,
|
| 128 |
+
"feature_extractor": None,
|
| 129 |
+
}
|
| 130 |
+
|
| 131 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 132 |
+
if str(device).startswith("mps"):
|
| 133 |
+
generator = torch.manual_seed(seed)
|
| 134 |
+
else:
|
| 135 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 136 |
+
|
| 137 |
+
inputs = {
|
| 138 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 139 |
+
"generator": generator,
|
| 140 |
+
"num_inference_steps": 2,
|
| 141 |
+
"guidance_scale": 5.0,
|
| 142 |
+
"height": 8,
|
| 143 |
+
"width": 8,
|
| 144 |
+
"max_sequence_length": 48,
|
| 145 |
+
"output_type": "np",
|
| 146 |
+
}
|
| 147 |
+
return inputs
|
| 148 |
+
|
| 149 |
+
def test_flux_different_prompts(self):
|
| 150 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 151 |
+
|
| 152 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 153 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 154 |
+
|
| 155 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 156 |
+
inputs["prompt_2"] = "a different prompt"
|
| 157 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 158 |
+
|
| 159 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 160 |
+
|
| 161 |
+
# Outputs should be different here
|
| 162 |
+
# For some reasons, they don't show large differences
|
| 163 |
+
self.assertGreater(max_diff, 1e-6, "Outputs should be different for different prompts.")
|
| 164 |
+
|
| 165 |
+
def test_fused_qkv_projections(self):
|
| 166 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 167 |
+
components = self.get_dummy_components()
|
| 168 |
+
pipe = self.pipeline_class(**components)
|
| 169 |
+
pipe = pipe.to(device)
|
| 170 |
+
pipe.set_progress_bar_config(disable=None)
|
| 171 |
+
|
| 172 |
+
inputs = self.get_dummy_inputs(device)
|
| 173 |
+
image = pipe(**inputs).images
|
| 174 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 175 |
+
|
| 176 |
+
# TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
|
| 177 |
+
# to the pipeline level.
|
| 178 |
+
pipe.transformer.fuse_qkv_projections()
|
| 179 |
+
self.assertTrue(
|
| 180 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 181 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 182 |
+
)
|
| 183 |
+
|
| 184 |
+
inputs = self.get_dummy_inputs(device)
|
| 185 |
+
image = pipe(**inputs).images
|
| 186 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 187 |
+
|
| 188 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 189 |
+
inputs = self.get_dummy_inputs(device)
|
| 190 |
+
image = pipe(**inputs).images
|
| 191 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 192 |
+
|
| 193 |
+
self.assertTrue(
|
| 194 |
+
np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3),
|
| 195 |
+
("Fusion of QKV projections shouldn't affect the outputs."),
|
| 196 |
+
)
|
| 197 |
+
self.assertTrue(
|
| 198 |
+
np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3),
|
| 199 |
+
("Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."),
|
| 200 |
+
)
|
| 201 |
+
self.assertTrue(
|
| 202 |
+
np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2),
|
| 203 |
+
("Original outputs should match when fused QKV projections are disabled."),
|
| 204 |
+
)
|
| 205 |
+
|
| 206 |
+
def test_flux_image_output_shape(self):
|
| 207 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 208 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 209 |
+
|
| 210 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 211 |
+
for height, width in height_width_pairs:
|
| 212 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 213 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 214 |
+
|
| 215 |
+
inputs.update({"height": height, "width": width})
|
| 216 |
+
image = pipe(**inputs).images[0]
|
| 217 |
+
output_height, output_width, _ = image.shape
|
| 218 |
+
self.assertEqual(
|
| 219 |
+
(output_height, output_width),
|
| 220 |
+
(expected_height, expected_width),
|
| 221 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
|
| 222 |
+
)
|
| 223 |
+
|
| 224 |
+
def test_flux_true_cfg(self):
|
| 225 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 226 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 227 |
+
inputs.pop("generator")
|
| 228 |
+
|
| 229 |
+
no_true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 230 |
+
inputs["negative_prompt"] = "bad quality"
|
| 231 |
+
inputs["true_cfg_scale"] = 2.0
|
| 232 |
+
true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 233 |
+
self.assertFalse(
|
| 234 |
+
np.allclose(no_true_cfg_out, true_cfg_out), "Outputs should be different when true_cfg_scale is set."
|
| 235 |
+
)
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
@nightly
|
| 239 |
+
@require_big_accelerator
|
| 240 |
+
class FluxPipelineSlowTests(unittest.TestCase):
|
| 241 |
+
pipeline_class = FluxPipeline
|
| 242 |
+
repo_id = "black-forest-labs/FLUX.1-schnell"
|
| 243 |
+
|
| 244 |
+
def setUp(self):
|
| 245 |
+
super().setUp()
|
| 246 |
+
gc.collect()
|
| 247 |
+
backend_empty_cache(torch_device)
|
| 248 |
+
|
| 249 |
+
def tearDown(self):
|
| 250 |
+
super().tearDown()
|
| 251 |
+
gc.collect()
|
| 252 |
+
backend_empty_cache(torch_device)
|
| 253 |
+
|
| 254 |
+
def get_inputs(self, device, seed=0):
|
| 255 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 256 |
+
|
| 257 |
+
prompt_embeds = torch.load(
|
| 258 |
+
hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
|
| 259 |
+
).to(torch_device)
|
| 260 |
+
pooled_prompt_embeds = torch.load(
|
| 261 |
+
hf_hub_download(
|
| 262 |
+
repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
|
| 263 |
+
)
|
| 264 |
+
).to(torch_device)
|
| 265 |
+
return {
|
| 266 |
+
"prompt_embeds": prompt_embeds,
|
| 267 |
+
"pooled_prompt_embeds": pooled_prompt_embeds,
|
| 268 |
+
"num_inference_steps": 2,
|
| 269 |
+
"guidance_scale": 0.0,
|
| 270 |
+
"max_sequence_length": 256,
|
| 271 |
+
"output_type": "np",
|
| 272 |
+
"generator": generator,
|
| 273 |
+
}
|
| 274 |
+
|
| 275 |
+
def test_flux_inference(self):
|
| 276 |
+
pipe = self.pipeline_class.from_pretrained(
|
| 277 |
+
self.repo_id, torch_dtype=torch.bfloat16, text_encoder=None, text_encoder_2=None
|
| 278 |
+
).to(torch_device)
|
| 279 |
+
|
| 280 |
+
inputs = self.get_inputs(torch_device)
|
| 281 |
+
|
| 282 |
+
image = pipe(**inputs).images[0]
|
| 283 |
+
image_slice = image[0, :10, :10]
|
| 284 |
+
# fmt: off
|
| 285 |
+
|
| 286 |
+
expected_slices = Expectations(
|
| 287 |
+
{
|
| 288 |
+
("cuda", None): np.array([0.3242, 0.3203, 0.3164, 0.3164, 0.3125, 0.3125, 0.3281, 0.3242, 0.3203, 0.3301, 0.3262, 0.3242, 0.3281, 0.3242, 0.3203, 0.3262, 0.3262, 0.3164, 0.3262, 0.3281, 0.3184, 0.3281, 0.3281, 0.3203, 0.3281, 0.3281, 0.3164, 0.3320, 0.3320, 0.3203], dtype=np.float32,),
|
| 289 |
+
("xpu", 3): np.array([0.3301, 0.3281, 0.3359, 0.3203, 0.3203, 0.3281, 0.3281, 0.3301, 0.3340, 0.3281, 0.3320, 0.3359, 0.3281, 0.3301, 0.3320, 0.3242, 0.3301, 0.3281, 0.3242, 0.3320, 0.3320, 0.3281, 0.3320, 0.3320, 0.3262, 0.3320, 0.3301, 0.3301, 0.3359, 0.3320], dtype=np.float32,),
|
| 290 |
+
}
|
| 291 |
+
)
|
| 292 |
+
expected_slice = expected_slices.get_expectation()
|
| 293 |
+
# fmt: on
|
| 294 |
+
|
| 295 |
+
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
|
| 296 |
+
self.assertLess(
|
| 297 |
+
max_diff, 1e-4, f"Image slice is different from expected slice: {image_slice} != {expected_slice}"
|
| 298 |
+
)
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
@slow
|
| 302 |
+
@require_big_accelerator
|
| 303 |
+
class FluxIPAdapterPipelineSlowTests(unittest.TestCase):
|
| 304 |
+
pipeline_class = FluxPipeline
|
| 305 |
+
repo_id = "black-forest-labs/FLUX.1-dev"
|
| 306 |
+
image_encoder_pretrained_model_name_or_path = "openai/clip-vit-large-patch14"
|
| 307 |
+
weight_name = "ip_adapter.safetensors"
|
| 308 |
+
ip_adapter_repo_id = "XLabs-AI/flux-ip-adapter"
|
| 309 |
+
|
| 310 |
+
def setUp(self):
|
| 311 |
+
super().setUp()
|
| 312 |
+
gc.collect()
|
| 313 |
+
backend_empty_cache(torch_device)
|
| 314 |
+
|
| 315 |
+
def tearDown(self):
|
| 316 |
+
super().tearDown()
|
| 317 |
+
gc.collect()
|
| 318 |
+
backend_empty_cache(torch_device)
|
| 319 |
+
|
| 320 |
+
def get_inputs(self, device, seed=0):
|
| 321 |
+
if str(device).startswith("mps"):
|
| 322 |
+
generator = torch.manual_seed(seed)
|
| 323 |
+
else:
|
| 324 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 325 |
+
|
| 326 |
+
prompt_embeds = torch.load(
|
| 327 |
+
hf_hub_download(repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/prompt_embeds.pt")
|
| 328 |
+
)
|
| 329 |
+
pooled_prompt_embeds = torch.load(
|
| 330 |
+
hf_hub_download(
|
| 331 |
+
repo_id="diffusers/test-slices", repo_type="dataset", filename="flux/pooled_prompt_embeds.pt"
|
| 332 |
+
)
|
| 333 |
+
)
|
| 334 |
+
negative_prompt_embeds = torch.zeros_like(prompt_embeds)
|
| 335 |
+
negative_pooled_prompt_embeds = torch.zeros_like(pooled_prompt_embeds)
|
| 336 |
+
ip_adapter_image = np.zeros((1024, 1024, 3), dtype=np.uint8)
|
| 337 |
+
return {
|
| 338 |
+
"prompt_embeds": prompt_embeds,
|
| 339 |
+
"pooled_prompt_embeds": pooled_prompt_embeds,
|
| 340 |
+
"negative_prompt_embeds": negative_prompt_embeds,
|
| 341 |
+
"negative_pooled_prompt_embeds": negative_pooled_prompt_embeds,
|
| 342 |
+
"ip_adapter_image": ip_adapter_image,
|
| 343 |
+
"num_inference_steps": 2,
|
| 344 |
+
"guidance_scale": 3.5,
|
| 345 |
+
"true_cfg_scale": 4.0,
|
| 346 |
+
"max_sequence_length": 256,
|
| 347 |
+
"output_type": "np",
|
| 348 |
+
"generator": generator,
|
| 349 |
+
}
|
| 350 |
+
|
| 351 |
+
def test_flux_ip_adapter_inference(self):
|
| 352 |
+
pipe = self.pipeline_class.from_pretrained(
|
| 353 |
+
self.repo_id, torch_dtype=torch.bfloat16, text_encoder=None, text_encoder_2=None
|
| 354 |
+
)
|
| 355 |
+
pipe.load_ip_adapter(
|
| 356 |
+
self.ip_adapter_repo_id,
|
| 357 |
+
weight_name=self.weight_name,
|
| 358 |
+
image_encoder_pretrained_model_name_or_path=self.image_encoder_pretrained_model_name_or_path,
|
| 359 |
+
)
|
| 360 |
+
pipe.set_ip_adapter_scale(1.0)
|
| 361 |
+
pipe.enable_model_cpu_offload()
|
| 362 |
+
|
| 363 |
+
inputs = self.get_inputs(torch_device)
|
| 364 |
+
|
| 365 |
+
image = pipe(**inputs).images[0]
|
| 366 |
+
image_slice = image[0, :10, :10]
|
| 367 |
+
|
| 368 |
+
# fmt: off
|
| 369 |
+
expected_slice = np.array(
|
| 370 |
+
[0.1855, 0.1680, 0.1406, 0.1953, 0.1699, 0.1465, 0.2012, 0.1738, 0.1484, 0.2051, 0.1797, 0.1523, 0.2012, 0.1719, 0.1445, 0.2070, 0.1777, 0.1465, 0.2090, 0.1836, 0.1484, 0.2129, 0.1875, 0.1523, 0.2090, 0.1816, 0.1484, 0.2110, 0.1836, 0.1543],
|
| 371 |
+
dtype=np.float32,
|
| 372 |
+
)
|
| 373 |
+
# fmt: on
|
| 374 |
+
|
| 375 |
+
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
|
| 376 |
+
self.assertLess(
|
| 377 |
+
max_diff, 1e-4, f"Image slice is different from expected slice: {image_slice} != {expected_slice}"
|
| 378 |
+
)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control.py
ADDED
|
@@ -0,0 +1,176 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxControlPipeline, FluxTransformer2DModel
|
| 9 |
+
|
| 10 |
+
from ...testing_utils import torch_device
|
| 11 |
+
from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
|
| 12 |
+
|
| 13 |
+
|
| 14 |
+
class FluxControlPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 15 |
+
pipeline_class = FluxControlPipeline
|
| 16 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 17 |
+
batch_params = frozenset(["prompt"])
|
| 18 |
+
|
| 19 |
+
# there is no xformers processor for Flux
|
| 20 |
+
test_xformers_attention = False
|
| 21 |
+
test_layerwise_casting = True
|
| 22 |
+
test_group_offloading = True
|
| 23 |
+
|
| 24 |
+
def get_dummy_components(self):
|
| 25 |
+
torch.manual_seed(0)
|
| 26 |
+
transformer = FluxTransformer2DModel(
|
| 27 |
+
patch_size=1,
|
| 28 |
+
in_channels=8,
|
| 29 |
+
out_channels=4,
|
| 30 |
+
num_layers=1,
|
| 31 |
+
num_single_layers=1,
|
| 32 |
+
attention_head_dim=16,
|
| 33 |
+
num_attention_heads=2,
|
| 34 |
+
joint_attention_dim=32,
|
| 35 |
+
pooled_projection_dim=32,
|
| 36 |
+
axes_dims_rope=[4, 4, 8],
|
| 37 |
+
)
|
| 38 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 39 |
+
bos_token_id=0,
|
| 40 |
+
eos_token_id=2,
|
| 41 |
+
hidden_size=32,
|
| 42 |
+
intermediate_size=37,
|
| 43 |
+
layer_norm_eps=1e-05,
|
| 44 |
+
num_attention_heads=4,
|
| 45 |
+
num_hidden_layers=5,
|
| 46 |
+
pad_token_id=1,
|
| 47 |
+
vocab_size=1000,
|
| 48 |
+
hidden_act="gelu",
|
| 49 |
+
projection_dim=32,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
torch.manual_seed(0)
|
| 53 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 54 |
+
|
| 55 |
+
torch.manual_seed(0)
|
| 56 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 57 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 58 |
+
|
| 59 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 60 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 61 |
+
|
| 62 |
+
torch.manual_seed(0)
|
| 63 |
+
vae = AutoencoderKL(
|
| 64 |
+
sample_size=32,
|
| 65 |
+
in_channels=3,
|
| 66 |
+
out_channels=3,
|
| 67 |
+
block_out_channels=(4,),
|
| 68 |
+
layers_per_block=1,
|
| 69 |
+
latent_channels=1,
|
| 70 |
+
norm_num_groups=1,
|
| 71 |
+
use_quant_conv=False,
|
| 72 |
+
use_post_quant_conv=False,
|
| 73 |
+
shift_factor=0.0609,
|
| 74 |
+
scaling_factor=1.5035,
|
| 75 |
+
)
|
| 76 |
+
|
| 77 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 78 |
+
|
| 79 |
+
return {
|
| 80 |
+
"scheduler": scheduler,
|
| 81 |
+
"text_encoder": text_encoder,
|
| 82 |
+
"text_encoder_2": text_encoder_2,
|
| 83 |
+
"tokenizer": tokenizer,
|
| 84 |
+
"tokenizer_2": tokenizer_2,
|
| 85 |
+
"transformer": transformer,
|
| 86 |
+
"vae": vae,
|
| 87 |
+
}
|
| 88 |
+
|
| 89 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 90 |
+
if str(device).startswith("mps"):
|
| 91 |
+
generator = torch.manual_seed(seed)
|
| 92 |
+
else:
|
| 93 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 94 |
+
|
| 95 |
+
control_image = Image.new("RGB", (16, 16), 0)
|
| 96 |
+
|
| 97 |
+
inputs = {
|
| 98 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 99 |
+
"control_image": control_image,
|
| 100 |
+
"generator": generator,
|
| 101 |
+
"num_inference_steps": 2,
|
| 102 |
+
"guidance_scale": 5.0,
|
| 103 |
+
"height": 8,
|
| 104 |
+
"width": 8,
|
| 105 |
+
"max_sequence_length": 48,
|
| 106 |
+
"output_type": "np",
|
| 107 |
+
}
|
| 108 |
+
return inputs
|
| 109 |
+
|
| 110 |
+
def test_flux_different_prompts(self):
|
| 111 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 112 |
+
|
| 113 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 114 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 115 |
+
|
| 116 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 117 |
+
inputs["prompt_2"] = "a different prompt"
|
| 118 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 119 |
+
|
| 120 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 121 |
+
|
| 122 |
+
# Outputs should be different here
|
| 123 |
+
# For some reasons, they don't show large differences
|
| 124 |
+
assert max_diff > 1e-6
|
| 125 |
+
|
| 126 |
+
def test_fused_qkv_projections(self):
|
| 127 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 128 |
+
components = self.get_dummy_components()
|
| 129 |
+
pipe = self.pipeline_class(**components)
|
| 130 |
+
pipe = pipe.to(device)
|
| 131 |
+
pipe.set_progress_bar_config(disable=None)
|
| 132 |
+
|
| 133 |
+
inputs = self.get_dummy_inputs(device)
|
| 134 |
+
image = pipe(**inputs).images
|
| 135 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 136 |
+
|
| 137 |
+
# TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
|
| 138 |
+
# to the pipeline level.
|
| 139 |
+
pipe.transformer.fuse_qkv_projections()
|
| 140 |
+
self.assertTrue(
|
| 141 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 142 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 143 |
+
)
|
| 144 |
+
|
| 145 |
+
inputs = self.get_dummy_inputs(device)
|
| 146 |
+
image = pipe(**inputs).images
|
| 147 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 148 |
+
|
| 149 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 150 |
+
inputs = self.get_dummy_inputs(device)
|
| 151 |
+
image = pipe(**inputs).images
|
| 152 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 153 |
+
|
| 154 |
+
assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
|
| 155 |
+
"Fusion of QKV projections shouldn't affect the outputs."
|
| 156 |
+
)
|
| 157 |
+
assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
|
| 158 |
+
"Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
|
| 159 |
+
)
|
| 160 |
+
assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
|
| 161 |
+
"Original outputs should match when fused QKV projections are disabled."
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def test_flux_image_output_shape(self):
|
| 165 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 166 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 167 |
+
|
| 168 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 169 |
+
for height, width in height_width_pairs:
|
| 170 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 171 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 172 |
+
|
| 173 |
+
inputs.update({"height": height, "width": width})
|
| 174 |
+
image = pipe(**inputs).images[0]
|
| 175 |
+
output_height, output_width, _ = image.shape
|
| 176 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control_img2img.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKL,
|
| 10 |
+
FlowMatchEulerDiscreteScheduler,
|
| 11 |
+
FluxControlImg2ImgPipeline,
|
| 12 |
+
FluxTransformer2DModel,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from ...testing_utils import enable_full_determinism, torch_device
|
| 16 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
enable_full_determinism()
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
class FluxControlImg2ImgPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 23 |
+
pipeline_class = FluxControlImg2ImgPipeline
|
| 24 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 25 |
+
batch_params = frozenset(["prompt"])
|
| 26 |
+
test_xformers_attention = False
|
| 27 |
+
|
| 28 |
+
def get_dummy_components(self):
|
| 29 |
+
torch.manual_seed(0)
|
| 30 |
+
transformer = FluxTransformer2DModel(
|
| 31 |
+
patch_size=1,
|
| 32 |
+
in_channels=8,
|
| 33 |
+
out_channels=4,
|
| 34 |
+
num_layers=1,
|
| 35 |
+
num_single_layers=1,
|
| 36 |
+
attention_head_dim=16,
|
| 37 |
+
num_attention_heads=2,
|
| 38 |
+
joint_attention_dim=32,
|
| 39 |
+
pooled_projection_dim=32,
|
| 40 |
+
axes_dims_rope=[4, 4, 8],
|
| 41 |
+
)
|
| 42 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 43 |
+
bos_token_id=0,
|
| 44 |
+
eos_token_id=2,
|
| 45 |
+
hidden_size=32,
|
| 46 |
+
intermediate_size=37,
|
| 47 |
+
layer_norm_eps=1e-05,
|
| 48 |
+
num_attention_heads=4,
|
| 49 |
+
num_hidden_layers=5,
|
| 50 |
+
pad_token_id=1,
|
| 51 |
+
vocab_size=1000,
|
| 52 |
+
hidden_act="gelu",
|
| 53 |
+
projection_dim=32,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
torch.manual_seed(0)
|
| 57 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 58 |
+
|
| 59 |
+
torch.manual_seed(0)
|
| 60 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 61 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 62 |
+
|
| 63 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 64 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 65 |
+
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
vae = AutoencoderKL(
|
| 68 |
+
sample_size=32,
|
| 69 |
+
in_channels=3,
|
| 70 |
+
out_channels=3,
|
| 71 |
+
block_out_channels=(4,),
|
| 72 |
+
layers_per_block=1,
|
| 73 |
+
latent_channels=1,
|
| 74 |
+
norm_num_groups=1,
|
| 75 |
+
use_quant_conv=False,
|
| 76 |
+
use_post_quant_conv=False,
|
| 77 |
+
shift_factor=0.0609,
|
| 78 |
+
scaling_factor=1.5035,
|
| 79 |
+
)
|
| 80 |
+
|
| 81 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 82 |
+
|
| 83 |
+
return {
|
| 84 |
+
"scheduler": scheduler,
|
| 85 |
+
"text_encoder": text_encoder,
|
| 86 |
+
"text_encoder_2": text_encoder_2,
|
| 87 |
+
"tokenizer": tokenizer,
|
| 88 |
+
"tokenizer_2": tokenizer_2,
|
| 89 |
+
"transformer": transformer,
|
| 90 |
+
"vae": vae,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 94 |
+
if str(device).startswith("mps"):
|
| 95 |
+
generator = torch.manual_seed(seed)
|
| 96 |
+
else:
|
| 97 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 98 |
+
|
| 99 |
+
image = Image.new("RGB", (16, 16), 0)
|
| 100 |
+
control_image = Image.new("RGB", (16, 16), 0)
|
| 101 |
+
|
| 102 |
+
inputs = {
|
| 103 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 104 |
+
"image": image,
|
| 105 |
+
"control_image": control_image,
|
| 106 |
+
"generator": generator,
|
| 107 |
+
"num_inference_steps": 2,
|
| 108 |
+
"guidance_scale": 5.0,
|
| 109 |
+
"height": 8,
|
| 110 |
+
"width": 8,
|
| 111 |
+
"max_sequence_length": 48,
|
| 112 |
+
"strength": 0.8,
|
| 113 |
+
"output_type": "np",
|
| 114 |
+
}
|
| 115 |
+
return inputs
|
| 116 |
+
|
| 117 |
+
def test_flux_different_prompts(self):
|
| 118 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 119 |
+
|
| 120 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 121 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 122 |
+
|
| 123 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 124 |
+
inputs["prompt_2"] = "a different prompt"
|
| 125 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 126 |
+
|
| 127 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 128 |
+
|
| 129 |
+
# Outputs should be different here
|
| 130 |
+
# For some reasons, they don't show large differences
|
| 131 |
+
assert max_diff > 1e-6
|
| 132 |
+
|
| 133 |
+
def test_flux_image_output_shape(self):
|
| 134 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 135 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 136 |
+
|
| 137 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 138 |
+
for height, width in height_width_pairs:
|
| 139 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 140 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 141 |
+
|
| 142 |
+
inputs.update({"height": height, "width": width})
|
| 143 |
+
image = pipe(**inputs).images[0]
|
| 144 |
+
output_height, output_width, _ = image.shape
|
| 145 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_control_inpaint.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKL,
|
| 10 |
+
FlowMatchEulerDiscreteScheduler,
|
| 11 |
+
FluxControlInpaintPipeline,
|
| 12 |
+
FluxTransformer2DModel,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from ...testing_utils import (
|
| 16 |
+
torch_device,
|
| 17 |
+
)
|
| 18 |
+
from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FluxControlInpaintPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 22 |
+
pipeline_class = FluxControlInpaintPipeline
|
| 23 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 24 |
+
batch_params = frozenset(["prompt"])
|
| 25 |
+
|
| 26 |
+
# there is no xformers processor for Flux
|
| 27 |
+
test_xformers_attention = False
|
| 28 |
+
|
| 29 |
+
def get_dummy_components(self):
|
| 30 |
+
torch.manual_seed(0)
|
| 31 |
+
transformer = FluxTransformer2DModel(
|
| 32 |
+
patch_size=1,
|
| 33 |
+
in_channels=8,
|
| 34 |
+
out_channels=4,
|
| 35 |
+
num_layers=1,
|
| 36 |
+
num_single_layers=1,
|
| 37 |
+
attention_head_dim=16,
|
| 38 |
+
num_attention_heads=2,
|
| 39 |
+
joint_attention_dim=32,
|
| 40 |
+
pooled_projection_dim=32,
|
| 41 |
+
axes_dims_rope=[4, 4, 8],
|
| 42 |
+
)
|
| 43 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 44 |
+
bos_token_id=0,
|
| 45 |
+
eos_token_id=2,
|
| 46 |
+
hidden_size=32,
|
| 47 |
+
intermediate_size=37,
|
| 48 |
+
layer_norm_eps=1e-05,
|
| 49 |
+
num_attention_heads=4,
|
| 50 |
+
num_hidden_layers=5,
|
| 51 |
+
pad_token_id=1,
|
| 52 |
+
vocab_size=1000,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
projection_dim=32,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 59 |
+
|
| 60 |
+
torch.manual_seed(0)
|
| 61 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 62 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 63 |
+
|
| 64 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 65 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 66 |
+
|
| 67 |
+
torch.manual_seed(0)
|
| 68 |
+
vae = AutoencoderKL(
|
| 69 |
+
sample_size=32,
|
| 70 |
+
in_channels=3,
|
| 71 |
+
out_channels=3,
|
| 72 |
+
block_out_channels=(4,),
|
| 73 |
+
layers_per_block=1,
|
| 74 |
+
latent_channels=1,
|
| 75 |
+
norm_num_groups=1,
|
| 76 |
+
use_quant_conv=False,
|
| 77 |
+
use_post_quant_conv=False,
|
| 78 |
+
shift_factor=0.0609,
|
| 79 |
+
scaling_factor=1.5035,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"scheduler": scheduler,
|
| 86 |
+
"text_encoder": text_encoder,
|
| 87 |
+
"text_encoder_2": text_encoder_2,
|
| 88 |
+
"tokenizer": tokenizer,
|
| 89 |
+
"tokenizer_2": tokenizer_2,
|
| 90 |
+
"transformer": transformer,
|
| 91 |
+
"vae": vae,
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 95 |
+
if str(device).startswith("mps"):
|
| 96 |
+
generator = torch.manual_seed(seed)
|
| 97 |
+
else:
|
| 98 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 99 |
+
|
| 100 |
+
image = Image.new("RGB", (8, 8), 0)
|
| 101 |
+
control_image = Image.new("RGB", (8, 8), 0)
|
| 102 |
+
mask_image = Image.new("RGB", (8, 8), 255)
|
| 103 |
+
|
| 104 |
+
inputs = {
|
| 105 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 106 |
+
"control_image": control_image,
|
| 107 |
+
"generator": generator,
|
| 108 |
+
"image": image,
|
| 109 |
+
"mask_image": mask_image,
|
| 110 |
+
"strength": 0.8,
|
| 111 |
+
"num_inference_steps": 2,
|
| 112 |
+
"guidance_scale": 30.0,
|
| 113 |
+
"height": 8,
|
| 114 |
+
"width": 8,
|
| 115 |
+
"max_sequence_length": 48,
|
| 116 |
+
"output_type": "np",
|
| 117 |
+
}
|
| 118 |
+
return inputs
|
| 119 |
+
|
| 120 |
+
def test_fused_qkv_projections(self):
|
| 121 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 122 |
+
components = self.get_dummy_components()
|
| 123 |
+
pipe = self.pipeline_class(**components)
|
| 124 |
+
pipe = pipe.to(device)
|
| 125 |
+
pipe.set_progress_bar_config(disable=None)
|
| 126 |
+
|
| 127 |
+
inputs = self.get_dummy_inputs(device)
|
| 128 |
+
image = pipe(**inputs).images
|
| 129 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 130 |
+
|
| 131 |
+
# TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
|
| 132 |
+
# to the pipeline level.
|
| 133 |
+
pipe.transformer.fuse_qkv_projections()
|
| 134 |
+
self.assertTrue(
|
| 135 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 136 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
inputs = self.get_dummy_inputs(device)
|
| 140 |
+
image = pipe(**inputs).images
|
| 141 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 142 |
+
|
| 143 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 144 |
+
inputs = self.get_dummy_inputs(device)
|
| 145 |
+
image = pipe(**inputs).images
|
| 146 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 147 |
+
|
| 148 |
+
assert np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3), (
|
| 149 |
+
"Fusion of QKV projections shouldn't affect the outputs."
|
| 150 |
+
)
|
| 151 |
+
assert np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3), (
|
| 152 |
+
"Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."
|
| 153 |
+
)
|
| 154 |
+
assert np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2), (
|
| 155 |
+
"Original outputs should match when fused QKV projections are disabled."
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def test_flux_image_output_shape(self):
|
| 159 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 160 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 161 |
+
|
| 162 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 163 |
+
for height, width in height_width_pairs:
|
| 164 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 165 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 166 |
+
|
| 167 |
+
inputs.update({"height": height, "width": width})
|
| 168 |
+
image = pipe(**inputs).images[0]
|
| 169 |
+
output_height, output_width, _ = image.shape
|
| 170 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_fill.py
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxFillPipeline, FluxTransformer2DModel
|
| 9 |
+
|
| 10 |
+
from ...testing_utils import (
|
| 11 |
+
enable_full_determinism,
|
| 12 |
+
floats_tensor,
|
| 13 |
+
torch_device,
|
| 14 |
+
)
|
| 15 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
enable_full_determinism()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FluxFillPipelineFastTests(unittest.TestCase, PipelineTesterMixin):
|
| 22 |
+
pipeline_class = FluxFillPipeline
|
| 23 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 24 |
+
batch_params = frozenset(["prompt"])
|
| 25 |
+
test_xformers_attention = False
|
| 26 |
+
test_layerwise_casting = True
|
| 27 |
+
test_group_offloading = True
|
| 28 |
+
|
| 29 |
+
def get_dummy_components(self):
|
| 30 |
+
torch.manual_seed(0)
|
| 31 |
+
transformer = FluxTransformer2DModel(
|
| 32 |
+
patch_size=1,
|
| 33 |
+
in_channels=20,
|
| 34 |
+
out_channels=8,
|
| 35 |
+
num_layers=1,
|
| 36 |
+
num_single_layers=1,
|
| 37 |
+
attention_head_dim=16,
|
| 38 |
+
num_attention_heads=2,
|
| 39 |
+
joint_attention_dim=32,
|
| 40 |
+
pooled_projection_dim=32,
|
| 41 |
+
axes_dims_rope=[4, 4, 8],
|
| 42 |
+
)
|
| 43 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 44 |
+
bos_token_id=0,
|
| 45 |
+
eos_token_id=2,
|
| 46 |
+
hidden_size=32,
|
| 47 |
+
intermediate_size=37,
|
| 48 |
+
layer_norm_eps=1e-05,
|
| 49 |
+
num_attention_heads=4,
|
| 50 |
+
num_hidden_layers=5,
|
| 51 |
+
pad_token_id=1,
|
| 52 |
+
vocab_size=1000,
|
| 53 |
+
hidden_act="gelu",
|
| 54 |
+
projection_dim=32,
|
| 55 |
+
)
|
| 56 |
+
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 59 |
+
|
| 60 |
+
torch.manual_seed(0)
|
| 61 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 62 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 63 |
+
|
| 64 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 65 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 66 |
+
|
| 67 |
+
torch.manual_seed(0)
|
| 68 |
+
vae = AutoencoderKL(
|
| 69 |
+
sample_size=32,
|
| 70 |
+
in_channels=3,
|
| 71 |
+
out_channels=3,
|
| 72 |
+
block_out_channels=(4,),
|
| 73 |
+
layers_per_block=1,
|
| 74 |
+
latent_channels=2,
|
| 75 |
+
norm_num_groups=1,
|
| 76 |
+
use_quant_conv=False,
|
| 77 |
+
use_post_quant_conv=False,
|
| 78 |
+
shift_factor=0.0609,
|
| 79 |
+
scaling_factor=1.5035,
|
| 80 |
+
)
|
| 81 |
+
|
| 82 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 83 |
+
|
| 84 |
+
return {
|
| 85 |
+
"scheduler": scheduler,
|
| 86 |
+
"text_encoder": text_encoder,
|
| 87 |
+
"text_encoder_2": text_encoder_2,
|
| 88 |
+
"tokenizer": tokenizer,
|
| 89 |
+
"tokenizer_2": tokenizer_2,
|
| 90 |
+
"transformer": transformer,
|
| 91 |
+
"vae": vae,
|
| 92 |
+
}
|
| 93 |
+
|
| 94 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 95 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 96 |
+
mask_image = torch.ones((1, 1, 32, 32)).to(device)
|
| 97 |
+
if str(device).startswith("mps"):
|
| 98 |
+
generator = torch.manual_seed(seed)
|
| 99 |
+
else:
|
| 100 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 101 |
+
|
| 102 |
+
inputs = {
|
| 103 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 104 |
+
"image": image,
|
| 105 |
+
"mask_image": mask_image,
|
| 106 |
+
"generator": generator,
|
| 107 |
+
"num_inference_steps": 2,
|
| 108 |
+
"guidance_scale": 5.0,
|
| 109 |
+
"height": 32,
|
| 110 |
+
"width": 32,
|
| 111 |
+
"max_sequence_length": 48,
|
| 112 |
+
"output_type": "np",
|
| 113 |
+
}
|
| 114 |
+
return inputs
|
| 115 |
+
|
| 116 |
+
def test_flux_fill_different_prompts(self):
|
| 117 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 118 |
+
|
| 119 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 120 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 121 |
+
|
| 122 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 123 |
+
inputs["prompt_2"] = "a different prompt"
|
| 124 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 125 |
+
|
| 126 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 127 |
+
|
| 128 |
+
# Outputs should be different here
|
| 129 |
+
# For some reasons, they don't show large differences
|
| 130 |
+
assert max_diff > 1e-6
|
| 131 |
+
|
| 132 |
+
def test_flux_image_output_shape(self):
|
| 133 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 134 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 135 |
+
|
| 136 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 137 |
+
for height, width in height_width_pairs:
|
| 138 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 139 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 140 |
+
|
| 141 |
+
inputs.update({"height": height, "width": width})
|
| 142 |
+
image = pipe(**inputs).images[0]
|
| 143 |
+
output_height, output_width, _ = image.shape
|
| 144 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
| 145 |
+
|
| 146 |
+
def test_inference_batch_single_identical(self):
|
| 147 |
+
self._test_inference_batch_single_identical(expected_max_diff=1e-3)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_img2img.py
ADDED
|
@@ -0,0 +1,170 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxImg2ImgPipeline, FluxTransformer2DModel
|
| 9 |
+
|
| 10 |
+
from ...testing_utils import (
|
| 11 |
+
enable_full_determinism,
|
| 12 |
+
floats_tensor,
|
| 13 |
+
torch_device,
|
| 14 |
+
)
|
| 15 |
+
from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
enable_full_determinism()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FluxImg2ImgPipelineFastTests(unittest.TestCase, PipelineTesterMixin, FluxIPAdapterTesterMixin):
|
| 22 |
+
pipeline_class = FluxImg2ImgPipeline
|
| 23 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 24 |
+
batch_params = frozenset(["prompt"])
|
| 25 |
+
test_xformers_attention = False
|
| 26 |
+
|
| 27 |
+
def get_dummy_components(self):
|
| 28 |
+
torch.manual_seed(0)
|
| 29 |
+
transformer = FluxTransformer2DModel(
|
| 30 |
+
patch_size=1,
|
| 31 |
+
in_channels=4,
|
| 32 |
+
num_layers=1,
|
| 33 |
+
num_single_layers=1,
|
| 34 |
+
attention_head_dim=16,
|
| 35 |
+
num_attention_heads=2,
|
| 36 |
+
joint_attention_dim=32,
|
| 37 |
+
pooled_projection_dim=32,
|
| 38 |
+
axes_dims_rope=[4, 4, 8],
|
| 39 |
+
)
|
| 40 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 41 |
+
bos_token_id=0,
|
| 42 |
+
eos_token_id=2,
|
| 43 |
+
hidden_size=32,
|
| 44 |
+
intermediate_size=37,
|
| 45 |
+
layer_norm_eps=1e-05,
|
| 46 |
+
num_attention_heads=4,
|
| 47 |
+
num_hidden_layers=5,
|
| 48 |
+
pad_token_id=1,
|
| 49 |
+
vocab_size=1000,
|
| 50 |
+
hidden_act="gelu",
|
| 51 |
+
projection_dim=32,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
torch.manual_seed(0)
|
| 55 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 56 |
+
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 59 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 60 |
+
|
| 61 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 62 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 63 |
+
|
| 64 |
+
torch.manual_seed(0)
|
| 65 |
+
vae = AutoencoderKL(
|
| 66 |
+
sample_size=32,
|
| 67 |
+
in_channels=3,
|
| 68 |
+
out_channels=3,
|
| 69 |
+
block_out_channels=(4,),
|
| 70 |
+
layers_per_block=1,
|
| 71 |
+
latent_channels=1,
|
| 72 |
+
norm_num_groups=1,
|
| 73 |
+
use_quant_conv=False,
|
| 74 |
+
use_post_quant_conv=False,
|
| 75 |
+
shift_factor=0.0609,
|
| 76 |
+
scaling_factor=1.5035,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"scheduler": scheduler,
|
| 83 |
+
"text_encoder": text_encoder,
|
| 84 |
+
"text_encoder_2": text_encoder_2,
|
| 85 |
+
"tokenizer": tokenizer,
|
| 86 |
+
"tokenizer_2": tokenizer_2,
|
| 87 |
+
"transformer": transformer,
|
| 88 |
+
"vae": vae,
|
| 89 |
+
"image_encoder": None,
|
| 90 |
+
"feature_extractor": None,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 94 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 95 |
+
if str(device).startswith("mps"):
|
| 96 |
+
generator = torch.manual_seed(seed)
|
| 97 |
+
else:
|
| 98 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 99 |
+
|
| 100 |
+
inputs = {
|
| 101 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 102 |
+
"image": image,
|
| 103 |
+
"generator": generator,
|
| 104 |
+
"num_inference_steps": 2,
|
| 105 |
+
"guidance_scale": 5.0,
|
| 106 |
+
"height": 8,
|
| 107 |
+
"width": 8,
|
| 108 |
+
"max_sequence_length": 48,
|
| 109 |
+
"strength": 0.8,
|
| 110 |
+
"output_type": "np",
|
| 111 |
+
}
|
| 112 |
+
return inputs
|
| 113 |
+
|
| 114 |
+
def test_flux_different_prompts(self):
|
| 115 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 116 |
+
|
| 117 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 118 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 119 |
+
|
| 120 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 121 |
+
inputs["prompt_2"] = "a different prompt"
|
| 122 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 123 |
+
|
| 124 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 125 |
+
|
| 126 |
+
# Outputs should be different here
|
| 127 |
+
# For some reasons, they don't show large differences
|
| 128 |
+
assert max_diff > 1e-6
|
| 129 |
+
|
| 130 |
+
def test_flux_true_cfg_with_negative_embeds(self):
|
| 131 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 132 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 133 |
+
inputs.pop("generator")
|
| 134 |
+
prompt = inputs.pop("prompt")
|
| 135 |
+
|
| 136 |
+
prompt_embeds, pooled_prompt_embeds, _ = pipe.encode_prompt(
|
| 137 |
+
prompt=prompt, prompt_2=None, device=torch_device, num_images_per_prompt=1, max_sequence_length=48
|
| 138 |
+
)
|
| 139 |
+
negative_prompt_embeds, negative_pooled_prompt_embeds, _ = pipe.encode_prompt(
|
| 140 |
+
prompt="bad quality", prompt_2=None, device=torch_device, num_images_per_prompt=1, max_sequence_length=48
|
| 141 |
+
)
|
| 142 |
+
inputs.update(
|
| 143 |
+
prompt_embeds=prompt_embeds,
|
| 144 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
| 145 |
+
negative_prompt_embeds=negative_prompt_embeds,
|
| 146 |
+
negative_pooled_prompt_embeds=negative_pooled_prompt_embeds,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
inputs["true_cfg_scale"] = 1.0
|
| 150 |
+
cfg_off = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 151 |
+
inputs["true_cfg_scale"] = 2.0
|
| 152 |
+
cfg_on = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 153 |
+
self.assertFalse(
|
| 154 |
+
np.allclose(cfg_off, cfg_on),
|
| 155 |
+
"Precomputed negative embeds should enable true CFG when negative_prompt is None.",
|
| 156 |
+
)
|
| 157 |
+
|
| 158 |
+
def test_flux_image_output_shape(self):
|
| 159 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 160 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 161 |
+
|
| 162 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 163 |
+
for height, width in height_width_pairs:
|
| 164 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 165 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 166 |
+
|
| 167 |
+
inputs.update({"height": height, "width": width})
|
| 168 |
+
image = pipe(**inputs).images[0]
|
| 169 |
+
output_height, output_width, _ = image.shape
|
| 170 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_inpaint.py
ADDED
|
@@ -0,0 +1,144 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, FluxInpaintPipeline, FluxTransformer2DModel
|
| 9 |
+
|
| 10 |
+
from ...testing_utils import (
|
| 11 |
+
enable_full_determinism,
|
| 12 |
+
floats_tensor,
|
| 13 |
+
torch_device,
|
| 14 |
+
)
|
| 15 |
+
from ..test_pipelines_common import FluxIPAdapterTesterMixin, PipelineTesterMixin
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
enable_full_determinism()
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
class FluxInpaintPipelineFastTests(unittest.TestCase, PipelineTesterMixin, FluxIPAdapterTesterMixin):
|
| 22 |
+
pipeline_class = FluxInpaintPipeline
|
| 23 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 24 |
+
batch_params = frozenset(["prompt"])
|
| 25 |
+
test_xformers_attention = False
|
| 26 |
+
|
| 27 |
+
def get_dummy_components(self):
|
| 28 |
+
torch.manual_seed(0)
|
| 29 |
+
transformer = FluxTransformer2DModel(
|
| 30 |
+
patch_size=1,
|
| 31 |
+
in_channels=8,
|
| 32 |
+
num_layers=1,
|
| 33 |
+
num_single_layers=1,
|
| 34 |
+
attention_head_dim=16,
|
| 35 |
+
num_attention_heads=2,
|
| 36 |
+
joint_attention_dim=32,
|
| 37 |
+
pooled_projection_dim=32,
|
| 38 |
+
axes_dims_rope=[4, 4, 8],
|
| 39 |
+
)
|
| 40 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 41 |
+
bos_token_id=0,
|
| 42 |
+
eos_token_id=2,
|
| 43 |
+
hidden_size=32,
|
| 44 |
+
intermediate_size=37,
|
| 45 |
+
layer_norm_eps=1e-05,
|
| 46 |
+
num_attention_heads=4,
|
| 47 |
+
num_hidden_layers=5,
|
| 48 |
+
pad_token_id=1,
|
| 49 |
+
vocab_size=1000,
|
| 50 |
+
hidden_act="gelu",
|
| 51 |
+
projection_dim=32,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
torch.manual_seed(0)
|
| 55 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 56 |
+
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 59 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 60 |
+
|
| 61 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 62 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 63 |
+
|
| 64 |
+
torch.manual_seed(0)
|
| 65 |
+
vae = AutoencoderKL(
|
| 66 |
+
sample_size=32,
|
| 67 |
+
in_channels=3,
|
| 68 |
+
out_channels=3,
|
| 69 |
+
block_out_channels=(4,),
|
| 70 |
+
layers_per_block=1,
|
| 71 |
+
latent_channels=2,
|
| 72 |
+
norm_num_groups=1,
|
| 73 |
+
use_quant_conv=False,
|
| 74 |
+
use_post_quant_conv=False,
|
| 75 |
+
shift_factor=0.0609,
|
| 76 |
+
scaling_factor=1.5035,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 80 |
+
|
| 81 |
+
return {
|
| 82 |
+
"scheduler": scheduler,
|
| 83 |
+
"text_encoder": text_encoder,
|
| 84 |
+
"text_encoder_2": text_encoder_2,
|
| 85 |
+
"tokenizer": tokenizer,
|
| 86 |
+
"tokenizer_2": tokenizer_2,
|
| 87 |
+
"transformer": transformer,
|
| 88 |
+
"vae": vae,
|
| 89 |
+
"image_encoder": None,
|
| 90 |
+
"feature_extractor": None,
|
| 91 |
+
}
|
| 92 |
+
|
| 93 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 94 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 95 |
+
mask_image = torch.ones((1, 1, 32, 32)).to(device)
|
| 96 |
+
if str(device).startswith("mps"):
|
| 97 |
+
generator = torch.manual_seed(seed)
|
| 98 |
+
else:
|
| 99 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 100 |
+
|
| 101 |
+
inputs = {
|
| 102 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 103 |
+
"image": image,
|
| 104 |
+
"mask_image": mask_image,
|
| 105 |
+
"generator": generator,
|
| 106 |
+
"num_inference_steps": 2,
|
| 107 |
+
"guidance_scale": 5.0,
|
| 108 |
+
"height": 32,
|
| 109 |
+
"width": 32,
|
| 110 |
+
"max_sequence_length": 48,
|
| 111 |
+
"strength": 0.8,
|
| 112 |
+
"output_type": "np",
|
| 113 |
+
}
|
| 114 |
+
return inputs
|
| 115 |
+
|
| 116 |
+
def test_flux_inpaint_different_prompts(self):
|
| 117 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 118 |
+
|
| 119 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 120 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 121 |
+
|
| 122 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 123 |
+
inputs["prompt_2"] = "a different prompt"
|
| 124 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 125 |
+
|
| 126 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 127 |
+
|
| 128 |
+
# Outputs should be different here
|
| 129 |
+
# For some reasons, they don't show large differences
|
| 130 |
+
assert max_diff > 1e-6
|
| 131 |
+
|
| 132 |
+
def test_flux_image_output_shape(self):
|
| 133 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 134 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 135 |
+
|
| 136 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 137 |
+
for height, width in height_width_pairs:
|
| 138 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 139 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 140 |
+
|
| 141 |
+
inputs.update({"height": height, "width": width})
|
| 142 |
+
image = pipe(**inputs).images[0]
|
| 143 |
+
output_height, output_width, _ = image.shape
|
| 144 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_kontext.py
ADDED
|
@@ -0,0 +1,178 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import PIL.Image
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKL,
|
| 10 |
+
FasterCacheConfig,
|
| 11 |
+
FlowMatchEulerDiscreteScheduler,
|
| 12 |
+
FluxKontextPipeline,
|
| 13 |
+
FluxTransformer2DModel,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from ...testing_utils import torch_device
|
| 17 |
+
from ..test_pipelines_common import (
|
| 18 |
+
FasterCacheTesterMixin,
|
| 19 |
+
FluxIPAdapterTesterMixin,
|
| 20 |
+
PipelineTesterMixin,
|
| 21 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class FluxKontextPipelineFastTests(
|
| 26 |
+
unittest.TestCase,
|
| 27 |
+
PipelineTesterMixin,
|
| 28 |
+
FluxIPAdapterTesterMixin,
|
| 29 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 30 |
+
FasterCacheTesterMixin,
|
| 31 |
+
):
|
| 32 |
+
pipeline_class = FluxKontextPipeline
|
| 33 |
+
params = frozenset(
|
| 34 |
+
["image", "prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"]
|
| 35 |
+
)
|
| 36 |
+
batch_params = frozenset(["image", "prompt"])
|
| 37 |
+
|
| 38 |
+
# there is no xformers processor for Flux
|
| 39 |
+
test_xformers_attention = False
|
| 40 |
+
test_layerwise_casting = True
|
| 41 |
+
test_group_offloading = True
|
| 42 |
+
|
| 43 |
+
faster_cache_config = FasterCacheConfig(
|
| 44 |
+
spatial_attention_block_skip_range=2,
|
| 45 |
+
spatial_attention_timestep_skip_range=(-1, 901),
|
| 46 |
+
unconditional_batch_skip_range=2,
|
| 47 |
+
attention_weight_callback=lambda _: 0.5,
|
| 48 |
+
is_guidance_distilled=True,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 52 |
+
torch.manual_seed(0)
|
| 53 |
+
transformer = FluxTransformer2DModel(
|
| 54 |
+
patch_size=1,
|
| 55 |
+
in_channels=4,
|
| 56 |
+
num_layers=num_layers,
|
| 57 |
+
num_single_layers=num_single_layers,
|
| 58 |
+
attention_head_dim=16,
|
| 59 |
+
num_attention_heads=2,
|
| 60 |
+
joint_attention_dim=32,
|
| 61 |
+
pooled_projection_dim=32,
|
| 62 |
+
axes_dims_rope=[4, 4, 8],
|
| 63 |
+
)
|
| 64 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 65 |
+
bos_token_id=0,
|
| 66 |
+
eos_token_id=2,
|
| 67 |
+
hidden_size=32,
|
| 68 |
+
intermediate_size=37,
|
| 69 |
+
layer_norm_eps=1e-05,
|
| 70 |
+
num_attention_heads=4,
|
| 71 |
+
num_hidden_layers=5,
|
| 72 |
+
pad_token_id=1,
|
| 73 |
+
vocab_size=1000,
|
| 74 |
+
hidden_act="gelu",
|
| 75 |
+
projection_dim=32,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 80 |
+
|
| 81 |
+
torch.manual_seed(0)
|
| 82 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 83 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 84 |
+
|
| 85 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 86 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 87 |
+
|
| 88 |
+
torch.manual_seed(0)
|
| 89 |
+
vae = AutoencoderKL(
|
| 90 |
+
sample_size=32,
|
| 91 |
+
in_channels=3,
|
| 92 |
+
out_channels=3,
|
| 93 |
+
block_out_channels=(4,),
|
| 94 |
+
layers_per_block=1,
|
| 95 |
+
latent_channels=1,
|
| 96 |
+
norm_num_groups=1,
|
| 97 |
+
use_quant_conv=False,
|
| 98 |
+
use_post_quant_conv=False,
|
| 99 |
+
shift_factor=0.0609,
|
| 100 |
+
scaling_factor=1.5035,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"scheduler": scheduler,
|
| 107 |
+
"text_encoder": text_encoder,
|
| 108 |
+
"text_encoder_2": text_encoder_2,
|
| 109 |
+
"tokenizer": tokenizer,
|
| 110 |
+
"tokenizer_2": tokenizer_2,
|
| 111 |
+
"transformer": transformer,
|
| 112 |
+
"vae": vae,
|
| 113 |
+
"image_encoder": None,
|
| 114 |
+
"feature_extractor": None,
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 118 |
+
if str(device).startswith("mps"):
|
| 119 |
+
generator = torch.manual_seed(seed)
|
| 120 |
+
else:
|
| 121 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 122 |
+
|
| 123 |
+
image = PIL.Image.new("RGB", (32, 32), 0)
|
| 124 |
+
inputs = {
|
| 125 |
+
"image": image,
|
| 126 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 127 |
+
"generator": generator,
|
| 128 |
+
"num_inference_steps": 2,
|
| 129 |
+
"guidance_scale": 5.0,
|
| 130 |
+
"height": 8,
|
| 131 |
+
"width": 8,
|
| 132 |
+
"max_area": 8 * 8,
|
| 133 |
+
"max_sequence_length": 48,
|
| 134 |
+
"output_type": "np",
|
| 135 |
+
"_auto_resize": False,
|
| 136 |
+
}
|
| 137 |
+
return inputs
|
| 138 |
+
|
| 139 |
+
def test_flux_different_prompts(self):
|
| 140 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 141 |
+
|
| 142 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 143 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 144 |
+
|
| 145 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 146 |
+
inputs["prompt_2"] = "a different prompt"
|
| 147 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 148 |
+
|
| 149 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 150 |
+
|
| 151 |
+
# Outputs should be different here
|
| 152 |
+
# For some reasons, they don't show large differences
|
| 153 |
+
assert max_diff > 1e-6
|
| 154 |
+
|
| 155 |
+
def test_flux_image_output_shape(self):
|
| 156 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 157 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 158 |
+
|
| 159 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 160 |
+
for height, width in height_width_pairs:
|
| 161 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 162 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 163 |
+
|
| 164 |
+
inputs.update({"height": height, "width": width, "max_area": height * width})
|
| 165 |
+
image = pipe(**inputs).images[0]
|
| 166 |
+
output_height, output_width, _ = image.shape
|
| 167 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
| 168 |
+
|
| 169 |
+
def test_flux_true_cfg(self):
|
| 170 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 171 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 172 |
+
inputs.pop("generator")
|
| 173 |
+
|
| 174 |
+
no_true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 175 |
+
inputs["negative_prompt"] = "bad quality"
|
| 176 |
+
inputs["true_cfg_scale"] = 2.0
|
| 177 |
+
true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 178 |
+
assert not np.allclose(no_true_cfg_out, true_cfg_out)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_kontext_inpaint.py
ADDED
|
@@ -0,0 +1,191 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import AutoConfig, AutoTokenizer, CLIPTextConfig, CLIPTextModel, CLIPTokenizer, T5EncoderModel
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKL,
|
| 10 |
+
FasterCacheConfig,
|
| 11 |
+
FlowMatchEulerDiscreteScheduler,
|
| 12 |
+
FluxKontextInpaintPipeline,
|
| 13 |
+
FluxTransformer2DModel,
|
| 14 |
+
)
|
| 15 |
+
|
| 16 |
+
from ...testing_utils import floats_tensor, torch_device
|
| 17 |
+
from ..test_pipelines_common import (
|
| 18 |
+
FasterCacheTesterMixin,
|
| 19 |
+
FluxIPAdapterTesterMixin,
|
| 20 |
+
PipelineTesterMixin,
|
| 21 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class FluxKontextInpaintPipelineFastTests(
|
| 26 |
+
unittest.TestCase,
|
| 27 |
+
PipelineTesterMixin,
|
| 28 |
+
FluxIPAdapterTesterMixin,
|
| 29 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 30 |
+
FasterCacheTesterMixin,
|
| 31 |
+
):
|
| 32 |
+
pipeline_class = FluxKontextInpaintPipeline
|
| 33 |
+
params = frozenset(
|
| 34 |
+
["image", "prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"]
|
| 35 |
+
)
|
| 36 |
+
batch_params = frozenset(["image", "prompt"])
|
| 37 |
+
|
| 38 |
+
# there is no xformers processor for Flux
|
| 39 |
+
test_xformers_attention = False
|
| 40 |
+
test_layerwise_casting = True
|
| 41 |
+
test_group_offloading = True
|
| 42 |
+
|
| 43 |
+
faster_cache_config = FasterCacheConfig(
|
| 44 |
+
spatial_attention_block_skip_range=2,
|
| 45 |
+
spatial_attention_timestep_skip_range=(-1, 901),
|
| 46 |
+
unconditional_batch_skip_range=2,
|
| 47 |
+
attention_weight_callback=lambda _: 0.5,
|
| 48 |
+
is_guidance_distilled=True,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 52 |
+
torch.manual_seed(0)
|
| 53 |
+
transformer = FluxTransformer2DModel(
|
| 54 |
+
patch_size=1,
|
| 55 |
+
in_channels=4,
|
| 56 |
+
num_layers=num_layers,
|
| 57 |
+
num_single_layers=num_single_layers,
|
| 58 |
+
attention_head_dim=16,
|
| 59 |
+
num_attention_heads=2,
|
| 60 |
+
joint_attention_dim=32,
|
| 61 |
+
pooled_projection_dim=32,
|
| 62 |
+
axes_dims_rope=[4, 4, 8],
|
| 63 |
+
)
|
| 64 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 65 |
+
bos_token_id=0,
|
| 66 |
+
eos_token_id=2,
|
| 67 |
+
hidden_size=32,
|
| 68 |
+
intermediate_size=37,
|
| 69 |
+
layer_norm_eps=1e-05,
|
| 70 |
+
num_attention_heads=4,
|
| 71 |
+
num_hidden_layers=5,
|
| 72 |
+
pad_token_id=1,
|
| 73 |
+
vocab_size=1000,
|
| 74 |
+
hidden_act="gelu",
|
| 75 |
+
projection_dim=32,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
torch.manual_seed(0)
|
| 79 |
+
text_encoder = CLIPTextModel(clip_text_encoder_config)
|
| 80 |
+
|
| 81 |
+
torch.manual_seed(0)
|
| 82 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 83 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 84 |
+
|
| 85 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 86 |
+
tokenizer_2 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 87 |
+
|
| 88 |
+
torch.manual_seed(0)
|
| 89 |
+
vae = AutoencoderKL(
|
| 90 |
+
sample_size=32,
|
| 91 |
+
in_channels=3,
|
| 92 |
+
out_channels=3,
|
| 93 |
+
block_out_channels=(4,),
|
| 94 |
+
layers_per_block=1,
|
| 95 |
+
latent_channels=1,
|
| 96 |
+
norm_num_groups=1,
|
| 97 |
+
use_quant_conv=False,
|
| 98 |
+
use_post_quant_conv=False,
|
| 99 |
+
shift_factor=0.0609,
|
| 100 |
+
scaling_factor=1.5035,
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 104 |
+
|
| 105 |
+
return {
|
| 106 |
+
"scheduler": scheduler,
|
| 107 |
+
"text_encoder": text_encoder,
|
| 108 |
+
"text_encoder_2": text_encoder_2,
|
| 109 |
+
"tokenizer": tokenizer,
|
| 110 |
+
"tokenizer_2": tokenizer_2,
|
| 111 |
+
"transformer": transformer,
|
| 112 |
+
"vae": vae,
|
| 113 |
+
"image_encoder": None,
|
| 114 |
+
"feature_extractor": None,
|
| 115 |
+
}
|
| 116 |
+
|
| 117 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 118 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 119 |
+
mask_image = torch.ones((1, 1, 32, 32)).to(device)
|
| 120 |
+
if str(device).startswith("mps"):
|
| 121 |
+
generator = torch.manual_seed(seed)
|
| 122 |
+
else:
|
| 123 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 124 |
+
|
| 125 |
+
inputs = {
|
| 126 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 127 |
+
"image": image,
|
| 128 |
+
"mask_image": mask_image,
|
| 129 |
+
"generator": generator,
|
| 130 |
+
"num_inference_steps": 2,
|
| 131 |
+
"guidance_scale": 5.0,
|
| 132 |
+
"height": 32,
|
| 133 |
+
"width": 32,
|
| 134 |
+
"max_sequence_length": 48,
|
| 135 |
+
"strength": 0.8,
|
| 136 |
+
"output_type": "np",
|
| 137 |
+
"_auto_resize": False,
|
| 138 |
+
}
|
| 139 |
+
return inputs
|
| 140 |
+
|
| 141 |
+
def test_flux_inpaint_different_prompts(self):
|
| 142 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 143 |
+
|
| 144 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 145 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 146 |
+
|
| 147 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 148 |
+
inputs["prompt_2"] = "a different prompt"
|
| 149 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 150 |
+
|
| 151 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 152 |
+
|
| 153 |
+
# Outputs should be different here
|
| 154 |
+
# For some reasons, they don't show large differences
|
| 155 |
+
assert max_diff > 1e-6
|
| 156 |
+
|
| 157 |
+
def test_flux_image_output_shape(self):
|
| 158 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 159 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 160 |
+
|
| 161 |
+
height_width_pairs = [(32, 32), (72, 56)]
|
| 162 |
+
for height, width in height_width_pairs:
|
| 163 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 164 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 165 |
+
# Because output shape is the same as the input shape, we need to create a dummy image and mask image
|
| 166 |
+
image = floats_tensor((1, 3, height, width), rng=random.Random(0)).to(torch_device)
|
| 167 |
+
mask_image = torch.ones((1, 1, height, width)).to(torch_device)
|
| 168 |
+
|
| 169 |
+
inputs.update(
|
| 170 |
+
{
|
| 171 |
+
"height": height,
|
| 172 |
+
"width": width,
|
| 173 |
+
"max_area": height * width,
|
| 174 |
+
"image": image,
|
| 175 |
+
"mask_image": mask_image,
|
| 176 |
+
}
|
| 177 |
+
)
|
| 178 |
+
image = pipe(**inputs).images[0]
|
| 179 |
+
output_height, output_width, _ = image.shape
|
| 180 |
+
assert (output_height, output_width) == (expected_height, expected_width)
|
| 181 |
+
|
| 182 |
+
def test_flux_true_cfg(self):
|
| 183 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 184 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 185 |
+
inputs.pop("generator")
|
| 186 |
+
|
| 187 |
+
no_true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 188 |
+
inputs["negative_prompt"] = "bad quality"
|
| 189 |
+
inputs["true_cfg_scale"] = 2.0
|
| 190 |
+
true_cfg_out = pipe(**inputs, generator=torch.manual_seed(0)).images[0]
|
| 191 |
+
assert not np.allclose(no_true_cfg_out, true_cfg_out)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux/test_pipeline_flux_redux.py
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
|
| 7 |
+
from diffusers import FluxPipeline, FluxPriorReduxPipeline
|
| 8 |
+
from diffusers.utils import load_image
|
| 9 |
+
|
| 10 |
+
from ...testing_utils import (
|
| 11 |
+
Expectations,
|
| 12 |
+
backend_empty_cache,
|
| 13 |
+
numpy_cosine_similarity_distance,
|
| 14 |
+
require_big_accelerator,
|
| 15 |
+
slow,
|
| 16 |
+
torch_device,
|
| 17 |
+
)
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@slow
|
| 21 |
+
@require_big_accelerator
|
| 22 |
+
class FluxReduxSlowTests(unittest.TestCase):
|
| 23 |
+
pipeline_class = FluxPriorReduxPipeline
|
| 24 |
+
repo_id = "black-forest-labs/FLUX.1-Redux-dev"
|
| 25 |
+
base_pipeline_class = FluxPipeline
|
| 26 |
+
base_repo_id = "black-forest-labs/FLUX.1-schnell"
|
| 27 |
+
|
| 28 |
+
def setUp(self):
|
| 29 |
+
super().setUp()
|
| 30 |
+
gc.collect()
|
| 31 |
+
backend_empty_cache(torch_device)
|
| 32 |
+
|
| 33 |
+
def tearDown(self):
|
| 34 |
+
super().tearDown()
|
| 35 |
+
gc.collect()
|
| 36 |
+
backend_empty_cache(torch_device)
|
| 37 |
+
|
| 38 |
+
def get_inputs(self, device, seed=0):
|
| 39 |
+
init_image = load_image(
|
| 40 |
+
"https://huggingface.co/datasets/YiYiXu/testing-images/resolve/main/style_ziggy/img5.png"
|
| 41 |
+
)
|
| 42 |
+
return {"image": init_image}
|
| 43 |
+
|
| 44 |
+
def get_base_pipeline_inputs(self, device, seed=0):
|
| 45 |
+
if str(device).startswith("mps"):
|
| 46 |
+
generator = torch.manual_seed(seed)
|
| 47 |
+
else:
|
| 48 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 49 |
+
|
| 50 |
+
return {
|
| 51 |
+
"num_inference_steps": 2,
|
| 52 |
+
"guidance_scale": 2.0,
|
| 53 |
+
"output_type": "np",
|
| 54 |
+
"generator": generator,
|
| 55 |
+
}
|
| 56 |
+
|
| 57 |
+
def test_flux_redux_inference(self):
|
| 58 |
+
pipe_redux = self.pipeline_class.from_pretrained(self.repo_id, torch_dtype=torch.bfloat16)
|
| 59 |
+
pipe_base = self.base_pipeline_class.from_pretrained(
|
| 60 |
+
self.base_repo_id, torch_dtype=torch.bfloat16, text_encoder=None, text_encoder_2=None
|
| 61 |
+
)
|
| 62 |
+
pipe_redux.to(torch_device)
|
| 63 |
+
pipe_base.enable_model_cpu_offload(device=torch_device)
|
| 64 |
+
|
| 65 |
+
inputs = self.get_inputs(torch_device)
|
| 66 |
+
base_pipeline_inputs = self.get_base_pipeline_inputs(torch_device)
|
| 67 |
+
|
| 68 |
+
redux_pipeline_output = pipe_redux(**inputs)
|
| 69 |
+
image = pipe_base(**base_pipeline_inputs, **redux_pipeline_output).images[0]
|
| 70 |
+
|
| 71 |
+
image_slice = image[0, :10, :10]
|
| 72 |
+
expected_slices = Expectations(
|
| 73 |
+
{
|
| 74 |
+
("cuda", 7): np.array(
|
| 75 |
+
[
|
| 76 |
+
0.30078125,
|
| 77 |
+
0.37890625,
|
| 78 |
+
0.46875,
|
| 79 |
+
0.28125,
|
| 80 |
+
0.36914062,
|
| 81 |
+
0.47851562,
|
| 82 |
+
0.28515625,
|
| 83 |
+
0.375,
|
| 84 |
+
0.4765625,
|
| 85 |
+
0.28125,
|
| 86 |
+
0.375,
|
| 87 |
+
0.48046875,
|
| 88 |
+
0.27929688,
|
| 89 |
+
0.37695312,
|
| 90 |
+
0.47851562,
|
| 91 |
+
0.27734375,
|
| 92 |
+
0.38085938,
|
| 93 |
+
0.4765625,
|
| 94 |
+
0.2734375,
|
| 95 |
+
0.38085938,
|
| 96 |
+
0.47265625,
|
| 97 |
+
0.27539062,
|
| 98 |
+
0.37890625,
|
| 99 |
+
0.47265625,
|
| 100 |
+
0.27734375,
|
| 101 |
+
0.37695312,
|
| 102 |
+
0.47070312,
|
| 103 |
+
0.27929688,
|
| 104 |
+
0.37890625,
|
| 105 |
+
0.47460938,
|
| 106 |
+
],
|
| 107 |
+
dtype=np.float32,
|
| 108 |
+
),
|
| 109 |
+
("xpu", 3): np.array(
|
| 110 |
+
[
|
| 111 |
+
0.20507812,
|
| 112 |
+
0.30859375,
|
| 113 |
+
0.3984375,
|
| 114 |
+
0.18554688,
|
| 115 |
+
0.30078125,
|
| 116 |
+
0.41015625,
|
| 117 |
+
0.19921875,
|
| 118 |
+
0.3125,
|
| 119 |
+
0.40625,
|
| 120 |
+
0.19726562,
|
| 121 |
+
0.3125,
|
| 122 |
+
0.41601562,
|
| 123 |
+
0.19335938,
|
| 124 |
+
0.31445312,
|
| 125 |
+
0.4140625,
|
| 126 |
+
0.1953125,
|
| 127 |
+
0.3203125,
|
| 128 |
+
0.41796875,
|
| 129 |
+
0.19726562,
|
| 130 |
+
0.32421875,
|
| 131 |
+
0.41992188,
|
| 132 |
+
0.19726562,
|
| 133 |
+
0.32421875,
|
| 134 |
+
0.41992188,
|
| 135 |
+
0.20117188,
|
| 136 |
+
0.32421875,
|
| 137 |
+
0.41796875,
|
| 138 |
+
0.203125,
|
| 139 |
+
0.32617188,
|
| 140 |
+
0.41796875,
|
| 141 |
+
],
|
| 142 |
+
dtype=np.float32,
|
| 143 |
+
),
|
| 144 |
+
}
|
| 145 |
+
)
|
| 146 |
+
expected_slice = expected_slices.get_expectation()
|
| 147 |
+
|
| 148 |
+
max_diff = numpy_cosine_similarity_distance(expected_slice.flatten(), image_slice.flatten())
|
| 149 |
+
|
| 150 |
+
assert max_diff < 1e-4
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2.py
ADDED
|
@@ -0,0 +1,190 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from transformers import AutoProcessor, Mistral3Config, Mistral3ForConditionalGeneration
|
| 6 |
+
|
| 7 |
+
from diffusers import (
|
| 8 |
+
AutoencoderKLFlux2,
|
| 9 |
+
FlowMatchEulerDiscreteScheduler,
|
| 10 |
+
Flux2Pipeline,
|
| 11 |
+
Flux2Transformer2DModel,
|
| 12 |
+
)
|
| 13 |
+
|
| 14 |
+
from ...testing_utils import (
|
| 15 |
+
torch_device,
|
| 16 |
+
)
|
| 17 |
+
from ..test_pipelines_common import (
|
| 18 |
+
PipelineTesterMixin,
|
| 19 |
+
check_qkv_fused_layers_exist,
|
| 20 |
+
)
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
class Flux2PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 24 |
+
pipeline_class = Flux2Pipeline
|
| 25 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds"])
|
| 26 |
+
batch_params = frozenset(["prompt"])
|
| 27 |
+
|
| 28 |
+
test_xformers_attention = False
|
| 29 |
+
test_layerwise_casting = True
|
| 30 |
+
test_group_offloading = True
|
| 31 |
+
|
| 32 |
+
supports_dduf = False
|
| 33 |
+
|
| 34 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 35 |
+
torch.manual_seed(0)
|
| 36 |
+
transformer = Flux2Transformer2DModel(
|
| 37 |
+
patch_size=1,
|
| 38 |
+
in_channels=4,
|
| 39 |
+
num_layers=num_layers,
|
| 40 |
+
num_single_layers=num_single_layers,
|
| 41 |
+
attention_head_dim=16,
|
| 42 |
+
num_attention_heads=2,
|
| 43 |
+
joint_attention_dim=16,
|
| 44 |
+
timestep_guidance_channels=256, # Hardcoded in original code
|
| 45 |
+
axes_dims_rope=[4, 4, 4, 4],
|
| 46 |
+
)
|
| 47 |
+
|
| 48 |
+
config = Mistral3Config(
|
| 49 |
+
text_config={
|
| 50 |
+
"model_type": "mistral",
|
| 51 |
+
"vocab_size": 32000,
|
| 52 |
+
"hidden_size": 16,
|
| 53 |
+
"intermediate_size": 37,
|
| 54 |
+
"max_position_embeddings": 512,
|
| 55 |
+
"num_attention_heads": 4,
|
| 56 |
+
"num_hidden_layers": 1,
|
| 57 |
+
"num_key_value_heads": 2,
|
| 58 |
+
"rms_norm_eps": 1e-05,
|
| 59 |
+
"rope_theta": 1000000000.0,
|
| 60 |
+
"sliding_window": None,
|
| 61 |
+
"bos_token_id": 2,
|
| 62 |
+
"eos_token_id": 3,
|
| 63 |
+
"pad_token_id": 4,
|
| 64 |
+
},
|
| 65 |
+
vision_config={
|
| 66 |
+
"model_type": "pixtral",
|
| 67 |
+
"hidden_size": 16,
|
| 68 |
+
"num_hidden_layers": 1,
|
| 69 |
+
"num_attention_heads": 4,
|
| 70 |
+
"intermediate_size": 37,
|
| 71 |
+
"image_size": 30,
|
| 72 |
+
"patch_size": 6,
|
| 73 |
+
"num_channels": 3,
|
| 74 |
+
},
|
| 75 |
+
bos_token_id=2,
|
| 76 |
+
eos_token_id=3,
|
| 77 |
+
pad_token_id=4,
|
| 78 |
+
model_dtype="mistral3",
|
| 79 |
+
image_seq_length=4,
|
| 80 |
+
vision_feature_layer=-1,
|
| 81 |
+
image_token_index=1,
|
| 82 |
+
)
|
| 83 |
+
torch.manual_seed(0)
|
| 84 |
+
text_encoder = Mistral3ForConditionalGeneration(config)
|
| 85 |
+
tokenizer = AutoProcessor.from_pretrained(
|
| 86 |
+
"hf-internal-testing/Mistral-Small-3.1-24B-Instruct-2503-only-processor"
|
| 87 |
+
)
|
| 88 |
+
|
| 89 |
+
torch.manual_seed(0)
|
| 90 |
+
vae = AutoencoderKLFlux2(
|
| 91 |
+
sample_size=32,
|
| 92 |
+
in_channels=3,
|
| 93 |
+
out_channels=3,
|
| 94 |
+
down_block_types=("DownEncoderBlock2D",),
|
| 95 |
+
up_block_types=("UpDecoderBlock2D",),
|
| 96 |
+
block_out_channels=(4,),
|
| 97 |
+
layers_per_block=1,
|
| 98 |
+
latent_channels=1,
|
| 99 |
+
norm_num_groups=1,
|
| 100 |
+
use_quant_conv=False,
|
| 101 |
+
use_post_quant_conv=False,
|
| 102 |
+
)
|
| 103 |
+
|
| 104 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 105 |
+
|
| 106 |
+
return {
|
| 107 |
+
"scheduler": scheduler,
|
| 108 |
+
"text_encoder": text_encoder,
|
| 109 |
+
"tokenizer": tokenizer,
|
| 110 |
+
"transformer": transformer,
|
| 111 |
+
"vae": vae,
|
| 112 |
+
}
|
| 113 |
+
|
| 114 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 115 |
+
if str(device).startswith("mps"):
|
| 116 |
+
generator = torch.manual_seed(seed)
|
| 117 |
+
else:
|
| 118 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 119 |
+
|
| 120 |
+
inputs = {
|
| 121 |
+
"prompt": "a dog is dancing",
|
| 122 |
+
"generator": generator,
|
| 123 |
+
"num_inference_steps": 2,
|
| 124 |
+
"guidance_scale": 5.0,
|
| 125 |
+
"height": 8,
|
| 126 |
+
"width": 8,
|
| 127 |
+
"max_sequence_length": 8,
|
| 128 |
+
"output_type": "np",
|
| 129 |
+
"text_encoder_out_layers": (1,),
|
| 130 |
+
}
|
| 131 |
+
return inputs
|
| 132 |
+
|
| 133 |
+
def test_fused_qkv_projections(self):
|
| 134 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 135 |
+
components = self.get_dummy_components()
|
| 136 |
+
pipe = self.pipeline_class(**components)
|
| 137 |
+
pipe = 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 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 143 |
+
|
| 144 |
+
# TODO (sayakpaul): will refactor this once `fuse_qkv_projections()` has been added
|
| 145 |
+
# to the pipeline level.
|
| 146 |
+
pipe.transformer.fuse_qkv_projections()
|
| 147 |
+
self.assertTrue(
|
| 148 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 149 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 150 |
+
)
|
| 151 |
+
|
| 152 |
+
inputs = self.get_dummy_inputs(device)
|
| 153 |
+
image = pipe(**inputs).images
|
| 154 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 155 |
+
|
| 156 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 157 |
+
inputs = self.get_dummy_inputs(device)
|
| 158 |
+
image = pipe(**inputs).images
|
| 159 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 160 |
+
|
| 161 |
+
self.assertTrue(
|
| 162 |
+
np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3),
|
| 163 |
+
("Fusion of QKV projections shouldn't affect the outputs."),
|
| 164 |
+
)
|
| 165 |
+
self.assertTrue(
|
| 166 |
+
np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3),
|
| 167 |
+
("Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."),
|
| 168 |
+
)
|
| 169 |
+
self.assertTrue(
|
| 170 |
+
np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2),
|
| 171 |
+
("Original outputs should match when fused QKV projections are disabled."),
|
| 172 |
+
)
|
| 173 |
+
|
| 174 |
+
def test_flux_image_output_shape(self):
|
| 175 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 176 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 177 |
+
|
| 178 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 179 |
+
for height, width in height_width_pairs:
|
| 180 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 181 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 182 |
+
|
| 183 |
+
inputs.update({"height": height, "width": width})
|
| 184 |
+
image = pipe(**inputs).images[0]
|
| 185 |
+
output_height, output_width, _ = image.shape
|
| 186 |
+
self.assertEqual(
|
| 187 |
+
(output_height, output_width),
|
| 188 |
+
(expected_height, expected_width),
|
| 189 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
|
| 190 |
+
)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein.py
ADDED
|
@@ -0,0 +1,283 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gc
|
| 2 |
+
import os
|
| 3 |
+
import unittest
|
| 4 |
+
|
| 5 |
+
import numpy as np
|
| 6 |
+
import torch
|
| 7 |
+
from PIL import Image
|
| 8 |
+
from transformers import Qwen2TokenizerFast, Qwen3Config, Qwen3ForCausalLM
|
| 9 |
+
|
| 10 |
+
from diffusers import (
|
| 11 |
+
AutoencoderKLFlux2,
|
| 12 |
+
FlowMatchEulerDiscreteScheduler,
|
| 13 |
+
Flux2KleinPipeline,
|
| 14 |
+
Flux2Transformer2DModel,
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
from ...testing_utils import (
|
| 18 |
+
backend_empty_cache,
|
| 19 |
+
backend_synchronize,
|
| 20 |
+
require_torch_neuron,
|
| 21 |
+
torch_device,
|
| 22 |
+
)
|
| 23 |
+
from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Flux2KleinPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 27 |
+
pipeline_class = Flux2KleinPipeline
|
| 28 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds"])
|
| 29 |
+
batch_params = frozenset(["prompt"])
|
| 30 |
+
|
| 31 |
+
test_xformers_attention = False
|
| 32 |
+
test_layerwise_casting = True
|
| 33 |
+
test_group_offloading = True
|
| 34 |
+
|
| 35 |
+
supports_dduf = False
|
| 36 |
+
|
| 37 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 38 |
+
torch.manual_seed(0)
|
| 39 |
+
transformer = Flux2Transformer2DModel(
|
| 40 |
+
patch_size=1,
|
| 41 |
+
in_channels=4,
|
| 42 |
+
num_layers=num_layers,
|
| 43 |
+
num_single_layers=num_single_layers,
|
| 44 |
+
attention_head_dim=16,
|
| 45 |
+
num_attention_heads=2,
|
| 46 |
+
joint_attention_dim=16,
|
| 47 |
+
timestep_guidance_channels=256,
|
| 48 |
+
axes_dims_rope=[4, 4, 4, 4],
|
| 49 |
+
guidance_embeds=False,
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
# Create minimal Qwen3 config
|
| 53 |
+
config = Qwen3Config(
|
| 54 |
+
intermediate_size=16,
|
| 55 |
+
hidden_size=16,
|
| 56 |
+
num_hidden_layers=2,
|
| 57 |
+
num_attention_heads=2,
|
| 58 |
+
num_key_value_heads=2,
|
| 59 |
+
vocab_size=151936,
|
| 60 |
+
max_position_embeddings=512,
|
| 61 |
+
)
|
| 62 |
+
torch.manual_seed(0)
|
| 63 |
+
text_encoder = Qwen3ForCausalLM(config)
|
| 64 |
+
|
| 65 |
+
# Use a simple tokenizer for testing
|
| 66 |
+
tokenizer = Qwen2TokenizerFast.from_pretrained(
|
| 67 |
+
"hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"
|
| 68 |
+
)
|
| 69 |
+
|
| 70 |
+
torch.manual_seed(0)
|
| 71 |
+
vae = AutoencoderKLFlux2(
|
| 72 |
+
sample_size=32,
|
| 73 |
+
in_channels=3,
|
| 74 |
+
out_channels=3,
|
| 75 |
+
down_block_types=("DownEncoderBlock2D",),
|
| 76 |
+
up_block_types=("UpDecoderBlock2D",),
|
| 77 |
+
block_out_channels=(4,),
|
| 78 |
+
layers_per_block=1,
|
| 79 |
+
latent_channels=1,
|
| 80 |
+
norm_num_groups=1,
|
| 81 |
+
use_quant_conv=False,
|
| 82 |
+
use_post_quant_conv=False,
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 86 |
+
|
| 87 |
+
return {
|
| 88 |
+
"scheduler": scheduler,
|
| 89 |
+
"text_encoder": text_encoder,
|
| 90 |
+
"tokenizer": tokenizer,
|
| 91 |
+
"transformer": transformer,
|
| 92 |
+
"vae": vae,
|
| 93 |
+
}
|
| 94 |
+
|
| 95 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 96 |
+
if str(device).startswith("mps"):
|
| 97 |
+
generator = torch.manual_seed(seed)
|
| 98 |
+
else:
|
| 99 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 100 |
+
|
| 101 |
+
inputs = {
|
| 102 |
+
"prompt": "a dog is dancing",
|
| 103 |
+
"generator": generator,
|
| 104 |
+
"num_inference_steps": 2,
|
| 105 |
+
"guidance_scale": 4.0,
|
| 106 |
+
"height": 8,
|
| 107 |
+
"width": 8,
|
| 108 |
+
"max_sequence_length": 64,
|
| 109 |
+
"output_type": "np",
|
| 110 |
+
"text_encoder_out_layers": (1,),
|
| 111 |
+
}
|
| 112 |
+
return inputs
|
| 113 |
+
|
| 114 |
+
def test_fused_qkv_projections(self):
|
| 115 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 116 |
+
components = self.get_dummy_components()
|
| 117 |
+
pipe = self.pipeline_class(**components)
|
| 118 |
+
pipe = pipe.to(device)
|
| 119 |
+
pipe.set_progress_bar_config(disable=None)
|
| 120 |
+
|
| 121 |
+
inputs = self.get_dummy_inputs(device)
|
| 122 |
+
image = pipe(**inputs).images
|
| 123 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 124 |
+
|
| 125 |
+
pipe.transformer.fuse_qkv_projections()
|
| 126 |
+
self.assertTrue(
|
| 127 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 128 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 129 |
+
)
|
| 130 |
+
|
| 131 |
+
inputs = self.get_dummy_inputs(device)
|
| 132 |
+
image = pipe(**inputs).images
|
| 133 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 134 |
+
|
| 135 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 136 |
+
inputs = self.get_dummy_inputs(device)
|
| 137 |
+
image = pipe(**inputs).images
|
| 138 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 139 |
+
|
| 140 |
+
self.assertTrue(
|
| 141 |
+
np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3),
|
| 142 |
+
("Fusion of QKV projections shouldn't affect the outputs."),
|
| 143 |
+
)
|
| 144 |
+
self.assertTrue(
|
| 145 |
+
np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3),
|
| 146 |
+
("Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."),
|
| 147 |
+
)
|
| 148 |
+
self.assertTrue(
|
| 149 |
+
np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2),
|
| 150 |
+
("Original outputs should match when fused QKV projections are disabled."),
|
| 151 |
+
)
|
| 152 |
+
|
| 153 |
+
def test_image_output_shape(self):
|
| 154 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 155 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 156 |
+
|
| 157 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 158 |
+
for height, width in height_width_pairs:
|
| 159 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 160 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 161 |
+
|
| 162 |
+
inputs.update({"height": height, "width": width})
|
| 163 |
+
image = pipe(**inputs).images[0]
|
| 164 |
+
output_height, output_width, _ = image.shape
|
| 165 |
+
self.assertEqual(
|
| 166 |
+
(output_height, output_width),
|
| 167 |
+
(expected_height, expected_width),
|
| 168 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
|
| 169 |
+
)
|
| 170 |
+
|
| 171 |
+
def test_image_input(self):
|
| 172 |
+
device = "cpu"
|
| 173 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(device)
|
| 174 |
+
inputs = self.get_dummy_inputs(device)
|
| 175 |
+
|
| 176 |
+
inputs["image"] = Image.new("RGB", (64, 64))
|
| 177 |
+
image = pipe(**inputs).images.flatten()
|
| 178 |
+
generated_slice = np.concatenate([image[:8], image[-8:]])
|
| 179 |
+
# fmt: off
|
| 180 |
+
expected_slice = np.array(
|
| 181 |
+
[
|
| 182 |
+
0.8255048 , 0.66054785, 0.6643694 , 0.67462724, 0.5494932 , 0.3480271 , 0.52535003, 0.44510138, 0.23549396, 0.21372932, 0.21166152, 0.63198495, 0.49942136, 0.39147034, 0.49156153, 0.3713916
|
| 183 |
+
]
|
| 184 |
+
)
|
| 185 |
+
# fmt: on
|
| 186 |
+
assert np.allclose(expected_slice, generated_slice, atol=1e-4, rtol=1e-4)
|
| 187 |
+
|
| 188 |
+
@unittest.skip("Needs to be revisited")
|
| 189 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 190 |
+
pass
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
@require_torch_neuron
|
| 194 |
+
class Flux2KleinPipelineIntegrationTests(unittest.TestCase):
|
| 195 |
+
ckpt_id = "black-forest-labs/FLUX.2-klein-4B"
|
| 196 |
+
prompt = "A small cactus with a happy face in the Sahara desert."
|
| 197 |
+
|
| 198 |
+
def setUp(self):
|
| 199 |
+
super().setUp()
|
| 200 |
+
self._saved_env = {}
|
| 201 |
+
neff_cache_dir = "/tmp/neff_cache"
|
| 202 |
+
os.makedirs(neff_cache_dir, exist_ok=True)
|
| 203 |
+
for key in ("TORCH_NEURONX_NEFF_CACHE_DIR", "TORCH_NEURONX_ENABLE_NKI_SDPA"):
|
| 204 |
+
self._saved_env[key] = os.environ.get(key)
|
| 205 |
+
os.environ["TORCH_NEURONX_NEFF_CACHE_DIR"] = neff_cache_dir
|
| 206 |
+
os.environ.setdefault("TORCH_NEURONX_ENABLE_NKI_SDPA", "0")
|
| 207 |
+
gc.collect()
|
| 208 |
+
backend_empty_cache(torch_device)
|
| 209 |
+
|
| 210 |
+
def tearDown(self):
|
| 211 |
+
super().tearDown()
|
| 212 |
+
for key, original in self._saved_env.items():
|
| 213 |
+
if original is None:
|
| 214 |
+
os.environ.pop(key, None)
|
| 215 |
+
else:
|
| 216 |
+
os.environ[key] = original
|
| 217 |
+
gc.collect()
|
| 218 |
+
backend_empty_cache(torch_device)
|
| 219 |
+
|
| 220 |
+
def test_flux2_klein_inference_512(self):
|
| 221 |
+
generator = torch.Generator("cpu").manual_seed(0)
|
| 222 |
+
|
| 223 |
+
pipe = Flux2KleinPipeline.from_pretrained(self.ckpt_id, torch_dtype=torch.bfloat16)
|
| 224 |
+
pipe.to(torch_device)
|
| 225 |
+
backend_synchronize(torch_device)
|
| 226 |
+
pipe.set_progress_bar_config(disable=None)
|
| 227 |
+
|
| 228 |
+
image = pipe(
|
| 229 |
+
prompt=self.prompt,
|
| 230 |
+
height=512,
|
| 231 |
+
width=512,
|
| 232 |
+
num_inference_steps=4,
|
| 233 |
+
guidance_scale=1.0,
|
| 234 |
+
generator=generator,
|
| 235 |
+
output_type="np",
|
| 236 |
+
).images
|
| 237 |
+
|
| 238 |
+
image_slice = image[0, -3:, -3:, -1]
|
| 239 |
+
self.assertEqual(image.shape, (1, 512, 512, 3))
|
| 240 |
+
self.assertTrue(np.all((image >= 0.0) & (image <= 1.0)), "Pixel values must be in [0, 1]")
|
| 241 |
+
expected_slice = np.array([0.3652, 0.3574, 0.3633, 0.4102, 0.4062, 0.4043, 0.4453, 0.4355, 0.4570])
|
| 242 |
+
self.assertLess(np.abs(image_slice.flatten() - expected_slice).max(), 5e-2)
|
| 243 |
+
|
| 244 |
+
@require_torch_neuron
|
| 245 |
+
def test_flux2_klein_neuron_compile_128(self):
|
| 246 |
+
from torch_neuronx.neuron_dynamo_backend import set_model_name
|
| 247 |
+
|
| 248 |
+
device = torch.neuron.current_device()
|
| 249 |
+
generator = torch.Generator("cpu").manual_seed(0)
|
| 250 |
+
|
| 251 |
+
pipe = Flux2KleinPipeline.from_pretrained(self.ckpt_id, torch_dtype=torch.bfloat16)
|
| 252 |
+
pipe = pipe.to(device)
|
| 253 |
+
backend_synchronize(torch_device)
|
| 254 |
+
|
| 255 |
+
pipe.transformer.eval()
|
| 256 |
+
pipe.vae.eval()
|
| 257 |
+
pipe.text_encoder.eval()
|
| 258 |
+
|
| 259 |
+
# Keep the text encoder eager: it reads intermediate hidden_states, which
|
| 260 |
+
# transformers only materializes outside of torch.compile(fullgraph=True).
|
| 261 |
+
# It runs once per generation, so leaving it uncompiled is negligible.
|
| 262 |
+
set_model_name("flux2_klein_transformer")
|
| 263 |
+
pipe.transformer = torch.compile(pipe.transformer, backend="neuron", fullgraph=True)
|
| 264 |
+
|
| 265 |
+
set_model_name("flux2_klein_vae")
|
| 266 |
+
pipe.vae = torch.compile(pipe.vae, backend="neuron", fullgraph=True)
|
| 267 |
+
|
| 268 |
+
image = pipe(
|
| 269 |
+
prompt=self.prompt,
|
| 270 |
+
height=128,
|
| 271 |
+
width=128,
|
| 272 |
+
num_inference_steps=4,
|
| 273 |
+
guidance_scale=1.0,
|
| 274 |
+
generator=generator,
|
| 275 |
+
output_type="np",
|
| 276 |
+
).images
|
| 277 |
+
|
| 278 |
+
self.assertEqual(image.shape, (1, 128, 128, 3))
|
| 279 |
+
self.assertFalse(np.isnan(image).any(), "Output contains NaN values")
|
| 280 |
+
self.assertTrue(
|
| 281 |
+
(image >= 0.0).all() and (image <= 1.0).all(),
|
| 282 |
+
"Output pixel values outside [0, 1]",
|
| 283 |
+
)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein_inpaint.py
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import random
|
| 2 |
+
import unittest
|
| 3 |
+
|
| 4 |
+
import numpy as np
|
| 5 |
+
import torch
|
| 6 |
+
from transformers import Qwen2TokenizerFast, Qwen3Config, Qwen3ForCausalLM
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKLFlux2,
|
| 10 |
+
FlowMatchEulerDiscreteScheduler,
|
| 11 |
+
Flux2KleinInpaintPipeline,
|
| 12 |
+
Flux2Transformer2DModel,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from ...testing_utils import (
|
| 16 |
+
enable_full_determinism,
|
| 17 |
+
floats_tensor,
|
| 18 |
+
torch_device,
|
| 19 |
+
)
|
| 20 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
enable_full_determinism()
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class Flux2KleinInpaintPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 27 |
+
pipeline_class = Flux2KleinInpaintPipeline
|
| 28 |
+
params = frozenset(
|
| 29 |
+
["prompt", "image", "image_reference", "mask_image", "height", "width", "guidance_scale", "prompt_embeds"]
|
| 30 |
+
)
|
| 31 |
+
batch_params = frozenset(["prompt", "image", "image_reference", "mask_image"])
|
| 32 |
+
|
| 33 |
+
test_xformers_attention = False
|
| 34 |
+
test_layerwise_casting = True
|
| 35 |
+
test_group_offloading = True
|
| 36 |
+
|
| 37 |
+
supports_dduf = False
|
| 38 |
+
|
| 39 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 40 |
+
torch.manual_seed(0)
|
| 41 |
+
transformer = Flux2Transformer2DModel(
|
| 42 |
+
patch_size=1,
|
| 43 |
+
in_channels=4,
|
| 44 |
+
num_layers=num_layers,
|
| 45 |
+
num_single_layers=num_single_layers,
|
| 46 |
+
attention_head_dim=16,
|
| 47 |
+
num_attention_heads=2,
|
| 48 |
+
joint_attention_dim=16,
|
| 49 |
+
timestep_guidance_channels=256,
|
| 50 |
+
axes_dims_rope=[4, 4, 4, 4],
|
| 51 |
+
guidance_embeds=False,
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
# Create minimal Qwen3 config
|
| 55 |
+
config = Qwen3Config(
|
| 56 |
+
intermediate_size=16,
|
| 57 |
+
hidden_size=16,
|
| 58 |
+
num_hidden_layers=2,
|
| 59 |
+
num_attention_heads=2,
|
| 60 |
+
num_key_value_heads=2,
|
| 61 |
+
vocab_size=151936,
|
| 62 |
+
max_position_embeddings=512,
|
| 63 |
+
)
|
| 64 |
+
torch.manual_seed(0)
|
| 65 |
+
text_encoder = Qwen3ForCausalLM(config)
|
| 66 |
+
|
| 67 |
+
# Use a simple tokenizer for testing
|
| 68 |
+
tokenizer = Qwen2TokenizerFast.from_pretrained(
|
| 69 |
+
"hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"
|
| 70 |
+
)
|
| 71 |
+
|
| 72 |
+
torch.manual_seed(0)
|
| 73 |
+
vae = AutoencoderKLFlux2(
|
| 74 |
+
sample_size=32,
|
| 75 |
+
in_channels=3,
|
| 76 |
+
out_channels=3,
|
| 77 |
+
down_block_types=("DownEncoderBlock2D",),
|
| 78 |
+
up_block_types=("UpDecoderBlock2D",),
|
| 79 |
+
block_out_channels=(4,),
|
| 80 |
+
layers_per_block=1,
|
| 81 |
+
latent_channels=1,
|
| 82 |
+
norm_num_groups=1,
|
| 83 |
+
use_quant_conv=False,
|
| 84 |
+
use_post_quant_conv=False,
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 88 |
+
|
| 89 |
+
return {
|
| 90 |
+
"scheduler": scheduler,
|
| 91 |
+
"text_encoder": text_encoder,
|
| 92 |
+
"tokenizer": tokenizer,
|
| 93 |
+
"transformer": transformer,
|
| 94 |
+
"vae": vae,
|
| 95 |
+
}
|
| 96 |
+
|
| 97 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 98 |
+
image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)
|
| 99 |
+
mask_image = torch.ones((1, 1, 32, 32)).to(device)
|
| 100 |
+
|
| 101 |
+
if str(device).startswith("mps"):
|
| 102 |
+
generator = torch.manual_seed(seed)
|
| 103 |
+
else:
|
| 104 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 105 |
+
|
| 106 |
+
inputs = {
|
| 107 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 108 |
+
"image": image,
|
| 109 |
+
"mask_image": mask_image,
|
| 110 |
+
"generator": generator,
|
| 111 |
+
"num_inference_steps": 2,
|
| 112 |
+
"guidance_scale": 8.0,
|
| 113 |
+
"height": 32,
|
| 114 |
+
"width": 32,
|
| 115 |
+
"max_sequence_length": 64,
|
| 116 |
+
"strength": 0.8,
|
| 117 |
+
"output_type": "np",
|
| 118 |
+
"text_encoder_out_layers": (1,),
|
| 119 |
+
}
|
| 120 |
+
return inputs
|
| 121 |
+
|
| 122 |
+
def test_flux2_klein_inpaint_different_prompts(self):
|
| 123 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 124 |
+
|
| 125 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 126 |
+
output_same_prompt = pipe(**inputs).images[0]
|
| 127 |
+
|
| 128 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 129 |
+
inputs["prompt"] = "a different prompt"
|
| 130 |
+
output_different_prompts = pipe(**inputs).images[0]
|
| 131 |
+
|
| 132 |
+
max_diff = np.abs(output_same_prompt - output_different_prompts).max()
|
| 133 |
+
|
| 134 |
+
# Outputs should be different here
|
| 135 |
+
assert max_diff > 1e-6
|
| 136 |
+
|
| 137 |
+
def test_flux2_klein_inpaint_image_output_shape(self):
|
| 138 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 139 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 140 |
+
|
| 141 |
+
height_width_pairs = [(32, 32), (72, 56)]
|
| 142 |
+
for height, width in height_width_pairs:
|
| 143 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 144 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 145 |
+
|
| 146 |
+
# Update image and mask to match height/width
|
| 147 |
+
image = floats_tensor((1, 3, height, width), rng=random.Random(0)).to(torch_device)
|
| 148 |
+
mask_image = torch.ones((1, 1, height, width)).to(torch_device)
|
| 149 |
+
|
| 150 |
+
inputs.update({"height": height, "width": width, "image": image, "mask_image": mask_image})
|
| 151 |
+
image = pipe(**inputs).images[0]
|
| 152 |
+
output_height, output_width, _ = image.shape
|
| 153 |
+
self.assertEqual(
|
| 154 |
+
(output_height, output_width),
|
| 155 |
+
(expected_height, expected_width),
|
| 156 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
|
| 157 |
+
)
|
| 158 |
+
|
| 159 |
+
def test_flux2_klein_inpaint_strength(self):
|
| 160 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 161 |
+
|
| 162 |
+
# Test with strength=1.0 (full denoising)
|
| 163 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 164 |
+
inputs["strength"] = 1.0
|
| 165 |
+
output_full_strength = pipe(**inputs).images[0]
|
| 166 |
+
|
| 167 |
+
# Test with strength=0.5 (partial denoising)
|
| 168 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 169 |
+
inputs["strength"] = 0.5
|
| 170 |
+
output_half_strength = pipe(**inputs).images[0]
|
| 171 |
+
|
| 172 |
+
max_diff = np.abs(output_full_strength - output_half_strength).max()
|
| 173 |
+
|
| 174 |
+
# Outputs should be different with different strength values
|
| 175 |
+
assert max_diff > 1e-6
|
| 176 |
+
|
| 177 |
+
def test_flux2_klein_inpaint_image_reference(self):
|
| 178 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 179 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 180 |
+
|
| 181 |
+
# Add a reference image to the inputs
|
| 182 |
+
ref_image = floats_tensor((1, 3, 32, 32), rng=random.Random(1)).to(torch_device)
|
| 183 |
+
inputs["image_reference"] = ref_image
|
| 184 |
+
|
| 185 |
+
image = pipe(**inputs).images[0]
|
| 186 |
+
|
| 187 |
+
expected_height = inputs["height"] - inputs["height"] % (pipe.vae_scale_factor * 2)
|
| 188 |
+
expected_width = inputs["width"] - inputs["width"] % (pipe.vae_scale_factor * 2)
|
| 189 |
+
|
| 190 |
+
output_height, output_width, _ = image.shape
|
| 191 |
+
self.assertEqual(
|
| 192 |
+
(output_height, output_width),
|
| 193 |
+
(expected_height, expected_width),
|
| 194 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)} when conditioned on a reference image.",
|
| 195 |
+
)
|
| 196 |
+
|
| 197 |
+
@unittest.skip("Needs to be revisited")
|
| 198 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 199 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/flux2/test_pipeline_flux2_klein_kv.py
ADDED
|
@@ -0,0 +1,174 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import unittest
|
| 2 |
+
|
| 3 |
+
import numpy as np
|
| 4 |
+
import torch
|
| 5 |
+
from PIL import Image
|
| 6 |
+
from transformers import Qwen2TokenizerFast, Qwen3Config, Qwen3ForCausalLM
|
| 7 |
+
|
| 8 |
+
from diffusers import (
|
| 9 |
+
AutoencoderKLFlux2,
|
| 10 |
+
FlowMatchEulerDiscreteScheduler,
|
| 11 |
+
Flux2KleinKVPipeline,
|
| 12 |
+
Flux2Transformer2DModel,
|
| 13 |
+
)
|
| 14 |
+
|
| 15 |
+
from ...testing_utils import torch_device
|
| 16 |
+
from ..test_pipelines_common import PipelineTesterMixin, check_qkv_fused_layers_exist
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
class Flux2KleinKVPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 20 |
+
pipeline_class = Flux2KleinKVPipeline
|
| 21 |
+
params = frozenset(["prompt", "height", "width", "prompt_embeds", "image"])
|
| 22 |
+
batch_params = frozenset(["prompt"])
|
| 23 |
+
|
| 24 |
+
test_xformers_attention = False
|
| 25 |
+
test_layerwise_casting = True
|
| 26 |
+
test_group_offloading = True
|
| 27 |
+
|
| 28 |
+
supports_dduf = False
|
| 29 |
+
|
| 30 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 31 |
+
torch.manual_seed(0)
|
| 32 |
+
transformer = Flux2Transformer2DModel(
|
| 33 |
+
patch_size=1,
|
| 34 |
+
in_channels=4,
|
| 35 |
+
num_layers=num_layers,
|
| 36 |
+
num_single_layers=num_single_layers,
|
| 37 |
+
attention_head_dim=16,
|
| 38 |
+
num_attention_heads=2,
|
| 39 |
+
joint_attention_dim=16,
|
| 40 |
+
timestep_guidance_channels=256,
|
| 41 |
+
axes_dims_rope=[4, 4, 4, 4],
|
| 42 |
+
guidance_embeds=False,
|
| 43 |
+
)
|
| 44 |
+
|
| 45 |
+
# Create minimal Qwen3 config
|
| 46 |
+
config = Qwen3Config(
|
| 47 |
+
intermediate_size=16,
|
| 48 |
+
hidden_size=16,
|
| 49 |
+
num_hidden_layers=2,
|
| 50 |
+
num_attention_heads=2,
|
| 51 |
+
num_key_value_heads=2,
|
| 52 |
+
vocab_size=151936,
|
| 53 |
+
max_position_embeddings=512,
|
| 54 |
+
)
|
| 55 |
+
torch.manual_seed(0)
|
| 56 |
+
text_encoder = Qwen3ForCausalLM(config)
|
| 57 |
+
|
| 58 |
+
# Use a simple tokenizer for testing
|
| 59 |
+
tokenizer = Qwen2TokenizerFast.from_pretrained(
|
| 60 |
+
"hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration"
|
| 61 |
+
)
|
| 62 |
+
|
| 63 |
+
torch.manual_seed(0)
|
| 64 |
+
vae = AutoencoderKLFlux2(
|
| 65 |
+
sample_size=32,
|
| 66 |
+
in_channels=3,
|
| 67 |
+
out_channels=3,
|
| 68 |
+
down_block_types=("DownEncoderBlock2D",),
|
| 69 |
+
up_block_types=("UpDecoderBlock2D",),
|
| 70 |
+
block_out_channels=(4,),
|
| 71 |
+
layers_per_block=1,
|
| 72 |
+
latent_channels=1,
|
| 73 |
+
norm_num_groups=1,
|
| 74 |
+
use_quant_conv=False,
|
| 75 |
+
use_post_quant_conv=False,
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 79 |
+
|
| 80 |
+
return {
|
| 81 |
+
"scheduler": scheduler,
|
| 82 |
+
"text_encoder": text_encoder,
|
| 83 |
+
"tokenizer": tokenizer,
|
| 84 |
+
"transformer": transformer,
|
| 85 |
+
"vae": vae,
|
| 86 |
+
}
|
| 87 |
+
|
| 88 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 89 |
+
if str(device).startswith("mps"):
|
| 90 |
+
generator = torch.manual_seed(seed)
|
| 91 |
+
else:
|
| 92 |
+
generator = torch.Generator(device="cpu").manual_seed(seed)
|
| 93 |
+
|
| 94 |
+
inputs = {
|
| 95 |
+
"prompt": "a dog is dancing",
|
| 96 |
+
"image": Image.new("RGB", (64, 64)),
|
| 97 |
+
"generator": generator,
|
| 98 |
+
"num_inference_steps": 2,
|
| 99 |
+
"height": 8,
|
| 100 |
+
"width": 8,
|
| 101 |
+
"max_sequence_length": 64,
|
| 102 |
+
"output_type": "np",
|
| 103 |
+
"text_encoder_out_layers": (1,),
|
| 104 |
+
}
|
| 105 |
+
return inputs
|
| 106 |
+
|
| 107 |
+
def test_fused_qkv_projections(self):
|
| 108 |
+
device = "cpu" # ensure determinism for the device-dependent torch.Generator
|
| 109 |
+
components = self.get_dummy_components()
|
| 110 |
+
pipe = self.pipeline_class(**components)
|
| 111 |
+
pipe = pipe.to(device)
|
| 112 |
+
pipe.set_progress_bar_config(disable=None)
|
| 113 |
+
|
| 114 |
+
inputs = self.get_dummy_inputs(device)
|
| 115 |
+
image = pipe(**inputs).images
|
| 116 |
+
original_image_slice = image[0, -3:, -3:, -1]
|
| 117 |
+
|
| 118 |
+
pipe.transformer.fuse_qkv_projections()
|
| 119 |
+
self.assertTrue(
|
| 120 |
+
check_qkv_fused_layers_exist(pipe.transformer, ["to_qkv"]),
|
| 121 |
+
("Something wrong with the fused attention layers. Expected all the attention projections to be fused."),
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
inputs = self.get_dummy_inputs(device)
|
| 125 |
+
image = pipe(**inputs).images
|
| 126 |
+
image_slice_fused = image[0, -3:, -3:, -1]
|
| 127 |
+
|
| 128 |
+
pipe.transformer.unfuse_qkv_projections()
|
| 129 |
+
inputs = self.get_dummy_inputs(device)
|
| 130 |
+
image = pipe(**inputs).images
|
| 131 |
+
image_slice_disabled = image[0, -3:, -3:, -1]
|
| 132 |
+
|
| 133 |
+
self.assertTrue(
|
| 134 |
+
np.allclose(original_image_slice, image_slice_fused, atol=1e-3, rtol=1e-3),
|
| 135 |
+
("Fusion of QKV projections shouldn't affect the outputs."),
|
| 136 |
+
)
|
| 137 |
+
self.assertTrue(
|
| 138 |
+
np.allclose(image_slice_fused, image_slice_disabled, atol=1e-3, rtol=1e-3),
|
| 139 |
+
("Outputs, with QKV projection fusion enabled, shouldn't change when fused QKV projections are disabled."),
|
| 140 |
+
)
|
| 141 |
+
self.assertTrue(
|
| 142 |
+
np.allclose(original_image_slice, image_slice_disabled, atol=1e-2, rtol=1e-2),
|
| 143 |
+
("Original outputs should match when fused QKV projections are disabled."),
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
def test_image_output_shape(self):
|
| 147 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(torch_device)
|
| 148 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 149 |
+
|
| 150 |
+
height_width_pairs = [(32, 32), (72, 57)]
|
| 151 |
+
for height, width in height_width_pairs:
|
| 152 |
+
expected_height = height - height % (pipe.vae_scale_factor * 2)
|
| 153 |
+
expected_width = width - width % (pipe.vae_scale_factor * 2)
|
| 154 |
+
|
| 155 |
+
inputs.update({"height": height, "width": width})
|
| 156 |
+
image = pipe(**inputs).images[0]
|
| 157 |
+
output_height, output_width, _ = image.shape
|
| 158 |
+
self.assertEqual(
|
| 159 |
+
(output_height, output_width),
|
| 160 |
+
(expected_height, expected_width),
|
| 161 |
+
f"Output shape {image.shape} does not match expected shape {(expected_height, expected_width)}",
|
| 162 |
+
)
|
| 163 |
+
|
| 164 |
+
def test_without_image(self):
|
| 165 |
+
device = "cpu"
|
| 166 |
+
pipe = self.pipeline_class(**self.get_dummy_components()).to(device)
|
| 167 |
+
inputs = self.get_dummy_inputs(device)
|
| 168 |
+
del inputs["image"]
|
| 169 |
+
image = pipe(**inputs).images
|
| 170 |
+
self.assertEqual(image.shape, (1, 8, 8, 3))
|
| 171 |
+
|
| 172 |
+
@unittest.skip("Needs to be revisited")
|
| 173 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 174 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/glm_image/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/glm_image/test_glm_image.py
ADDED
|
@@ -0,0 +1,397 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
|
| 20 |
+
|
| 21 |
+
from diffusers import AutoencoderKL, FlowMatchEulerDiscreteScheduler, GlmImagePipeline, GlmImageTransformer2DModel
|
| 22 |
+
from diffusers.utils import is_transformers_version
|
| 23 |
+
|
| 24 |
+
from ...testing_utils import enable_full_determinism, require_torch_accelerator, require_transformers_version_greater
|
| 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
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
if is_transformers_version(">=", "5.0.0.dev0"):
|
| 30 |
+
from transformers import GlmImageConfig, GlmImageForConditionalGeneration, GlmImageProcessor
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
enable_full_determinism()
|
| 34 |
+
|
| 35 |
+
|
| 36 |
+
@require_transformers_version_greater("4.57.4")
|
| 37 |
+
@require_torch_accelerator
|
| 38 |
+
class GlmImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 39 |
+
pipeline_class = GlmImagePipeline
|
| 40 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs", "negative_prompt"}
|
| 41 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 42 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 43 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 44 |
+
required_optional_params = frozenset(
|
| 45 |
+
[
|
| 46 |
+
"num_inference_steps",
|
| 47 |
+
"generator",
|
| 48 |
+
"latents",
|
| 49 |
+
"return_dict",
|
| 50 |
+
"callback_on_step_end",
|
| 51 |
+
"callback_on_step_end_tensor_inputs",
|
| 52 |
+
]
|
| 53 |
+
)
|
| 54 |
+
test_xformers_attention = False
|
| 55 |
+
test_attention_slicing = False
|
| 56 |
+
supports_dduf = False
|
| 57 |
+
|
| 58 |
+
def get_dummy_components(self):
|
| 59 |
+
torch.manual_seed(0)
|
| 60 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 61 |
+
text_encoder = T5EncoderModel(config)
|
| 62 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 63 |
+
|
| 64 |
+
glm_config = GlmImageConfig(
|
| 65 |
+
text_config={
|
| 66 |
+
"vocab_size": 168064,
|
| 67 |
+
"hidden_size": 32,
|
| 68 |
+
"intermediate_size": 32,
|
| 69 |
+
"num_hidden_layers": 2,
|
| 70 |
+
"num_attention_heads": 2,
|
| 71 |
+
"num_key_value_heads": 2,
|
| 72 |
+
"max_position_embeddings": 512,
|
| 73 |
+
"vision_vocab_size": 128,
|
| 74 |
+
"rope_parameters": {"mrope_section": (4, 2, 2)},
|
| 75 |
+
},
|
| 76 |
+
vision_config={
|
| 77 |
+
"depth": 2,
|
| 78 |
+
"hidden_size": 32,
|
| 79 |
+
"num_heads": 2,
|
| 80 |
+
"image_size": 32,
|
| 81 |
+
"patch_size": 8,
|
| 82 |
+
"intermediate_size": 32,
|
| 83 |
+
},
|
| 84 |
+
vq_config={"embed_dim": 32, "num_embeddings": 128, "latent_channels": 32},
|
| 85 |
+
)
|
| 86 |
+
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
vision_language_encoder = GlmImageForConditionalGeneration(glm_config)
|
| 89 |
+
|
| 90 |
+
processor = GlmImageProcessor.from_pretrained("zai-org/GLM-Image", subfolder="processor")
|
| 91 |
+
|
| 92 |
+
torch.manual_seed(0)
|
| 93 |
+
# For GLM-Image, the relationship between components must satisfy:
|
| 94 |
+
# patch_size × vae_scale_factor = 16 (since AR tokens are upsampled 2× from d32)
|
| 95 |
+
transformer = GlmImageTransformer2DModel(
|
| 96 |
+
patch_size=2,
|
| 97 |
+
in_channels=4,
|
| 98 |
+
out_channels=4,
|
| 99 |
+
num_layers=2,
|
| 100 |
+
attention_head_dim=8,
|
| 101 |
+
num_attention_heads=2,
|
| 102 |
+
text_embed_dim=text_encoder.config.hidden_size,
|
| 103 |
+
time_embed_dim=16,
|
| 104 |
+
condition_dim=8,
|
| 105 |
+
prior_vq_quantizer_codebook_size=128,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
torch.manual_seed(0)
|
| 109 |
+
vae = AutoencoderKL(
|
| 110 |
+
block_out_channels=(4, 8, 16, 16),
|
| 111 |
+
in_channels=3,
|
| 112 |
+
out_channels=3,
|
| 113 |
+
down_block_types=["DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D", "DownEncoderBlock2D"],
|
| 114 |
+
up_block_types=["UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D", "UpDecoderBlock2D"],
|
| 115 |
+
latent_channels=4,
|
| 116 |
+
norm_num_groups=4,
|
| 117 |
+
sample_size=128,
|
| 118 |
+
latents_mean=[0.0] * 4,
|
| 119 |
+
latents_std=[1.0] * 4,
|
| 120 |
+
)
|
| 121 |
+
|
| 122 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 123 |
+
|
| 124 |
+
components = {
|
| 125 |
+
"tokenizer": tokenizer,
|
| 126 |
+
"processor": processor,
|
| 127 |
+
"text_encoder": text_encoder,
|
| 128 |
+
"vision_language_encoder": vision_language_encoder,
|
| 129 |
+
"vae": vae,
|
| 130 |
+
"transformer": transformer,
|
| 131 |
+
"scheduler": scheduler,
|
| 132 |
+
}
|
| 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 |
+
height, width = 32, 32
|
| 143 |
+
|
| 144 |
+
inputs = {
|
| 145 |
+
"prompt": "A photo of a cat",
|
| 146 |
+
"generator": generator,
|
| 147 |
+
"num_inference_steps": 2,
|
| 148 |
+
"guidance_scale": 1.5,
|
| 149 |
+
"height": height,
|
| 150 |
+
"width": width,
|
| 151 |
+
"max_sequence_length": 16,
|
| 152 |
+
"output_type": "pt",
|
| 153 |
+
}
|
| 154 |
+
|
| 155 |
+
return inputs
|
| 156 |
+
|
| 157 |
+
def test_inference(self):
|
| 158 |
+
device = "cpu"
|
| 159 |
+
|
| 160 |
+
components = self.get_dummy_components()
|
| 161 |
+
pipe = self.pipeline_class(**components)
|
| 162 |
+
pipe.to(device)
|
| 163 |
+
pipe.set_progress_bar_config(disable=None)
|
| 164 |
+
|
| 165 |
+
inputs = self.get_dummy_inputs(device)
|
| 166 |
+
image = pipe(**inputs).images[0]
|
| 167 |
+
generated_slice = image.flatten()
|
| 168 |
+
generated_slice = np.concatenate([generated_slice[:8], generated_slice[-8:]])
|
| 169 |
+
|
| 170 |
+
# fmt: off
|
| 171 |
+
expected_slice = np.array(
|
| 172 |
+
[
|
| 173 |
+
0.5849247, 0.50278825, 0.45747858, 0.45895284, 0.43804976, 0.47044256, 0.5239665, 0.47904694, 0.3323419, 0.38725388, 0.28505728, 0.3161863, 0.35026982, 0.37546024, 0.4090118, 0.46629113
|
| 174 |
+
]
|
| 175 |
+
)
|
| 176 |
+
# fmt: on
|
| 177 |
+
|
| 178 |
+
self.assertEqual(image.shape, (3, 32, 32))
|
| 179 |
+
self.assertTrue(np.allclose(expected_slice, generated_slice, atol=1e-4, rtol=1e-4))
|
| 180 |
+
|
| 181 |
+
def test_inference_batch_single_identical(self):
|
| 182 |
+
"""Test that batch=1 produces consistent results with the same seed."""
|
| 183 |
+
device = "cpu"
|
| 184 |
+
components = self.get_dummy_components()
|
| 185 |
+
pipe = self.pipeline_class(**components)
|
| 186 |
+
pipe.to(device)
|
| 187 |
+
pipe.set_progress_bar_config(disable=None)
|
| 188 |
+
|
| 189 |
+
# Run twice with same seed
|
| 190 |
+
inputs1 = self.get_dummy_inputs(device, seed=42)
|
| 191 |
+
inputs2 = self.get_dummy_inputs(device, seed=42)
|
| 192 |
+
|
| 193 |
+
image1 = pipe(**inputs1).images[0]
|
| 194 |
+
image2 = pipe(**inputs2).images[0]
|
| 195 |
+
|
| 196 |
+
self.assertTrue(torch.allclose(image1, image2, atol=1e-4))
|
| 197 |
+
|
| 198 |
+
def test_inference_batch_multiple_prompts(self):
|
| 199 |
+
"""Test batch processing with multiple prompts."""
|
| 200 |
+
device = "cpu"
|
| 201 |
+
components = self.get_dummy_components()
|
| 202 |
+
pipe = self.pipeline_class(**components)
|
| 203 |
+
pipe.to(device)
|
| 204 |
+
pipe.set_progress_bar_config(disable=None)
|
| 205 |
+
|
| 206 |
+
generator = torch.Generator(device=device).manual_seed(42)
|
| 207 |
+
height, width = 32, 32
|
| 208 |
+
|
| 209 |
+
inputs = {
|
| 210 |
+
"prompt": ["A photo of a cat", "A photo of a dog"],
|
| 211 |
+
"generator": generator,
|
| 212 |
+
"num_inference_steps": 2,
|
| 213 |
+
"guidance_scale": 1.5,
|
| 214 |
+
"height": height,
|
| 215 |
+
"width": width,
|
| 216 |
+
"max_sequence_length": 16,
|
| 217 |
+
"output_type": "pt",
|
| 218 |
+
}
|
| 219 |
+
|
| 220 |
+
images = pipe(**inputs).images
|
| 221 |
+
|
| 222 |
+
# Should return 2 images
|
| 223 |
+
self.assertEqual(len(images), 2)
|
| 224 |
+
self.assertEqual(images[0].shape, (3, 32, 32))
|
| 225 |
+
self.assertEqual(images[1].shape, (3, 32, 32))
|
| 226 |
+
|
| 227 |
+
def test_num_images_per_prompt(self):
|
| 228 |
+
"""Test generating multiple images per prompt."""
|
| 229 |
+
device = "cpu"
|
| 230 |
+
components = self.get_dummy_components()
|
| 231 |
+
pipe = self.pipeline_class(**components)
|
| 232 |
+
pipe.to(device)
|
| 233 |
+
pipe.set_progress_bar_config(disable=None)
|
| 234 |
+
|
| 235 |
+
generator = torch.Generator(device=device).manual_seed(42)
|
| 236 |
+
height, width = 32, 32
|
| 237 |
+
|
| 238 |
+
inputs = {
|
| 239 |
+
"prompt": "A photo of a cat",
|
| 240 |
+
"generator": generator,
|
| 241 |
+
"num_inference_steps": 2,
|
| 242 |
+
"guidance_scale": 1.5,
|
| 243 |
+
"height": height,
|
| 244 |
+
"width": width,
|
| 245 |
+
"max_sequence_length": 16,
|
| 246 |
+
"output_type": "pt",
|
| 247 |
+
"num_images_per_prompt": 2,
|
| 248 |
+
}
|
| 249 |
+
|
| 250 |
+
images = pipe(**inputs).images
|
| 251 |
+
|
| 252 |
+
# Should return 2 images for single prompt
|
| 253 |
+
self.assertEqual(len(images), 2)
|
| 254 |
+
self.assertEqual(images[0].shape, (3, 32, 32))
|
| 255 |
+
self.assertEqual(images[1].shape, (3, 32, 32))
|
| 256 |
+
|
| 257 |
+
def test_batch_with_num_images_per_prompt(self):
|
| 258 |
+
"""Test batch prompts with num_images_per_prompt > 1."""
|
| 259 |
+
device = "cpu"
|
| 260 |
+
components = self.get_dummy_components()
|
| 261 |
+
pipe = self.pipeline_class(**components)
|
| 262 |
+
pipe.to(device)
|
| 263 |
+
pipe.set_progress_bar_config(disable=None)
|
| 264 |
+
|
| 265 |
+
generator = torch.Generator(device=device).manual_seed(42)
|
| 266 |
+
height, width = 32, 32
|
| 267 |
+
|
| 268 |
+
inputs = {
|
| 269 |
+
"prompt": ["A photo of a cat", "A photo of a dog"],
|
| 270 |
+
"generator": generator,
|
| 271 |
+
"num_inference_steps": 2,
|
| 272 |
+
"guidance_scale": 1.5,
|
| 273 |
+
"height": height,
|
| 274 |
+
"width": width,
|
| 275 |
+
"max_sequence_length": 16,
|
| 276 |
+
"output_type": "pt",
|
| 277 |
+
"num_images_per_prompt": 2,
|
| 278 |
+
}
|
| 279 |
+
|
| 280 |
+
images = pipe(**inputs).images
|
| 281 |
+
|
| 282 |
+
# Should return 4 images (2 prompts × 2 images per prompt)
|
| 283 |
+
self.assertEqual(len(images), 4)
|
| 284 |
+
|
| 285 |
+
def test_prompt_with_prior_token_ids(self):
|
| 286 |
+
"""Test that prompt and prior_token_ids can be provided together.
|
| 287 |
+
|
| 288 |
+
When both are given, the AR generation step is skipped (prior_token_ids is used
|
| 289 |
+
directly) and prompt is used to generate prompt_embeds via the glyph encoder.
|
| 290 |
+
"""
|
| 291 |
+
device = "cpu"
|
| 292 |
+
components = self.get_dummy_components()
|
| 293 |
+
pipe = self.pipeline_class(**components)
|
| 294 |
+
pipe.to(device)
|
| 295 |
+
pipe.set_progress_bar_config(disable=None)
|
| 296 |
+
|
| 297 |
+
height, width = 32, 32
|
| 298 |
+
|
| 299 |
+
# Step 1: Run with prompt only to get prior_token_ids from AR model
|
| 300 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 301 |
+
prior_token_ids, _, _ = pipe.generate_prior_tokens(
|
| 302 |
+
prompt="A photo of a cat",
|
| 303 |
+
height=height,
|
| 304 |
+
width=width,
|
| 305 |
+
device=torch.device(device),
|
| 306 |
+
generator=torch.Generator(device=device).manual_seed(0),
|
| 307 |
+
)
|
| 308 |
+
|
| 309 |
+
# Step 2: Run with both prompt and prior_token_ids — should not raise
|
| 310 |
+
generator = torch.Generator(device=device).manual_seed(0)
|
| 311 |
+
inputs_both = {
|
| 312 |
+
"prompt": "A photo of a cat",
|
| 313 |
+
"prior_token_ids": prior_token_ids,
|
| 314 |
+
"generator": generator,
|
| 315 |
+
"num_inference_steps": 2,
|
| 316 |
+
"guidance_scale": 1.5,
|
| 317 |
+
"height": height,
|
| 318 |
+
"width": width,
|
| 319 |
+
"max_sequence_length": 16,
|
| 320 |
+
"output_type": "pt",
|
| 321 |
+
}
|
| 322 |
+
images = pipe(**inputs_both).images
|
| 323 |
+
self.assertEqual(len(images), 1)
|
| 324 |
+
self.assertEqual(images[0].shape, (3, 32, 32))
|
| 325 |
+
|
| 326 |
+
def test_check_inputs_rejects_invalid_combinations(self):
|
| 327 |
+
"""Test that check_inputs correctly rejects invalid input combinations."""
|
| 328 |
+
device = "cpu"
|
| 329 |
+
components = self.get_dummy_components()
|
| 330 |
+
pipe = self.pipeline_class(**components)
|
| 331 |
+
pipe.to(device)
|
| 332 |
+
|
| 333 |
+
height, width = 32, 32
|
| 334 |
+
|
| 335 |
+
# Neither prompt nor prior_token_ids → error
|
| 336 |
+
with self.assertRaises(ValueError):
|
| 337 |
+
pipe.check_inputs(
|
| 338 |
+
prompt=None,
|
| 339 |
+
height=height,
|
| 340 |
+
width=width,
|
| 341 |
+
callback_on_step_end_tensor_inputs=None,
|
| 342 |
+
prompt_embeds=torch.randn(1, 16, 32),
|
| 343 |
+
)
|
| 344 |
+
|
| 345 |
+
# prior_token_ids alone without prompt or prompt_embeds → error
|
| 346 |
+
with self.assertRaises(ValueError):
|
| 347 |
+
pipe.check_inputs(
|
| 348 |
+
prompt=None,
|
| 349 |
+
height=height,
|
| 350 |
+
width=width,
|
| 351 |
+
callback_on_step_end_tensor_inputs=None,
|
| 352 |
+
prior_token_ids=torch.randint(0, 100, (1, 64)),
|
| 353 |
+
)
|
| 354 |
+
|
| 355 |
+
# prompt + prompt_embeds together → error
|
| 356 |
+
with self.assertRaises(ValueError):
|
| 357 |
+
pipe.check_inputs(
|
| 358 |
+
prompt="A cat",
|
| 359 |
+
height=height,
|
| 360 |
+
width=width,
|
| 361 |
+
callback_on_step_end_tensor_inputs=None,
|
| 362 |
+
prompt_embeds=torch.randn(1, 16, 32),
|
| 363 |
+
)
|
| 364 |
+
|
| 365 |
+
@unittest.skip("Needs to be revisited.")
|
| 366 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 367 |
+
pass
|
| 368 |
+
|
| 369 |
+
@unittest.skip("Needs to be revisited.")
|
| 370 |
+
def test_pipeline_level_group_offloading_inference(self):
|
| 371 |
+
pass
|
| 372 |
+
|
| 373 |
+
@unittest.skip(
|
| 374 |
+
"Follow set of tests are relaxed because this pipeline doesn't guarantee same outputs for the same inputs in consecutive runs."
|
| 375 |
+
)
|
| 376 |
+
def test_dict_tuple_outputs_equivalent(self):
|
| 377 |
+
pass
|
| 378 |
+
|
| 379 |
+
@unittest.skip("Skipped")
|
| 380 |
+
def test_cpu_offload_forward_pass_twice(self):
|
| 381 |
+
pass
|
| 382 |
+
|
| 383 |
+
@unittest.skip("Skipped")
|
| 384 |
+
def test_sequential_offload_forward_pass_twice(self):
|
| 385 |
+
pass
|
| 386 |
+
|
| 387 |
+
@unittest.skip("Skipped")
|
| 388 |
+
def test_float16_inference(self):
|
| 389 |
+
pass
|
| 390 |
+
|
| 391 |
+
@unittest.skip("Skipped")
|
| 392 |
+
def test_save_load_float16(self):
|
| 393 |
+
pass
|
| 394 |
+
|
| 395 |
+
@unittest.skip("Skipped")
|
| 396 |
+
def test_save_load_local(self):
|
| 397 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/helios/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/helios/test_helios.py
ADDED
|
@@ -0,0 +1,172 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 unittest
|
| 17 |
+
|
| 18 |
+
import torch
|
| 19 |
+
from transformers import AutoConfig, AutoTokenizer, T5EncoderModel
|
| 20 |
+
|
| 21 |
+
from diffusers import AutoencoderKLWan, HeliosPipeline, HeliosScheduler, HeliosTransformer3DModel
|
| 22 |
+
|
| 23 |
+
from ...testing_utils import (
|
| 24 |
+
backend_empty_cache,
|
| 25 |
+
enable_full_determinism,
|
| 26 |
+
require_torch_accelerator,
|
| 27 |
+
slow,
|
| 28 |
+
torch_device,
|
| 29 |
+
)
|
| 30 |
+
from ..pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_IMAGE_PARAMS, TEXT_TO_IMAGE_PARAMS
|
| 31 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
enable_full_determinism()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class HeliosPipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 38 |
+
pipeline_class = HeliosPipeline
|
| 39 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs"}
|
| 40 |
+
batch_params = TEXT_TO_IMAGE_BATCH_PARAMS
|
| 41 |
+
image_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 42 |
+
image_latents_params = TEXT_TO_IMAGE_IMAGE_PARAMS
|
| 43 |
+
required_optional_params = frozenset(
|
| 44 |
+
[
|
| 45 |
+
"num_inference_steps",
|
| 46 |
+
"generator",
|
| 47 |
+
"latents",
|
| 48 |
+
"return_dict",
|
| 49 |
+
"callback_on_step_end",
|
| 50 |
+
"callback_on_step_end_tensor_inputs",
|
| 51 |
+
]
|
| 52 |
+
)
|
| 53 |
+
test_xformers_attention = False
|
| 54 |
+
supports_dduf = False
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
vae = AutoencoderKLWan(
|
| 59 |
+
base_dim=3,
|
| 60 |
+
z_dim=16,
|
| 61 |
+
dim_mult=[1, 1, 1, 1],
|
| 62 |
+
num_res_blocks=1,
|
| 63 |
+
temperal_downsample=[False, True, True],
|
| 64 |
+
)
|
| 65 |
+
|
| 66 |
+
torch.manual_seed(0)
|
| 67 |
+
scheduler = HeliosScheduler(stage_range=[0, 1], stages=1, use_dynamic_shifting=True)
|
| 68 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 69 |
+
text_encoder = T5EncoderModel(config)
|
| 70 |
+
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 71 |
+
|
| 72 |
+
torch.manual_seed(0)
|
| 73 |
+
transformer = HeliosTransformer3DModel(
|
| 74 |
+
patch_size=(1, 2, 2),
|
| 75 |
+
num_attention_heads=2,
|
| 76 |
+
attention_head_dim=12,
|
| 77 |
+
in_channels=16,
|
| 78 |
+
out_channels=16,
|
| 79 |
+
text_dim=32,
|
| 80 |
+
freq_dim=256,
|
| 81 |
+
ffn_dim=32,
|
| 82 |
+
num_layers=2,
|
| 83 |
+
cross_attn_norm=True,
|
| 84 |
+
qk_norm="rms_norm_across_heads",
|
| 85 |
+
rope_dim=(4, 4, 4),
|
| 86 |
+
has_multi_term_memory_patch=True,
|
| 87 |
+
guidance_cross_attn=True,
|
| 88 |
+
zero_history_timestep=True,
|
| 89 |
+
is_amplify_history=False,
|
| 90 |
+
)
|
| 91 |
+
|
| 92 |
+
components = {
|
| 93 |
+
"transformer": transformer,
|
| 94 |
+
"vae": vae,
|
| 95 |
+
"scheduler": scheduler,
|
| 96 |
+
"text_encoder": text_encoder,
|
| 97 |
+
"tokenizer": tokenizer,
|
| 98 |
+
}
|
| 99 |
+
return components
|
| 100 |
+
|
| 101 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 102 |
+
if str(device).startswith("mps"):
|
| 103 |
+
generator = torch.manual_seed(seed)
|
| 104 |
+
else:
|
| 105 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 106 |
+
inputs = {
|
| 107 |
+
"prompt": "dance monkey",
|
| 108 |
+
"negative_prompt": "negative",
|
| 109 |
+
"generator": generator,
|
| 110 |
+
"num_inference_steps": 2,
|
| 111 |
+
"guidance_scale": 1.0,
|
| 112 |
+
"height": 16,
|
| 113 |
+
"width": 16,
|
| 114 |
+
"num_frames": 9,
|
| 115 |
+
"max_sequence_length": 16,
|
| 116 |
+
"output_type": "pt",
|
| 117 |
+
}
|
| 118 |
+
return inputs
|
| 119 |
+
|
| 120 |
+
def test_inference(self):
|
| 121 |
+
device = "cpu"
|
| 122 |
+
|
| 123 |
+
components = self.get_dummy_components()
|
| 124 |
+
pipe = self.pipeline_class(**components)
|
| 125 |
+
pipe.to(device)
|
| 126 |
+
pipe.set_progress_bar_config(disable=None)
|
| 127 |
+
|
| 128 |
+
inputs = self.get_dummy_inputs(device)
|
| 129 |
+
video = pipe(**inputs).frames
|
| 130 |
+
generated_video = video[0]
|
| 131 |
+
self.assertEqual(generated_video.shape, (33, 3, 16, 16))
|
| 132 |
+
|
| 133 |
+
# fmt: off
|
| 134 |
+
expected_slice = torch.tensor([0.4529, 0.4527, 0.4499, 0.4542, 0.4528, 0.4524, 0.4531, 0.4534, 0.5328,
|
| 135 |
+
0.5340, 0.5012, 0.5135, 0.5322, 0.5203, 0.5144, 0.5101])
|
| 136 |
+
# fmt: on
|
| 137 |
+
|
| 138 |
+
generated_slice = generated_video.flatten()
|
| 139 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 140 |
+
self.assertTrue(torch.allclose(generated_slice, expected_slice, atol=1e-3))
|
| 141 |
+
|
| 142 |
+
@unittest.skip("Helios uses a lot of mixed precision internally, which is not suitable for this test case")
|
| 143 |
+
def test_save_load_float16(self):
|
| 144 |
+
pass
|
| 145 |
+
|
| 146 |
+
@unittest.skip("Test not supported")
|
| 147 |
+
def test_attention_slicing_forward_pass(self):
|
| 148 |
+
pass
|
| 149 |
+
|
| 150 |
+
@unittest.skip("Optional components not applicable for Helios")
|
| 151 |
+
def test_save_load_optional_components(self):
|
| 152 |
+
pass
|
| 153 |
+
|
| 154 |
+
|
| 155 |
+
@slow
|
| 156 |
+
@require_torch_accelerator
|
| 157 |
+
class HeliosPipelineIntegrationTests(unittest.TestCase):
|
| 158 |
+
prompt = "A painting of a squirrel eating a burger."
|
| 159 |
+
|
| 160 |
+
def setUp(self):
|
| 161 |
+
super().setUp()
|
| 162 |
+
gc.collect()
|
| 163 |
+
backend_empty_cache(torch_device)
|
| 164 |
+
|
| 165 |
+
def tearDown(self):
|
| 166 |
+
super().tearDown()
|
| 167 |
+
gc.collect()
|
| 168 |
+
backend_empty_cache(torch_device)
|
| 169 |
+
|
| 170 |
+
@unittest.skip("TODO: test needs to be implemented")
|
| 171 |
+
def test_helios(self):
|
| 172 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hidream_image/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hidream_image/test_pipeline_hidream.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 (
|
| 21 |
+
AutoConfig,
|
| 22 |
+
AutoTokenizer,
|
| 23 |
+
CLIPTextConfig,
|
| 24 |
+
CLIPTextModelWithProjection,
|
| 25 |
+
CLIPTokenizer,
|
| 26 |
+
LlamaForCausalLM,
|
| 27 |
+
T5EncoderModel,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from diffusers import (
|
| 31 |
+
AutoencoderKL,
|
| 32 |
+
FlowMatchEulerDiscreteScheduler,
|
| 33 |
+
HiDreamImagePipeline,
|
| 34 |
+
HiDreamImageTransformer2DModel,
|
| 35 |
+
)
|
| 36 |
+
|
| 37 |
+
from ...testing_utils import enable_full_determinism
|
| 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
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
enable_full_determinism()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class HiDreamImagePipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 46 |
+
pipeline_class = HiDreamImagePipeline
|
| 47 |
+
params = TEXT_TO_IMAGE_PARAMS - {"cross_attention_kwargs", "prompt_embeds", "negative_prompt_embeds"}
|
| 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 = PipelineTesterMixin.required_optional_params
|
| 52 |
+
test_xformers_attention = False
|
| 53 |
+
test_layerwise_casting = True
|
| 54 |
+
supports_dduf = False
|
| 55 |
+
|
| 56 |
+
def get_dummy_components(self):
|
| 57 |
+
torch.manual_seed(0)
|
| 58 |
+
transformer = HiDreamImageTransformer2DModel(
|
| 59 |
+
patch_size=2,
|
| 60 |
+
in_channels=4,
|
| 61 |
+
out_channels=4,
|
| 62 |
+
num_layers=1,
|
| 63 |
+
num_single_layers=1,
|
| 64 |
+
attention_head_dim=8,
|
| 65 |
+
num_attention_heads=4,
|
| 66 |
+
caption_channels=[32, 16],
|
| 67 |
+
text_emb_dim=64,
|
| 68 |
+
num_routed_experts=4,
|
| 69 |
+
num_activated_experts=2,
|
| 70 |
+
axes_dims_rope=(4, 2, 2),
|
| 71 |
+
max_resolution=(32, 32),
|
| 72 |
+
llama_layers=(0, 1),
|
| 73 |
+
).eval()
|
| 74 |
+
torch.manual_seed(0)
|
| 75 |
+
vae = AutoencoderKL(scaling_factor=0.3611, shift_factor=0.1159)
|
| 76 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 77 |
+
bos_token_id=0,
|
| 78 |
+
eos_token_id=2,
|
| 79 |
+
hidden_size=32,
|
| 80 |
+
intermediate_size=37,
|
| 81 |
+
layer_norm_eps=1e-05,
|
| 82 |
+
num_attention_heads=4,
|
| 83 |
+
num_hidden_layers=5,
|
| 84 |
+
pad_token_id=1,
|
| 85 |
+
vocab_size=1000,
|
| 86 |
+
hidden_act="gelu",
|
| 87 |
+
projection_dim=32,
|
| 88 |
+
max_position_embeddings=128,
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
torch.manual_seed(0)
|
| 92 |
+
text_encoder = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 93 |
+
|
| 94 |
+
torch.manual_seed(0)
|
| 95 |
+
text_encoder_2 = CLIPTextModelWithProjection(clip_text_encoder_config)
|
| 96 |
+
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 99 |
+
text_encoder_3 = T5EncoderModel(config).eval()
|
| 100 |
+
|
| 101 |
+
torch.manual_seed(0)
|
| 102 |
+
text_encoder_4 = LlamaForCausalLM.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
|
| 103 |
+
text_encoder_4.generation_config.pad_token_id = 1
|
| 104 |
+
tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 105 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 106 |
+
tokenizer_3 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 107 |
+
tokenizer_4 = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-LlamaForCausalLM")
|
| 108 |
+
|
| 109 |
+
scheduler = FlowMatchEulerDiscreteScheduler()
|
| 110 |
+
|
| 111 |
+
components = {
|
| 112 |
+
"scheduler": scheduler,
|
| 113 |
+
"vae": vae,
|
| 114 |
+
"text_encoder": text_encoder,
|
| 115 |
+
"tokenizer": tokenizer,
|
| 116 |
+
"text_encoder_2": text_encoder_2,
|
| 117 |
+
"tokenizer_2": tokenizer_2,
|
| 118 |
+
"text_encoder_3": text_encoder_3,
|
| 119 |
+
"tokenizer_3": tokenizer_3,
|
| 120 |
+
"text_encoder_4": text_encoder_4,
|
| 121 |
+
"tokenizer_4": tokenizer_4,
|
| 122 |
+
"transformer": transformer,
|
| 123 |
+
}
|
| 124 |
+
return components
|
| 125 |
+
|
| 126 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 127 |
+
if str(device).startswith("mps"):
|
| 128 |
+
generator = torch.manual_seed(seed)
|
| 129 |
+
else:
|
| 130 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 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 |
+
}
|
| 138 |
+
return inputs
|
| 139 |
+
|
| 140 |
+
def test_inference(self):
|
| 141 |
+
device = "cpu"
|
| 142 |
+
|
| 143 |
+
components = self.get_dummy_components()
|
| 144 |
+
pipe = self.pipeline_class(**components)
|
| 145 |
+
pipe.to(device)
|
| 146 |
+
pipe.set_progress_bar_config(disable=None)
|
| 147 |
+
|
| 148 |
+
inputs = self.get_dummy_inputs(device)
|
| 149 |
+
image = pipe(**inputs)[0]
|
| 150 |
+
generated_image = image[0]
|
| 151 |
+
self.assertEqual(generated_image.shape, (128, 128, 3))
|
| 152 |
+
|
| 153 |
+
# fmt: off
|
| 154 |
+
expected_slice = np.array([0.4501, 0.5256, 0.4207, 0.5783, 0.4842, 0.4833, 0.4441, 0.5112, 0.6587, 0.3169, 0.7308, 0.5927, 0.6251, 0.5509, 0.5355, 0.5969])
|
| 155 |
+
# fmt: on
|
| 156 |
+
|
| 157 |
+
generated_slice = generated_image.flatten()
|
| 158 |
+
generated_slice = np.concatenate([generated_slice[:8], generated_slice[-8:]])
|
| 159 |
+
self.assertTrue(np.allclose(generated_slice, expected_slice, atol=5e-3))
|
| 160 |
+
|
| 161 |
+
def test_inference_batch_single_identical(self):
|
| 162 |
+
super().test_inference_batch_single_identical(expected_max_diff=3e-4)
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_image_21/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_image_21/test_hunyuanimage.py
ADDED
|
@@ -0,0 +1,286 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 unittest
|
| 16 |
+
|
| 17 |
+
import numpy as np
|
| 18 |
+
import torch
|
| 19 |
+
from transformers import (
|
| 20 |
+
ByT5Tokenizer,
|
| 21 |
+
Qwen2_5_VLConfig,
|
| 22 |
+
Qwen2_5_VLForConditionalGeneration,
|
| 23 |
+
Qwen2Tokenizer,
|
| 24 |
+
T5Config,
|
| 25 |
+
T5EncoderModel,
|
| 26 |
+
)
|
| 27 |
+
|
| 28 |
+
from diffusers import (
|
| 29 |
+
AdaptiveProjectedMixGuidance,
|
| 30 |
+
AutoencoderKLHunyuanImage,
|
| 31 |
+
FlowMatchEulerDiscreteScheduler,
|
| 32 |
+
HunyuanImagePipeline,
|
| 33 |
+
HunyuanImageTransformer2DModel,
|
| 34 |
+
)
|
| 35 |
+
|
| 36 |
+
from ...testing_utils import enable_full_determinism
|
| 37 |
+
from ..test_pipelines_common import FirstBlockCacheTesterMixin, PipelineTesterMixin, to_np
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
enable_full_determinism()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class HunyuanImagePipelineFastTests(
|
| 44 |
+
PipelineTesterMixin,
|
| 45 |
+
FirstBlockCacheTesterMixin,
|
| 46 |
+
unittest.TestCase,
|
| 47 |
+
):
|
| 48 |
+
pipeline_class = HunyuanImagePipeline
|
| 49 |
+
params = frozenset(["prompt", "height", "width"])
|
| 50 |
+
batch_params = frozenset(["prompt", "negative_prompt"])
|
| 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 |
+
test_xformers_attention = False
|
| 63 |
+
test_layerwise_casting = True
|
| 64 |
+
test_group_offloading = True
|
| 65 |
+
test_attention_slicing = False
|
| 66 |
+
supports_dduf = False
|
| 67 |
+
|
| 68 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1, guidance_embeds: bool = False):
|
| 69 |
+
torch.manual_seed(0)
|
| 70 |
+
transformer = HunyuanImageTransformer2DModel(
|
| 71 |
+
in_channels=4,
|
| 72 |
+
out_channels=4,
|
| 73 |
+
num_attention_heads=4,
|
| 74 |
+
attention_head_dim=8,
|
| 75 |
+
num_layers=num_layers,
|
| 76 |
+
num_single_layers=num_single_layers,
|
| 77 |
+
num_refiner_layers=1,
|
| 78 |
+
patch_size=(1, 1),
|
| 79 |
+
guidance_embeds=guidance_embeds,
|
| 80 |
+
text_embed_dim=32,
|
| 81 |
+
text_embed_2_dim=32,
|
| 82 |
+
rope_axes_dim=(4, 4),
|
| 83 |
+
)
|
| 84 |
+
|
| 85 |
+
torch.manual_seed(0)
|
| 86 |
+
vae = AutoencoderKLHunyuanImage(
|
| 87 |
+
in_channels=3,
|
| 88 |
+
out_channels=3,
|
| 89 |
+
latent_channels=4,
|
| 90 |
+
block_out_channels=(32, 64, 64, 64),
|
| 91 |
+
layers_per_block=1,
|
| 92 |
+
scaling_factor=0.476986,
|
| 93 |
+
spatial_compression_ratio=8,
|
| 94 |
+
sample_size=128,
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 99 |
+
|
| 100 |
+
if not guidance_embeds:
|
| 101 |
+
torch.manual_seed(0)
|
| 102 |
+
guider = AdaptiveProjectedMixGuidance(adaptive_projected_guidance_start_step=2)
|
| 103 |
+
ocr_guider = AdaptiveProjectedMixGuidance(adaptive_projected_guidance_start_step=3)
|
| 104 |
+
else:
|
| 105 |
+
guider = None
|
| 106 |
+
ocr_guider = None
|
| 107 |
+
torch.manual_seed(0)
|
| 108 |
+
config = Qwen2_5_VLConfig(
|
| 109 |
+
text_config={
|
| 110 |
+
"hidden_size": 32,
|
| 111 |
+
"intermediate_size": 32,
|
| 112 |
+
"num_hidden_layers": 2,
|
| 113 |
+
"num_attention_heads": 2,
|
| 114 |
+
"num_key_value_heads": 2,
|
| 115 |
+
"rope_scaling": {
|
| 116 |
+
"mrope_section": [2, 2, 4],
|
| 117 |
+
"rope_type": "default",
|
| 118 |
+
"type": "default",
|
| 119 |
+
},
|
| 120 |
+
"rope_theta": 1000000.0,
|
| 121 |
+
},
|
| 122 |
+
vision_config={
|
| 123 |
+
"depth": 2,
|
| 124 |
+
"hidden_size": 32,
|
| 125 |
+
"intermediate_size": 32,
|
| 126 |
+
"num_heads": 2,
|
| 127 |
+
"out_hidden_size": 32,
|
| 128 |
+
},
|
| 129 |
+
hidden_size=32,
|
| 130 |
+
vocab_size=152064,
|
| 131 |
+
vision_end_token_id=151653,
|
| 132 |
+
vision_start_token_id=151652,
|
| 133 |
+
vision_token_id=151654,
|
| 134 |
+
)
|
| 135 |
+
text_encoder = Qwen2_5_VLForConditionalGeneration(config)
|
| 136 |
+
tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 137 |
+
|
| 138 |
+
torch.manual_seed(0)
|
| 139 |
+
t5_config = T5Config(
|
| 140 |
+
d_model=32,
|
| 141 |
+
d_kv=4,
|
| 142 |
+
d_ff=16,
|
| 143 |
+
num_layers=2,
|
| 144 |
+
num_heads=2,
|
| 145 |
+
relative_attention_num_buckets=8,
|
| 146 |
+
relative_attention_max_distance=32,
|
| 147 |
+
vocab_size=256,
|
| 148 |
+
feed_forward_proj="gated-gelu",
|
| 149 |
+
dense_act_fn="gelu_new",
|
| 150 |
+
is_encoder_decoder=False,
|
| 151 |
+
use_cache=False,
|
| 152 |
+
tie_word_embeddings=False,
|
| 153 |
+
)
|
| 154 |
+
text_encoder_2 = T5EncoderModel(t5_config)
|
| 155 |
+
tokenizer_2 = ByT5Tokenizer()
|
| 156 |
+
|
| 157 |
+
components = {
|
| 158 |
+
"transformer": transformer,
|
| 159 |
+
"vae": vae,
|
| 160 |
+
"scheduler": scheduler,
|
| 161 |
+
"text_encoder": text_encoder,
|
| 162 |
+
"text_encoder_2": text_encoder_2,
|
| 163 |
+
"tokenizer": tokenizer,
|
| 164 |
+
"tokenizer_2": tokenizer_2,
|
| 165 |
+
"guider": guider,
|
| 166 |
+
"ocr_guider": ocr_guider,
|
| 167 |
+
}
|
| 168 |
+
return components
|
| 169 |
+
|
| 170 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 171 |
+
if str(device).startswith("mps"):
|
| 172 |
+
generator = torch.manual_seed(seed)
|
| 173 |
+
else:
|
| 174 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 175 |
+
|
| 176 |
+
inputs = {
|
| 177 |
+
"prompt": "A painting of a squirrel eating a burger",
|
| 178 |
+
"generator": generator,
|
| 179 |
+
"num_inference_steps": 5,
|
| 180 |
+
"height": 16,
|
| 181 |
+
"width": 16,
|
| 182 |
+
"output_type": "pt",
|
| 183 |
+
}
|
| 184 |
+
return inputs
|
| 185 |
+
|
| 186 |
+
def test_inference(self):
|
| 187 |
+
device = "cpu"
|
| 188 |
+
|
| 189 |
+
components = self.get_dummy_components()
|
| 190 |
+
pipe = self.pipeline_class(**components)
|
| 191 |
+
pipe.to(device)
|
| 192 |
+
pipe.set_progress_bar_config(disable=None)
|
| 193 |
+
|
| 194 |
+
inputs = self.get_dummy_inputs(device)
|
| 195 |
+
image = pipe(**inputs).images
|
| 196 |
+
generated_image = image[0]
|
| 197 |
+
self.assertEqual(generated_image.shape, (3, 16, 16))
|
| 198 |
+
|
| 199 |
+
expected_slice_np = np.array(
|
| 200 |
+
[0.6252659, 0.51482046, 0.60799813, 0.59267783, 0.488082, 0.5857634, 0.523781, 0.58028054, 0.5674121]
|
| 201 |
+
)
|
| 202 |
+
output_slice = generated_image[0, -3:, -3:].flatten().cpu().numpy()
|
| 203 |
+
|
| 204 |
+
self.assertTrue(
|
| 205 |
+
np.abs(output_slice - expected_slice_np).max() < 1e-3,
|
| 206 |
+
f"output_slice: {output_slice}, expected_slice_np: {expected_slice_np}",
|
| 207 |
+
)
|
| 208 |
+
|
| 209 |
+
def test_inference_guider(self):
|
| 210 |
+
device = "cpu"
|
| 211 |
+
|
| 212 |
+
components = self.get_dummy_components()
|
| 213 |
+
pipe = self.pipeline_class(**components)
|
| 214 |
+
pipe.to(device)
|
| 215 |
+
pipe.set_progress_bar_config(disable=None)
|
| 216 |
+
|
| 217 |
+
pipe.guider = pipe.guider.new(guidance_scale=1000)
|
| 218 |
+
pipe.ocr_guider = pipe.ocr_guider.new(guidance_scale=1000)
|
| 219 |
+
|
| 220 |
+
inputs = self.get_dummy_inputs(device)
|
| 221 |
+
image = pipe(**inputs).images
|
| 222 |
+
generated_image = image[0]
|
| 223 |
+
self.assertEqual(generated_image.shape, (3, 16, 16))
|
| 224 |
+
|
| 225 |
+
expected_slice_np = np.array(
|
| 226 |
+
[0.6068114, 0.48716035, 0.5984431, 0.60241306, 0.48849544, 0.5624479, 0.53696984, 0.58964247, 0.54248774]
|
| 227 |
+
)
|
| 228 |
+
output_slice = generated_image[0, -3:, -3:].flatten().cpu().numpy()
|
| 229 |
+
|
| 230 |
+
self.assertTrue(
|
| 231 |
+
np.abs(output_slice - expected_slice_np).max() < 1e-3,
|
| 232 |
+
f"output_slice: {output_slice}, expected_slice_np: {expected_slice_np}",
|
| 233 |
+
)
|
| 234 |
+
|
| 235 |
+
def test_inference_with_distilled_guidance(self):
|
| 236 |
+
device = "cpu"
|
| 237 |
+
|
| 238 |
+
components = self.get_dummy_components(guidance_embeds=True)
|
| 239 |
+
pipe = self.pipeline_class(**components)
|
| 240 |
+
pipe.to(device)
|
| 241 |
+
pipe.set_progress_bar_config(disable=None)
|
| 242 |
+
|
| 243 |
+
inputs = self.get_dummy_inputs(device)
|
| 244 |
+
inputs["distilled_guidance_scale"] = 3.5
|
| 245 |
+
image = pipe(**inputs).images
|
| 246 |
+
generated_image = image[0]
|
| 247 |
+
self.assertEqual(generated_image.shape, (3, 16, 16))
|
| 248 |
+
|
| 249 |
+
expected_slice_np = np.array(
|
| 250 |
+
[0.63667065, 0.5187377, 0.66757566, 0.6320319, 0.4913387, 0.54813194, 0.5335031, 0.5736143, 0.5461346]
|
| 251 |
+
)
|
| 252 |
+
output_slice = generated_image[0, -3:, -3:].flatten().cpu().numpy()
|
| 253 |
+
|
| 254 |
+
self.assertTrue(
|
| 255 |
+
np.abs(output_slice - expected_slice_np).max() < 1e-3,
|
| 256 |
+
f"output_slice: {output_slice}, expected_slice_np: {expected_slice_np}",
|
| 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(tile_sample_min_size=96)
|
| 274 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 275 |
+
inputs["height"] = inputs["width"] = 128
|
| 276 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 277 |
+
|
| 278 |
+
self.assertLess(
|
| 279 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 280 |
+
expected_diff_max,
|
| 281 |
+
"VAE tiling should not affect the inference results",
|
| 282 |
+
)
|
| 283 |
+
|
| 284 |
+
@unittest.skip("TODO: Test not supported for now because needs to be adjusted to work with guiders.")
|
| 285 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 286 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/__init__.py
ADDED
|
File without changes
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_image2video.py
ADDED
|
@@ -0,0 +1,390 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 PIL import Image
|
| 21 |
+
from transformers import (
|
| 22 |
+
CLIPImageProcessor,
|
| 23 |
+
CLIPTextConfig,
|
| 24 |
+
CLIPTextModel,
|
| 25 |
+
CLIPTokenizer,
|
| 26 |
+
LlamaConfig,
|
| 27 |
+
LlamaTokenizerFast,
|
| 28 |
+
LlavaConfig,
|
| 29 |
+
LlavaForConditionalGeneration,
|
| 30 |
+
)
|
| 31 |
+
from transformers.models.clip import CLIPVisionConfig
|
| 32 |
+
|
| 33 |
+
from diffusers import (
|
| 34 |
+
AutoencoderKLHunyuanVideo,
|
| 35 |
+
FlowMatchEulerDiscreteScheduler,
|
| 36 |
+
HunyuanVideoImageToVideoPipeline,
|
| 37 |
+
HunyuanVideoTransformer3DModel,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
from ...testing_utils import enable_full_determinism, torch_device
|
| 41 |
+
from ..test_pipelines_common import PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, to_np
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
enable_full_determinism()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
class HunyuanVideoImageToVideoPipelineFastTests(
|
| 48 |
+
PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, unittest.TestCase
|
| 49 |
+
):
|
| 50 |
+
pipeline_class = HunyuanVideoImageToVideoPipeline
|
| 51 |
+
params = frozenset(
|
| 52 |
+
["image", "prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"]
|
| 53 |
+
)
|
| 54 |
+
batch_params = frozenset(["prompt", "image"])
|
| 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 |
+
|
| 67 |
+
# there is no xformers processor for Flux
|
| 68 |
+
test_xformers_attention = False
|
| 69 |
+
test_layerwise_casting = True
|
| 70 |
+
test_group_offloading = True
|
| 71 |
+
|
| 72 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 73 |
+
torch.manual_seed(0)
|
| 74 |
+
transformer = HunyuanVideoTransformer3DModel(
|
| 75 |
+
in_channels=2 * 4 + 1,
|
| 76 |
+
out_channels=4,
|
| 77 |
+
num_attention_heads=2,
|
| 78 |
+
attention_head_dim=10,
|
| 79 |
+
num_layers=num_layers,
|
| 80 |
+
num_single_layers=num_single_layers,
|
| 81 |
+
num_refiner_layers=1,
|
| 82 |
+
patch_size=1,
|
| 83 |
+
patch_size_t=1,
|
| 84 |
+
guidance_embeds=False,
|
| 85 |
+
text_embed_dim=16,
|
| 86 |
+
pooled_projection_dim=8,
|
| 87 |
+
rope_axes_dim=(2, 4, 4),
|
| 88 |
+
image_condition_type="latent_concat",
|
| 89 |
+
)
|
| 90 |
+
|
| 91 |
+
torch.manual_seed(0)
|
| 92 |
+
vae = AutoencoderKLHunyuanVideo(
|
| 93 |
+
in_channels=3,
|
| 94 |
+
out_channels=3,
|
| 95 |
+
latent_channels=4,
|
| 96 |
+
down_block_types=(
|
| 97 |
+
"HunyuanVideoDownBlock3D",
|
| 98 |
+
"HunyuanVideoDownBlock3D",
|
| 99 |
+
"HunyuanVideoDownBlock3D",
|
| 100 |
+
"HunyuanVideoDownBlock3D",
|
| 101 |
+
),
|
| 102 |
+
up_block_types=(
|
| 103 |
+
"HunyuanVideoUpBlock3D",
|
| 104 |
+
"HunyuanVideoUpBlock3D",
|
| 105 |
+
"HunyuanVideoUpBlock3D",
|
| 106 |
+
"HunyuanVideoUpBlock3D",
|
| 107 |
+
),
|
| 108 |
+
block_out_channels=(8, 8, 8, 8),
|
| 109 |
+
layers_per_block=1,
|
| 110 |
+
act_fn="silu",
|
| 111 |
+
norm_num_groups=4,
|
| 112 |
+
scaling_factor=0.476986,
|
| 113 |
+
spatial_compression_ratio=8,
|
| 114 |
+
temporal_compression_ratio=4,
|
| 115 |
+
mid_block_add_attention=True,
|
| 116 |
+
)
|
| 117 |
+
|
| 118 |
+
torch.manual_seed(0)
|
| 119 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 120 |
+
|
| 121 |
+
text_config = LlamaConfig(
|
| 122 |
+
bos_token_id=0,
|
| 123 |
+
eos_token_id=2,
|
| 124 |
+
hidden_size=16,
|
| 125 |
+
intermediate_size=37,
|
| 126 |
+
layer_norm_eps=1e-05,
|
| 127 |
+
num_attention_heads=4,
|
| 128 |
+
num_hidden_layers=2,
|
| 129 |
+
pad_token_id=100,
|
| 130 |
+
vocab_size=1000,
|
| 131 |
+
hidden_act="gelu",
|
| 132 |
+
projection_dim=32,
|
| 133 |
+
)
|
| 134 |
+
vision_config = CLIPVisionConfig(
|
| 135 |
+
hidden_size=8,
|
| 136 |
+
intermediate_size=37,
|
| 137 |
+
projection_dim=32,
|
| 138 |
+
num_attention_heads=4,
|
| 139 |
+
num_hidden_layers=2,
|
| 140 |
+
image_size=224,
|
| 141 |
+
)
|
| 142 |
+
llava_text_encoder_config = LlavaConfig(
|
| 143 |
+
vision_config=vision_config, text_config=text_config, pad_token_id=100, image_token_index=101
|
| 144 |
+
)
|
| 145 |
+
|
| 146 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 147 |
+
bos_token_id=0,
|
| 148 |
+
eos_token_id=2,
|
| 149 |
+
hidden_size=8,
|
| 150 |
+
intermediate_size=37,
|
| 151 |
+
layer_norm_eps=1e-05,
|
| 152 |
+
num_attention_heads=4,
|
| 153 |
+
num_hidden_layers=2,
|
| 154 |
+
pad_token_id=1,
|
| 155 |
+
vocab_size=1000,
|
| 156 |
+
hidden_act="gelu",
|
| 157 |
+
projection_dim=32,
|
| 158 |
+
)
|
| 159 |
+
|
| 160 |
+
torch.manual_seed(0)
|
| 161 |
+
text_encoder = LlavaForConditionalGeneration(llava_text_encoder_config)
|
| 162 |
+
tokenizer = LlamaTokenizerFast.from_pretrained("finetrainers/dummy-hunyaunvideo", subfolder="tokenizer")
|
| 163 |
+
|
| 164 |
+
torch.manual_seed(0)
|
| 165 |
+
text_encoder_2 = CLIPTextModel(clip_text_encoder_config)
|
| 166 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 167 |
+
|
| 168 |
+
torch.manual_seed(0)
|
| 169 |
+
image_processor = 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 |
+
"transformer": transformer,
|
| 182 |
+
"vae": vae,
|
| 183 |
+
"scheduler": scheduler,
|
| 184 |
+
"text_encoder": text_encoder,
|
| 185 |
+
"text_encoder_2": text_encoder_2,
|
| 186 |
+
"tokenizer": tokenizer,
|
| 187 |
+
"tokenizer_2": tokenizer_2,
|
| 188 |
+
"image_processor": image_processor,
|
| 189 |
+
}
|
| 190 |
+
return components
|
| 191 |
+
|
| 192 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 193 |
+
if str(device).startswith("mps"):
|
| 194 |
+
generator = torch.manual_seed(seed)
|
| 195 |
+
else:
|
| 196 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 197 |
+
|
| 198 |
+
image_height = 16
|
| 199 |
+
image_width = 16
|
| 200 |
+
image = Image.new("RGB", (image_width, image_height))
|
| 201 |
+
inputs = {
|
| 202 |
+
"image": image,
|
| 203 |
+
"prompt": "dance monkey",
|
| 204 |
+
"prompt_template": {
|
| 205 |
+
"template": "{}",
|
| 206 |
+
"crop_start": 0,
|
| 207 |
+
"image_emb_len": 49,
|
| 208 |
+
"image_emb_start": 5,
|
| 209 |
+
"image_emb_end": 54,
|
| 210 |
+
},
|
| 211 |
+
"generator": generator,
|
| 212 |
+
"num_inference_steps": 2,
|
| 213 |
+
"guidance_scale": 4.5,
|
| 214 |
+
"height": image_height,
|
| 215 |
+
"width": image_width,
|
| 216 |
+
"num_frames": 9,
|
| 217 |
+
"max_sequence_length": 64,
|
| 218 |
+
"output_type": "pt",
|
| 219 |
+
}
|
| 220 |
+
return inputs
|
| 221 |
+
|
| 222 |
+
def test_inference(self):
|
| 223 |
+
device = "cpu"
|
| 224 |
+
|
| 225 |
+
components = self.get_dummy_components()
|
| 226 |
+
pipe = self.pipeline_class(**components)
|
| 227 |
+
pipe.to(device)
|
| 228 |
+
pipe.set_progress_bar_config(disable=None)
|
| 229 |
+
|
| 230 |
+
inputs = self.get_dummy_inputs(device)
|
| 231 |
+
video = pipe(**inputs).frames
|
| 232 |
+
generated_video = video[0]
|
| 233 |
+
# NOTE: The expected video has 4 lesser frames because they are dropped in the pipeline
|
| 234 |
+
self.assertEqual(generated_video.shape, (5, 3, 16, 16))
|
| 235 |
+
|
| 236 |
+
# fmt: off
|
| 237 |
+
expected_slice = torch.tensor([0.4441, 0.4790, 0.4485, 0.5748, 0.3539, 0.1553, 0.2707, 0.3594, 0.5331, 0.6645, 0.6799, 0.5257, 0.5092, 0.3450, 0.4276, 0.4127])
|
| 238 |
+
# fmt: on
|
| 239 |
+
|
| 240 |
+
generated_slice = generated_video.flatten()
|
| 241 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 242 |
+
self.assertTrue(
|
| 243 |
+
torch.allclose(generated_slice, expected_slice, atol=1e-3),
|
| 244 |
+
"The generated video does not match the expected slice.",
|
| 245 |
+
)
|
| 246 |
+
|
| 247 |
+
def test_callback_inputs(self):
|
| 248 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 249 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 250 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 251 |
+
|
| 252 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 253 |
+
return
|
| 254 |
+
|
| 255 |
+
components = self.get_dummy_components()
|
| 256 |
+
pipe = self.pipeline_class(**components)
|
| 257 |
+
pipe = pipe.to(torch_device)
|
| 258 |
+
pipe.set_progress_bar_config(disable=None)
|
| 259 |
+
self.assertTrue(
|
| 260 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 261 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 262 |
+
)
|
| 263 |
+
|
| 264 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 265 |
+
# iterate over callback args
|
| 266 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 267 |
+
# check that we're only passing in allowed tensor inputs
|
| 268 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 269 |
+
|
| 270 |
+
return callback_kwargs
|
| 271 |
+
|
| 272 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 273 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 274 |
+
assert tensor_name in callback_kwargs
|
| 275 |
+
|
| 276 |
+
# iterate over callback args
|
| 277 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 278 |
+
# check that we're only passing in allowed tensor inputs
|
| 279 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 280 |
+
|
| 281 |
+
return callback_kwargs
|
| 282 |
+
|
| 283 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 284 |
+
|
| 285 |
+
# Test passing in a subset
|
| 286 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 287 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 288 |
+
output = pipe(**inputs)[0]
|
| 289 |
+
|
| 290 |
+
# Test passing in a everything
|
| 291 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 292 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 293 |
+
output = pipe(**inputs)[0]
|
| 294 |
+
|
| 295 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 296 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 297 |
+
if is_last:
|
| 298 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 299 |
+
return callback_kwargs
|
| 300 |
+
|
| 301 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 302 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 303 |
+
output = pipe(**inputs)[0]
|
| 304 |
+
assert output.abs().sum() < 1e10
|
| 305 |
+
|
| 306 |
+
def test_attention_slicing_forward_pass(
|
| 307 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 308 |
+
):
|
| 309 |
+
if not self.test_attention_slicing:
|
| 310 |
+
return
|
| 311 |
+
|
| 312 |
+
components = self.get_dummy_components()
|
| 313 |
+
pipe = self.pipeline_class(**components)
|
| 314 |
+
for component in pipe.components.values():
|
| 315 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 316 |
+
component.set_default_attn_processor()
|
| 317 |
+
pipe.to(torch_device)
|
| 318 |
+
pipe.set_progress_bar_config(disable=None)
|
| 319 |
+
|
| 320 |
+
generator_device = "cpu"
|
| 321 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 322 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 323 |
+
|
| 324 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 325 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 326 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 327 |
+
|
| 328 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 329 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 330 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 331 |
+
|
| 332 |
+
if test_max_difference:
|
| 333 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 334 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 335 |
+
self.assertLess(
|
| 336 |
+
max(max_diff1, max_diff2),
|
| 337 |
+
expected_max_diff,
|
| 338 |
+
"Attention slicing should not affect the inference results",
|
| 339 |
+
)
|
| 340 |
+
|
| 341 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 342 |
+
# Seems to require higher tolerance than the other tests
|
| 343 |
+
expected_diff_max = 0.6
|
| 344 |
+
generator_device = "cpu"
|
| 345 |
+
components = self.get_dummy_components()
|
| 346 |
+
|
| 347 |
+
pipe = self.pipeline_class(**components)
|
| 348 |
+
pipe.to("cpu")
|
| 349 |
+
pipe.set_progress_bar_config(disable=None)
|
| 350 |
+
|
| 351 |
+
# Without tiling
|
| 352 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 353 |
+
inputs["height"] = inputs["width"] = 128
|
| 354 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 355 |
+
|
| 356 |
+
# With tiling
|
| 357 |
+
pipe.vae.enable_tiling(
|
| 358 |
+
tile_sample_min_height=96,
|
| 359 |
+
tile_sample_min_width=96,
|
| 360 |
+
tile_sample_stride_height=64,
|
| 361 |
+
tile_sample_stride_width=64,
|
| 362 |
+
)
|
| 363 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 364 |
+
inputs["height"] = inputs["width"] = 128
|
| 365 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 366 |
+
|
| 367 |
+
self.assertLess(
|
| 368 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 369 |
+
expected_diff_max,
|
| 370 |
+
"VAE tiling should not affect the inference results",
|
| 371 |
+
)
|
| 372 |
+
|
| 373 |
+
# TODO(aryan): Create a dummy gemma model with smol vocab size
|
| 374 |
+
@unittest.skip(
|
| 375 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 376 |
+
)
|
| 377 |
+
def test_inference_batch_consistent(self):
|
| 378 |
+
pass
|
| 379 |
+
|
| 380 |
+
@unittest.skip(
|
| 381 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 382 |
+
)
|
| 383 |
+
def test_inference_batch_single_identical(self):
|
| 384 |
+
pass
|
| 385 |
+
|
| 386 |
+
@unittest.skip(
|
| 387 |
+
"Encode prompt currently does not work in isolation because of requiring image embeddings from image processor. The test does not handle this case, or we need to rewrite encode_prompt."
|
| 388 |
+
)
|
| 389 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 390 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_skyreels_image2video.py
ADDED
|
@@ -0,0 +1,345 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 PIL import Image
|
| 21 |
+
from transformers import CLIPTextConfig, CLIPTextModel, CLIPTokenizer, LlamaConfig, LlamaModel, LlamaTokenizer
|
| 22 |
+
|
| 23 |
+
from diffusers import (
|
| 24 |
+
AutoencoderKLHunyuanVideo,
|
| 25 |
+
FlowMatchEulerDiscreteScheduler,
|
| 26 |
+
HunyuanSkyreelsImageToVideoPipeline,
|
| 27 |
+
HunyuanVideoTransformer3DModel,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from ...testing_utils import enable_full_determinism, torch_device
|
| 31 |
+
from ..test_pipelines_common import PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, to_np
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
enable_full_determinism()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class HunyuanSkyreelsImageToVideoPipelineFastTests(
|
| 38 |
+
PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, unittest.TestCase
|
| 39 |
+
):
|
| 40 |
+
pipeline_class = HunyuanSkyreelsImageToVideoPipeline
|
| 41 |
+
params = frozenset(
|
| 42 |
+
["image", "prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"]
|
| 43 |
+
)
|
| 44 |
+
batch_params = frozenset(["prompt", "image"])
|
| 45 |
+
required_optional_params = frozenset(
|
| 46 |
+
[
|
| 47 |
+
"num_inference_steps",
|
| 48 |
+
"generator",
|
| 49 |
+
"latents",
|
| 50 |
+
"return_dict",
|
| 51 |
+
"callback_on_step_end",
|
| 52 |
+
"callback_on_step_end_tensor_inputs",
|
| 53 |
+
]
|
| 54 |
+
)
|
| 55 |
+
supports_dduf = False
|
| 56 |
+
|
| 57 |
+
# there is no xformers processor for Flux
|
| 58 |
+
test_xformers_attention = False
|
| 59 |
+
test_layerwise_casting = True
|
| 60 |
+
test_group_offloading = True
|
| 61 |
+
|
| 62 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 63 |
+
torch.manual_seed(0)
|
| 64 |
+
transformer = HunyuanVideoTransformer3DModel(
|
| 65 |
+
in_channels=8,
|
| 66 |
+
out_channels=4,
|
| 67 |
+
num_attention_heads=2,
|
| 68 |
+
attention_head_dim=10,
|
| 69 |
+
num_layers=num_layers,
|
| 70 |
+
num_single_layers=num_single_layers,
|
| 71 |
+
num_refiner_layers=1,
|
| 72 |
+
patch_size=1,
|
| 73 |
+
patch_size_t=1,
|
| 74 |
+
guidance_embeds=True,
|
| 75 |
+
text_embed_dim=16,
|
| 76 |
+
pooled_projection_dim=8,
|
| 77 |
+
rope_axes_dim=(2, 4, 4),
|
| 78 |
+
)
|
| 79 |
+
|
| 80 |
+
torch.manual_seed(0)
|
| 81 |
+
vae = AutoencoderKLHunyuanVideo(
|
| 82 |
+
in_channels=3,
|
| 83 |
+
out_channels=3,
|
| 84 |
+
latent_channels=4,
|
| 85 |
+
down_block_types=(
|
| 86 |
+
"HunyuanVideoDownBlock3D",
|
| 87 |
+
"HunyuanVideoDownBlock3D",
|
| 88 |
+
"HunyuanVideoDownBlock3D",
|
| 89 |
+
"HunyuanVideoDownBlock3D",
|
| 90 |
+
),
|
| 91 |
+
up_block_types=(
|
| 92 |
+
"HunyuanVideoUpBlock3D",
|
| 93 |
+
"HunyuanVideoUpBlock3D",
|
| 94 |
+
"HunyuanVideoUpBlock3D",
|
| 95 |
+
"HunyuanVideoUpBlock3D",
|
| 96 |
+
),
|
| 97 |
+
block_out_channels=(8, 8, 8, 8),
|
| 98 |
+
layers_per_block=1,
|
| 99 |
+
act_fn="silu",
|
| 100 |
+
norm_num_groups=4,
|
| 101 |
+
scaling_factor=0.476986,
|
| 102 |
+
spatial_compression_ratio=8,
|
| 103 |
+
temporal_compression_ratio=4,
|
| 104 |
+
mid_block_add_attention=True,
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
torch.manual_seed(0)
|
| 108 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 109 |
+
|
| 110 |
+
llama_text_encoder_config = LlamaConfig(
|
| 111 |
+
bos_token_id=0,
|
| 112 |
+
eos_token_id=2,
|
| 113 |
+
hidden_size=16,
|
| 114 |
+
intermediate_size=37,
|
| 115 |
+
layer_norm_eps=1e-05,
|
| 116 |
+
num_attention_heads=4,
|
| 117 |
+
num_hidden_layers=2,
|
| 118 |
+
pad_token_id=1,
|
| 119 |
+
vocab_size=1000,
|
| 120 |
+
hidden_act="gelu",
|
| 121 |
+
projection_dim=32,
|
| 122 |
+
)
|
| 123 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 124 |
+
bos_token_id=0,
|
| 125 |
+
eos_token_id=2,
|
| 126 |
+
hidden_size=8,
|
| 127 |
+
intermediate_size=37,
|
| 128 |
+
layer_norm_eps=1e-05,
|
| 129 |
+
num_attention_heads=4,
|
| 130 |
+
num_hidden_layers=2,
|
| 131 |
+
pad_token_id=1,
|
| 132 |
+
vocab_size=1000,
|
| 133 |
+
hidden_act="gelu",
|
| 134 |
+
projection_dim=32,
|
| 135 |
+
)
|
| 136 |
+
|
| 137 |
+
torch.manual_seed(0)
|
| 138 |
+
text_encoder = LlamaModel(llama_text_encoder_config)
|
| 139 |
+
tokenizer = LlamaTokenizer.from_pretrained("finetrainers/dummy-hunyaunvideo", subfolder="tokenizer")
|
| 140 |
+
|
| 141 |
+
torch.manual_seed(0)
|
| 142 |
+
text_encoder_2 = CLIPTextModel(clip_text_encoder_config)
|
| 143 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 144 |
+
|
| 145 |
+
components = {
|
| 146 |
+
"transformer": transformer,
|
| 147 |
+
"vae": vae,
|
| 148 |
+
"scheduler": scheduler,
|
| 149 |
+
"text_encoder": text_encoder,
|
| 150 |
+
"text_encoder_2": text_encoder_2,
|
| 151 |
+
"tokenizer": tokenizer,
|
| 152 |
+
"tokenizer_2": tokenizer_2,
|
| 153 |
+
}
|
| 154 |
+
return components
|
| 155 |
+
|
| 156 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 157 |
+
if str(device).startswith("mps"):
|
| 158 |
+
generator = torch.manual_seed(seed)
|
| 159 |
+
else:
|
| 160 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 161 |
+
|
| 162 |
+
image_height = 16
|
| 163 |
+
image_width = 16
|
| 164 |
+
image = Image.new("RGB", (image_width, image_height))
|
| 165 |
+
inputs = {
|
| 166 |
+
"image": image,
|
| 167 |
+
"prompt": "dance monkey",
|
| 168 |
+
"prompt_template": {
|
| 169 |
+
"template": "{}",
|
| 170 |
+
"crop_start": 0,
|
| 171 |
+
},
|
| 172 |
+
"generator": generator,
|
| 173 |
+
"num_inference_steps": 2,
|
| 174 |
+
"guidance_scale": 4.5,
|
| 175 |
+
"height": 16,
|
| 176 |
+
"width": 16,
|
| 177 |
+
# 4 * k + 1 is the recommendation
|
| 178 |
+
"num_frames": 9,
|
| 179 |
+
"max_sequence_length": 16,
|
| 180 |
+
"output_type": "pt",
|
| 181 |
+
}
|
| 182 |
+
return inputs
|
| 183 |
+
|
| 184 |
+
def test_inference(self):
|
| 185 |
+
device = "cpu"
|
| 186 |
+
|
| 187 |
+
components = self.get_dummy_components()
|
| 188 |
+
pipe = self.pipeline_class(**components)
|
| 189 |
+
pipe.to(device)
|
| 190 |
+
pipe.set_progress_bar_config(disable=None)
|
| 191 |
+
|
| 192 |
+
inputs = self.get_dummy_inputs(device)
|
| 193 |
+
video = pipe(**inputs).frames
|
| 194 |
+
generated_video = video[0]
|
| 195 |
+
self.assertEqual(generated_video.shape, (9, 3, 16, 16))
|
| 196 |
+
|
| 197 |
+
# fmt: off
|
| 198 |
+
expected_slice = torch.tensor([0.5832, 0.5498, 0.4839, 0.4744, 0.4515, 0.4832, 0.496, 0.563, 0.5918, 0.5979, 0.5101, 0.6168, 0.6613, 0.536, 0.55, 0.5775])
|
| 199 |
+
# fmt: on
|
| 200 |
+
|
| 201 |
+
generated_slice = generated_video.flatten()
|
| 202 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 203 |
+
self.assertTrue(
|
| 204 |
+
torch.allclose(generated_slice, expected_slice, atol=1e-3),
|
| 205 |
+
"The generated video does not match the expected slice.",
|
| 206 |
+
)
|
| 207 |
+
|
| 208 |
+
def test_callback_inputs(self):
|
| 209 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 210 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 211 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 212 |
+
|
| 213 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 214 |
+
return
|
| 215 |
+
|
| 216 |
+
components = self.get_dummy_components()
|
| 217 |
+
pipe = self.pipeline_class(**components)
|
| 218 |
+
pipe = pipe.to(torch_device)
|
| 219 |
+
pipe.set_progress_bar_config(disable=None)
|
| 220 |
+
self.assertTrue(
|
| 221 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 222 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 226 |
+
# iterate over callback args
|
| 227 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 228 |
+
# check that we're only passing in allowed tensor inputs
|
| 229 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 230 |
+
|
| 231 |
+
return callback_kwargs
|
| 232 |
+
|
| 233 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 234 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 235 |
+
assert tensor_name in callback_kwargs
|
| 236 |
+
|
| 237 |
+
# iterate over callback args
|
| 238 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 239 |
+
# check that we're only passing in allowed tensor inputs
|
| 240 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 241 |
+
|
| 242 |
+
return callback_kwargs
|
| 243 |
+
|
| 244 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 245 |
+
|
| 246 |
+
# Test passing in a subset
|
| 247 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 248 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 249 |
+
output = pipe(**inputs)[0]
|
| 250 |
+
|
| 251 |
+
# Test passing in a everything
|
| 252 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 253 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 254 |
+
output = pipe(**inputs)[0]
|
| 255 |
+
|
| 256 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 257 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 258 |
+
if is_last:
|
| 259 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 260 |
+
return callback_kwargs
|
| 261 |
+
|
| 262 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 263 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 264 |
+
output = pipe(**inputs)[0]
|
| 265 |
+
assert output.abs().sum() < 1e10
|
| 266 |
+
|
| 267 |
+
def test_attention_slicing_forward_pass(
|
| 268 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 269 |
+
):
|
| 270 |
+
if not self.test_attention_slicing:
|
| 271 |
+
return
|
| 272 |
+
|
| 273 |
+
components = self.get_dummy_components()
|
| 274 |
+
pipe = self.pipeline_class(**components)
|
| 275 |
+
for component in pipe.components.values():
|
| 276 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 277 |
+
component.set_default_attn_processor()
|
| 278 |
+
pipe.to(torch_device)
|
| 279 |
+
pipe.set_progress_bar_config(disable=None)
|
| 280 |
+
|
| 281 |
+
generator_device = "cpu"
|
| 282 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 283 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 284 |
+
|
| 285 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 286 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 287 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 288 |
+
|
| 289 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 290 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 291 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 292 |
+
|
| 293 |
+
if test_max_difference:
|
| 294 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 295 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 296 |
+
self.assertLess(
|
| 297 |
+
max(max_diff1, max_diff2),
|
| 298 |
+
expected_max_diff,
|
| 299 |
+
"Attention slicing should not affect the inference results",
|
| 300 |
+
)
|
| 301 |
+
|
| 302 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 303 |
+
# Seems to require higher tolerance than the other tests
|
| 304 |
+
expected_diff_max = 0.6
|
| 305 |
+
generator_device = "cpu"
|
| 306 |
+
components = self.get_dummy_components()
|
| 307 |
+
|
| 308 |
+
pipe = self.pipeline_class(**components)
|
| 309 |
+
pipe.to("cpu")
|
| 310 |
+
pipe.set_progress_bar_config(disable=None)
|
| 311 |
+
|
| 312 |
+
# Without tiling
|
| 313 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 314 |
+
inputs["height"] = inputs["width"] = 128
|
| 315 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 316 |
+
|
| 317 |
+
# With tiling
|
| 318 |
+
pipe.vae.enable_tiling(
|
| 319 |
+
tile_sample_min_height=96,
|
| 320 |
+
tile_sample_min_width=96,
|
| 321 |
+
tile_sample_stride_height=64,
|
| 322 |
+
tile_sample_stride_width=64,
|
| 323 |
+
)
|
| 324 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 325 |
+
inputs["height"] = inputs["width"] = 128
|
| 326 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 327 |
+
|
| 328 |
+
self.assertLess(
|
| 329 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 330 |
+
expected_diff_max,
|
| 331 |
+
"VAE tiling should not affect the inference results",
|
| 332 |
+
)
|
| 333 |
+
|
| 334 |
+
# TODO(aryan): Create a dummy gemma model with smol vocab size
|
| 335 |
+
@unittest.skip(
|
| 336 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 337 |
+
)
|
| 338 |
+
def test_inference_batch_consistent(self):
|
| 339 |
+
pass
|
| 340 |
+
|
| 341 |
+
@unittest.skip(
|
| 342 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 343 |
+
)
|
| 344 |
+
def test_inference_batch_single_identical(self):
|
| 345 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_video.py
ADDED
|
@@ -0,0 +1,358 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 CLIPTextConfig, CLIPTextModel, CLIPTokenizer, LlamaConfig, LlamaModel, LlamaTokenizer
|
| 21 |
+
|
| 22 |
+
from diffusers import (
|
| 23 |
+
AutoencoderKLHunyuanVideo,
|
| 24 |
+
FasterCacheConfig,
|
| 25 |
+
FlowMatchEulerDiscreteScheduler,
|
| 26 |
+
HunyuanVideoPipeline,
|
| 27 |
+
HunyuanVideoTransformer3DModel,
|
| 28 |
+
)
|
| 29 |
+
|
| 30 |
+
from ...testing_utils import enable_full_determinism, torch_device
|
| 31 |
+
from ..test_pipelines_common import (
|
| 32 |
+
FasterCacheTesterMixin,
|
| 33 |
+
FirstBlockCacheTesterMixin,
|
| 34 |
+
PipelineTesterMixin,
|
| 35 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 36 |
+
TaylorSeerCacheTesterMixin,
|
| 37 |
+
to_np,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
enable_full_determinism()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
class HunyuanVideoPipelineFastTests(
|
| 45 |
+
PipelineTesterMixin,
|
| 46 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 47 |
+
FasterCacheTesterMixin,
|
| 48 |
+
FirstBlockCacheTesterMixin,
|
| 49 |
+
TaylorSeerCacheTesterMixin,
|
| 50 |
+
unittest.TestCase,
|
| 51 |
+
):
|
| 52 |
+
pipeline_class = HunyuanVideoPipeline
|
| 53 |
+
params = frozenset(["prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"])
|
| 54 |
+
batch_params = frozenset(["prompt"])
|
| 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 |
+
|
| 66 |
+
# there is no xformers processor for Flux
|
| 67 |
+
test_xformers_attention = False
|
| 68 |
+
test_layerwise_casting = True
|
| 69 |
+
test_group_offloading = True
|
| 70 |
+
|
| 71 |
+
faster_cache_config = FasterCacheConfig(
|
| 72 |
+
spatial_attention_block_skip_range=2,
|
| 73 |
+
spatial_attention_timestep_skip_range=(-1, 901),
|
| 74 |
+
unconditional_batch_skip_range=2,
|
| 75 |
+
attention_weight_callback=lambda _: 0.5,
|
| 76 |
+
is_guidance_distilled=True,
|
| 77 |
+
)
|
| 78 |
+
|
| 79 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 80 |
+
torch.manual_seed(0)
|
| 81 |
+
transformer = HunyuanVideoTransformer3DModel(
|
| 82 |
+
in_channels=4,
|
| 83 |
+
out_channels=4,
|
| 84 |
+
num_attention_heads=2,
|
| 85 |
+
attention_head_dim=10,
|
| 86 |
+
num_layers=num_layers,
|
| 87 |
+
num_single_layers=num_single_layers,
|
| 88 |
+
num_refiner_layers=1,
|
| 89 |
+
patch_size=1,
|
| 90 |
+
patch_size_t=1,
|
| 91 |
+
guidance_embeds=True,
|
| 92 |
+
text_embed_dim=16,
|
| 93 |
+
pooled_projection_dim=8,
|
| 94 |
+
rope_axes_dim=(2, 4, 4),
|
| 95 |
+
)
|
| 96 |
+
|
| 97 |
+
torch.manual_seed(0)
|
| 98 |
+
vae = AutoencoderKLHunyuanVideo(
|
| 99 |
+
in_channels=3,
|
| 100 |
+
out_channels=3,
|
| 101 |
+
latent_channels=4,
|
| 102 |
+
down_block_types=(
|
| 103 |
+
"HunyuanVideoDownBlock3D",
|
| 104 |
+
"HunyuanVideoDownBlock3D",
|
| 105 |
+
"HunyuanVideoDownBlock3D",
|
| 106 |
+
"HunyuanVideoDownBlock3D",
|
| 107 |
+
),
|
| 108 |
+
up_block_types=(
|
| 109 |
+
"HunyuanVideoUpBlock3D",
|
| 110 |
+
"HunyuanVideoUpBlock3D",
|
| 111 |
+
"HunyuanVideoUpBlock3D",
|
| 112 |
+
"HunyuanVideoUpBlock3D",
|
| 113 |
+
),
|
| 114 |
+
block_out_channels=(8, 8, 8, 8),
|
| 115 |
+
layers_per_block=1,
|
| 116 |
+
act_fn="silu",
|
| 117 |
+
norm_num_groups=4,
|
| 118 |
+
scaling_factor=0.476986,
|
| 119 |
+
spatial_compression_ratio=8,
|
| 120 |
+
temporal_compression_ratio=4,
|
| 121 |
+
mid_block_add_attention=True,
|
| 122 |
+
)
|
| 123 |
+
|
| 124 |
+
torch.manual_seed(0)
|
| 125 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 126 |
+
|
| 127 |
+
llama_text_encoder_config = LlamaConfig(
|
| 128 |
+
bos_token_id=0,
|
| 129 |
+
eos_token_id=2,
|
| 130 |
+
hidden_size=16,
|
| 131 |
+
intermediate_size=37,
|
| 132 |
+
layer_norm_eps=1e-05,
|
| 133 |
+
num_attention_heads=4,
|
| 134 |
+
num_hidden_layers=2,
|
| 135 |
+
pad_token_id=1,
|
| 136 |
+
vocab_size=1000,
|
| 137 |
+
hidden_act="gelu",
|
| 138 |
+
projection_dim=32,
|
| 139 |
+
)
|
| 140 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 141 |
+
bos_token_id=0,
|
| 142 |
+
eos_token_id=2,
|
| 143 |
+
hidden_size=8,
|
| 144 |
+
intermediate_size=37,
|
| 145 |
+
layer_norm_eps=1e-05,
|
| 146 |
+
num_attention_heads=4,
|
| 147 |
+
num_hidden_layers=2,
|
| 148 |
+
pad_token_id=1,
|
| 149 |
+
vocab_size=1000,
|
| 150 |
+
hidden_act="gelu",
|
| 151 |
+
projection_dim=32,
|
| 152 |
+
)
|
| 153 |
+
|
| 154 |
+
torch.manual_seed(0)
|
| 155 |
+
text_encoder = LlamaModel(llama_text_encoder_config)
|
| 156 |
+
tokenizer = LlamaTokenizer.from_pretrained("finetrainers/dummy-hunyaunvideo", subfolder="tokenizer")
|
| 157 |
+
|
| 158 |
+
torch.manual_seed(0)
|
| 159 |
+
text_encoder_2 = CLIPTextModel(clip_text_encoder_config)
|
| 160 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 161 |
+
|
| 162 |
+
components = {
|
| 163 |
+
"transformer": transformer,
|
| 164 |
+
"vae": vae,
|
| 165 |
+
"scheduler": scheduler,
|
| 166 |
+
"text_encoder": text_encoder,
|
| 167 |
+
"text_encoder_2": text_encoder_2,
|
| 168 |
+
"tokenizer": tokenizer,
|
| 169 |
+
"tokenizer_2": tokenizer_2,
|
| 170 |
+
}
|
| 171 |
+
return components
|
| 172 |
+
|
| 173 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 174 |
+
if str(device).startswith("mps"):
|
| 175 |
+
generator = torch.manual_seed(seed)
|
| 176 |
+
else:
|
| 177 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 178 |
+
|
| 179 |
+
inputs = {
|
| 180 |
+
"prompt": "dance monkey",
|
| 181 |
+
"prompt_template": {
|
| 182 |
+
"template": "{}",
|
| 183 |
+
"crop_start": 0,
|
| 184 |
+
},
|
| 185 |
+
"generator": generator,
|
| 186 |
+
"num_inference_steps": 2,
|
| 187 |
+
"guidance_scale": 4.5,
|
| 188 |
+
"height": 16,
|
| 189 |
+
"width": 16,
|
| 190 |
+
# 4 * k + 1 is the recommendation
|
| 191 |
+
"num_frames": 9,
|
| 192 |
+
"max_sequence_length": 16,
|
| 193 |
+
"output_type": "pt",
|
| 194 |
+
}
|
| 195 |
+
return inputs
|
| 196 |
+
|
| 197 |
+
def test_inference(self):
|
| 198 |
+
device = "cpu"
|
| 199 |
+
|
| 200 |
+
components = self.get_dummy_components()
|
| 201 |
+
pipe = self.pipeline_class(**components)
|
| 202 |
+
pipe.to(device)
|
| 203 |
+
pipe.set_progress_bar_config(disable=None)
|
| 204 |
+
|
| 205 |
+
inputs = self.get_dummy_inputs(device)
|
| 206 |
+
video = pipe(**inputs).frames
|
| 207 |
+
generated_video = video[0]
|
| 208 |
+
self.assertEqual(generated_video.shape, (9, 3, 16, 16))
|
| 209 |
+
|
| 210 |
+
# fmt: off
|
| 211 |
+
expected_slice = torch.tensor([0.3946, 0.4649, 0.3196, 0.4569, 0.3312, 0.3687, 0.3216, 0.3972, 0.4469, 0.3888, 0.3929, 0.3802, 0.3479, 0.3888, 0.3825, 0.3542])
|
| 212 |
+
# fmt: on
|
| 213 |
+
|
| 214 |
+
generated_slice = generated_video.flatten()
|
| 215 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 216 |
+
self.assertTrue(
|
| 217 |
+
torch.allclose(generated_slice, expected_slice, atol=1e-3),
|
| 218 |
+
"The generated video does not match the expected slice.",
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
def test_callback_inputs(self):
|
| 222 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 223 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 224 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 225 |
+
|
| 226 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 227 |
+
return
|
| 228 |
+
|
| 229 |
+
components = self.get_dummy_components()
|
| 230 |
+
pipe = self.pipeline_class(**components)
|
| 231 |
+
pipe = pipe.to(torch_device)
|
| 232 |
+
pipe.set_progress_bar_config(disable=None)
|
| 233 |
+
self.assertTrue(
|
| 234 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 235 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 236 |
+
)
|
| 237 |
+
|
| 238 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 239 |
+
# iterate over callback args
|
| 240 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 241 |
+
# check that we're only passing in allowed tensor inputs
|
| 242 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 243 |
+
|
| 244 |
+
return callback_kwargs
|
| 245 |
+
|
| 246 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 247 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 248 |
+
assert tensor_name in callback_kwargs
|
| 249 |
+
|
| 250 |
+
# iterate over callback args
|
| 251 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 252 |
+
# check that we're only passing in allowed tensor inputs
|
| 253 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 254 |
+
|
| 255 |
+
return callback_kwargs
|
| 256 |
+
|
| 257 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 258 |
+
|
| 259 |
+
# Test passing in a subset
|
| 260 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 261 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 262 |
+
output = pipe(**inputs)[0]
|
| 263 |
+
|
| 264 |
+
# Test passing in a everything
|
| 265 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 266 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 267 |
+
output = pipe(**inputs)[0]
|
| 268 |
+
|
| 269 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 270 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 271 |
+
if is_last:
|
| 272 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 273 |
+
return callback_kwargs
|
| 274 |
+
|
| 275 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 276 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 277 |
+
output = pipe(**inputs)[0]
|
| 278 |
+
assert output.abs().sum() < 1e10
|
| 279 |
+
|
| 280 |
+
def test_attention_slicing_forward_pass(
|
| 281 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 282 |
+
):
|
| 283 |
+
if not self.test_attention_slicing:
|
| 284 |
+
return
|
| 285 |
+
|
| 286 |
+
components = self.get_dummy_components()
|
| 287 |
+
pipe = self.pipeline_class(**components)
|
| 288 |
+
for component in pipe.components.values():
|
| 289 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 290 |
+
component.set_default_attn_processor()
|
| 291 |
+
pipe.to(torch_device)
|
| 292 |
+
pipe.set_progress_bar_config(disable=None)
|
| 293 |
+
|
| 294 |
+
generator_device = "cpu"
|
| 295 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 296 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 297 |
+
|
| 298 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 299 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 300 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 301 |
+
|
| 302 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 303 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 304 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 305 |
+
|
| 306 |
+
if test_max_difference:
|
| 307 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 308 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 309 |
+
self.assertLess(
|
| 310 |
+
max(max_diff1, max_diff2),
|
| 311 |
+
expected_max_diff,
|
| 312 |
+
"Attention slicing should not affect the inference results",
|
| 313 |
+
)
|
| 314 |
+
|
| 315 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 316 |
+
# Seems to require higher tolerance than the other tests
|
| 317 |
+
expected_diff_max = 0.6
|
| 318 |
+
generator_device = "cpu"
|
| 319 |
+
components = self.get_dummy_components()
|
| 320 |
+
|
| 321 |
+
pipe = self.pipeline_class(**components)
|
| 322 |
+
pipe.to("cpu")
|
| 323 |
+
pipe.set_progress_bar_config(disable=None)
|
| 324 |
+
|
| 325 |
+
# Without tiling
|
| 326 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 327 |
+
inputs["height"] = inputs["width"] = 128
|
| 328 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 329 |
+
|
| 330 |
+
# With tiling
|
| 331 |
+
pipe.vae.enable_tiling(
|
| 332 |
+
tile_sample_min_height=96,
|
| 333 |
+
tile_sample_min_width=96,
|
| 334 |
+
tile_sample_stride_height=64,
|
| 335 |
+
tile_sample_stride_width=64,
|
| 336 |
+
)
|
| 337 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 338 |
+
inputs["height"] = inputs["width"] = 128
|
| 339 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 340 |
+
|
| 341 |
+
self.assertLess(
|
| 342 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 343 |
+
expected_diff_max,
|
| 344 |
+
"VAE tiling should not affect the inference results",
|
| 345 |
+
)
|
| 346 |
+
|
| 347 |
+
# TODO(aryan): Create a dummy gemma model with smol vocab size
|
| 348 |
+
@unittest.skip(
|
| 349 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 350 |
+
)
|
| 351 |
+
def test_inference_batch_consistent(self):
|
| 352 |
+
pass
|
| 353 |
+
|
| 354 |
+
@unittest.skip(
|
| 355 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 356 |
+
)
|
| 357 |
+
def test_inference_batch_single_identical(self):
|
| 358 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video/test_hunyuan_video_framepack.py
ADDED
|
@@ -0,0 +1,404 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 PIL import Image
|
| 21 |
+
from transformers import (
|
| 22 |
+
CLIPTextConfig,
|
| 23 |
+
CLIPTextModel,
|
| 24 |
+
CLIPTokenizer,
|
| 25 |
+
LlamaConfig,
|
| 26 |
+
LlamaModel,
|
| 27 |
+
LlamaTokenizer,
|
| 28 |
+
SiglipImageProcessor,
|
| 29 |
+
SiglipVisionModel,
|
| 30 |
+
)
|
| 31 |
+
|
| 32 |
+
from diffusers import (
|
| 33 |
+
AutoencoderKLHunyuanVideo,
|
| 34 |
+
FasterCacheConfig,
|
| 35 |
+
FlowMatchEulerDiscreteScheduler,
|
| 36 |
+
HunyuanVideoFramepackPipeline,
|
| 37 |
+
HunyuanVideoFramepackTransformer3DModel,
|
| 38 |
+
)
|
| 39 |
+
|
| 40 |
+
from ...testing_utils import (
|
| 41 |
+
enable_full_determinism,
|
| 42 |
+
torch_device,
|
| 43 |
+
)
|
| 44 |
+
from ..test_pipelines_common import (
|
| 45 |
+
FasterCacheTesterMixin,
|
| 46 |
+
PipelineTesterMixin,
|
| 47 |
+
PyramidAttentionBroadcastTesterMixin,
|
| 48 |
+
to_np,
|
| 49 |
+
)
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
enable_full_determinism()
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
class HunyuanVideoFramepackPipelineFastTests(
|
| 56 |
+
PipelineTesterMixin, PyramidAttentionBroadcastTesterMixin, FasterCacheTesterMixin, unittest.TestCase
|
| 57 |
+
):
|
| 58 |
+
pipeline_class = HunyuanVideoFramepackPipeline
|
| 59 |
+
params = frozenset(
|
| 60 |
+
["image", "prompt", "height", "width", "guidance_scale", "prompt_embeds", "pooled_prompt_embeds"]
|
| 61 |
+
)
|
| 62 |
+
batch_params = frozenset(["image", "prompt"])
|
| 63 |
+
required_optional_params = frozenset(
|
| 64 |
+
[
|
| 65 |
+
"num_inference_steps",
|
| 66 |
+
"generator",
|
| 67 |
+
"return_dict",
|
| 68 |
+
"callback_on_step_end",
|
| 69 |
+
"callback_on_step_end_tensor_inputs",
|
| 70 |
+
]
|
| 71 |
+
)
|
| 72 |
+
|
| 73 |
+
supports_dduf = False
|
| 74 |
+
test_xformers_attention = False
|
| 75 |
+
test_layerwise_casting = True
|
| 76 |
+
test_group_offloading = True
|
| 77 |
+
|
| 78 |
+
faster_cache_config = FasterCacheConfig(
|
| 79 |
+
spatial_attention_block_skip_range=2,
|
| 80 |
+
spatial_attention_timestep_skip_range=(-1, 901),
|
| 81 |
+
unconditional_batch_skip_range=2,
|
| 82 |
+
attention_weight_callback=lambda _: 0.5,
|
| 83 |
+
is_guidance_distilled=True,
|
| 84 |
+
)
|
| 85 |
+
|
| 86 |
+
def get_dummy_components(self, num_layers: int = 1, num_single_layers: int = 1):
|
| 87 |
+
torch.manual_seed(0)
|
| 88 |
+
transformer = HunyuanVideoFramepackTransformer3DModel(
|
| 89 |
+
in_channels=4,
|
| 90 |
+
out_channels=4,
|
| 91 |
+
num_attention_heads=2,
|
| 92 |
+
attention_head_dim=10,
|
| 93 |
+
num_layers=num_layers,
|
| 94 |
+
num_single_layers=num_single_layers,
|
| 95 |
+
num_refiner_layers=1,
|
| 96 |
+
patch_size=2,
|
| 97 |
+
patch_size_t=1,
|
| 98 |
+
guidance_embeds=True,
|
| 99 |
+
text_embed_dim=16,
|
| 100 |
+
pooled_projection_dim=8,
|
| 101 |
+
rope_axes_dim=(2, 4, 4),
|
| 102 |
+
image_condition_type=None,
|
| 103 |
+
has_image_proj=True,
|
| 104 |
+
image_proj_dim=32,
|
| 105 |
+
has_clean_x_embedder=True,
|
| 106 |
+
)
|
| 107 |
+
|
| 108 |
+
torch.manual_seed(0)
|
| 109 |
+
vae = AutoencoderKLHunyuanVideo(
|
| 110 |
+
in_channels=3,
|
| 111 |
+
out_channels=3,
|
| 112 |
+
latent_channels=4,
|
| 113 |
+
down_block_types=(
|
| 114 |
+
"HunyuanVideoDownBlock3D",
|
| 115 |
+
"HunyuanVideoDownBlock3D",
|
| 116 |
+
"HunyuanVideoDownBlock3D",
|
| 117 |
+
"HunyuanVideoDownBlock3D",
|
| 118 |
+
),
|
| 119 |
+
up_block_types=(
|
| 120 |
+
"HunyuanVideoUpBlock3D",
|
| 121 |
+
"HunyuanVideoUpBlock3D",
|
| 122 |
+
"HunyuanVideoUpBlock3D",
|
| 123 |
+
"HunyuanVideoUpBlock3D",
|
| 124 |
+
),
|
| 125 |
+
block_out_channels=(8, 8, 8, 8),
|
| 126 |
+
layers_per_block=1,
|
| 127 |
+
act_fn="silu",
|
| 128 |
+
norm_num_groups=4,
|
| 129 |
+
scaling_factor=0.476986,
|
| 130 |
+
spatial_compression_ratio=8,
|
| 131 |
+
temporal_compression_ratio=4,
|
| 132 |
+
mid_block_add_attention=True,
|
| 133 |
+
)
|
| 134 |
+
|
| 135 |
+
torch.manual_seed(0)
|
| 136 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 137 |
+
|
| 138 |
+
llama_text_encoder_config = LlamaConfig(
|
| 139 |
+
bos_token_id=0,
|
| 140 |
+
eos_token_id=2,
|
| 141 |
+
hidden_size=16,
|
| 142 |
+
intermediate_size=37,
|
| 143 |
+
layer_norm_eps=1e-05,
|
| 144 |
+
num_attention_heads=4,
|
| 145 |
+
num_hidden_layers=2,
|
| 146 |
+
pad_token_id=1,
|
| 147 |
+
vocab_size=1000,
|
| 148 |
+
hidden_act="gelu",
|
| 149 |
+
projection_dim=32,
|
| 150 |
+
)
|
| 151 |
+
clip_text_encoder_config = CLIPTextConfig(
|
| 152 |
+
bos_token_id=0,
|
| 153 |
+
eos_token_id=2,
|
| 154 |
+
hidden_size=8,
|
| 155 |
+
intermediate_size=37,
|
| 156 |
+
layer_norm_eps=1e-05,
|
| 157 |
+
num_attention_heads=4,
|
| 158 |
+
num_hidden_layers=2,
|
| 159 |
+
pad_token_id=1,
|
| 160 |
+
vocab_size=1000,
|
| 161 |
+
hidden_act="gelu",
|
| 162 |
+
projection_dim=32,
|
| 163 |
+
)
|
| 164 |
+
|
| 165 |
+
torch.manual_seed(0)
|
| 166 |
+
text_encoder = LlamaModel(llama_text_encoder_config)
|
| 167 |
+
tokenizer = LlamaTokenizer.from_pretrained("finetrainers/dummy-hunyaunvideo", subfolder="tokenizer")
|
| 168 |
+
|
| 169 |
+
torch.manual_seed(0)
|
| 170 |
+
text_encoder_2 = CLIPTextModel(clip_text_encoder_config)
|
| 171 |
+
tokenizer_2 = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")
|
| 172 |
+
|
| 173 |
+
feature_extractor = SiglipImageProcessor.from_pretrained(
|
| 174 |
+
"hf-internal-testing/tiny-random-SiglipVisionModel", size={"height": 30, "width": 30}
|
| 175 |
+
)
|
| 176 |
+
image_encoder = SiglipVisionModel.from_pretrained("hf-internal-testing/tiny-random-SiglipVisionModel")
|
| 177 |
+
|
| 178 |
+
components = {
|
| 179 |
+
"transformer": transformer,
|
| 180 |
+
"vae": vae,
|
| 181 |
+
"scheduler": scheduler,
|
| 182 |
+
"text_encoder": text_encoder,
|
| 183 |
+
"text_encoder_2": text_encoder_2,
|
| 184 |
+
"tokenizer": tokenizer,
|
| 185 |
+
"tokenizer_2": tokenizer_2,
|
| 186 |
+
"feature_extractor": feature_extractor,
|
| 187 |
+
"image_encoder": image_encoder,
|
| 188 |
+
}
|
| 189 |
+
return components
|
| 190 |
+
|
| 191 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 192 |
+
if str(device).startswith("mps"):
|
| 193 |
+
generator = torch.manual_seed(seed)
|
| 194 |
+
else:
|
| 195 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 196 |
+
|
| 197 |
+
image_height = 32
|
| 198 |
+
image_width = 32
|
| 199 |
+
image = Image.new("RGB", (image_width, image_height))
|
| 200 |
+
inputs = {
|
| 201 |
+
"image": image,
|
| 202 |
+
"prompt": "dance monkey",
|
| 203 |
+
"prompt_template": {
|
| 204 |
+
"template": "{}",
|
| 205 |
+
"crop_start": 0,
|
| 206 |
+
},
|
| 207 |
+
"generator": generator,
|
| 208 |
+
"num_inference_steps": 2,
|
| 209 |
+
"guidance_scale": 4.5,
|
| 210 |
+
"height": image_height,
|
| 211 |
+
"width": image_width,
|
| 212 |
+
"num_frames": 9,
|
| 213 |
+
"latent_window_size": 3,
|
| 214 |
+
"max_sequence_length": 256,
|
| 215 |
+
"output_type": "pt",
|
| 216 |
+
}
|
| 217 |
+
return inputs
|
| 218 |
+
|
| 219 |
+
def test_inference(self):
|
| 220 |
+
device = "cpu"
|
| 221 |
+
|
| 222 |
+
components = self.get_dummy_components()
|
| 223 |
+
pipe = self.pipeline_class(**components)
|
| 224 |
+
pipe.to(device)
|
| 225 |
+
pipe.set_progress_bar_config(disable=None)
|
| 226 |
+
|
| 227 |
+
inputs = self.get_dummy_inputs(device)
|
| 228 |
+
video = pipe(**inputs).frames
|
| 229 |
+
generated_video = video[0]
|
| 230 |
+
self.assertEqual(generated_video.shape, (13, 3, 32, 32))
|
| 231 |
+
|
| 232 |
+
# fmt: off
|
| 233 |
+
expected_slice = torch.tensor([0.363, 0.3384, 0.3426, 0.3512, 0.3372, 0.3276, 0.417, 0.4061, 0.5221, 0.467, 0.4813, 0.4556, 0.4107, 0.3945, 0.4049, 0.4551])
|
| 234 |
+
# fmt: on
|
| 235 |
+
|
| 236 |
+
generated_slice = generated_video.flatten()
|
| 237 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 238 |
+
self.assertTrue(
|
| 239 |
+
torch.allclose(generated_slice, expected_slice, atol=1e-3),
|
| 240 |
+
"The generated video does not match the expected slice.",
|
| 241 |
+
)
|
| 242 |
+
|
| 243 |
+
def test_callback_inputs(self):
|
| 244 |
+
sig = inspect.signature(self.pipeline_class.__call__)
|
| 245 |
+
has_callback_tensor_inputs = "callback_on_step_end_tensor_inputs" in sig.parameters
|
| 246 |
+
has_callback_step_end = "callback_on_step_end" in sig.parameters
|
| 247 |
+
|
| 248 |
+
if not (has_callback_tensor_inputs and has_callback_step_end):
|
| 249 |
+
return
|
| 250 |
+
|
| 251 |
+
components = self.get_dummy_components()
|
| 252 |
+
pipe = self.pipeline_class(**components)
|
| 253 |
+
pipe = pipe.to(torch_device)
|
| 254 |
+
pipe.set_progress_bar_config(disable=None)
|
| 255 |
+
self.assertTrue(
|
| 256 |
+
hasattr(pipe, "_callback_tensor_inputs"),
|
| 257 |
+
f" {self.pipeline_class} should have `_callback_tensor_inputs` that defines a list of tensor variables its callback function can use as inputs",
|
| 258 |
+
)
|
| 259 |
+
|
| 260 |
+
def callback_inputs_subset(pipe, i, t, callback_kwargs):
|
| 261 |
+
# iterate over callback args
|
| 262 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 263 |
+
# check that we're only passing in allowed tensor inputs
|
| 264 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 265 |
+
|
| 266 |
+
return callback_kwargs
|
| 267 |
+
|
| 268 |
+
def callback_inputs_all(pipe, i, t, callback_kwargs):
|
| 269 |
+
for tensor_name in pipe._callback_tensor_inputs:
|
| 270 |
+
assert tensor_name in callback_kwargs
|
| 271 |
+
|
| 272 |
+
# iterate over callback args
|
| 273 |
+
for tensor_name, tensor_value in callback_kwargs.items():
|
| 274 |
+
# check that we're only passing in allowed tensor inputs
|
| 275 |
+
assert tensor_name in pipe._callback_tensor_inputs
|
| 276 |
+
|
| 277 |
+
return callback_kwargs
|
| 278 |
+
|
| 279 |
+
inputs = self.get_dummy_inputs(torch_device)
|
| 280 |
+
|
| 281 |
+
# Test passing in a subset
|
| 282 |
+
inputs["callback_on_step_end"] = callback_inputs_subset
|
| 283 |
+
inputs["callback_on_step_end_tensor_inputs"] = ["latents"]
|
| 284 |
+
output = pipe(**inputs)[0]
|
| 285 |
+
|
| 286 |
+
# Test passing in a everything
|
| 287 |
+
inputs["callback_on_step_end"] = callback_inputs_all
|
| 288 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 289 |
+
output = pipe(**inputs)[0]
|
| 290 |
+
|
| 291 |
+
def callback_inputs_change_tensor(pipe, i, t, callback_kwargs):
|
| 292 |
+
is_last = i == (pipe.num_timesteps - 1)
|
| 293 |
+
if is_last:
|
| 294 |
+
callback_kwargs["latents"] = torch.zeros_like(callback_kwargs["latents"])
|
| 295 |
+
return callback_kwargs
|
| 296 |
+
|
| 297 |
+
inputs["callback_on_step_end"] = callback_inputs_change_tensor
|
| 298 |
+
inputs["callback_on_step_end_tensor_inputs"] = pipe._callback_tensor_inputs
|
| 299 |
+
output = pipe(**inputs)[0]
|
| 300 |
+
assert output.abs().sum() < 1e10
|
| 301 |
+
|
| 302 |
+
def test_attention_slicing_forward_pass(
|
| 303 |
+
self, test_max_difference=True, test_mean_pixel_difference=True, expected_max_diff=1e-3
|
| 304 |
+
):
|
| 305 |
+
if not self.test_attention_slicing:
|
| 306 |
+
return
|
| 307 |
+
|
| 308 |
+
components = self.get_dummy_components()
|
| 309 |
+
pipe = self.pipeline_class(**components)
|
| 310 |
+
for component in pipe.components.values():
|
| 311 |
+
if hasattr(component, "set_default_attn_processor"):
|
| 312 |
+
component.set_default_attn_processor()
|
| 313 |
+
pipe.to(torch_device)
|
| 314 |
+
pipe.set_progress_bar_config(disable=None)
|
| 315 |
+
|
| 316 |
+
generator_device = "cpu"
|
| 317 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 318 |
+
output_without_slicing = pipe(**inputs)[0]
|
| 319 |
+
|
| 320 |
+
pipe.enable_attention_slicing(slice_size=1)
|
| 321 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 322 |
+
output_with_slicing1 = pipe(**inputs)[0]
|
| 323 |
+
|
| 324 |
+
pipe.enable_attention_slicing(slice_size=2)
|
| 325 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 326 |
+
output_with_slicing2 = pipe(**inputs)[0]
|
| 327 |
+
|
| 328 |
+
if test_max_difference:
|
| 329 |
+
max_diff1 = np.abs(to_np(output_with_slicing1) - to_np(output_without_slicing)).max()
|
| 330 |
+
max_diff2 = np.abs(to_np(output_with_slicing2) - to_np(output_without_slicing)).max()
|
| 331 |
+
self.assertLess(
|
| 332 |
+
max(max_diff1, max_diff2),
|
| 333 |
+
expected_max_diff,
|
| 334 |
+
"Attention slicing should not affect the inference results",
|
| 335 |
+
)
|
| 336 |
+
|
| 337 |
+
def test_vae_tiling(self, expected_diff_max: float = 0.2):
|
| 338 |
+
# Seems to require higher tolerance than the other tests
|
| 339 |
+
expected_diff_max = 0.6
|
| 340 |
+
generator_device = "cpu"
|
| 341 |
+
components = self.get_dummy_components()
|
| 342 |
+
|
| 343 |
+
pipe = self.pipeline_class(**components)
|
| 344 |
+
pipe.to("cpu")
|
| 345 |
+
pipe.set_progress_bar_config(disable=None)
|
| 346 |
+
|
| 347 |
+
# Without tiling
|
| 348 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 349 |
+
inputs["height"] = inputs["width"] = 128
|
| 350 |
+
output_without_tiling = pipe(**inputs)[0]
|
| 351 |
+
|
| 352 |
+
# With tiling
|
| 353 |
+
pipe.vae.enable_tiling(
|
| 354 |
+
tile_sample_min_height=96,
|
| 355 |
+
tile_sample_min_width=96,
|
| 356 |
+
tile_sample_stride_height=64,
|
| 357 |
+
tile_sample_stride_width=64,
|
| 358 |
+
)
|
| 359 |
+
inputs = self.get_dummy_inputs(generator_device)
|
| 360 |
+
inputs["height"] = inputs["width"] = 128
|
| 361 |
+
output_with_tiling = pipe(**inputs)[0]
|
| 362 |
+
|
| 363 |
+
self.assertLess(
|
| 364 |
+
(to_np(output_without_tiling) - to_np(output_with_tiling)).max(),
|
| 365 |
+
expected_diff_max,
|
| 366 |
+
"VAE tiling should not affect the inference results",
|
| 367 |
+
)
|
| 368 |
+
|
| 369 |
+
def test_float16_inference(self, expected_max_diff=0.2):
|
| 370 |
+
# NOTE: this test needs a higher tolerance because of multiple forwards through
|
| 371 |
+
# the model, which compounds the overall fp32 vs fp16 numerical differences. It
|
| 372 |
+
# shouldn't be expected that the results are the same, so we bump the tolerance.
|
| 373 |
+
return super().test_float16_inference(expected_max_diff)
|
| 374 |
+
|
| 375 |
+
@unittest.skip("The image_encoder uses SiglipVisionModel, which does not support sequential CPU offloading.")
|
| 376 |
+
def test_sequential_cpu_offload_forward_pass(self):
|
| 377 |
+
# https://github.com/huggingface/transformers/blob/21cb353b7b4f77c6f5f5c3341d660f86ff416d04/src/transformers/models/siglip/modeling_siglip.py#L803
|
| 378 |
+
# This is because it instantiates it's attention layer from torch.nn.MultiheadAttention, which calls to
|
| 379 |
+
# `torch.nn.functional.multi_head_attention_forward` with the weights and bias. Since the hook is never
|
| 380 |
+
# triggered with a forward pass call, the weights stay on the CPU. There are more examples where we skip
|
| 381 |
+
# this test because of MHA (example: HunyuanDiT because of AttentionPooling layer).
|
| 382 |
+
pass
|
| 383 |
+
|
| 384 |
+
@unittest.skip("The image_encoder uses SiglipVisionModel, which does not support sequential CPU offloading.")
|
| 385 |
+
def test_sequential_offload_forward_pass_twice(self):
|
| 386 |
+
# https://github.com/huggingface/transformers/blob/21cb353b7b4f77c6f5f5c3341d660f86ff416d04/src/transformers/models/siglip/modeling_siglip.py#L803
|
| 387 |
+
# This is because it instantiates it's attention layer from torch.nn.MultiheadAttention, which calls to
|
| 388 |
+
# `torch.nn.functional.multi_head_attention_forward` with the weights and bias. Since the hook is never
|
| 389 |
+
# triggered with a forward pass call, the weights stay on the CPU. There are more examples where we skip
|
| 390 |
+
# this test because of MHA (example: HunyuanDiT because of AttentionPooling layer).
|
| 391 |
+
pass
|
| 392 |
+
|
| 393 |
+
# TODO(aryan): Create a dummy gemma model with smol vocab size
|
| 394 |
+
@unittest.skip(
|
| 395 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 396 |
+
)
|
| 397 |
+
def test_inference_batch_consistent(self):
|
| 398 |
+
pass
|
| 399 |
+
|
| 400 |
+
@unittest.skip(
|
| 401 |
+
"A very small vocab size is used for fast tests. So, Any kind of prompt other than the empty default used in other tests will lead to a embedding lookup error. This test uses a long prompt that causes the error."
|
| 402 |
+
)
|
| 403 |
+
def test_inference_batch_single_identical(self):
|
| 404 |
+
pass
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video1_5/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Copyright 2025 The HuggingFace Team.
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuan_video1_5/test_hunyuan_1_5.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 unittest
|
| 16 |
+
|
| 17 |
+
import torch
|
| 18 |
+
from transformers import (
|
| 19 |
+
AutoConfig,
|
| 20 |
+
ByT5Tokenizer,
|
| 21 |
+
Qwen2_5_VLTextConfig,
|
| 22 |
+
Qwen2_5_VLTextModel,
|
| 23 |
+
Qwen2Tokenizer,
|
| 24 |
+
T5EncoderModel,
|
| 25 |
+
)
|
| 26 |
+
|
| 27 |
+
from diffusers import (
|
| 28 |
+
AutoencoderKLHunyuanVideo15,
|
| 29 |
+
FlowMatchEulerDiscreteScheduler,
|
| 30 |
+
HunyuanVideo15Pipeline,
|
| 31 |
+
HunyuanVideo15Transformer3DModel,
|
| 32 |
+
)
|
| 33 |
+
from diffusers.guiders import ClassifierFreeGuidance
|
| 34 |
+
|
| 35 |
+
from ...testing_utils import enable_full_determinism
|
| 36 |
+
from ..test_pipelines_common import PipelineTesterMixin
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
enable_full_determinism()
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
class HunyuanVideo15PipelineFastTests(PipelineTesterMixin, unittest.TestCase):
|
| 43 |
+
pipeline_class = HunyuanVideo15Pipeline
|
| 44 |
+
params = frozenset(
|
| 45 |
+
[
|
| 46 |
+
"prompt",
|
| 47 |
+
"negative_prompt",
|
| 48 |
+
"height",
|
| 49 |
+
"width",
|
| 50 |
+
"prompt_embeds",
|
| 51 |
+
"prompt_embeds_mask",
|
| 52 |
+
"negative_prompt_embeds",
|
| 53 |
+
"negative_prompt_embeds_mask",
|
| 54 |
+
"prompt_embeds_2",
|
| 55 |
+
"prompt_embeds_mask_2",
|
| 56 |
+
"negative_prompt_embeds_2",
|
| 57 |
+
"negative_prompt_embeds_mask_2",
|
| 58 |
+
]
|
| 59 |
+
)
|
| 60 |
+
batch_params = ["prompt", "negative_prompt"]
|
| 61 |
+
required_optional_params = frozenset(["num_inference_steps", "generator", "latents", "return_dict"])
|
| 62 |
+
test_attention_slicing = False
|
| 63 |
+
test_xformers_attention = False
|
| 64 |
+
test_layerwise_casting = True
|
| 65 |
+
test_group_offloading = False
|
| 66 |
+
supports_dduf = False
|
| 67 |
+
|
| 68 |
+
def get_dummy_components(self, num_layers: int = 1):
|
| 69 |
+
torch.manual_seed(0)
|
| 70 |
+
transformer = HunyuanVideo15Transformer3DModel(
|
| 71 |
+
in_channels=9,
|
| 72 |
+
out_channels=4,
|
| 73 |
+
num_attention_heads=2,
|
| 74 |
+
attention_head_dim=8,
|
| 75 |
+
num_layers=num_layers,
|
| 76 |
+
num_refiner_layers=1,
|
| 77 |
+
mlp_ratio=2.0,
|
| 78 |
+
patch_size=1,
|
| 79 |
+
patch_size_t=1,
|
| 80 |
+
text_embed_dim=16,
|
| 81 |
+
text_embed_2_dim=32,
|
| 82 |
+
image_embed_dim=12,
|
| 83 |
+
rope_axes_dim=(2, 2, 4),
|
| 84 |
+
target_size=16,
|
| 85 |
+
task_type="t2v",
|
| 86 |
+
)
|
| 87 |
+
|
| 88 |
+
torch.manual_seed(0)
|
| 89 |
+
vae = AutoencoderKLHunyuanVideo15(
|
| 90 |
+
in_channels=3,
|
| 91 |
+
out_channels=3,
|
| 92 |
+
latent_channels=4,
|
| 93 |
+
block_out_channels=(16, 16),
|
| 94 |
+
layers_per_block=1,
|
| 95 |
+
spatial_compression_ratio=4,
|
| 96 |
+
temporal_compression_ratio=2,
|
| 97 |
+
downsample_match_channel=False,
|
| 98 |
+
upsample_match_channel=False,
|
| 99 |
+
)
|
| 100 |
+
|
| 101 |
+
torch.manual_seed(0)
|
| 102 |
+
scheduler = FlowMatchEulerDiscreteScheduler(shift=7.0)
|
| 103 |
+
|
| 104 |
+
torch.manual_seed(0)
|
| 105 |
+
qwen_config = Qwen2_5_VLTextConfig(
|
| 106 |
+
**{
|
| 107 |
+
"hidden_size": 16,
|
| 108 |
+
"intermediate_size": 16,
|
| 109 |
+
"num_hidden_layers": 2,
|
| 110 |
+
"num_attention_heads": 2,
|
| 111 |
+
"num_key_value_heads": 2,
|
| 112 |
+
"rope_scaling": {
|
| 113 |
+
"mrope_section": [1, 1, 2],
|
| 114 |
+
"rope_type": "default",
|
| 115 |
+
"type": "default",
|
| 116 |
+
},
|
| 117 |
+
"rope_theta": 1000000.0,
|
| 118 |
+
}
|
| 119 |
+
)
|
| 120 |
+
text_encoder = Qwen2_5_VLTextModel(qwen_config)
|
| 121 |
+
tokenizer = Qwen2Tokenizer.from_pretrained("hf-internal-testing/tiny-random-Qwen2VLForConditionalGeneration")
|
| 122 |
+
|
| 123 |
+
torch.manual_seed(0)
|
| 124 |
+
config = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-t5")
|
| 125 |
+
text_encoder_2 = T5EncoderModel(config)
|
| 126 |
+
tokenizer_2 = ByT5Tokenizer()
|
| 127 |
+
|
| 128 |
+
guider = ClassifierFreeGuidance(guidance_scale=1.0)
|
| 129 |
+
|
| 130 |
+
components = {
|
| 131 |
+
"transformer": transformer.eval(),
|
| 132 |
+
"vae": vae.eval(),
|
| 133 |
+
"scheduler": scheduler,
|
| 134 |
+
"text_encoder": text_encoder.eval(),
|
| 135 |
+
"text_encoder_2": text_encoder_2.eval(),
|
| 136 |
+
"tokenizer": tokenizer,
|
| 137 |
+
"tokenizer_2": tokenizer_2,
|
| 138 |
+
"guider": guider,
|
| 139 |
+
}
|
| 140 |
+
return components
|
| 141 |
+
|
| 142 |
+
def get_dummy_inputs(self, device, seed=0):
|
| 143 |
+
if str(device).startswith("mps"):
|
| 144 |
+
generator = torch.manual_seed(seed)
|
| 145 |
+
else:
|
| 146 |
+
generator = torch.Generator(device=device).manual_seed(seed)
|
| 147 |
+
|
| 148 |
+
inputs = {
|
| 149 |
+
"prompt": "monkey",
|
| 150 |
+
"generator": generator,
|
| 151 |
+
"num_inference_steps": 2,
|
| 152 |
+
"height": 16,
|
| 153 |
+
"width": 16,
|
| 154 |
+
"num_frames": 9,
|
| 155 |
+
"output_type": "pt",
|
| 156 |
+
}
|
| 157 |
+
return inputs
|
| 158 |
+
|
| 159 |
+
def test_inference(self):
|
| 160 |
+
device = "cpu"
|
| 161 |
+
|
| 162 |
+
components = self.get_dummy_components()
|
| 163 |
+
pipe = self.pipeline_class(**components)
|
| 164 |
+
pipe.to(device)
|
| 165 |
+
pipe.set_progress_bar_config(disable=None)
|
| 166 |
+
|
| 167 |
+
inputs = self.get_dummy_inputs(device)
|
| 168 |
+
result = pipe(**inputs)
|
| 169 |
+
video = result.frames
|
| 170 |
+
|
| 171 |
+
generated_video = video[0]
|
| 172 |
+
self.assertEqual(generated_video.shape, (9, 3, 16, 16))
|
| 173 |
+
generated_slice = generated_video.flatten()
|
| 174 |
+
generated_slice = torch.cat([generated_slice[:8], generated_slice[-8:]])
|
| 175 |
+
|
| 176 |
+
# fmt: off
|
| 177 |
+
expected_slice = torch.tensor([0.4296, 0.5549, 0.3088, 0.9115, 0.5049, 0.7926, 0.5549, 0.8618, 0.5091, 0.5075, 0.7117, 0.5292, 0.7053, 0.4864, 0.5206, 0.3878])
|
| 178 |
+
# fmt: on
|
| 179 |
+
|
| 180 |
+
self.assertTrue(
|
| 181 |
+
torch.abs(generated_slice - expected_slice).max() < 1e-3,
|
| 182 |
+
f"output_slice: {generated_slice}, expected_slice: {expected_slice}",
|
| 183 |
+
)
|
| 184 |
+
|
| 185 |
+
@unittest.skip("TODO: Test not supported for now because needs to be adjusted to work with guiders.")
|
| 186 |
+
def test_encode_prompt_works_in_isolation(self):
|
| 187 |
+
pass
|
| 188 |
+
|
| 189 |
+
@unittest.skip("Needs to be revisited.")
|
| 190 |
+
def test_inference_batch_consistent(self):
|
| 191 |
+
super().test_inference_batch_consistent()
|
| 192 |
+
|
| 193 |
+
@unittest.skip("Needs to be revisited.")
|
| 194 |
+
def test_inference_batch_single_identical(self):
|
| 195 |
+
super().test_inference_batch_single_identical()
|
tasks/tasksmith-ee553a5e62c1/tests/source/tests/pipelines/hunyuandit/__init__.py
ADDED
|
File without changes
|