Path: blob/main/tests/models/test_models_unet_2d_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 gc16import os17import tempfile18import unittest1920import torch21from parameterized import parameterized2223from diffusers import UNet2DConditionModel24from diffusers.models.attention_processor import AttnProcessor, LoRAAttnProcessor25from diffusers.utils import (26floats_tensor,27load_hf_numpy,28logging,29require_torch_gpu,30slow,31torch_all_close,32torch_device,33)34from diffusers.utils.import_utils import is_xformers_available3536from ..test_modeling_common import ModelTesterMixin373839logger = logging.get_logger(__name__)40torch.backends.cuda.matmul.allow_tf32 = False414243def create_lora_layers(model):44lora_attn_procs = {}45for name in model.attn_processors.keys():46cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim47if name.startswith("mid_block"):48hidden_size = model.config.block_out_channels[-1]49elif name.startswith("up_blocks"):50block_id = int(name[len("up_blocks.")])51hidden_size = list(reversed(model.config.block_out_channels))[block_id]52elif name.startswith("down_blocks"):53block_id = int(name[len("down_blocks.")])54hidden_size = model.config.block_out_channels[block_id]5556lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)57lora_attn_procs[name] = lora_attn_procs[name].to(model.device)5859# add 1 to weights to mock trained weights60with torch.no_grad():61lora_attn_procs[name].to_q_lora.up.weight += 162lora_attn_procs[name].to_k_lora.up.weight += 163lora_attn_procs[name].to_v_lora.up.weight += 164lora_attn_procs[name].to_out_lora.up.weight += 16566return lora_attn_procs676869class UNet2DConditionModelTests(ModelTesterMixin, unittest.TestCase):70model_class = UNet2DConditionModel7172@property73def dummy_input(self):74batch_size = 475num_channels = 476sizes = (32, 32)7778noise = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)79time_step = torch.tensor([10]).to(torch_device)80encoder_hidden_states = floats_tensor((batch_size, 4, 32)).to(torch_device)8182return {"sample": noise, "timestep": time_step, "encoder_hidden_states": encoder_hidden_states}8384@property85def input_shape(self):86return (4, 32, 32)8788@property89def output_shape(self):90return (4, 32, 32)9192def prepare_init_args_and_inputs_for_common(self):93init_dict = {94"block_out_channels": (32, 64),95"down_block_types": ("CrossAttnDownBlock2D", "DownBlock2D"),96"up_block_types": ("UpBlock2D", "CrossAttnUpBlock2D"),97"cross_attention_dim": 32,98"attention_head_dim": 8,99"out_channels": 4,100"in_channels": 4,101"layers_per_block": 2,102"sample_size": 32,103}104inputs_dict = self.dummy_input105return init_dict, inputs_dict106107@unittest.skipIf(108torch_device != "cuda" or not is_xformers_available(),109reason="XFormers attention is only available with CUDA and `xformers` installed",110)111def test_xformers_enable_works(self):112init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()113model = self.model_class(**init_dict)114115model.enable_xformers_memory_efficient_attention()116117assert (118model.mid_block.attentions[0].transformer_blocks[0].attn1.processor.__class__.__name__119== "XFormersAttnProcessor"120), "xformers is not enabled"121122@unittest.skipIf(torch_device == "mps", "Gradient checkpointing skipped on MPS")123def test_gradient_checkpointing(self):124# enable deterministic behavior for gradient checkpointing125init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()126model = self.model_class(**init_dict)127model.to(torch_device)128129assert not model.is_gradient_checkpointing and model.training130131out = model(**inputs_dict).sample132# run the backwards pass on the model. For backwards pass, for simplicity purpose,133# we won't calculate the loss and rather backprop on out.sum()134model.zero_grad()135136labels = torch.randn_like(out)137loss = (out - labels).mean()138loss.backward()139140# re-instantiate the model now enabling gradient checkpointing141model_2 = self.model_class(**init_dict)142# clone model143model_2.load_state_dict(model.state_dict())144model_2.to(torch_device)145model_2.enable_gradient_checkpointing()146147assert model_2.is_gradient_checkpointing and model_2.training148149out_2 = model_2(**inputs_dict).sample150# run the backwards pass on the model. For backwards pass, for simplicity purpose,151# we won't calculate the loss and rather backprop on out.sum()152model_2.zero_grad()153loss_2 = (out_2 - labels).mean()154loss_2.backward()155156# compare the output and parameters gradients157self.assertTrue((loss - loss_2).abs() < 1e-5)158named_params = dict(model.named_parameters())159named_params_2 = dict(model_2.named_parameters())160for name, param in named_params.items():161self.assertTrue(torch_all_close(param.grad.data, named_params_2[name].grad.data, atol=5e-5))162163def test_model_with_attention_head_dim_tuple(self):164init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()165166init_dict["attention_head_dim"] = (8, 16)167168model = self.model_class(**init_dict)169model.to(torch_device)170model.eval()171172with torch.no_grad():173output = model(**inputs_dict)174175if isinstance(output, dict):176output = output.sample177178self.assertIsNotNone(output)179expected_shape = inputs_dict["sample"].shape180self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")181182def test_model_with_use_linear_projection(self):183init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()184185init_dict["use_linear_projection"] = True186187model = self.model_class(**init_dict)188model.to(torch_device)189model.eval()190191with torch.no_grad():192output = model(**inputs_dict)193194if isinstance(output, dict):195output = output.sample196197self.assertIsNotNone(output)198expected_shape = inputs_dict["sample"].shape199self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")200201def test_model_with_cross_attention_dim_tuple(self):202init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()203204init_dict["cross_attention_dim"] = (32, 32)205206model = self.model_class(**init_dict)207model.to(torch_device)208model.eval()209210with torch.no_grad():211output = model(**inputs_dict)212213if isinstance(output, dict):214output = output.sample215216self.assertIsNotNone(output)217expected_shape = inputs_dict["sample"].shape218self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")219220def test_model_with_simple_projection(self):221init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()222223batch_size, _, _, sample_size = inputs_dict["sample"].shape224225init_dict["class_embed_type"] = "simple_projection"226init_dict["projection_class_embeddings_input_dim"] = sample_size227228inputs_dict["class_labels"] = floats_tensor((batch_size, sample_size)).to(torch_device)229230model = self.model_class(**init_dict)231model.to(torch_device)232model.eval()233234with torch.no_grad():235output = model(**inputs_dict)236237if isinstance(output, dict):238output = output.sample239240self.assertIsNotNone(output)241expected_shape = inputs_dict["sample"].shape242self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")243244def test_model_with_class_embeddings_concat(self):245init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()246247batch_size, _, _, sample_size = inputs_dict["sample"].shape248249init_dict["class_embed_type"] = "simple_projection"250init_dict["projection_class_embeddings_input_dim"] = sample_size251init_dict["class_embeddings_concat"] = True252253inputs_dict["class_labels"] = floats_tensor((batch_size, sample_size)).to(torch_device)254255model = self.model_class(**init_dict)256model.to(torch_device)257model.eval()258259with torch.no_grad():260output = model(**inputs_dict)261262if isinstance(output, dict):263output = output.sample264265self.assertIsNotNone(output)266expected_shape = inputs_dict["sample"].shape267self.assertEqual(output.shape, expected_shape, "Input and output shapes do not match")268269def test_model_attention_slicing(self):270init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()271272init_dict["attention_head_dim"] = (8, 16)273274model = self.model_class(**init_dict)275model.to(torch_device)276model.eval()277278model.set_attention_slice("auto")279with torch.no_grad():280output = model(**inputs_dict)281assert output is not None282283model.set_attention_slice("max")284with torch.no_grad():285output = model(**inputs_dict)286assert output is not None287288model.set_attention_slice(2)289with torch.no_grad():290output = model(**inputs_dict)291assert output is not None292293def test_model_sliceable_head_dim(self):294init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()295296init_dict["attention_head_dim"] = (8, 16)297298model = self.model_class(**init_dict)299300def check_sliceable_dim_attr(module: torch.nn.Module):301if hasattr(module, "set_attention_slice"):302assert isinstance(module.sliceable_head_dim, int)303304for child in module.children():305check_sliceable_dim_attr(child)306307# retrieve number of attention layers308for module in model.children():309check_sliceable_dim_attr(module)310311def test_special_attn_proc(self):312class AttnEasyProc(torch.nn.Module):313def __init__(self, num):314super().__init__()315self.weight = torch.nn.Parameter(torch.tensor(num))316self.is_run = False317self.number = 0318self.counter = 0319320def __call__(self, attn, hidden_states, encoder_hidden_states=None, attention_mask=None, number=None):321batch_size, sequence_length, _ = hidden_states.shape322attention_mask = attn.prepare_attention_mask(attention_mask, sequence_length, batch_size)323324query = attn.to_q(hidden_states)325326encoder_hidden_states = encoder_hidden_states if encoder_hidden_states is not None else hidden_states327key = attn.to_k(encoder_hidden_states)328value = attn.to_v(encoder_hidden_states)329330query = attn.head_to_batch_dim(query)331key = attn.head_to_batch_dim(key)332value = attn.head_to_batch_dim(value)333334attention_probs = attn.get_attention_scores(query, key, attention_mask)335hidden_states = torch.bmm(attention_probs, value)336hidden_states = attn.batch_to_head_dim(hidden_states)337338# linear proj339hidden_states = attn.to_out[0](hidden_states)340# dropout341hidden_states = attn.to_out[1](hidden_states)342343hidden_states += self.weight344345self.is_run = True346self.counter += 1347self.number = number348349return hidden_states350351# enable deterministic behavior for gradient checkpointing352init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()353354init_dict["attention_head_dim"] = (8, 16)355356model = self.model_class(**init_dict)357model.to(torch_device)358359processor = AttnEasyProc(5.0)360361model.set_attn_processor(processor)362model(**inputs_dict, cross_attention_kwargs={"number": 123}).sample363364assert processor.counter == 12365assert processor.is_run366assert processor.number == 123367368def test_lora_processors(self):369# enable deterministic behavior for gradient checkpointing370init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()371372init_dict["attention_head_dim"] = (8, 16)373374model = self.model_class(**init_dict)375model.to(torch_device)376377with torch.no_grad():378sample1 = model(**inputs_dict).sample379380lora_attn_procs = {}381for name in model.attn_processors.keys():382cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim383if name.startswith("mid_block"):384hidden_size = model.config.block_out_channels[-1]385elif name.startswith("up_blocks"):386block_id = int(name[len("up_blocks.")])387hidden_size = list(reversed(model.config.block_out_channels))[block_id]388elif name.startswith("down_blocks"):389block_id = int(name[len("down_blocks.")])390hidden_size = model.config.block_out_channels[block_id]391392lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)393394# add 1 to weights to mock trained weights395with torch.no_grad():396lora_attn_procs[name].to_q_lora.up.weight += 1397lora_attn_procs[name].to_k_lora.up.weight += 1398lora_attn_procs[name].to_v_lora.up.weight += 1399lora_attn_procs[name].to_out_lora.up.weight += 1400401# make sure we can set a list of attention processors402model.set_attn_processor(lora_attn_procs)403model.to(torch_device)404405# test that attn processors can be set to itself406model.set_attn_processor(model.attn_processors)407408with torch.no_grad():409sample2 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.0}).sample410sample3 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample411sample4 = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample412413assert (sample1 - sample2).abs().max() < 1e-4414assert (sample3 - sample4).abs().max() < 1e-4415416# sample 2 and sample 3 should be different417assert (sample2 - sample3).abs().max() > 1e-4418419def test_lora_save_load(self):420# enable deterministic behavior for gradient checkpointing421init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()422423init_dict["attention_head_dim"] = (8, 16)424425torch.manual_seed(0)426model = self.model_class(**init_dict)427model.to(torch_device)428429with torch.no_grad():430old_sample = model(**inputs_dict).sample431432lora_attn_procs = create_lora_layers(model)433model.set_attn_processor(lora_attn_procs)434435with torch.no_grad():436sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample437438with tempfile.TemporaryDirectory() as tmpdirname:439model.save_attn_procs(tmpdirname)440self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin")))441torch.manual_seed(0)442new_model = self.model_class(**init_dict)443new_model.to(torch_device)444new_model.load_attn_procs(tmpdirname)445446with torch.no_grad():447new_sample = new_model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample448449assert (sample - new_sample).abs().max() < 1e-4450451# LoRA and no LoRA should NOT be the same452assert (sample - old_sample).abs().max() > 1e-4453454def test_lora_save_load_safetensors(self):455# enable deterministic behavior for gradient checkpointing456init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()457458init_dict["attention_head_dim"] = (8, 16)459460torch.manual_seed(0)461model = self.model_class(**init_dict)462model.to(torch_device)463464with torch.no_grad():465old_sample = model(**inputs_dict).sample466467lora_attn_procs = {}468for name in model.attn_processors.keys():469cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim470if name.startswith("mid_block"):471hidden_size = model.config.block_out_channels[-1]472elif name.startswith("up_blocks"):473block_id = int(name[len("up_blocks.")])474hidden_size = list(reversed(model.config.block_out_channels))[block_id]475elif name.startswith("down_blocks"):476block_id = int(name[len("down_blocks.")])477hidden_size = model.config.block_out_channels[block_id]478479lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)480lora_attn_procs[name] = lora_attn_procs[name].to(model.device)481482# add 1 to weights to mock trained weights483with torch.no_grad():484lora_attn_procs[name].to_q_lora.up.weight += 1485lora_attn_procs[name].to_k_lora.up.weight += 1486lora_attn_procs[name].to_v_lora.up.weight += 1487lora_attn_procs[name].to_out_lora.up.weight += 1488489model.set_attn_processor(lora_attn_procs)490491with torch.no_grad():492sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample493494with tempfile.TemporaryDirectory() as tmpdirname:495model.save_attn_procs(tmpdirname, safe_serialization=True)496self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.safetensors")))497torch.manual_seed(0)498new_model = self.model_class(**init_dict)499new_model.to(torch_device)500new_model.load_attn_procs(tmpdirname)501502with torch.no_grad():503new_sample = new_model(**inputs_dict, cross_attention_kwargs={"scale": 0.5}).sample504505assert (sample - new_sample).abs().max() < 1e-4506507# LoRA and no LoRA should NOT be the same508assert (sample - old_sample).abs().max() > 1e-4509510def test_lora_save_safetensors_load_torch(self):511# enable deterministic behavior for gradient checkpointing512init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()513514init_dict["attention_head_dim"] = (8, 16)515516torch.manual_seed(0)517model = self.model_class(**init_dict)518model.to(torch_device)519520lora_attn_procs = {}521for name in model.attn_processors.keys():522cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim523if name.startswith("mid_block"):524hidden_size = model.config.block_out_channels[-1]525elif name.startswith("up_blocks"):526block_id = int(name[len("up_blocks.")])527hidden_size = list(reversed(model.config.block_out_channels))[block_id]528elif name.startswith("down_blocks"):529block_id = int(name[len("down_blocks.")])530hidden_size = model.config.block_out_channels[block_id]531532lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)533lora_attn_procs[name] = lora_attn_procs[name].to(model.device)534535model.set_attn_processor(lora_attn_procs)536# Saving as torch, properly reloads with directly filename537with tempfile.TemporaryDirectory() as tmpdirname:538model.save_attn_procs(tmpdirname)539self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin")))540torch.manual_seed(0)541new_model = self.model_class(**init_dict)542new_model.to(torch_device)543new_model.load_attn_procs(tmpdirname, weight_name="pytorch_lora_weights.bin")544545def test_lora_save_torch_force_load_safetensors_error(self):546# enable deterministic behavior for gradient checkpointing547init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()548549init_dict["attention_head_dim"] = (8, 16)550551torch.manual_seed(0)552model = self.model_class(**init_dict)553model.to(torch_device)554555lora_attn_procs = {}556for name in model.attn_processors.keys():557cross_attention_dim = None if name.endswith("attn1.processor") else model.config.cross_attention_dim558if name.startswith("mid_block"):559hidden_size = model.config.block_out_channels[-1]560elif name.startswith("up_blocks"):561block_id = int(name[len("up_blocks.")])562hidden_size = list(reversed(model.config.block_out_channels))[block_id]563elif name.startswith("down_blocks"):564block_id = int(name[len("down_blocks.")])565hidden_size = model.config.block_out_channels[block_id]566567lora_attn_procs[name] = LoRAAttnProcessor(hidden_size=hidden_size, cross_attention_dim=cross_attention_dim)568lora_attn_procs[name] = lora_attn_procs[name].to(model.device)569570model.set_attn_processor(lora_attn_procs)571# Saving as torch, properly reloads with directly filename572with tempfile.TemporaryDirectory() as tmpdirname:573model.save_attn_procs(tmpdirname)574self.assertTrue(os.path.isfile(os.path.join(tmpdirname, "pytorch_lora_weights.bin")))575torch.manual_seed(0)576new_model = self.model_class(**init_dict)577new_model.to(torch_device)578with self.assertRaises(IOError) as e:579new_model.load_attn_procs(tmpdirname, use_safetensors=True)580self.assertIn("Error no file named pytorch_lora_weights.safetensors", str(e.exception))581582def test_lora_on_off(self):583# enable deterministic behavior for gradient checkpointing584init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()585586init_dict["attention_head_dim"] = (8, 16)587588torch.manual_seed(0)589model = self.model_class(**init_dict)590model.to(torch_device)591592with torch.no_grad():593old_sample = model(**inputs_dict).sample594595lora_attn_procs = create_lora_layers(model)596model.set_attn_processor(lora_attn_procs)597598with torch.no_grad():599sample = model(**inputs_dict, cross_attention_kwargs={"scale": 0.0}).sample600601model.set_attn_processor(AttnProcessor())602603with torch.no_grad():604new_sample = model(**inputs_dict).sample605606assert (sample - new_sample).abs().max() < 1e-4607assert (sample - old_sample).abs().max() < 1e-4608609@unittest.skipIf(610torch_device != "cuda" or not is_xformers_available(),611reason="XFormers attention is only available with CUDA and `xformers` installed",612)613def test_lora_xformers_on_off(self):614# enable deterministic behavior for gradient checkpointing615init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()616617init_dict["attention_head_dim"] = (8, 16)618619torch.manual_seed(0)620model = self.model_class(**init_dict)621model.to(torch_device)622lora_attn_procs = create_lora_layers(model)623model.set_attn_processor(lora_attn_procs)624625# default626with torch.no_grad():627sample = model(**inputs_dict).sample628629model.enable_xformers_memory_efficient_attention()630on_sample = model(**inputs_dict).sample631632model.disable_xformers_memory_efficient_attention()633off_sample = model(**inputs_dict).sample634635assert (sample - on_sample).abs().max() < 1e-4636assert (sample - off_sample).abs().max() < 1e-4637638639@slow640class UNet2DConditionModelIntegrationTests(unittest.TestCase):641def get_file_format(self, seed, shape):642return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"643644def tearDown(self):645# clean up the VRAM after each test646super().tearDown()647gc.collect()648torch.cuda.empty_cache()649650def get_latents(self, seed=0, shape=(4, 4, 64, 64), fp16=False):651dtype = torch.float16 if fp16 else torch.float32652image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)653return image654655def get_unet_model(self, fp16=False, model_id="CompVis/stable-diffusion-v1-4"):656revision = "fp16" if fp16 else None657torch_dtype = torch.float16 if fp16 else torch.float32658659model = UNet2DConditionModel.from_pretrained(660model_id, subfolder="unet", torch_dtype=torch_dtype, revision=revision661)662model.to(torch_device).eval()663664return model665666def test_set_attention_slice_auto(self):667torch.cuda.empty_cache()668torch.cuda.reset_max_memory_allocated()669torch.cuda.reset_peak_memory_stats()670671unet = self.get_unet_model()672unet.set_attention_slice("auto")673674latents = self.get_latents(33)675encoder_hidden_states = self.get_encoder_hidden_states(33)676timestep = 1677678with torch.no_grad():679_ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample680681mem_bytes = torch.cuda.max_memory_allocated()682683assert mem_bytes < 5 * 10**9684685def test_set_attention_slice_max(self):686torch.cuda.empty_cache()687torch.cuda.reset_max_memory_allocated()688torch.cuda.reset_peak_memory_stats()689690unet = self.get_unet_model()691unet.set_attention_slice("max")692693latents = self.get_latents(33)694encoder_hidden_states = self.get_encoder_hidden_states(33)695timestep = 1696697with torch.no_grad():698_ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample699700mem_bytes = torch.cuda.max_memory_allocated()701702assert mem_bytes < 5 * 10**9703704def test_set_attention_slice_int(self):705torch.cuda.empty_cache()706torch.cuda.reset_max_memory_allocated()707torch.cuda.reset_peak_memory_stats()708709unet = self.get_unet_model()710unet.set_attention_slice(2)711712latents = self.get_latents(33)713encoder_hidden_states = self.get_encoder_hidden_states(33)714timestep = 1715716with torch.no_grad():717_ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample718719mem_bytes = torch.cuda.max_memory_allocated()720721assert mem_bytes < 5 * 10**9722723def test_set_attention_slice_list(self):724torch.cuda.empty_cache()725torch.cuda.reset_max_memory_allocated()726torch.cuda.reset_peak_memory_stats()727728# there are 32 sliceable layers729slice_list = 16 * [2, 3]730unet = self.get_unet_model()731unet.set_attention_slice(slice_list)732733latents = self.get_latents(33)734encoder_hidden_states = self.get_encoder_hidden_states(33)735timestep = 1736737with torch.no_grad():738_ = unet(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample739740mem_bytes = torch.cuda.max_memory_allocated()741742assert mem_bytes < 5 * 10**9743744def get_encoder_hidden_states(self, seed=0, shape=(4, 77, 768), fp16=False):745dtype = torch.float16 if fp16 else torch.float32746hidden_states = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)747return hidden_states748749@parameterized.expand(750[751# fmt: off752[33, 4, [-0.4424, 0.1510, -0.1937, 0.2118, 0.3746, -0.3957, 0.0160, -0.0435]],753[47, 0.55, [-0.1508, 0.0379, -0.3075, 0.2540, 0.3633, -0.0821, 0.1719, -0.0207]],754[21, 0.89, [-0.6479, 0.6364, -0.3464, 0.8697, 0.4443, -0.6289, -0.0091, 0.1778]],755[9, 1000, [0.8888, -0.5659, 0.5834, -0.7469, 1.1912, -0.3923, 1.1241, -0.4424]],756# fmt: on757]758)759@require_torch_gpu760def test_compvis_sd_v1_4(self, seed, timestep, expected_slice):761model = self.get_unet_model(model_id="CompVis/stable-diffusion-v1-4")762latents = self.get_latents(seed)763encoder_hidden_states = self.get_encoder_hidden_states(seed)764765timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)766767with torch.no_grad():768sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample769770assert sample.shape == latents.shape771772output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()773expected_output_slice = torch.tensor(expected_slice)774775assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)776777@parameterized.expand(778[779# fmt: off780[83, 4, [-0.2323, -0.1304, 0.0813, -0.3093, -0.0919, -0.1571, -0.1125, -0.5806]],781[17, 0.55, [-0.0831, -0.2443, 0.0901, -0.0919, 0.3396, 0.0103, -0.3743, 0.0701]],782[8, 0.89, [-0.4863, 0.0859, 0.0875, -0.1658, 0.9199, -0.0114, 0.4839, 0.4639]],783[3, 1000, [-0.5649, 0.2402, -0.5518, 0.1248, 1.1328, -0.2443, -0.0325, -1.0078]],784# fmt: on785]786)787@require_torch_gpu788def test_compvis_sd_v1_4_fp16(self, seed, timestep, expected_slice):789model = self.get_unet_model(model_id="CompVis/stable-diffusion-v1-4", fp16=True)790latents = self.get_latents(seed, fp16=True)791encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True)792793timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)794795with torch.no_grad():796sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample797798assert sample.shape == latents.shape799800output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()801expected_output_slice = torch.tensor(expected_slice)802803assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)804805@parameterized.expand(806[807# fmt: off808[33, 4, [-0.4430, 0.1570, -0.1867, 0.2376, 0.3205, -0.3681, 0.0525, -0.0722]],809[47, 0.55, [-0.1415, 0.0129, -0.3136, 0.2257, 0.3430, -0.0536, 0.2114, -0.0436]],810[21, 0.89, [-0.7091, 0.6664, -0.3643, 0.9032, 0.4499, -0.6541, 0.0139, 0.1750]],811[9, 1000, [0.8878, -0.5659, 0.5844, -0.7442, 1.1883, -0.3927, 1.1192, -0.4423]],812# fmt: on813]814)815@require_torch_gpu816def test_compvis_sd_v1_5(self, seed, timestep, expected_slice):817model = self.get_unet_model(model_id="runwayml/stable-diffusion-v1-5")818latents = self.get_latents(seed)819encoder_hidden_states = self.get_encoder_hidden_states(seed)820821timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)822823with torch.no_grad():824sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample825826assert sample.shape == latents.shape827828output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()829expected_output_slice = torch.tensor(expected_slice)830831assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)832833@parameterized.expand(834[835# fmt: off836[83, 4, [-0.2695, -0.1669, 0.0073, -0.3181, -0.1187, -0.1676, -0.1395, -0.5972]],837[17, 0.55, [-0.1290, -0.2588, 0.0551, -0.0916, 0.3286, 0.0238, -0.3669, 0.0322]],838[8, 0.89, [-0.5283, 0.1198, 0.0870, -0.1141, 0.9189, -0.0150, 0.5474, 0.4319]],839[3, 1000, [-0.5601, 0.2411, -0.5435, 0.1268, 1.1338, -0.2427, -0.0280, -1.0020]],840# fmt: on841]842)843@require_torch_gpu844def test_compvis_sd_v1_5_fp16(self, seed, timestep, expected_slice):845model = self.get_unet_model(model_id="runwayml/stable-diffusion-v1-5", fp16=True)846latents = self.get_latents(seed, fp16=True)847encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True)848849timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)850851with torch.no_grad():852sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample853854assert sample.shape == latents.shape855856output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()857expected_output_slice = torch.tensor(expected_slice)858859assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)860861@parameterized.expand(862[863# fmt: off864[33, 4, [-0.7639, 0.0106, -0.1615, -0.3487, -0.0423, -0.7972, 0.0085, -0.4858]],865[47, 0.55, [-0.6564, 0.0795, -1.9026, -0.6258, 1.8235, 1.2056, 1.2169, 0.9073]],866[21, 0.89, [0.0327, 0.4399, -0.6358, 0.3417, 0.4120, -0.5621, -0.0397, -1.0430]],867[9, 1000, [0.1600, 0.7303, -1.0556, -0.3515, -0.7440, -1.2037, -1.8149, -1.8931]],868# fmt: on869]870)871@require_torch_gpu872def test_compvis_sd_inpaint(self, seed, timestep, expected_slice):873model = self.get_unet_model(model_id="runwayml/stable-diffusion-inpainting")874latents = self.get_latents(seed, shape=(4, 9, 64, 64))875encoder_hidden_states = self.get_encoder_hidden_states(seed)876877timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)878879with torch.no_grad():880sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample881882assert sample.shape == (4, 4, 64, 64)883884output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()885expected_output_slice = torch.tensor(expected_slice)886887assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)888889@parameterized.expand(890[891# fmt: off892[83, 4, [-0.1047, -1.7227, 0.1067, 0.0164, -0.5698, -0.4172, -0.1388, 1.1387]],893[17, 0.55, [0.0975, -0.2856, -0.3508, -0.4600, 0.3376, 0.2930, -0.2747, -0.7026]],894[8, 0.89, [-0.0952, 0.0183, -0.5825, -0.1981, 0.1131, 0.4668, -0.0395, -0.3486]],895[3, 1000, [0.4790, 0.4949, -1.0732, -0.7158, 0.7959, -0.9478, 0.1105, -0.9741]],896# fmt: on897]898)899@require_torch_gpu900def test_compvis_sd_inpaint_fp16(self, seed, timestep, expected_slice):901model = self.get_unet_model(model_id="runwayml/stable-diffusion-inpainting", fp16=True)902latents = self.get_latents(seed, shape=(4, 9, 64, 64), fp16=True)903encoder_hidden_states = self.get_encoder_hidden_states(seed, fp16=True)904905timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)906907with torch.no_grad():908sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample909910assert sample.shape == (4, 4, 64, 64)911912output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()913expected_output_slice = torch.tensor(expected_slice)914915assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)916917@parameterized.expand(918[919# fmt: off920[83, 4, [0.1514, 0.0807, 0.1624, 0.1016, -0.1896, 0.0263, 0.0677, 0.2310]],921[17, 0.55, [0.1164, -0.0216, 0.0170, 0.1589, -0.3120, 0.1005, -0.0581, -0.1458]],922[8, 0.89, [-0.1758, -0.0169, 0.1004, -0.1411, 0.1312, 0.1103, -0.1996, 0.2139]],923[3, 1000, [0.1214, 0.0352, -0.0731, -0.1562, -0.0994, -0.0906, -0.2340, -0.0539]],924# fmt: on925]926)927@require_torch_gpu928def test_stabilityai_sd_v2_fp16(self, seed, timestep, expected_slice):929model = self.get_unet_model(model_id="stabilityai/stable-diffusion-2", fp16=True)930latents = self.get_latents(seed, shape=(4, 4, 96, 96), fp16=True)931encoder_hidden_states = self.get_encoder_hidden_states(seed, shape=(4, 77, 1024), fp16=True)932933timestep = torch.tensor([timestep], dtype=torch.long, device=torch_device)934935with torch.no_grad():936sample = model(latents, timestep=timestep, encoder_hidden_states=encoder_hidden_states).sample937938assert sample.shape == latents.shape939940output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()941expected_output_slice = torch.tensor(expected_slice)942943assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)944945946