giulio98 commited on
Commit
7b49c9d
1 Parent(s): 79b0e2c

Create pipeline.py

Browse files
Files changed (1) hide show
  1. pipeline.py +82 -0
pipeline.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import Optional, Union, List, Tuple
2
+
3
+ import torch
4
+ from diffusers.utils.torch_utils import randn_tensor
5
+ from diffusers.pipelines.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
6
+
7
+
8
+ class ScoreSdeVePipeline(DiffusionPipeline):
9
+ r"""
10
+ Pipeline for unconditional image generation.
11
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods
12
+ implemented for all pipelines (downloading, saving, running on a particular device, etc.).
13
+ Parameters:
14
+ unet ([`UNet2DModel`]):
15
+ A `UNet2DModel` to denoise the encoded image.
16
+ scheduler ([`ScoreSdeVeScheduler`]):
17
+ A `ScoreSdeVeScheduler` to be used in combination with `unet` to denoise the encoded image.
18
+ """
19
+ def __init__(self, unet, scheduler):
20
+ super().__init__()
21
+ self.register_modules(unet=unet, scheduler=scheduler)
22
+
23
+ @torch.no_grad()
24
+ def __call__(
25
+ self,
26
+ batch_size: int = 1,
27
+ num_inference_steps: int = 2000,
28
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
29
+ output_type: Optional[str] = "pil",
30
+ return_dict: bool = True,
31
+ **kwargs,
32
+ ) -> Union[ImagePipelineOutput, Tuple]:
33
+ r"""
34
+ The call function to the pipeline for generation.
35
+ Args:
36
+ batch_size (`int`, *optional*, defaults to 1):
37
+ The number of images to generate.
38
+ generator (`torch.Generator`, `optional`):
39
+ A [`torch.Generator`](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make
40
+ generation deterministic.
41
+ output_type (`str`, `optional`, defaults to `"pil"`):
42
+ The output format of the generated image. Choose between `PIL.Image` or `np.array`.
43
+ return_dict (`bool`, *optional*, defaults to `True`):
44
+ Whether or not to return a [`ImagePipelineOutput`] instead of a plain tuple.
45
+ Returns:
46
+ [`~pipelines.ImagePipelineOutput`] or `tuple`:
47
+ If `return_dict` is `True`, [`~pipelines.ImagePipelineOutput`] is returned, otherwise a `tuple` is
48
+ returned where the first element is a list with the generated images.
49
+ """
50
+ img_size = self.unet.config.sample_size
51
+ shape = (batch_size, 3, img_size, img_size)
52
+
53
+ model = self.unet
54
+
55
+ sample = randn_tensor(shape, generator=generator, device=self.device) * self.scheduler.init_noise_sigma
56
+ sample = sample.to(self.device)
57
+
58
+ self.scheduler.set_timesteps(num_inference_steps)
59
+ self.scheduler.set_sigmas(num_inference_steps)
60
+
61
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
62
+ sigma_t = self.scheduler.sigmas[i] * torch.ones(shape[0], device=self.device)
63
+
64
+ # correction step
65
+ for _ in range(self.scheduler.config.correct_steps):
66
+ model_output = self.unet(sample, sigma_t).sample
67
+ sample = self.scheduler.step_correct(model_output, sample, generator=generator).prev_sample
68
+
69
+ # prediction step
70
+ model_output = model(sample, sigma_t).sample
71
+ output = self.scheduler.step_pred(model_output, t, sample, generator=generator)
72
+
73
+ sample, sample_mean = output.prev_sample, output.prev_sample_mean
74
+
75
+ sample = sample_mean.clamp(0, 1)
76
+ sample = sample.cpu().permute(0, 2, 3, 1).numpy()
77
+ if output_type == "pil":
78
+ sample = self.numpy_to_pil(sample)
79
+
80
+ if not return_dict:
81
+ return (sample,)
82
+ return ImagePipelineOutput(images=sample)