Path: blob/main/tests/pipelines/unclip/test_unclip_image_variation.py
1451 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 random17import unittest1819import numpy as np20import torch21from transformers import (22CLIPImageProcessor,23CLIPTextConfig,24CLIPTextModelWithProjection,25CLIPTokenizer,26CLIPVisionConfig,27CLIPVisionModelWithProjection,28)2930from diffusers import (31DiffusionPipeline,32UnCLIPImageVariationPipeline,33UnCLIPScheduler,34UNet2DConditionModel,35UNet2DModel,36)37from diffusers.pipelines.unclip.text_proj import UnCLIPTextProjModel38from diffusers.utils import floats_tensor, load_numpy, slow, torch_device39from diffusers.utils.testing_utils import load_image, require_torch_gpu, skip_mps4041from ...pipeline_params import IMAGE_VARIATION_BATCH_PARAMS, IMAGE_VARIATION_PARAMS42from ...test_pipelines_common import PipelineTesterMixin, assert_mean_pixel_difference434445class UnCLIPImageVariationPipelineFastTests(PipelineTesterMixin, unittest.TestCase):46pipeline_class = UnCLIPImageVariationPipeline47params = IMAGE_VARIATION_PARAMS - {"height", "width", "guidance_scale"}48batch_params = IMAGE_VARIATION_BATCH_PARAMS4950required_optional_params = [51"generator",52"return_dict",53"decoder_num_inference_steps",54"super_res_num_inference_steps",55]5657@property58def text_embedder_hidden_size(self):59return 326061@property62def time_input_dim(self):63return 326465@property66def block_out_channels_0(self):67return self.time_input_dim6869@property70def time_embed_dim(self):71return self.time_input_dim * 47273@property74def cross_attention_dim(self):75return 1007677@property78def dummy_tokenizer(self):79tokenizer = CLIPTokenizer.from_pretrained("hf-internal-testing/tiny-random-clip")80return tokenizer8182@property83def dummy_text_encoder(self):84torch.manual_seed(0)85config = CLIPTextConfig(86bos_token_id=0,87eos_token_id=2,88hidden_size=self.text_embedder_hidden_size,89projection_dim=self.text_embedder_hidden_size,90intermediate_size=37,91layer_norm_eps=1e-05,92num_attention_heads=4,93num_hidden_layers=5,94pad_token_id=1,95vocab_size=1000,96)97return CLIPTextModelWithProjection(config)9899@property100def dummy_image_encoder(self):101torch.manual_seed(0)102config = CLIPVisionConfig(103hidden_size=self.text_embedder_hidden_size,104projection_dim=self.text_embedder_hidden_size,105num_hidden_layers=5,106num_attention_heads=4,107image_size=32,108intermediate_size=37,109patch_size=1,110)111return CLIPVisionModelWithProjection(config)112113@property114def dummy_text_proj(self):115torch.manual_seed(0)116117model_kwargs = {118"clip_embeddings_dim": self.text_embedder_hidden_size,119"time_embed_dim": self.time_embed_dim,120"cross_attention_dim": self.cross_attention_dim,121}122123model = UnCLIPTextProjModel(**model_kwargs)124return model125126@property127def dummy_decoder(self):128torch.manual_seed(0)129130model_kwargs = {131"sample_size": 32,132# RGB in channels133"in_channels": 3,134# Out channels is double in channels because predicts mean and variance135"out_channels": 6,136"down_block_types": ("ResnetDownsampleBlock2D", "SimpleCrossAttnDownBlock2D"),137"up_block_types": ("SimpleCrossAttnUpBlock2D", "ResnetUpsampleBlock2D"),138"mid_block_type": "UNetMidBlock2DSimpleCrossAttn",139"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),140"layers_per_block": 1,141"cross_attention_dim": self.cross_attention_dim,142"attention_head_dim": 4,143"resnet_time_scale_shift": "scale_shift",144"class_embed_type": "identity",145}146147model = UNet2DConditionModel(**model_kwargs)148return model149150@property151def dummy_super_res_kwargs(self):152return {153"sample_size": 64,154"layers_per_block": 1,155"down_block_types": ("ResnetDownsampleBlock2D", "ResnetDownsampleBlock2D"),156"up_block_types": ("ResnetUpsampleBlock2D", "ResnetUpsampleBlock2D"),157"block_out_channels": (self.block_out_channels_0, self.block_out_channels_0 * 2),158"in_channels": 6,159"out_channels": 3,160}161162@property163def dummy_super_res_first(self):164torch.manual_seed(0)165166model = UNet2DModel(**self.dummy_super_res_kwargs)167return model168169@property170def dummy_super_res_last(self):171# seeded differently to get different unet than `self.dummy_super_res_first`172torch.manual_seed(1)173174model = UNet2DModel(**self.dummy_super_res_kwargs)175return model176177def get_dummy_components(self):178decoder = self.dummy_decoder179text_proj = self.dummy_text_proj180text_encoder = self.dummy_text_encoder181tokenizer = self.dummy_tokenizer182super_res_first = self.dummy_super_res_first183super_res_last = self.dummy_super_res_last184185decoder_scheduler = UnCLIPScheduler(186variance_type="learned_range",187prediction_type="epsilon",188num_train_timesteps=1000,189)190191super_res_scheduler = UnCLIPScheduler(192variance_type="fixed_small_log",193prediction_type="epsilon",194num_train_timesteps=1000,195)196197feature_extractor = CLIPImageProcessor(crop_size=32, size=32)198199image_encoder = self.dummy_image_encoder200201return {202"decoder": decoder,203"text_encoder": text_encoder,204"tokenizer": tokenizer,205"text_proj": text_proj,206"feature_extractor": feature_extractor,207"image_encoder": image_encoder,208"super_res_first": super_res_first,209"super_res_last": super_res_last,210"decoder_scheduler": decoder_scheduler,211"super_res_scheduler": super_res_scheduler,212}213214def get_dummy_inputs(self, device, seed=0, pil_image=True):215input_image = floats_tensor((1, 3, 32, 32), rng=random.Random(seed)).to(device)216if str(device).startswith("mps"):217generator = torch.manual_seed(seed)218else:219generator = torch.Generator(device=device).manual_seed(seed)220221if pil_image:222input_image = input_image * 0.5 + 0.5223input_image = input_image.clamp(0, 1)224input_image = input_image.cpu().permute(0, 2, 3, 1).float().numpy()225input_image = DiffusionPipeline.numpy_to_pil(input_image)[0]226227return {228"image": input_image,229"generator": generator,230"decoder_num_inference_steps": 2,231"super_res_num_inference_steps": 2,232"output_type": "np",233}234235def test_unclip_image_variation_input_tensor(self):236device = "cpu"237238components = self.get_dummy_components()239240pipe = self.pipeline_class(**components)241pipe = pipe.to(device)242243pipe.set_progress_bar_config(disable=None)244245pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)246247output = pipe(**pipeline_inputs)248image = output.images249250tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)251252image_from_tuple = pipe(253**tuple_pipeline_inputs,254return_dict=False,255)[0]256257image_slice = image[0, -3:, -3:, -1]258image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]259260assert image.shape == (1, 64, 64, 3)261262expected_slice = np.array(263[2640.9997,2650.0002,2660.9997,2670.9997,2680.9969,2690.0023,2700.9997,2710.9969,2720.9970,273]274)275276assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2277assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2278279def test_unclip_image_variation_input_image(self):280device = "cpu"281282components = self.get_dummy_components()283284pipe = self.pipeline_class(**components)285pipe = pipe.to(device)286287pipe.set_progress_bar_config(disable=None)288289pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)290291output = pipe(**pipeline_inputs)292image = output.images293294tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)295296image_from_tuple = pipe(297**tuple_pipeline_inputs,298return_dict=False,299)[0]300301image_slice = image[0, -3:, -3:, -1]302image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]303304assert image.shape == (1, 64, 64, 3)305306expected_slice = np.array([0.9997, 0.0003, 0.9997, 0.9997, 0.9970, 0.0024, 0.9997, 0.9971, 0.9971])307308assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2309assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2310311def test_unclip_image_variation_input_list_images(self):312device = "cpu"313314components = self.get_dummy_components()315316pipe = self.pipeline_class(**components)317pipe = pipe.to(device)318319pipe.set_progress_bar_config(disable=None)320321pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)322pipeline_inputs["image"] = [323pipeline_inputs["image"],324pipeline_inputs["image"],325]326327output = pipe(**pipeline_inputs)328image = output.images329330tuple_pipeline_inputs = self.get_dummy_inputs(device, pil_image=True)331tuple_pipeline_inputs["image"] = [332tuple_pipeline_inputs["image"],333tuple_pipeline_inputs["image"],334]335336image_from_tuple = pipe(337**tuple_pipeline_inputs,338return_dict=False,339)[0]340341image_slice = image[0, -3:, -3:, -1]342image_from_tuple_slice = image_from_tuple[0, -3:, -3:, -1]343344assert image.shape == (2, 64, 64, 3)345346expected_slice = np.array(347[3480.9997,3490.9989,3500.0008,3510.0021,3520.9960,3530.0018,3540.0014,3550.0002,3560.9933,357]358)359360assert np.abs(image_slice.flatten() - expected_slice).max() < 1e-2361assert np.abs(image_from_tuple_slice.flatten() - expected_slice).max() < 1e-2362363def test_unclip_passed_image_embed(self):364device = torch.device("cpu")365366class DummyScheduler:367init_noise_sigma = 1368369components = self.get_dummy_components()370371pipe = self.pipeline_class(**components)372pipe = pipe.to(device)373374pipe.set_progress_bar_config(disable=None)375376generator = torch.Generator(device=device).manual_seed(0)377dtype = pipe.decoder.dtype378batch_size = 1379380shape = (batch_size, pipe.decoder.in_channels, pipe.decoder.sample_size, pipe.decoder.sample_size)381decoder_latents = pipe.prepare_latents(382shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()383)384385shape = (386batch_size,387pipe.super_res_first.in_channels // 2,388pipe.super_res_first.sample_size,389pipe.super_res_first.sample_size,390)391super_res_latents = pipe.prepare_latents(392shape, dtype=dtype, device=device, generator=generator, latents=None, scheduler=DummyScheduler()393)394395pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)396397img_out_1 = pipe(398**pipeline_inputs, decoder_latents=decoder_latents, super_res_latents=super_res_latents399).images400401pipeline_inputs = self.get_dummy_inputs(device, pil_image=False)402# Don't pass image, instead pass embedding403image = pipeline_inputs.pop("image")404image_embeddings = pipe.image_encoder(image).image_embeds405406img_out_2 = pipe(407**pipeline_inputs,408decoder_latents=decoder_latents,409super_res_latents=super_res_latents,410image_embeddings=image_embeddings,411).images412413# make sure passing text embeddings manually is identical414assert np.abs(img_out_1 - img_out_2).max() < 1e-4415416# Overriding PipelineTesterMixin::test_attention_slicing_forward_pass417# because UnCLIP GPU undeterminism requires a looser check.418@skip_mps419def test_attention_slicing_forward_pass(self):420test_max_difference = torch_device == "cpu"421422self._test_attention_slicing_forward_pass(test_max_difference=test_max_difference)423424# Overriding PipelineTesterMixin::test_inference_batch_single_identical425# because UnCLIP undeterminism requires a looser check.426@skip_mps427def test_inference_batch_single_identical(self):428test_max_difference = torch_device == "cpu"429relax_max_difference = True430additional_params_copy_to_batched_inputs = [431"decoder_num_inference_steps",432"super_res_num_inference_steps",433]434435self._test_inference_batch_single_identical(436test_max_difference=test_max_difference,437relax_max_difference=relax_max_difference,438additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,439)440441def test_inference_batch_consistent(self):442additional_params_copy_to_batched_inputs = [443"decoder_num_inference_steps",444"super_res_num_inference_steps",445]446447if torch_device == "mps":448# TODO: MPS errors with larger batch sizes449batch_sizes = [2, 3]450self._test_inference_batch_consistent(451batch_sizes=batch_sizes,452additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs,453)454else:455self._test_inference_batch_consistent(456additional_params_copy_to_batched_inputs=additional_params_copy_to_batched_inputs457)458459@skip_mps460def test_dict_tuple_outputs_equivalent(self):461return super().test_dict_tuple_outputs_equivalent()462463@skip_mps464def test_save_load_local(self):465return super().test_save_load_local()466467@skip_mps468def test_save_load_optional_components(self):469return super().test_save_load_optional_components()470471472@slow473@require_torch_gpu474class UnCLIPImageVariationPipelineIntegrationTests(unittest.TestCase):475def tearDown(self):476# clean up the VRAM after each test477super().tearDown()478gc.collect()479torch.cuda.empty_cache()480481def test_unclip_image_variation_karlo(self):482input_image = load_image(483"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main/unclip/cat.png"484)485expected_image = load_numpy(486"https://huggingface.co/datasets/hf-internal-testing/diffusers-images/resolve/main"487"/unclip/karlo_v1_alpha_cat_variation_fp16.npy"488)489490pipeline = UnCLIPImageVariationPipeline.from_pretrained(491"kakaobrain/karlo-v1-alpha-image-variations", torch_dtype=torch.float16492)493pipeline = pipeline.to(torch_device)494pipeline.set_progress_bar_config(disable=None)495496generator = torch.Generator(device="cpu").manual_seed(0)497output = pipeline(498input_image,499generator=generator,500output_type="np",501)502503image = output.images[0]504505assert image.shape == (256, 256, 3)506507assert_mean_pixel_difference(image, expected_image)508509510