Spaces:
Running
on
Zero
Running
on
Zero
| # coding=utf-8 | |
| # Copyright 2023 HuggingFace Inc. | |
| # | |
| # Licensed under the Apache License, Version 2.0 (the "License"); | |
| # you may not use this file except in compliance with the License. | |
| # You may obtain a copy of the License at | |
| # | |
| # http://www.apache.org/licenses/LICENSE-2.0 | |
| # | |
| # Unless required by applicable law or agreed to in writing, software | |
| # distributed under the License is distributed on an "AS IS" BASIS, | |
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | |
| # See the License for the specific language governing permissions and | |
| # limitations under the License. | |
| import gc | |
| import os | |
| import tempfile | |
| import unittest | |
| import torch | |
| from parameterized import parameterized | |
| from diffusers import UNet2DConditionModel | |
| from diffusers.models.attention_processor import LoRAAttnProcessor | |
| from diffusers.utils import ( | |
| floats_tensor, | |
| load_hf_numpy, | |
| logging, | |
| require_torch_gpu, | |
| slow, | |
| torch_all_close, | |
| torch_device, | |
| ) | |
| from diffusers.utils.import_utils import is_xformers_available | |
| from ..test_modeling_common import ModelTesterMixin | |
| logger = logging.get_logger(__name__) | |
| torch.backends.cuda.matmul.allow_tf32 = False | |
| def create_lora_layers(model): | |
| lora_attn_procs = {} | |
| for name in model.attn_processors.keys(): | |
| cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim | |
| if name.startswith("mid_block"): | |
| hidden_size = model.config.block_out_channels[-1] | |
| elif name.startswith("up_blocks"): | |
| block_id = int(name[len("up_blocks.")]) | |
| hidden_size = list(reversed(model.config.block_out_channels))[block_id] | |
| elif name.startswith("down_blocks"): | |
| block_id = int(name[len("down_blocks.")]) | |
| hidden_size = model.config.block_out_channels[block_id] | |
| lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim) | |
| lora_attn_procs[name] = lora_attn_procs[name].to(model.device) | |
| # add 1 to weights to mock trained weights | |
| with torch.no_grad(): | |
| lora_attn_procs[name].to_q_lora.up.weight += 1 | |
| lora_attn_procs[name].to_k_lora.up.weight += 1 | |
| lora_attn_procs[name].to_v_lora.up.weight += 1 | |
| lora_attn_procs[name].to_out_lora.up.weight += 1 | |
| return lora_attn_procs | |
| class UNet2DConditionModelTests(ModelTesterMixin, unittest.TestCase): | |
| model_class = UNet2DConditionModel | |
| def dummy_input(self): | |
| batch_size = 4 | |
| num_channels = 4 | |
| sizes = (32, 32) | |
| noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device) | |
| time_step = torch.tensor([10]).to(torch_device) | |
| encoder_hidden_states = floats_tensor((batch_size, 4, 32)).to(torch_device) | |
| return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states} | |
| def input_shape(self): | |
| return (4, 32, 32) | |
| def output_shape(self): | |
| return (4, 32, 32) | |
| def prepare_init_args_and_inputs_for_common(self): | |
| init_dict = { | |
| "block_out_channels": (32, 64), | |
| "down_block_types": ("CrossAttnDownBlock2D", "DownBlock2D"), | |
| "up_block_types": ("UpBlock2D", "CrossAttnUpBlock2D"), | |
| "cross_attention_dim": 32, | |
| "attention_head_dim": 8, | |
| "out_channels": 4, | |
| "in_channels": 4, | |
| "layers_per_block": 2, | |
| "sample_size": 32, | |
| } | |
| inputs_dict = self.dummy_input | |
| return init_dict, inputs_dict | |
| def test_xformers_enable_works(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| model = self.model_class(**init_dict) | |
| model.enable_xformers_memory_efficient_attention() | |
| assert ( | |
| model.mid_block.attentions[0].transformer_blocks[0].attn1.processor.__class__.__name__ | |
| == "XFormersAttnProcessor" | |
| ), "xformers is not enabled" | |
| def test_gradient_checkpointing(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| assert not model.is_gradient_checkpointing and model.training | |
| out = model(**inputs_dict).sample | |
| # run the backwards pass on the model. For backwards pass, for simplicity purpose, | |
| # we won't calculate the loss and rather backprop on out.sum() | |
| model.zero_grad() | |
| labels = torch.randn_like(out) | |
| loss = (out - labels).mean() | |
| loss.backward() | |
| # re-instantiate the model now enabling gradient checkpointing | |
| model_2 = self.model_class(**init_dict) | |
| # clone model | |
| model_2.load_state_dict(model.state_dict()) | |
| model_2.to(torch_device) | |
| model_2.enable_gradient_checkpointing() | |
| assert model_2.is_gradient_checkpointing and model_2.training | |
| out_2 = model_2(**inputs_dict).sample | |
| # run the backwards pass on the model. For backwards pass, for simplicity purpose, | |
| # we won't calculate the loss and rather backprop on out.sum() | |
| model_2.zero_grad() | |
| loss_2 = (out_2 - labels).mean() | |
| loss_2.backward() | |
| # compare the output and parameters gradients | |
| self.assertTrue((loss - loss_2).abs() < 1e-5) | |
| named_params = dict(model.named_parameters()) | |
| named_params_2 = dict(model_2.named_parameters()) | |
| for name, param in named_params.items(): | |
| self.assertTrue(torch_all_close(param.grad.data, named_params_2[name].grad.data, atol=5e-5)) | |
| def test_model_with_attention_head_dim_tuple(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| if isinstance(output, dict): | |
| output = output.sample | |
| self.assertIsNotNone(output) | |
| expected_shape = inputs_dict["sample"].shape | |
| self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match") | |
| def test_model_with_use_linear_projection(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["use_linear_projection"] = True | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| if isinstance(output, dict): | |
| output = output.sample | |
| self.assertIsNotNone(output) | |
| expected_shape = inputs_dict["sample"].shape | |
| self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match") | |
| def test_model_with_cross_attention_dim_tuple(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["cross_attention_dim"] = (32, 32) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| if isinstance(output, dict): | |
| output = output.sample | |
| self.assertIsNotNone(output) | |
| expected_shape = inputs_dict["sample"].shape | |
| self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match") | |
| def test_model_with_simple_projection(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| batch_size, _, _, sample_size = inputs_dict["sample"].shape | |
| init_dict["class_embed_type"] = "simple_projection" | |
| init_dict["projection_class_embeddings_input_dim"] = sample_size | |
| inputs_dict["class_labels"] = floats_tensor((batch_size, sample_size)).to(torch_device) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| if isinstance(output, dict): | |
| output = output.sample | |
| self.assertIsNotNone(output) | |
| expected_shape = inputs_dict["sample"].shape | |
| self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match") | |
| def test_model_with_class_embeddings_concat(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| batch_size, _, _, sample_size = inputs_dict["sample"].shape | |
| init_dict["class_embed_type"] = "simple_projection" | |
| init_dict["projection_class_embeddings_input_dim"] = sample_size | |
| init_dict["class_embeddings_concat"] = True | |
| inputs_dict["class_labels"] = floats_tensor((batch_size, sample_size)).to(torch_device) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| if isinstance(output, dict): | |
| output = output.sample | |
| self.assertIsNotNone(output) | |
| expected_shape = inputs_dict["sample"].shape | |
| self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match") | |
| def test_model_attention_slicing(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| model.eval() | |
| model.set_attention_slice("auto") | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| assert output is not None | |
| model.set_attention_slice("max") | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| assert output is not None | |
| model.set_attention_slice(2) | |
| with torch.no_grad(): | |
| output = model(**inputs_dict) | |
| assert output is not None | |
| def test_model_sliceable_head_dim(self): | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| model = self.model_class(**init_dict) | |
| def check_sliceable_dim_attr(module: torch.nn.Module): | |
| if hasattr(module, "set_attention_slice"): | |
| assert isinstance(module.sliceable_head_dim, int) | |
| for child in module.children(): | |
| check_sliceable_dim_attr(child) | |
| # retrieve number of attention layers | |
| for module in model.children(): | |
| check_sliceable_dim_attr(module) | |
| def test_special_attn_proc(self): | |
| class AttnEasyProc(torch.nn.Module): | |
| def __init__(self, num): | |
| super().__init__() | |
| self.weight = torch.nn.Parameter(torch.tensor(num)) | |
| self.is_run = False | |
| self.number = 0 | |
| self.counter = 0 | |
| def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, number=None): | |
| batch_size, sequence_length, _ = hidden_states.shape | |
| attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size) | |
| query = attn.to_q(hidden_states) | |
| encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states | |
| key = attn.to_k(encoder_hidden_states) | |
| value = attn.to_v(encoder_hidden_states) | |
| query = attn.head_to_batch_dim(query) | |
| key = attn.head_to_batch_dim(key) | |
| value = attn.head_to_batch_dim(value) | |
| attention_probs = attn.get_attention_scores(query, key, attention_mask) | |
| hidden_states = torch.bmm(attention_probs, value) | |
| hidden_states = attn.batch_to_head_dim(hidden_states) | |
| # linear proj | |
| hidden_states = attn.to_out[0](hidden_states) | |
| # dropout | |
| hidden_states = attn.to_out[1](hidden_states) | |
| hidden_states += self.weight | |
| self.is_run = True | |
| self.counter += 1 | |
| self.number = number | |
| return hidden_states | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| processor = AttnEasyProc(5.0) | |
| model.set_attn_processor(processor) | |
| model(**inputs_dict, cross_attention_kwargs={"number": 123}).sample | |
| assert processor.counter == 12 | |
| assert processor.is_run | |
| assert processor.number == 123 | |
| def test_lora_processors(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| with torch.no_grad(): | |
| sample1 = model(**inputs_dict).sample | |
| lora_attn_procs = {} | |
| for name in model.attn_processors.keys(): | |
| cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim | |
| if name.startswith("mid_block"): | |
| hidden_size = model.config.block_out_channels[-1] | |
| elif name.startswith("up_blocks"): | |
| block_id = int(name[len("up_blocks.")]) | |
| hidden_size = list(reversed(model.config.block_out_channels))[block_id] | |
| elif name.startswith("down_blocks"): | |
| block_id = int(name[len("down_blocks.")]) | |
| hidden_size = model.config.block_out_channels[block_id] | |
| lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim) | |
| # add 1 to weights to mock trained weights | |
| with torch.no_grad(): | |
| lora_attn_procs[name].to_q_lora.up.weight += 1 | |
| lora_attn_procs[name].to_k_lora.up.weight += 1 | |
| lora_attn_procs[name].to_v_lora.up.weight += 1 | |
| lora_attn_procs[name].to_out_lora.up.weight += 1 | |
| # make sure we can set a list of attention processors | |
| model.set_attn_processor(lora_attn_procs) | |
| model.to(torch_device) | |
| # test that attn processors can be set to itself | |
| model.set_attn_processor(model.attn_processors) | |
| with torch.no_grad(): | |
| sample2 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.0}).sample | |
| sample3 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| sample4 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| assert (sample1 - sample2).abs().max() < 1e-4 | |
| assert (sample3 - sample4).abs().max() < 1e-4 | |
| # sample 2 and sample 3 should be different | |
| assert (sample2 - sample3).abs().max() > 1e-4 | |
| def test_lora_save_load(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| with torch.no_grad(): | |
| old_sample = model(**inputs_dict).sample | |
| lora_attn_procs = create_lora_layers(model) | |
| model.set_attn_processor(lora_attn_procs) | |
| with torch.no_grad(): | |
| sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| with tempfile.TemporaryDirectory() as tmpdirname: | |
| model.save_attn_procs(tmpdirname) | |
| self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin"))) | |
| torch.manual_seed(0) | |
| new_model = self.model_class(**init_dict) | |
| new_model.to(torch_device) | |
| new_model.load_attn_procs(tmpdirname) | |
| with torch.no_grad(): | |
| new_sample = new_model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| assert (sample - new_sample).abs().max() < 1e-4 | |
| # LoRA and no LoRA should NOT be the same | |
| assert (sample - old_sample).abs().max() > 1e-4 | |
| def test_lora_save_load_safetensors(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| with torch.no_grad(): | |
| old_sample = model(**inputs_dict).sample | |
| lora_attn_procs = {} | |
| for name in model.attn_processors.keys(): | |
| cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim | |
| if name.startswith("mid_block"): | |
| hidden_size = model.config.block_out_channels[-1] | |
| elif name.startswith("up_blocks"): | |
| block_id = int(name[len("up_blocks.")]) | |
| hidden_size = list(reversed(model.config.block_out_channels))[block_id] | |
| elif name.startswith("down_blocks"): | |
| block_id = int(name[len("down_blocks.")]) | |
| hidden_size = model.config.block_out_channels[block_id] | |
| lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim) | |
| lora_attn_procs[name] = lora_attn_procs[name].to(model.device) | |
| # add 1 to weights to mock trained weights | |
| with torch.no_grad(): | |
| lora_attn_procs[name].to_q_lora.up.weight += 1 | |
| lora_attn_procs[name].to_k_lora.up.weight += 1 | |
| lora_attn_procs[name].to_v_lora.up.weight += 1 | |
| lora_attn_procs[name].to_out_lora.up.weight += 1 | |
| model.set_attn_processor(lora_attn_procs) | |
| with torch.no_grad(): | |
| sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| with tempfile.TemporaryDirectory() as tmpdirname: | |
| model.save_attn_procs(tmpdirname, safe_serialization=True) | |
| self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors"))) | |
| torch.manual_seed(0) | |
| new_model = self.model_class(**init_dict) | |
| new_model.to(torch_device) | |
| new_model.load_attn_procs(tmpdirname) | |
| with torch.no_grad(): | |
| new_sample = new_model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample | |
| assert (sample - new_sample).abs().max() < 1e-4 | |
| # LoRA and no LoRA should NOT be the same | |
| assert (sample - old_sample).abs().max() > 1e-4 | |
| def test_lora_save_safetensors_load_torch(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| lora_attn_procs = {} | |
| for name in model.attn_processors.keys(): | |
| cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim | |
| if name.startswith("mid_block"): | |
| hidden_size = model.config.block_out_channels[-1] | |
| elif name.startswith("up_blocks"): | |
| block_id = int(name[len("up_blocks.")]) | |
| hidden_size = list(reversed(model.config.block_out_channels))[block_id] | |
| elif name.startswith("down_blocks"): | |
| block_id = int(name[len("down_blocks.")]) | |
| hidden_size = model.config.block_out_channels[block_id] | |
| lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim) | |
| lora_attn_procs[name] = lora_attn_procs[name].to(model.device) | |
| model.set_attn_processor(lora_attn_procs) | |
| # Saving as torch, properly reloads with directly filename | |
| with tempfile.TemporaryDirectory() as tmpdirname: | |
| model.save_attn_procs(tmpdirname) | |
| self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin"))) | |
| torch.manual_seed(0) | |
| new_model = self.model_class(**init_dict) | |
| new_model.to(torch_device) | |
| new_model.load_attn_procs(tmpdirname, weight_name="pytorch_lora_weights.bin") | |
| def test_lora_save_torch_force_load_safetensors_error(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| lora_attn_procs = {} | |
| for name in model.attn_processors.keys(): | |
| cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim | |
| if name.startswith("mid_block"): | |
| hidden_size = model.config.block_out_channels[-1] | |
| elif name.startswith("up_blocks"): | |
| block_id = int(name[len("up_blocks.")]) | |
| hidden_size = list(reversed(model.config.block_out_channels))[block_id] | |
| elif name.startswith("down_blocks"): | |
| block_id = int(name[len("down_blocks.")]) | |
| hidden_size = model.config.block_out_channels[block_id] | |
| lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim) | |
| lora_attn_procs[name] = lora_attn_procs[name].to(model.device) | |
| model.set_attn_processor(lora_attn_procs) | |
| # Saving as torch, properly reloads with directly filename | |
| with tempfile.TemporaryDirectory() as tmpdirname: | |
| model.save_attn_procs(tmpdirname) | |
| self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin"))) | |
| torch.manual_seed(0) | |
| new_model = self.model_class(**init_dict) | |
| new_model.to(torch_device) | |
| with self.assertRaises(IOError) as e: | |
| new_model.load_attn_procs(tmpdirname, use_safetensors=True) | |
| self.assertIn("Error no file named pytorch_lora_weights.safetensors", str(e.exception)) | |
| def test_lora_on_off(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| with torch.no_grad(): | |
| old_sample = model(**inputs_dict).sample | |
| lora_attn_procs = create_lora_layers(model) | |
| model.set_attn_processor(lora_attn_procs) | |
| with torch.no_grad(): | |
| sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.0}).sample | |
| model.set_default_attn_processor() | |
| with torch.no_grad(): | |
| new_sample = model(**inputs_dict).sample | |
| assert (sample - new_sample).abs().max() < 1e-4 | |
| assert (sample - old_sample).abs().max() < 1e-4 | |
| def test_lora_xformers_on_off(self): | |
| # enable deterministic behavior for gradient checkpointing | |
| init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common() | |
| init_dict["attention_head_dim"] = (8, 16) | |
| torch.manual_seed(0) | |
| model = self.model_class(**init_dict) | |
| model.to(torch_device) | |
| lora_attn_procs = create_lora_layers(model) | |
| model.set_attn_processor(lora_attn_procs) | |
| # default | |
| with torch.no_grad(): | |
| sample = model(**inputs_dict).sample | |
| model.enable_xformers_memory_efficient_attention() | |
| on_sample = model(**inputs_dict).sample | |
| model.disable_xformers_memory_efficient_attention() | |
| off_sample = model(**inputs_dict).sample | |
| assert (sample - on_sample).abs().max() < 1e-4 | |
| assert (sample - off_sample).abs().max() < 1e-4 | |
| class UNet2DConditionModelIntegrationTests(unittest.TestCase): | |
| def get_file_format(self, seed, shape): | |
| return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy" | |
| def tearDown(self): | |
| # clean up the VRAM after each test | |
| super().tearDown() | |
| gc.collect() | |
| torch.cuda.empty_cache() | |
| def get_latents(self, seed=0, shape=(4, 4, 64, 64), fp16=False): | |
| dtype = torch.float16 if fp16 else torch.float32 | |
| image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype) | |
| return image | |
| def get_unet_model(self, fp16=False, model_id="CompVis/stable-diffusion-v1-4"): | |
| revision = "fp16" if fp16 else None | |
| torch_dtype = torch.float16 if fp16 else torch.float32 | |
| model = UNet2DConditionModel.from_pretrained( | |
| model_id, subfolder="unet", torch_dtype=torch_dtype, revision=revision | |
| ) | |
| model.to(torch_device).eval() | |
| return model | |
| def test_set_attention_slice_auto(self): | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_max_memory_allocated() | |
| torch.cuda.reset_peak_memory_stats() | |
| unet = self.get_unet_model() | |
| unet.set_attention_slice("auto") | |
| latents = self.get_latents(33) | |
| encoder_hidden_states = self.get_encoder_hidden_states(33) | |
| timestep = 1 | |
| with torch.no_grad(): | |
| _ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| mem_bytes = torch.cuda.max_memory_allocated() | |
| assert mem_bytes < 5 * 10**9 | |
| def test_set_attention_slice_max(self): | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_max_memory_allocated() | |
| torch.cuda.reset_peak_memory_stats() | |
| unet = self.get_unet_model() | |
| unet.set_attention_slice("max") | |
| latents = self.get_latents(33) | |
| encoder_hidden_states = self.get_encoder_hidden_states(33) | |
| timestep = 1 | |
| with torch.no_grad(): | |
| _ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| mem_bytes = torch.cuda.max_memory_allocated() | |
| assert mem_bytes < 5 * 10**9 | |
| def test_set_attention_slice_int(self): | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_max_memory_allocated() | |
| torch.cuda.reset_peak_memory_stats() | |
| unet = self.get_unet_model() | |
| unet.set_attention_slice(2) | |
| latents = self.get_latents(33) | |
| encoder_hidden_states = self.get_encoder_hidden_states(33) | |
| timestep = 1 | |
| with torch.no_grad(): | |
| _ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| mem_bytes = torch.cuda.max_memory_allocated() | |
| assert mem_bytes < 5 * 10**9 | |
| def test_set_attention_slice_list(self): | |
| torch.cuda.empty_cache() | |
| torch.cuda.reset_max_memory_allocated() | |
| torch.cuda.reset_peak_memory_stats() | |
| # there are 32 sliceable layers | |
| slice_list = 16 * [2, 3] | |
| unet = self.get_unet_model() | |
| unet.set_attention_slice(slice_list) | |
| latents = self.get_latents(33) | |
| encoder_hidden_states = self.get_encoder_hidden_states(33) | |
| timestep = 1 | |
| with torch.no_grad(): | |
| _ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| mem_bytes = torch.cuda.max_memory_allocated() | |
| assert mem_bytes < 5 * 10**9 | |
| def get_encoder_hidden_states(self, seed=0, shape=(4, 77, 768), fp16=False): | |
| dtype = torch.float16 if fp16 else torch.float32 | |
| hidden_states = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype) | |
| return hidden_states | |
| def test_compvis_sd_v1_4(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="CompVis/stable-diffusion-v1-4") | |
| latents = self.get_latents(seed) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == latents.shape | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=1e-3) | |
| def test_compvis_sd_v1_4_fp16(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="CompVis/stable-diffusion-v1-4", fp16=True) | |
| latents = self.get_latents(seed, fp16=True) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == latents.shape | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=5e-3) | |
| def test_compvis_sd_v1_5(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="runwayml/stable-diffusion-v1-5") | |
| latents = self.get_latents(seed) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == latents.shape | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=1e-3) | |
| def test_compvis_sd_v1_5_fp16(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="runwayml/stable-diffusion-v1-5", fp16=True) | |
| latents = self.get_latents(seed, fp16=True) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == latents.shape | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=5e-3) | |
| def test_compvis_sd_inpaint(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="runwayml/stable-diffusion-inpainting") | |
| latents = self.get_latents(seed, shape=(4, 9, 64, 64)) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == (4, 4, 64, 64) | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=1e-3) | |
| def test_compvis_sd_inpaint_fp16(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="runwayml/stable-diffusion-inpainting", fp16=True) | |
| latents = self.get_latents(seed, shape=(4, 9, 64, 64), fp16=True) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == (4, 4, 64, 64) | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=5e-3) | |
| def test_stabilityai_sd_v2_fp16(self, seed, timestep, expected_slice): | |
| model = self.get_unet_model(model_id="stabilityai/stable-diffusion-2", fp16=True) | |
| latents = self.get_latents(seed, shape=(4, 4, 96, 96), fp16=True) | |
| encoder_hidden_states = self.get_encoder_hidden_states(seed, shape=(4, 77, 1024), fp16=True) | |
| timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device) | |
| with torch.no_grad(): | |
| sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample | |
| assert sample.shape == latents.shape | |
| output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu() | |
| expected_output_slice = torch.tensor(expected_slice) | |
| assert torch_all_close(output_slice, expected_output_slice, atol=5e-3) | |