|
| 1 | +# coding=utf-8 |
| 2 | +# Copyright 2024 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 torch |
| 19 | + |
| 20 | +from diffusers import ChromaTransformer2DModel |
| 21 | +from diffusers.models.attention_processor import FluxIPAdapterJointAttnProcessor2_0 |
| 22 | +from diffusers.models.embeddings import ImageProjection |
| 23 | +from diffusers.utils.testing_utils import enable_full_determinism, torch_device |
| 24 | + |
| 25 | +from ..test_modeling_common import LoraHotSwappingForModelTesterMixin, ModelTesterMixin, TorchCompileTesterMixin |
| 26 | + |
| 27 | + |
| 28 | +enable_full_determinism() |
| 29 | + |
| 30 | + |
| 31 | +def create_chroma_ip_adapter_state_dict(model): |
| 32 | + # "ip_adapter" (cross-attention weights) |
| 33 | + ip_cross_attn_state_dict = {} |
| 34 | + key_id = 0 |
| 35 | + |
| 36 | + for name in model.attn_processors.keys(): |
| 37 | + if name.startswith("single_transformer_blocks"): |
| 38 | + continue |
| 39 | + |
| 40 | + joint_attention_dim = model.config["joint_attention_dim"] |
| 41 | + hidden_size = model.config["num_attention_heads"] * model.config["attention_head_dim"] |
| 42 | + sd = FluxIPAdapterJointAttnProcessor2_0( |
| 43 | + hidden_size=hidden_size, cross_attention_dim=joint_attention_dim, scale=1.0 |
| 44 | + ).state_dict() |
| 45 | + ip_cross_attn_state_dict.update( |
| 46 | + { |
| 47 | + f"{key_id}.to_k_ip.weight": sd["to_k_ip.0.weight"], |
| 48 | + f"{key_id}.to_v_ip.weight": sd["to_v_ip.0.weight"], |
| 49 | + f"{key_id}.to_k_ip.bias": sd["to_k_ip.0.bias"], |
| 50 | + f"{key_id}.to_v_ip.bias": sd["to_v_ip.0.bias"], |
| 51 | + } |
| 52 | + ) |
| 53 | + |
| 54 | + key_id += 1 |
| 55 | + |
| 56 | + # "image_proj" (ImageProjection layer weights) |
| 57 | + |
| 58 | + image_projection = ImageProjection( |
| 59 | + cross_attention_dim=model.config["joint_attention_dim"], |
| 60 | + image_embed_dim=model.config["pooled_projection_dim"], |
| 61 | + num_image_text_embeds=4, |
| 62 | + ) |
| 63 | + |
| 64 | + ip_image_projection_state_dict = {} |
| 65 | + sd = image_projection.state_dict() |
| 66 | + ip_image_projection_state_dict.update( |
| 67 | + { |
| 68 | + "proj.weight": sd["image_embeds.weight"], |
| 69 | + "proj.bias": sd["image_embeds.bias"], |
| 70 | + "norm.weight": sd["norm.weight"], |
| 71 | + "norm.bias": sd["norm.bias"], |
| 72 | + } |
| 73 | + ) |
| 74 | + |
| 75 | + del sd |
| 76 | + ip_state_dict = {} |
| 77 | + ip_state_dict.update({"image_proj": ip_image_projection_state_dict, "ip_adapter": ip_cross_attn_state_dict}) |
| 78 | + return ip_state_dict |
| 79 | + |
| 80 | + |
| 81 | +class ChromaTransformerTests(ModelTesterMixin, unittest.TestCase): |
| 82 | + model_class = ChromaTransformer2DModel |
| 83 | + main_input_name = "hidden_states" |
| 84 | + # We override the items here because the transformer under consideration is small. |
| 85 | + model_split_percents = [0.7, 0.6, 0.6] |
| 86 | + |
| 87 | + # Skip setting testing with default: AttnProcessor |
| 88 | + uses_custom_attn_processor = True |
| 89 | + |
| 90 | + @property |
| 91 | + def dummy_input(self): |
| 92 | + batch_size = 1 |
| 93 | + num_latent_channels = 4 |
| 94 | + num_image_channels = 3 |
| 95 | + height = width = 4 |
| 96 | + sequence_length = 48 |
| 97 | + embedding_dim = 32 |
| 98 | + |
| 99 | + hidden_states = torch.randn((batch_size, height * width, num_latent_channels)).to(torch_device) |
| 100 | + encoder_hidden_states = torch.randn((batch_size, sequence_length, embedding_dim)).to(torch_device) |
| 101 | + text_ids = torch.randn((sequence_length, num_image_channels)).to(torch_device) |
| 102 | + image_ids = torch.randn((height * width, num_image_channels)).to(torch_device) |
| 103 | + timestep = torch.tensor([1.0]).to(torch_device).expand(batch_size) |
| 104 | + |
| 105 | + return { |
| 106 | + "hidden_states": hidden_states, |
| 107 | + "encoder_hidden_states": encoder_hidden_states, |
| 108 | + "img_ids": image_ids, |
| 109 | + "txt_ids": text_ids, |
| 110 | + "timestep": timestep, |
| 111 | + } |
| 112 | + |
| 113 | + @property |
| 114 | + def input_shape(self): |
| 115 | + return (16, 4) |
| 116 | + |
| 117 | + @property |
| 118 | + def output_shape(self): |
| 119 | + return (16, 4) |
| 120 | + |
| 121 | + def prepare_init_args_and_inputs_for_common(self): |
| 122 | + init_dict = { |
| 123 | + "patch_size": 1, |
| 124 | + "in_channels": 4, |
| 125 | + "num_layers": 1, |
| 126 | + "num_single_layers": 1, |
| 127 | + "attention_head_dim": 16, |
| 128 | + "num_attention_heads": 2, |
| 129 | + "joint_attention_dim": 32, |
| 130 | + "axes_dims_rope": [4, 4, 8], |
| 131 | + } |
| 132 | + |
| 133 | + inputs_dict = self.dummy_input |
| 134 | + return init_dict, inputs_dict |
| 135 | + |
| 136 | + def test_deprecated_inputs_img_txt_ids_3d(self): |
| 137 | + init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() |
| 138 | + model = self.model_class(**init_dict) |
| 139 | + model.to(torch_device) |
| 140 | + model.eval() |
| 141 | + |
| 142 | + with torch.no_grad(): |
| 143 | + output_1 = model(**inputs_dict).to_tuple()[0] |
| 144 | + |
| 145 | + # update inputs_dict with txt_ids and img_ids as 3d tensors (deprecated) |
| 146 | + text_ids_3d = inputs_dict["txt_ids"].unsqueeze(0) |
| 147 | + image_ids_3d = inputs_dict["img_ids"].unsqueeze(0) |
| 148 | + |
| 149 | + assert text_ids_3d.ndim == 3, "text_ids_3d should be a 3d tensor" |
| 150 | + assert image_ids_3d.ndim == 3, "img_ids_3d should be a 3d tensor" |
| 151 | + |
| 152 | + inputs_dict["txt_ids"] = text_ids_3d |
| 153 | + inputs_dict["img_ids"] = image_ids_3d |
| 154 | + |
| 155 | + with torch.no_grad(): |
| 156 | + output_2 = model(**inputs_dict).to_tuple()[0] |
| 157 | + |
| 158 | + self.assertEqual(output_1.shape, output_2.shape) |
| 159 | + self.assertTrue( |
| 160 | + torch.allclose(output_1, output_2, atol=1e-5), |
| 161 | + msg="output with deprecated inputs (img_ids and txt_ids as 3d torch tensors) are not equal as them as 2d inputs", |
| 162 | + ) |
| 163 | + |
| 164 | + def test_gradient_checkpointing_is_applied(self): |
| 165 | + expected_set = {"ChromaTransformer2DModel"} |
| 166 | + super().test_gradient_checkpointing_is_applied(expected_set=expected_set) |
| 167 | + |
| 168 | + |
| 169 | +class ChromaTransformerCompileTests(TorchCompileTesterMixin, unittest.TestCase): |
| 170 | + model_class = FluxTransformer2DModel |
| 171 | + |
| 172 | + def prepare_init_args_and_inputs_for_common(self): |
| 173 | + return ChromaTransformerTests().prepare_init_args_and_inputs_for_common() |
| 174 | + |
| 175 | + |
| 176 | +class ChromaTransformerLoRAHotSwapTests(LoraHotSwappingForModelTesterMixin, unittest.TestCase): |
| 177 | + model_class = ChromaTransformer2DModel |
| 178 | + |
| 179 | + def prepare_init_args_and_inputs_for_common(self): |
| 180 | + return ChromaTransformerTests().prepare_init_args_and_inputs_for_common() |
0 commit comments