Path: blob/main/tests/models/test_models_vae.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 unittest1718import torch19from parameterized import parameterized2021from diffusers import AutoencoderKL22from diffusers.utils import floats_tensor, load_hf_numpy, require_torch_gpu, slow, torch_all_close, torch_device2324from ..test_modeling_common import ModelTesterMixin252627torch.backends.cuda.matmul.allow_tf32 = False282930class AutoencoderKLTests(ModelTesterMixin, unittest.TestCase):31model_class = AutoencoderKL3233@property34def dummy_input(self):35batch_size = 436num_channels = 337sizes = (32, 32)3839image = floats_tensor((batch_size, num_channels) + sizes).to(torch_device)4041return {"sample": image}4243@property44def input_shape(self):45return (3, 32, 32)4647@property48def output_shape(self):49return (3, 32, 32)5051def prepare_init_args_and_inputs_for_common(self):52init_dict = {53"block_out_channels": [32, 64],54"in_channels": 3,55"out_channels": 3,56"down_block_types": ["DownEncoderBlock2D", "DownEncoderBlock2D"],57"up_block_types": ["UpDecoderBlock2D", "UpDecoderBlock2D"],58"latent_channels": 4,59}60inputs_dict = self.dummy_input61return init_dict, inputs_dict6263def test_forward_signature(self):64pass6566def test_training(self):67pass6869@unittest.skipIf(torch_device == "mps", "Gradient checkpointing skipped on MPS")70def test_gradient_checkpointing(self):71# enable deterministic behavior for gradient checkpointing72init_dict, inputs_dict = self.prepare_init_args_and_inputs_for_common()73model = self.model_class(**init_dict)74model.to(torch_device)7576assert not model.is_gradient_checkpointing and model.training7778out = model(**inputs_dict).sample79# run the backwards pass on the model. For backwards pass, for simplicity purpose,80# we won't calculate the loss and rather backprop on out.sum()81model.zero_grad()8283labels = torch.randn_like(out)84loss = (out - labels).mean()85loss.backward()8687# re-instantiate the model now enabling gradient checkpointing88model_2 = self.model_class(**init_dict)89# clone model90model_2.load_state_dict(model.state_dict())91model_2.to(torch_device)92model_2.enable_gradient_checkpointing()9394assert model_2.is_gradient_checkpointing and model_2.training9596out_2 = model_2(**inputs_dict).sample97# run the backwards pass on the model. For backwards pass, for simplicity purpose,98# we won't calculate the loss and rather backprop on out.sum()99model_2.zero_grad()100loss_2 = (out_2 - labels).mean()101loss_2.backward()102103# compare the output and parameters gradients104self.assertTrue((loss - loss_2).abs() < 1e-5)105named_params = dict(model.named_parameters())106named_params_2 = dict(model_2.named_parameters())107for name, param in named_params.items():108self.assertTrue(torch_all_close(param.grad.data, named_params_2[name].grad.data, atol=5e-5))109110def test_from_pretrained_hub(self):111model, loading_info = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy", output_loading_info=True)112self.assertIsNotNone(model)113self.assertEqual(len(loading_info["missing_keys"]), 0)114115model.to(torch_device)116image = model(**self.dummy_input)117118assert image is not None, "Make sure output is not None"119120def test_output_pretrained(self):121model = AutoencoderKL.from_pretrained("fusing/autoencoder-kl-dummy")122model = model.to(torch_device)123model.eval()124125if torch_device == "mps":126generator = torch.manual_seed(0)127else:128generator = torch.Generator(device=torch_device).manual_seed(0)129130image = torch.randn(1311,132model.config.in_channels,133model.config.sample_size,134model.config.sample_size,135generator=torch.manual_seed(0),136)137image = image.to(torch_device)138with torch.no_grad():139output = model(image, sample_posterior=True, generator=generator).sample140141output_slice = output[0, -1, -3:, -3:].flatten().cpu()142143# Since the VAE Gaussian prior's generator is seeded on the appropriate device,144# the expected output slices are not the same for CPU and GPU.145if torch_device == "mps":146expected_output_slice = torch.tensor(147[148-4.0078e-01,149-3.8323e-04,150-1.2681e-01,151-1.1462e-01,1522.0095e-01,1531.0893e-01,154-8.8247e-02,155-3.0361e-01,156-9.8644e-03,157]158)159elif torch_device == "cpu":160expected_output_slice = torch.tensor(161[-0.1352, 0.0878, 0.0419, -0.0818, -0.1069, 0.0688, -0.1458, -0.4446, -0.0026]162)163else:164expected_output_slice = torch.tensor(165[-0.2421, 0.4642, 0.2507, -0.0438, 0.0682, 0.3160, -0.2018, -0.0727, 0.2485]166)167168self.assertTrue(torch_all_close(output_slice, expected_output_slice, rtol=1e-2))169170171@slow172class AutoencoderKLIntegrationTests(unittest.TestCase):173def get_file_format(self, seed, shape):174return f"gaussian_noise_s={seed}_shape={'_'.join([str(s) for s in shape])}.npy"175176def tearDown(self):177# clean up the VRAM after each test178super().tearDown()179gc.collect()180torch.cuda.empty_cache()181182def get_sd_image(self, seed=0, shape=(4, 3, 512, 512), fp16=False):183dtype = torch.float16 if fp16 else torch.float32184image = torch.from_numpy(load_hf_numpy(self.get_file_format(seed, shape))).to(torch_device).to(dtype)185return image186187def get_sd_vae_model(self, model_id="CompVis/stable-diffusion-v1-4", fp16=False):188revision = "fp16" if fp16 else None189torch_dtype = torch.float16 if fp16 else torch.float32190191model = AutoencoderKL.from_pretrained(192model_id,193subfolder="vae",194torch_dtype=torch_dtype,195revision=revision,196)197model.to(torch_device).eval()198199return model200201def get_generator(self, seed=0):202if torch_device == "mps":203return torch.manual_seed(seed)204return torch.Generator(device=torch_device).manual_seed(seed)205206@parameterized.expand(207[208# fmt: off209[33, [-0.1603, 0.9878, -0.0495, -0.0790, -0.2709, 0.8375, -0.2060, -0.0824], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],210[47, [-0.2376, 0.1168, 0.1332, -0.4840, -0.2508, -0.0791, -0.0493, -0.4089], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],211# fmt: on212]213)214def test_stable_diffusion(self, seed, expected_slice, expected_slice_mps):215model = self.get_sd_vae_model()216image = self.get_sd_image(seed)217generator = self.get_generator(seed)218219with torch.no_grad():220sample = model(image, generator=generator, sample_posterior=True).sample221222assert sample.shape == image.shape223224output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()225expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)226227assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)228229@parameterized.expand(230[231# fmt: off232[33, [-0.0513, 0.0289, 1.3799, 0.2166, -0.2573, -0.0871, 0.5103, -0.0999]],233[47, [-0.4128, -0.1320, -0.3704, 0.1965, -0.4116, -0.2332, -0.3340, 0.2247]],234# fmt: on235]236)237@require_torch_gpu238def test_stable_diffusion_fp16(self, seed, expected_slice):239model = self.get_sd_vae_model(fp16=True)240image = self.get_sd_image(seed, fp16=True)241generator = self.get_generator(seed)242243with torch.no_grad():244sample = model(image, generator=generator, sample_posterior=True).sample245246assert sample.shape == image.shape247248output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu()249expected_output_slice = torch.tensor(expected_slice)250251assert torch_all_close(output_slice, expected_output_slice, atol=1e-2)252253@parameterized.expand(254[255# fmt: off256[33, [-0.1609, 0.9866, -0.0487, -0.0777, -0.2716, 0.8368, -0.2055, -0.0814], [-0.2395, 0.0098, 0.0102, -0.0709, -0.2840, -0.0274, -0.0718, -0.1824]],257[47, [-0.2377, 0.1147, 0.1333, -0.4841, -0.2506, -0.0805, -0.0491, -0.4085], [0.0350, 0.0847, 0.0467, 0.0344, -0.0842, -0.0547, -0.0633, -0.1131]],258# fmt: on259]260)261def test_stable_diffusion_mode(self, seed, expected_slice, expected_slice_mps):262model = self.get_sd_vae_model()263image = self.get_sd_image(seed)264265with torch.no_grad():266sample = model(image).sample267268assert sample.shape == image.shape269270output_slice = sample[-1, -2:, -2:, :2].flatten().float().cpu()271expected_output_slice = torch.tensor(expected_slice_mps if torch_device == "mps" else expected_slice)272273assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)274275@parameterized.expand(276[277# fmt: off278[13, [-0.2051, -0.1803, -0.2311, -0.2114, -0.3292, -0.3574, -0.2953, -0.3323]],279[37, [-0.2632, -0.2625, -0.2199, -0.2741, -0.4539, -0.4990, -0.3720, -0.4925]],280# fmt: on281]282)283@require_torch_gpu284def test_stable_diffusion_decode(self, seed, expected_slice):285model = self.get_sd_vae_model()286encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64))287288with torch.no_grad():289sample = model.decode(encoding).sample290291assert list(sample.shape) == [3, 3, 512, 512]292293output_slice = sample[-1, -2:, :2, -2:].flatten().cpu()294expected_output_slice = torch.tensor(expected_slice)295296assert torch_all_close(output_slice, expected_output_slice, atol=1e-3)297298@parameterized.expand(299[300# fmt: off301[27, [-0.0369, 0.0207, -0.0776, -0.0682, -0.1747, -0.1930, -0.1465, -0.2039]],302[16, [-0.1628, -0.2134, -0.2747, -0.2642, -0.3774, -0.4404, -0.3687, -0.4277]],303# fmt: on304]305)306@require_torch_gpu307def test_stable_diffusion_decode_fp16(self, seed, expected_slice):308model = self.get_sd_vae_model(fp16=True)309encoding = self.get_sd_image(seed, shape=(3, 4, 64, 64), fp16=True)310311with torch.no_grad():312sample = model.decode(encoding).sample313314assert list(sample.shape) == [3, 3, 512, 512]315316output_slice = sample[-1, -2:, :2, -2:].flatten().float().cpu()317expected_output_slice = torch.tensor(expected_slice)318319assert torch_all_close(output_slice, expected_output_slice, atol=5e-3)320321@parameterized.expand(322[323# fmt: off324[33, [-0.3001, 0.0918, -2.6984, -3.9720, -3.2099, -5.0353, 1.7338, -0.2065, 3.4267]],325[47, [-1.5030, -4.3871, -6.0355, -9.1157, -1.6661, -2.7853, 2.1607, -5.0823, 2.5633]],326# fmt: on327]328)329def test_stable_diffusion_encode_sample(self, seed, expected_slice):330model = self.get_sd_vae_model()331image = self.get_sd_image(seed)332generator = self.get_generator(seed)333334with torch.no_grad():335dist = model.encode(image).latent_dist336sample = dist.sample(generator=generator)337338assert list(sample.shape) == [image.shape[0], 4] + [i // 8 for i in image.shape[2:]]339340output_slice = sample[0, -1, -3:, -3:].flatten().cpu()341expected_output_slice = torch.tensor(expected_slice)342343tolerance = 1e-3 if torch_device != "mps" else 1e-2344assert torch_all_close(output_slice, expected_output_slice, atol=tolerance)345346347