Path: blob/main/tests/fixtures/custom_pipeline/what_ever.py
1451 views
# Copyright 2023 The HuggingFace Team. All rights reserved.1#2# Licensed under the Apache License, Version 2.0 (the "License");3# you may not use this file except in compliance with the License.4# You may obtain a copy of the License at5#6# http://www.apache.org/licenses/LICENSE-2.07#8# Unless required by applicable law or agreed to in writing, software9# distributed under the License is distributed on an "AS IS" BASIS,10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11# See the License for the specific language governing permissions and1213# limitations under the License.141516from typing import Optional, Tuple, Union1718import torch1920from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput212223class CustomLocalPipeline(DiffusionPipeline):24r"""25This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the26library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)2728Parameters:29unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.30scheduler ([`SchedulerMixin`]):31A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of32[`DDPMScheduler`], or [`DDIMScheduler`].33"""3435def __init__(self, unet, scheduler):36super().__init__()37self.register_modules(unet=unet, scheduler=scheduler)3839@torch.no_grad()40def __call__(41self,42batch_size: int = 1,43generator: Optional[torch.Generator] = None,44num_inference_steps: int = 50,45output_type: Optional[str] = "pil",46return_dict: bool = True,47**kwargs,48) -> Union[ImagePipelineOutput, Tuple]:49r"""50Args:51batch_size (`int`, *optional*, defaults to 1):52The number of images to generate.53generator (`torch.Generator`, *optional*):54A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation55deterministic.56eta (`float`, *optional*, defaults to 0.0):57The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).58num_inference_steps (`int`, *optional*, defaults to 50):59The number of denoising steps. More denoising steps usually lead to a higher quality image at the60expense of slower inference.61output_type (`str`, *optional*, defaults to `"pil"`):62The output format of the generate image. Choose between63[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.64return_dict (`bool`, *optional*, defaults to `True`):65Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.6667Returns:68[`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if69`return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the70generated images.71"""7273# Sample gaussian noise to begin loop74image = torch.randn(75(batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),76generator=generator,77)78image = image.to(self.device)7980# set step values81self.scheduler.set_timesteps(num_inference_steps)8283for t in self.progress_bar(self.scheduler.timesteps):84# 1. predict noise model_output85model_output = self.unet(image, t).sample8687# 2. predict previous mean of image x_t-1 and add variance depending on eta88# eta corresponds to η in paper and should be between [0, 1]89# do x_t -> x_t-190image = self.scheduler.step(model_output, t, image).prev_sample9192image = (image / 2 + 0.5).clamp(0, 1)93image = image.cpu().permute(0, 2, 3, 1).numpy()94if output_type == "pil":95image = self.numpy_to_pil(image)9697if not return_dict:98return (image,), "This is a local test"99100return ImagePipelineOutput(images=image), "This is a local test"101102103