Path: blob/main/tests/models/test_models_unet_3d_condition.py
1448 views
# coding=utf-81# Copyright 2023 HuggingFace Inc.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 at6#7# http://www.apache.org/licenses/LICENSE-2.08#9# Unless required by applicable law or agreed to in writing, software10# 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 and13# limitations under the License.1415import unittest1617import numpy as np18import torch1920from diffusers.models import ModelMixin, UNet3DConditionModel21from diffusers.models.attention_processor import LoRAAttnProcessor22from diffusers.utils import (23floats_tensor,24logging,25skip_mps,26torch_device,27)28from diffusers.utils.import_utils import is_xformers_available2930from ..test_modeling_common import ModelTesterMixin313233logger = logging.get_logger(__name__)34torch.backends.cuda.matmul.allow_tf32 = False353637def create_lora_layers(model):38lora_attn_procs = {}39for name in model.attn_processors.keys():40cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim41if name.startswith("mid_block"):42hidden_size = model.config.block_out_channels[-1]43elif name.startswith("up_blocks"):44block_id = int(name[len("up_blocks.")])45hidden_size = list(reversed(model.config.block_out_channels))[block_id]46elif name.startswith("down_blocks"):47block_id = int(name[len("down_blocks.")])48hidden_size = model.config.block_out_channels[block_id]4950lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)51lora_attn_procs[name] = lora_attn_procs[name].to(model.device)5253# add 1 to weights to mock trained weights54with torch.no_grad():55lora_attn_procs[name].to_q_lora.up.weight += 156lora_attn_procs[name].to_k_lora.up.weight += 157lora_attn_procs[name].to_v_lora.up.weight += 158lora_attn_procs[name].to_out_lora.up.weight += 15960return lora_attn_procs616263@skip_mps64class UNet3DConditionModelTests(ModelTesterMixin, unittest.TestCase):65model_class = UNet3DConditionModel6667@property68def dummy_input(self):69batch_size = 470num_channels = 471num_frames = 472sizes = (32, 32)7374noise = floats_tensor((batch_size, num_channels, num_frames) + sizes).to(torch_device)75time_step = torch.tensor([10]).to(torch_device)76encoder_hidden_states = floats_tensor((batch_size, 4, 32)).to(torch_device)7778return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}7980@property81def input_shape(self):82return (4, 4, 32, 32)8384@property85def output_shape(self):86return (4, 4, 32, 32)8788def prepare_init_args_and_inputs_for_common(self):89init_dict = {90"block_out_channels": (32, 64, 64, 64),91"down_block_types": (92"CrossAttnDownBlock3D",93"CrossAttnDownBlock3D",94"CrossAttnDownBlock3D",95"DownBlock3D",96),97"up_block_types": ("UpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D", "CrossAttnUpBlock3D"),98"cross_attention_dim": 32,99"attention_head_dim": 4,100"out_channels": 4,101"in_channels": 4,102"layers_per_block": 2,103"sample_size": 32,104}105inputs_dict = self.dummy_input106return init_dict, inputs_dict107108@unittest.skipIf(109torch_device != "cuda" or not is_xformers_available(),110reason="XFormers attention is only available with CUDA and `xformers` installed",111)112def test_xformers_enable_works(self):113init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()114model = self.model_class(**init_dict)115116model.enable_xformers_memory_efficient_attention()117118assert (119model.mid_block.attentions[0].transformer_blocks[0].attn1.processor.__class__.__name__120== "XFormersAttnProcessor"121), "xformers is not enabled"122123# Overriding because `block_out_channels` needs to be different for this model.124def test_forward_with_norm_groups(self):125init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()126127init_dict["norm_num_groups"] = 32128init_dict["block_out_channels"] = (32, 64, 64, 64)129130model = self.model_class(**init_dict)131model.to(torch_device)132model.eval()133134with torch.no_grad():135output = model(**inputs_dict)136137if isinstance(output, dict):138output = output.sample139140self.assertIsNotNone(output)141expected_shape = inputs_dict["sample"].shape142self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")143144# Overriding since the UNet3D outputs a different structure.145def test_determinism(self):146init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()147model = self.model_class(**init_dict)148model.to(torch_device)149model.eval()150151with torch.no_grad():152# Warmup pass when using mps (see #372)153if torch_device == "mps" and isinstance(model, ModelMixin):154model(**self.dummy_input)155156first = model(**inputs_dict)157if isinstance(first, dict):158first = first.sample159160second = model(**inputs_dict)161if isinstance(second, dict):162second = second.sample163164out_1 = first.cpu().numpy()165out_2 = second.cpu().numpy()166out_1 = out_1[~np.isnan(out_1)]167out_2 = out_2[~np.isnan(out_2)]168max_diff = np.amax(np.abs(out_1 - out_2))169self.assertLessEqual(max_diff, 1e-5)170171def test_model_attention_slicing(self):172init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()173174init_dict["attention_head_dim"] = 8175176model = self.model_class(**init_dict)177model.to(torch_device)178model.eval()179180model.set_attention_slice("auto")181with torch.no_grad():182output = model(**inputs_dict)183assert output is not None184185model.set_attention_slice("max")186with torch.no_grad():187output = model(**inputs_dict)188assert output is not None189190model.set_attention_slice(2)191with torch.no_grad():192output = model(**inputs_dict)193assert output is not None194195# (`attn_processors`) needs to be implemented in this model for this test.196# def test_lora_processors(self):197198# (`attn_processors`) needs to be implemented in this model for this test.199# def test_lora_save_load(self):200201# (`attn_processors`) needs to be implemented for this test in the model.202# def test_lora_save_load_safetensors(self):203204# (`attn_processors`) needs to be implemented for this test in the model.205# def test_lora_save_safetensors_load_torch(self):206207# (`attn_processors`) needs to be implemented for this test.208# def test_lora_save_torch_force_load_safetensors_error(self):209210# (`attn_processors`) needs to be added for this test.211# def test_lora_on_off(self):212213@unittest.skipIf(214torch_device != "cuda" or not is_xformers_available(),215reason="XFormers attention is only available with CUDA and `xformers` installed",216)217def test_lora_xformers_on_off(self):218# enable deterministic behavior for gradient checkpointing219init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()220221init_dict["attention_head_dim"] = 4222223torch.manual_seed(0)224model = self.model_class(**init_dict)225model.to(torch_device)226lora_attn_procs = create_lora_layers(model)227model.set_attn_processor(lora_attn_procs)228229# default230with torch.no_grad():231sample = model(**inputs_dict).sample232233model.enable_xformers_memory_efficient_attention()234on_sample = model(**inputs_dict).sample235236model.disable_xformers_memory_efficient_attention()237off_sample = model(**inputs_dict).sample238239assert (sample - on_sample).abs().max() < 1e-4240assert (sample - off_sample).abs().max() < 1e-4241242243# (todo: sayakpaul) implement SLOW tests.244245246