Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
shivamshrirao
GitHub Repository: shivamshrirao/diffusers
Path: blob/main/tests/fixtures/custom_pipeline/what_ever.py
1451 views
1
# Copyright 2023 The HuggingFace Team. All rights reserved.
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 at
6
#
7
# http://www.apache.org/licenses/LICENSE-2.0
8
#
9
# Unless required by applicable law or agreed to in writing, software
10
# 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 and
13
14
# limitations under the License.
15
16
17
from typing import Optional, Tuple, Union
18
19
import torch
20
21
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
22
23
24
class CustomLocalPipeline(DiffusionPipeline):
25
r"""
26
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
27
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
28
29
Parameters:
30
unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
31
scheduler ([`SchedulerMixin`]):
32
A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
33
[`DDPMScheduler`], or [`DDIMScheduler`].
34
"""
35
36
def __init__(self, unet, scheduler):
37
super().__init__()
38
self.register_modules(unet=unet, scheduler=scheduler)
39
40
@torch.no_grad()
41
def __call__(
42
self,
43
batch_size: int = 1,
44
generator: Optional[torch.Generator] = None,
45
num_inference_steps: int = 50,
46
output_type: Optional[str] = "pil",
47
return_dict: bool = True,
48
**kwargs,
49
) -> Union[ImagePipelineOutput, Tuple]:
50
r"""
51
Args:
52
batch_size (`int`, *optional*, defaults to 1):
53
The number of images to generate.
54
generator (`torch.Generator`, *optional*):
55
A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
56
deterministic.
57
eta (`float`, *optional*, defaults to 0.0):
58
The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).
59
num_inference_steps (`int`, *optional*, defaults to 50):
60
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
61
expense of slower inference.
62
output_type (`str`, *optional*, defaults to `"pil"`):
63
The output format of the generate image. Choose between
64
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
65
return_dict (`bool`, *optional*, defaults to `True`):
66
Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
67
68
Returns:
69
[`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
70
`return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
71
generated images.
72
"""
73
74
# Sample gaussian noise to begin loop
75
image = torch.randn(
76
(batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),
77
generator=generator,
78
)
79
image = image.to(self.device)
80
81
# set step values
82
self.scheduler.set_timesteps(num_inference_steps)
83
84
for t in self.progress_bar(self.scheduler.timesteps):
85
# 1. predict noise model_output
86
model_output = self.unet(image, t).sample
87
88
# 2. predict previous mean of image x_t-1 and add variance depending on eta
89
# eta corresponds to η in paper and should be between [0, 1]
90
# do x_t -> x_t-1
91
image = self.scheduler.step(model_output, t, image).prev_sample
92
93
image = (image / 2 + 0.5).clamp(0, 1)
94
image = image.cpu().permute(0, 2, 3, 1).numpy()
95
if output_type == "pil":
96
image = self.numpy_to_pil(image)
97
98
if not return_dict:
99
return (image,), "This is a local test"
100
101
return ImagePipelineOutput(images=image), "This is a local test"
102
103