Path: blob/main/tests/pipelines/unclip/test_unclip.py
1450 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 unittest1718import numpy as np19import torch20from transformers import CLIPTextConfig, CLIPTextModelWithProjection, CLIPTokenizer2122from diffusers import PriorTransformer, UnCLIPPipeline, UnCLIPScheduler, UNet2DConditionModel, UNet2DModel23from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel24from diffusers.utils import load_numpy, nightly, slow, torch_device25from diffusers.utils.testing_utils import require_torch_gpu, skip_mps2627from ...pipeline_params import TEXT_TO_IMAGE_BATCH_PARAMS, TEXT_TO_IMAGE_PARAMS28from ...test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference293031class UnCLIPPipelineFastTests(PipelineTesterMixin, unittest.TestCase):32pipeline_class = UnCLIPPipeline33params = TEXT_TO_IMAGE_PARAMS - {34"negative_prompt",35"height",36"width",37"negative_prompt_embeds",38"guidance_scale",39"prompt_embeds",40"cross_attention_kwargs",41}42batch_params = TEXT_TO_IMAGE_BATCH_PARAMS43required_optional_params = [44"generator",45"return_dict",46"prior_num_inference_steps",47"decoder_num_inference_steps",48"super_res_num_inference_steps",49]50test_xformers_attention = False5152@property53def text_embedder_hidden_size(self):54return 325556@property57def time_input_dim(self):58return 325960@property61def block_out_channels_0(self):62return self.time_input_dim6364@property65def time_embed_dim(self):66return self.time_input_dim * 46768@property69def cross_attention_dim(self):70return 1007172@property73def dummy_tokenizer(self):74tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")75return tokenizer7677@property78def dummy_text_encoder(self):79torch.manual_seed(0)80config = CLIPTextConfig(81bos_token_id=0,82eos_token_id=2,83hidden_size=self.text_embedder_hidden_size,84projection_dim=self.text_embedder_hidden_size,85intermediate_size=37,86layer_norm_eps=1e-05,87num_attention_heads=4,88num_hidden_layers=5,89pad_token_id=1,90vocab_size=1000,91)92return CLIPTextModelWithProjection(config)9394@property95def dummy_prior(self):96torch.manual_seed(0)9798model_kwargs = {99"num_attention_heads": 2,100"attention_head_dim": 12,101"embedding_dim": self.text_embedder_hidden_size,102"num_layers": 1,103}104105model = PriorTransformer(**model_kwargs)106return model107108@property109def dummy_text_proj(self):110torch.manual_seed(0)111112model_kwargs = {113"clip_embeddings_dim": self.text_embedder_hidden_size,114"time_embed_dim": self.time_embed_dim,115"cross_attention_dim": self.cross_attention_dim,116}117118model = UnCLIPTextProjModel(**model_kwargs)119return model120121@property122def dummy_decoder(self):123torch.manual_seed(0)124125model_kwargs = {126"sample_size": 32,127# RGB in channels128"in_channels": 3,129# Out channels is double in channels because predicts mean and variance130"out_channels": 6,131"down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),132"up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),133"mid_block_type": "UNetMidBlock2DSimpleCrossAttn",134"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),135"layers_per_block": 1,136"cross_attention_dim": self.cross_attention_dim,137"attention_head_dim": 4,138"resnet_time_scale_shift": "scale_shift",139"class_embed_type": "identity",140}141142model = UNet2DConditionModel(**model_kwargs)143return model144145@property146def dummy_super_res_kwargs(self):147return {148"sample_size": 64,149"layers_per_block": 1,150"down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),151"up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),152"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),153"in_channels": 6,154"out_channels": 3,155}156157@property158def dummy_super_res_first(self):159torch.manual_seed(0)160161model = UNet2DModel(**self.dummy_super_res_kwargs)162return model163164@property165def dummy_super_res_last(self):166# seeded differently to get different unet than `self.dummy_super_res_first`167torch.manual_seed(1)168169model = UNet2DModel(**self.dummy_super_res_kwargs)170return model171172def get_dummy_components(self):173prior = self.dummy_prior174decoder = self.dummy_decoder175text_proj = self.dummy_text_proj176text_encoder = self.dummy_text_encoder177tokenizer = self.dummy_tokenizer178super_res_first = self.dummy_super_res_first179super_res_last = self.dummy_super_res_last180181prior_scheduler = UnCLIPScheduler(182variance_type="fixed_small_log",183prediction_type="sample",184num_train_timesteps=1000,185clip_sample_range=5.0,186)187188decoder_scheduler = UnCLIPScheduler(189variance_type="learned_range",190prediction_type="epsilon",191num_train_timesteps=1000,192)193194super_res_scheduler = UnCLIPScheduler(195variance_type="fixed_small_log",196prediction_type="epsilon",197num_train_timesteps=1000,198)199200components = {201"prior": prior,202"decoder": decoder,203"text_proj": text_proj,204"text_encoder": text_encoder,205"tokenizer": tokenizer,206"super_res_first": super_res_first,207"super_res_last": super_res_last,208"prior_scheduler": prior_scheduler,209"decoder_scheduler": decoder_scheduler,210"super_res_scheduler": super_res_scheduler,211}212213return components214215def get_dummy_inputs(self, device, seed=0):216if str(device).startswith("mps"):217generator = torch.manual_seed(seed)218else:219generator = torch.Generator(device=device).manual_seed(seed)220inputs = {221"prompt": "horse",222"generator": generator,223"prior_num_inference_steps": 2,224"decoder_num_inference_steps": 2,225"super_res_num_inference_steps": 2,226"output_type": "numpy",227}228return inputs229230def test_unclip(self):231device = "cpu"232233components = self.get_dummy_components()234235pipe = self.pipeline_class(**components)236pipe = pipe.to(device)237238pipe.set_progress_bar_config(disable=None)239240output = pipe(**self.get_dummy_inputs(device))241image = output.images242243image_from_tuple = pipe(244**self.get_dummy_inputs(device),245return_dict=False,246)[0]247248image_slice = image[0, -3:, -3:, -1]249image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]250251assert image.shape == (1, 64, 64, 3)252253expected_slice = np.array(254[2550.9997,2560.9988,2570.0028,2580.9997,2590.9984,2600.9965,2610.0029,2620.9986,2630.0025,264]265)266267assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2268assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2269270def test_unclip_passed_text_embed(self):271device = torch.device("cpu")272273class DummyScheduler:274init_noise_sigma = 1275276components = self.get_dummy_components()277278pipe = self.pipeline_class(**components)279pipe = pipe.to(device)280281prior = components["prior"]282decoder = components["decoder"]283super_res_first = components["super_res_first"]284tokenizer = components["tokenizer"]285text_encoder = components["text_encoder"]286287generator = torch.Generator(device=device).manual_seed(0)288dtype = prior.dtype289batch_size = 1290291shape = (batch_size, prior.config.embedding_dim)292prior_latents = pipe.prepare_latents(293shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()294)295shape = (batch_size, decoder.in_channels, decoder.sample_size, decoder.sample_size)296decoder_latents = pipe.prepare_latents(297shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()298)299300shape = (301batch_size,302super_res_first.in_channels // 2,303super_res_first.sample_size,304super_res_first.sample_size,305)306super_res_latents = pipe.prepare_latents(307shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()308)309310pipe.set_progress_bar_config(disable=None)311312prompt = "this is a prompt example"313314generator = torch.Generator(device=device).manual_seed(0)315output = pipe(316[prompt],317generator=generator,318prior_num_inference_steps=2,319decoder_num_inference_steps=2,320super_res_num_inference_steps=2,321prior_latents=prior_latents,322decoder_latents=decoder_latents,323super_res_latents=super_res_latents,324output_type="np",325)326image = output.images327328text_inputs = tokenizer(329prompt,330padding="max_length",331max_length=tokenizer.model_max_length,332return_tensors="pt",333)334text_model_output = text_encoder(text_inputs.input_ids)335text_attention_mask = text_inputs.attention_mask336337generator = torch.Generator(device=device).manual_seed(0)338image_from_text = pipe(339generator=generator,340prior_num_inference_steps=2,341decoder_num_inference_steps=2,342super_res_num_inference_steps=2,343prior_latents=prior_latents,344decoder_latents=decoder_latents,345super_res_latents=super_res_latents,346text_model_output=text_model_output,347text_attention_mask=text_attention_mask,348output_type="np",349)[0]350351# make sure passing text embeddings manually is identical352assert np.abs(image - image_from_text).max() < 1e-4353354# Overriding PipelineTesterMixin::test_attention_slicing_forward_pass355# because UnCLIP GPU undeterminism requires a looser check.356@skip_mps357def test_attention_slicing_forward_pass(self):358test_max_difference = torch_device == "cpu"359360self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference)361362# Overriding PipelineTesterMixin::test_inference_batch_single_identical363# because UnCLIP undeterminism requires a looser check.364@skip_mps365def test_inference_batch_single_identical(self):366test_max_difference = torch_device == "cpu"367relax_max_difference = True368additional_params_copy_to_batched_inputs = [369"prior_num_inference_steps",370"decoder_num_inference_steps",371"super_res_num_inference_steps",372]373374self._test_inference_batch_single_identical(375test_max_difference=test_max_difference,376relax_max_difference=relax_max_difference,377additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,378)379380def test_inference_batch_consistent(self):381additional_params_copy_to_batched_inputs = [382"prior_num_inference_steps",383"decoder_num_inference_steps",384"super_res_num_inference_steps",385]386387if torch_device == "mps":388# TODO: MPS errors with larger batch sizes389batch_sizes = [2, 3]390self._test_inference_batch_consistent(391batch_sizes=batch_sizes,392additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,393)394else:395self._test_inference_batch_consistent(396additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs397)398399@skip_mps400def test_dict_tuple_outputs_equivalent(self):401return super().test_dict_tuple_outputs_equivalent()402403@skip_mps404def test_save_load_local(self):405return super().test_save_load_local()406407@skip_mps408def test_save_load_optional_components(self):409return super().test_save_load_optional_components()410411412@nightly413class UnCLIPPipelineCPUIntegrationTests(unittest.TestCase):414def tearDown(self):415# clean up the VRAM after each test416super().tearDown()417gc.collect()418torch.cuda.empty_cache()419420def test_unclip_karlo_cpu_fp32(self):421expected_image = load_numpy(422"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"423"/unclip/karlo_v1_alpha_horse_cpu.npy"424)425426pipeline = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha")427pipeline.set_progress_bar_config(disable=None)428429generator = torch.manual_seed(0)430output = pipeline(431"horse",432num_images_per_prompt=1,433generator=generator,434output_type="np",435)436437image = output.images[0]438439assert image.shape == (256, 256, 3)440assert np.abs(expected_image - image).max() < 1e-1441442443@slow444@require_torch_gpu445class UnCLIPPipelineIntegrationTests(unittest.TestCase):446def tearDown(self):447# clean up the VRAM after each test448super().tearDown()449gc.collect()450torch.cuda.empty_cache()451452def test_unclip_karlo(self):453expected_image = load_numpy(454"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"455"/unclip/karlo_v1_alpha_horse_fp16.npy"456)457458pipeline = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha", torch_dtype=torch.float16)459pipeline = pipeline.to(torch_device)460pipeline.set_progress_bar_config(disable=None)461462generator = torch.Generator(device="cpu").manual_seed(0)463output = pipeline(464"horse",465generator=generator,466output_type="np",467)468469image = output.images[0]470471assert image.shape == (256, 256, 3)472473assert_mean_pixel_difference(image, expected_image)474475def test_unclip_pipeline_with_sequential_cpu_offloading(self):476torch.cuda.empty_cache()477torch.cuda.reset_max_memory_allocated()478torch.cuda.reset_peak_memory_stats()479480pipe = UnCLIPPipeline.from_pretrained("kakaobrain/karlo-v1-alpha", torch_dtype=torch.float16)481pipe = pipe.to(torch_device)482pipe.set_progress_bar_config(disable=None)483pipe.enable_attention_slicing()484pipe.enable_sequential_cpu_offload()485486_ = pipe(487"horse",488num_images_per_prompt=1,489prior_num_inference_steps=2,490decoder_num_inference_steps=2,491super_res_num_inference_steps=2,492output_type="np",493)494495mem_bytes = torch.cuda.max_memory_allocated()496# make sure that less than 7 GB is allocated497assert mem_bytes < 7 * 10**9498499500