Moyao001 commited on
Commit
f0439ba
·
verified ·
1 Parent(s): 6af5d30

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000014473.jpg +3 -0
  2. CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000017379.jpg +3 -0
  3. CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000017905.jpg +3 -0
  4. pix2video-main/mydiffusers/mydiffusers/pipelines/__pycache__/__init__.cpython-313.pyc +0 -0
  5. pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/__init__.cpython-38.pyc +0 -0
  6. pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/modeling_roberta_series.cpython-313.pyc +0 -0
  7. pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/pipeline_alt_diffusion_img2img.cpython-313.pyc +0 -0
  8. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__init__.py +2 -0
  9. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/__init__.cpython-313.pyc +0 -0
  10. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/__init__.cpython-38.pyc +0 -0
  11. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/pipeline_ddim.cpython-313.pyc +0 -0
  12. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/pipeline_ddim.cpython-38.pyc +0 -0
  13. pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/pipeline_ddim.py +126 -0
  14. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__init__.py +2 -0
  15. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/__init__.cpython-313.pyc +0 -0
  16. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/__init__.cpython-38.pyc +0 -0
  17. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/pipeline_pndm.cpython-313.pyc +0 -0
  18. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/pipeline_pndm.cpython-38.pyc +0 -0
  19. pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/pipeline_pndm.py +96 -0
  20. pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__init__.py +1 -0
  21. pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/__init__.cpython-313.pyc +0 -0
  22. pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/pipeline_repaint.cpython-313.pyc +0 -0
  23. pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/pipeline_repaint.cpython-38.pyc +0 -0
  24. pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/pipeline_repaint.py +140 -0
  25. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__init__.py +101 -0
  26. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/__init__.cpython-313.pyc +0 -0
  27. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/__init__.cpython-38.pyc +0 -0
  28. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_cycle_diffusion.cpython-313.pyc +0 -0
  29. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_cycle_diffusion.cpython-38.pyc +0 -0
  30. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-313.pyc +0 -0
  31. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-38.pyc +0 -0
  32. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_depth2img.cpython-313.pyc +0 -0
  33. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_depth2img.cpython-38.pyc +0 -0
  34. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_image_variation.cpython-313.pyc +0 -0
  35. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_image_variation.cpython-38.pyc +0 -0
  36. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_img2img.cpython-313.pyc +0 -0
  37. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_img2img.cpython-38.pyc +0 -0
  38. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint.cpython-313.pyc +0 -0
  39. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint.cpython-38.pyc +0 -0
  40. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint_legacy.cpython-313.pyc +0 -0
  41. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint_legacy.cpython-38.pyc +0 -0
  42. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_upscale.cpython-313.pyc +0 -0
  43. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_upscale.cpython-38.pyc +0 -0
  44. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/safety_checker.cpython-313.pyc +0 -0
  45. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/safety_checker.cpython-38.pyc +0 -0
  46. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py +653 -0
  47. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py +353 -0
  48. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py +459 -0
  49. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py +478 -0
  50. pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py +461 -0
CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000014473.jpg ADDED

Git LFS Details

  • SHA256: 1b0fad3e8260366a27f9cb20fdd0f9d7c669bb40a535f6364b8c2e1c03d7b5c2
  • Pointer size: 131 Bytes
  • Size of remote file: 166 kB
CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000017379.jpg ADDED

Git LFS Details

  • SHA256: 52b592adcb73170d7d07994a8781e92feddf3c7f1c45173a050c7ecfe12e7743
  • Pointer size: 131 Bytes
  • Size of remote file: 180 kB
CCEdit-main/src/taming-transformers/data/coco_annotations_100/val2017/000000017905.jpg ADDED

Git LFS Details

  • SHA256: 5fcff2c9895b398fa086180c2fbe39b17a4e07d47282bd0b184599764afba33d
  • Pointer size: 131 Bytes
  • Size of remote file: 185 kB
pix2video-main/mydiffusers/mydiffusers/pipelines/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (3.66 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (1.64 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/modeling_roberta_series.cpython-313.pyc ADDED
Binary file (5.81 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/alt_diffusion/__pycache__/pipeline_alt_diffusion_img2img.cpython-313.pyc ADDED
Binary file (29.5 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # flake8: noqa
2
+ from .pipeline_ddim import DDIMPipeline
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (233 Bytes). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (214 Bytes). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/pipeline_ddim.cpython-313.pyc ADDED
Binary file (6.19 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/__pycache__/pipeline_ddim.cpython-38.pyc ADDED
Binary file (4.53 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/ddim/pipeline_ddim.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+ from typing import Optional, Tuple, Union
16
+
17
+ import torch
18
+
19
+ from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
20
+ from ...utils import deprecate
21
+
22
+
23
+ class DDIMPipeline(DiffusionPipeline):
24
+ r"""
25
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
26
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
27
+
28
+ Parameters:
29
+ unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
30
+ scheduler ([`SchedulerMixin`]):
31
+ A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
32
+ [`DDPMScheduler`], or [`DDIMScheduler`].
33
+ """
34
+
35
+ def __init__(self, unet, scheduler):
36
+ super().__init__()
37
+ self.register_modules(unet=unet, scheduler=scheduler)
38
+
39
+ @torch.no_grad()
40
+ def __call__(
41
+ self,
42
+ batch_size: int = 1,
43
+ generator: Optional[torch.Generator] = None,
44
+ eta: float = 0.0,
45
+ num_inference_steps: int = 50,
46
+ use_clipped_model_output: Optional[bool] = None,
47
+ output_type: Optional[str] = "pil",
48
+ return_dict: bool = True,
49
+ **kwargs,
50
+ ) -> Union[ImagePipelineOutput, Tuple]:
51
+ r"""
52
+ Args:
53
+ batch_size (`int`, *optional*, defaults to 1):
54
+ The number of images to generate.
55
+ generator (`torch.Generator`, *optional*):
56
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
57
+ deterministic.
58
+ eta (`float`, *optional*, defaults to 0.0):
59
+ The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).
60
+ num_inference_steps (`int`, *optional*, defaults to 50):
61
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
62
+ expense of slower inference.
63
+ use_clipped_model_output (`bool`, *optional*, defaults to `None`):
64
+ if `True` or `False`, see documentation for `DDIMScheduler.step`. If `None`, nothing is passed
65
+ downstream to the scheduler. So use `None` for schedulers which don't support this argument.
66
+ output_type (`str`, *optional*, defaults to `"pil"`):
67
+ The output format of the generate image. Choose between
68
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
69
+ return_dict (`bool`, *optional*, defaults to `True`):
70
+ Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
71
+
72
+ Returns:
73
+ [`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
74
+ `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
75
+ generated images.
76
+ """
77
+
78
+ if generator is not None and generator.device.type != self.device.type and self.device.type != "mps":
79
+ message = (
80
+ f"The `generator` device is `{generator.device}` and does not match the pipeline "
81
+ f"device `{self.device}`, so the `generator` will be ignored. "
82
+ f'Please use `generator=torch.Generator(device="{self.device}")` instead.'
83
+ )
84
+ deprecate(
85
+ "generator.device == 'cpu'",
86
+ "0.11.0",
87
+ message,
88
+ )
89
+ generator = None
90
+
91
+ # Sample gaussian noise to begin loop
92
+ if isinstance(self.unet.sample_size, int):
93
+ image_shape = (batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size)
94
+ else:
95
+ image_shape = (batch_size, self.unet.in_channels, *self.unet.sample_size)
96
+
97
+ if self.device.type == "mps":
98
+ # randn does not work reproducibly on mps
99
+ image = torch.randn(image_shape, generator=generator, dtype=self.unet.dtype)
100
+ image = image.to(self.device)
101
+ else:
102
+ image = torch.randn(image_shape, generator=generator, device=self.device, dtype=self.unet.dtype)
103
+
104
+ # set step values
105
+ self.scheduler.set_timesteps(num_inference_steps)
106
+
107
+ for t in self.progress_bar(self.scheduler.timesteps):
108
+ # 1. predict noise model_output
109
+ model_output = self.unet(image, t).sample
110
+
111
+ # 2. predict previous mean of image x_t-1 and add variance depending on eta
112
+ # eta corresponds to η in paper and should be between [0, 1]
113
+ # do x_t -> x_t-1
114
+ image = self.scheduler.step(
115
+ model_output, t, image, eta=eta, use_clipped_model_output=use_clipped_model_output, generator=generator
116
+ ).prev_sample
117
+
118
+ image = (image / 2 + 0.5).clamp(0, 1)
119
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
120
+ if output_type == "pil":
121
+ image = self.numpy_to_pil(image)
122
+
123
+ if not return_dict:
124
+ return (image,)
125
+
126
+ return ImagePipelineOutput(images=image)
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__init__.py ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ # flake8: noqa
2
+ from .pipeline_pndm import PNDMPipeline
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (233 Bytes). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (214 Bytes). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/pipeline_pndm.cpython-313.pyc ADDED
Binary file (4.49 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/__pycache__/pipeline_pndm.cpython-38.pyc ADDED
Binary file (3.49 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/pndm/pipeline_pndm.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+
16
+ from typing import Optional, Tuple, Union
17
+
18
+ import torch
19
+
20
+ from ...models import UNet2DModel
21
+ from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
22
+ from ...schedulers import PNDMScheduler
23
+
24
+
25
+ class PNDMPipeline(DiffusionPipeline):
26
+ r"""
27
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
28
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
29
+
30
+ Parameters:
31
+ unet (`UNet2DModel`): U-Net architecture to denoise the encoded image latents.
32
+ scheduler ([`SchedulerMixin`]):
33
+ The `PNDMScheduler` to be used in combination with `unet` to denoise the encoded image.
34
+ """
35
+
36
+ unet: UNet2DModel
37
+ scheduler: PNDMScheduler
38
+
39
+ def __init__(self, unet: UNet2DModel, scheduler: PNDMScheduler):
40
+ super().__init__()
41
+ self.register_modules(unet=unet, scheduler=scheduler)
42
+
43
+ @torch.no_grad()
44
+ def __call__(
45
+ self,
46
+ batch_size: int = 1,
47
+ num_inference_steps: int = 50,
48
+ generator: Optional[torch.Generator] = None,
49
+ output_type: Optional[str] = "pil",
50
+ return_dict: bool = True,
51
+ **kwargs,
52
+ ) -> Union[ImagePipelineOutput, Tuple]:
53
+ r"""
54
+ Args:
55
+ batch_size (`int`, `optional`, defaults to 1): The number of images to generate.
56
+ num_inference_steps (`int`, `optional`, defaults to 50):
57
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
58
+ expense of slower inference.
59
+ generator (`torch.Generator`, `optional`): A [torch
60
+ generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
61
+ deterministic.
62
+ output_type (`str`, `optional`, defaults to `"pil"`): The output format of the generate image. Choose
63
+ between [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
64
+ return_dict (`bool`, `optional`, defaults to `True`): Whether or not to return a
65
+ [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
66
+
67
+ Returns:
68
+ [`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
69
+ `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
70
+ generated images.
71
+ """
72
+ # For more information on the sampling method you can take a look at Algorithm 2 of
73
+ # the official paper: https://arxiv.org/pdf/2202.09778.pdf
74
+
75
+ # Sample gaussian noise to begin loop
76
+ image = torch.randn(
77
+ (batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),
78
+ generator=generator,
79
+ )
80
+ image = image.to(self.device)
81
+
82
+ self.scheduler.set_timesteps(num_inference_steps)
83
+ for t in self.progress_bar(self.scheduler.timesteps):
84
+ model_output = self.unet(image, t).sample
85
+
86
+ image = self.scheduler.step(model_output, t, image).prev_sample
87
+
88
+ image = (image / 2 + 0.5).clamp(0, 1)
89
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
90
+ if output_type == "pil":
91
+ image = self.numpy_to_pil(image)
92
+
93
+ if not return_dict:
94
+ return (image,)
95
+
96
+ return ImagePipelineOutput(images=image)
pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__init__.py ADDED
@@ -0,0 +1 @@
 
 
1
+ from .pipeline_repaint import RePaintPipeline
pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (242 Bytes). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/pipeline_repaint.cpython-313.pyc ADDED
Binary file (7.1 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/__pycache__/pipeline_repaint.cpython-38.pyc ADDED
Binary file (4.97 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/repaint/pipeline_repaint.py ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 ETH Zurich Computer Vision Lab and 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
+ # limitations under the License.
14
+
15
+
16
+ from typing import Optional, Tuple, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ import PIL
22
+ from tqdm.auto import tqdm
23
+
24
+ from ...models import UNet2DModel
25
+ from ...pipeline_utils import DiffusionPipeline, ImagePipelineOutput
26
+ from ...schedulers import RePaintScheduler
27
+
28
+
29
+ def _preprocess_image(image: PIL.Image.Image):
30
+ image = np.array(image.convert("RGB"))
31
+ image = image[None].transpose(0, 3, 1, 2)
32
+ image = torch.from_numpy(image).to(dtype=torch.float32) / 127.5 - 1.0
33
+ return image
34
+
35
+
36
+ def _preprocess_mask(mask: PIL.Image.Image):
37
+ mask = np.array(mask.convert("L"))
38
+ mask = mask.astype(np.float32) / 255.0
39
+ mask = mask[None, None]
40
+ mask[mask < 0.5] = 0
41
+ mask[mask >= 0.5] = 1
42
+ mask = torch.from_numpy(mask)
43
+ return mask
44
+
45
+
46
+ class RePaintPipeline(DiffusionPipeline):
47
+ unet: UNet2DModel
48
+ scheduler: RePaintScheduler
49
+
50
+ def __init__(self, unet, scheduler):
51
+ super().__init__()
52
+ self.register_modules(unet=unet, scheduler=scheduler)
53
+
54
+ @torch.no_grad()
55
+ def __call__(
56
+ self,
57
+ original_image: Union[torch.FloatTensor, PIL.Image.Image],
58
+ mask_image: Union[torch.FloatTensor, PIL.Image.Image],
59
+ num_inference_steps: int = 250,
60
+ eta: float = 0.0,
61
+ jump_length: int = 10,
62
+ jump_n_sample: int = 10,
63
+ generator: Optional[torch.Generator] = None,
64
+ output_type: Optional[str] = "pil",
65
+ return_dict: bool = True,
66
+ ) -> Union[ImagePipelineOutput, Tuple]:
67
+ r"""
68
+ Args:
69
+ original_image (`torch.FloatTensor` or `PIL.Image.Image`):
70
+ The original image to inpaint on.
71
+ mask_image (`torch.FloatTensor` or `PIL.Image.Image`):
72
+ The mask_image where 0.0 values define which part of the original image to inpaint (change).
73
+ num_inference_steps (`int`, *optional*, defaults to 1000):
74
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
75
+ expense of slower inference.
76
+ eta (`float`):
77
+ The weight of noise for added noise in a diffusion step. Its value is between 0.0 and 1.0 - 0.0 is DDIM
78
+ and 1.0 is DDPM scheduler respectively.
79
+ jump_length (`int`, *optional*, defaults to 10):
80
+ The number of steps taken forward in time before going backward in time for a single jump ("j" in
81
+ RePaint paper). Take a look at Figure 9 and 10 in https://arxiv.org/pdf/2201.09865.pdf.
82
+ jump_n_sample (`int`, *optional*, defaults to 10):
83
+ The number of times we will make forward time jump for a given chosen time sample. Take a look at
84
+ Figure 9 and 10 in https://arxiv.org/pdf/2201.09865.pdf.
85
+ generator (`torch.Generator`, *optional*):
86
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
87
+ deterministic.
88
+ output_type (`str`, *optional*, defaults to `"pil"`):
89
+ The output format of the generate image. Choose between
90
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
91
+ return_dict (`bool`, *optional*, defaults to `True`):
92
+ Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
93
+
94
+ Returns:
95
+ [`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
96
+ `return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
97
+ generated images.
98
+ """
99
+
100
+ if not isinstance(original_image, torch.FloatTensor):
101
+ original_image = _preprocess_image(original_image)
102
+ original_image = original_image.to(self.device)
103
+ if not isinstance(mask_image, torch.FloatTensor):
104
+ mask_image = _preprocess_mask(mask_image)
105
+ mask_image = mask_image.to(self.device)
106
+
107
+ # sample gaussian noise to begin the loop
108
+ image = torch.randn(
109
+ original_image.shape,
110
+ generator=generator,
111
+ device=self.device,
112
+ )
113
+ image = image.to(self.device)
114
+
115
+ # set step values
116
+ self.scheduler.set_timesteps(num_inference_steps, jump_length, jump_n_sample, self.device)
117
+ self.scheduler.eta = eta
118
+
119
+ t_last = self.scheduler.timesteps[0] + 1
120
+ for i, t in enumerate(tqdm(self.scheduler.timesteps)):
121
+ if t < t_last:
122
+ # predict the noise residual
123
+ model_output = self.unet(image, t).sample
124
+ # compute previous image: x_t -> x_t-1
125
+ image = self.scheduler.step(model_output, t, image, original_image, mask_image, generator).prev_sample
126
+
127
+ else:
128
+ # compute the reverse: x_t-1 -> x_t
129
+ image = self.scheduler.undo_step(image, t_last, generator)
130
+ t_last = t
131
+
132
+ image = (image / 2 + 0.5).clamp(0, 1)
133
+ image = image.cpu().permute(0, 2, 3, 1).numpy()
134
+ if output_type == "pil":
135
+ image = self.numpy_to_pil(image)
136
+
137
+ if not return_dict:
138
+ return (image,)
139
+
140
+ return ImagePipelineOutput(images=image)
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__init__.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from dataclasses import dataclass
2
+ from typing import List, Optional, Union
3
+
4
+ import numpy as np
5
+
6
+ import PIL
7
+ from PIL import Image
8
+
9
+ from ...utils import (
10
+ BaseOutput,
11
+ OptionalDependencyNotAvailable,
12
+ is_flax_available,
13
+ is_k_diffusion_available,
14
+ is_onnx_available,
15
+ is_torch_available,
16
+ is_transformers_available,
17
+ is_transformers_version,
18
+ )
19
+
20
+
21
+ @dataclass
22
+ class StableDiffusionPipelineOutput(BaseOutput):
23
+ """
24
+ Output class for Stable Diffusion pipelines.
25
+
26
+ Args:
27
+ images (`List[PIL.Image.Image]` or `np.ndarray`)
28
+ List of denoised PIL images of length `batch_size` or numpy array of shape `(batch_size, height, width,
29
+ num_channels)`. PIL images or numpy array present the denoised images of the diffusion pipeline.
30
+ nsfw_content_detected (`List[bool]`)
31
+ List of flags denoting whether the corresponding generated image likely represents "not-safe-for-work"
32
+ (nsfw) content, or `None` if safety checking could not be performed.
33
+ """
34
+
35
+ images: Union[List[PIL.Image.Image], np.ndarray]
36
+ nsfw_content_detected: Optional[List[bool]]
37
+
38
+
39
+ if is_transformers_available() and is_torch_available():
40
+ from .pipeline_cycle_diffusion import CycleDiffusionPipeline
41
+ from .pipeline_stable_diffusion import StableDiffusionPipeline
42
+ from .pipeline_stable_diffusion_img2img import StableDiffusionImg2ImgPipeline
43
+ from .pipeline_stable_diffusion_inpaint import StableDiffusionInpaintPipeline
44
+ from .pipeline_stable_diffusion_inpaint_legacy import StableDiffusionInpaintPipelineLegacy
45
+ from .pipeline_stable_diffusion_upscale import StableDiffusionUpscalePipeline
46
+ from .safety_checker import StableDiffusionSafetyChecker
47
+
48
+ try:
49
+ if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.25.0")):
50
+ raise OptionalDependencyNotAvailable()
51
+ except OptionalDependencyNotAvailable:
52
+ from ...utils.dummy_torch_and_transformers_objects import StableDiffusionImageVariationPipeline
53
+ else:
54
+ from .pipeline_stable_diffusion_image_variation import StableDiffusionImageVariationPipeline
55
+
56
+
57
+ try:
58
+ if not (is_transformers_available() and is_torch_available() and is_transformers_version(">=", "4.26.0.dev0")):
59
+ raise OptionalDependencyNotAvailable()
60
+ except OptionalDependencyNotAvailable:
61
+ from ...utils.dummy_torch_and_transformers_objects import StableDiffusionDepth2ImgPipeline
62
+ else:
63
+ from .pipeline_stable_diffusion_depth2img import StableDiffusionDepth2ImgPipeline
64
+
65
+
66
+ try:
67
+ if not (is_torch_available() and is_transformers_available() and is_k_diffusion_available()):
68
+ raise OptionalDependencyNotAvailable()
69
+ except OptionalDependencyNotAvailable:
70
+ from ...utils.dummy_torch_and_transformers_and_k_diffusion_objects import * # noqa F403
71
+ else:
72
+ from .pipeline_stable_diffusion_k_diffusion import StableDiffusionKDiffusionPipeline
73
+
74
+ if is_transformers_available() and is_onnx_available():
75
+ from .pipeline_onnx_stable_diffusion import OnnxStableDiffusionPipeline, StableDiffusionOnnxPipeline
76
+ from .pipeline_onnx_stable_diffusion_img2img import OnnxStableDiffusionImg2ImgPipeline
77
+ from .pipeline_onnx_stable_diffusion_inpaint import OnnxStableDiffusionInpaintPipeline
78
+ from .pipeline_onnx_stable_diffusion_inpaint_legacy import OnnxStableDiffusionInpaintPipelineLegacy
79
+
80
+ if is_transformers_available() and is_flax_available():
81
+ import flax
82
+
83
+ @flax.struct.dataclass
84
+ class FlaxStableDiffusionPipelineOutput(BaseOutput):
85
+ """
86
+ Output class for Stable Diffusion pipelines.
87
+
88
+ Args:
89
+ images (`np.ndarray`)
90
+ Array of shape `(batch_size, height, width, num_channels)` with images from the diffusion pipeline.
91
+ nsfw_content_detected (`List[bool]`)
92
+ List of flags denoting whether the corresponding generated image likely represents "not-safe-for-work"
93
+ (nsfw) content.
94
+ """
95
+
96
+ images: np.ndarray
97
+ nsfw_content_detected: List[bool]
98
+
99
+ from ...schedulers.scheduling_pndm_flax import PNDMSchedulerState
100
+ from .pipeline_flax_stable_diffusion import FlaxStableDiffusionPipeline
101
+ from .safety_checker_flax import FlaxStableDiffusionSafetyChecker
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (5.13 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/__init__.cpython-38.pyc ADDED
Binary file (4.21 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_cycle_diffusion.cpython-313.pyc ADDED
Binary file (31.4 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_cycle_diffusion.cpython-38.pyc ADDED
Binary file (21.6 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-313.pyc ADDED
Binary file (27.4 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion.cpython-38.pyc ADDED
Binary file (19.6 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_depth2img.cpython-313.pyc ADDED
Binary file (28.5 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_depth2img.cpython-38.pyc ADDED
Binary file (19.5 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_image_variation.cpython-313.pyc ADDED
Binary file (22.3 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_image_variation.cpython-38.pyc ADDED
Binary file (16.1 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_img2img.cpython-313.pyc ADDED
Binary file (29.4 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_img2img.cpython-38.pyc ADDED
Binary file (20.7 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint.cpython-313.pyc ADDED
Binary file (34.7 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint.cpython-38.pyc ADDED
Binary file (23.7 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint_legacy.cpython-313.pyc ADDED
Binary file (30.7 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_inpaint_legacy.cpython-38.pyc ADDED
Binary file (21.5 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_upscale.cpython-313.pyc ADDED
Binary file (24.2 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/pipeline_stable_diffusion_upscale.cpython-38.pyc ADDED
Binary file (16.2 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/safety_checker.cpython-313.pyc ADDED
Binary file (6.51 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/__pycache__/safety_checker.cpython-38.pyc ADDED
Binary file (3.52 kB). View file
 
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_cycle_diffusion.py ADDED
@@ -0,0 +1,653 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ import PIL
22
+ from mydiffusers.utils import is_accelerate_available
23
+ from packaging import version
24
+ from transformers import CLIPFeatureExtractor, CLIPTextModel, CLIPTokenizer
25
+
26
+ from ...configuration_utils import FrozenDict
27
+ from ...models import AutoencoderKL, UNet2DConditionModel
28
+ from ...pipeline_utils import DiffusionPipeline
29
+ from ...schedulers import DDIMScheduler
30
+ from ...utils import PIL_INTERPOLATION, deprecate, logging
31
+ from . import StableDiffusionPipelineOutput
32
+ from .safety_checker import StableDiffusionSafetyChecker
33
+
34
+
35
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
36
+
37
+
38
+ def preprocess(image):
39
+ w, h = image.size
40
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
41
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
42
+ image = np.array(image).astype(np.float32) / 255.0
43
+ image = image[None].transpose(0, 3, 1, 2)
44
+ image = torch.from_numpy(image)
45
+ return 2.0 * image - 1.0
46
+
47
+
48
+ def posterior_sample(scheduler, latents, timestep, clean_latents, generator, eta):
49
+ # 1. get previous step value (=t-1)
50
+ prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
51
+
52
+ if prev_timestep <= 0:
53
+ return clean_latents
54
+
55
+ # 2. compute alphas, betas
56
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
57
+ alpha_prod_t_prev = (
58
+ scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
59
+ )
60
+
61
+ variance = scheduler._get_variance(timestep, prev_timestep)
62
+ std_dev_t = eta * variance ** (0.5)
63
+
64
+ # direction pointing to x_t
65
+ e_t = (latents - alpha_prod_t ** (0.5) * clean_latents) / (1 - alpha_prod_t) ** (0.5)
66
+ dir_xt = (1.0 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * e_t
67
+ noise = std_dev_t * torch.randn(
68
+ clean_latents.shape, dtype=clean_latents.dtype, device=clean_latents.device, generator=generator
69
+ )
70
+ prev_latents = alpha_prod_t_prev ** (0.5) * clean_latents + dir_xt + noise
71
+
72
+ return prev_latents
73
+
74
+
75
+ def compute_noise(scheduler, prev_latents, latents, timestep, noise_pred, eta):
76
+ # 1. get previous step value (=t-1)
77
+ prev_timestep = timestep - scheduler.config.num_train_timesteps // scheduler.num_inference_steps
78
+
79
+ # 2. compute alphas, betas
80
+ alpha_prod_t = scheduler.alphas_cumprod[timestep]
81
+ alpha_prod_t_prev = (
82
+ scheduler.alphas_cumprod[prev_timestep] if prev_timestep >= 0 else scheduler.final_alpha_cumprod
83
+ )
84
+
85
+ beta_prod_t = 1 - alpha_prod_t
86
+
87
+ # 3. compute predicted original sample from predicted noise also called
88
+ # "predicted x_0" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
89
+ pred_original_sample = (latents - beta_prod_t ** (0.5) * noise_pred) / alpha_prod_t ** (0.5)
90
+
91
+ # 4. Clip "predicted x_0"
92
+ if scheduler.config.clip_sample:
93
+ pred_original_sample = torch.clamp(pred_original_sample, -1, 1)
94
+
95
+ # 5. compute variance: "sigma_t(η)" -> see formula (16)
96
+ # σ_t = sqrt((1 − α_t−1)/(1 − α_t)) * sqrt(1 − α_t/α_t−1)
97
+ variance = scheduler._get_variance(timestep, prev_timestep)
98
+ std_dev_t = eta * variance ** (0.5)
99
+
100
+ # 6. compute "direction pointing to x_t" of formula (12) from https://arxiv.org/pdf/2010.02502.pdf
101
+ pred_sample_direction = (1 - alpha_prod_t_prev - std_dev_t**2) ** (0.5) * noise_pred
102
+
103
+ noise = (prev_latents - (alpha_prod_t_prev ** (0.5) * pred_original_sample + pred_sample_direction)) / (
104
+ variance ** (0.5) * eta
105
+ )
106
+ return noise
107
+
108
+
109
+ class CycleDiffusionPipeline(DiffusionPipeline):
110
+ r"""
111
+ Pipeline for text-guided image to image generation using Stable Diffusion.
112
+
113
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
114
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
115
+
116
+ Args:
117
+ vae ([`AutoencoderKL`]):
118
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
119
+ text_encoder ([`CLIPTextModel`]):
120
+ Frozen text-encoder. Stable Diffusion uses the text portion of
121
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
122
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
123
+ tokenizer (`CLIPTokenizer`):
124
+ Tokenizer of class
125
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
126
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
127
+ scheduler ([`SchedulerMixin`]):
128
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
129
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
130
+ safety_checker ([`StableDiffusionSafetyChecker`]):
131
+ Classification module that estimates whether generated images could be considered offensive or harmful.
132
+ Please, refer to the [model card](https://huggingface.co/CompVis/stable-diffusion-v1-4) for details.
133
+ feature_extractor ([`CLIPFeatureExtractor`]):
134
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
135
+ """
136
+ _optional_components = ["safety_checker", "feature_extractor"]
137
+
138
+ def __init__(
139
+ self,
140
+ vae: AutoencoderKL,
141
+ text_encoder: CLIPTextModel,
142
+ tokenizer: CLIPTokenizer,
143
+ unet: UNet2DConditionModel,
144
+ scheduler: DDIMScheduler,
145
+ safety_checker: StableDiffusionSafetyChecker,
146
+ feature_extractor: CLIPFeatureExtractor,
147
+ requires_safety_checker: bool = True,
148
+ ):
149
+ super().__init__()
150
+
151
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
152
+ deprecation_message = (
153
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
154
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
155
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
156
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
157
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
158
+ " file"
159
+ )
160
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
161
+ new_config = dict(scheduler.config)
162
+ new_config["steps_offset"] = 1
163
+ scheduler._internal_dict = FrozenDict(new_config)
164
+
165
+ if safety_checker is None and requires_safety_checker:
166
+ logger.warning(
167
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
168
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
169
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
170
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
171
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
172
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
173
+ )
174
+
175
+ if safety_checker is not None and feature_extractor is None:
176
+ raise ValueError(
177
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
178
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
179
+ )
180
+ is_unet_version_less_0_9_0 = hasattr(unet.config, "_mydiffusers_version") and version.parse(
181
+ version.parse(unet.config._mydiffusers_version).base_version
182
+ ) < version.parse("0.9.0.dev0")
183
+ is_unet_sample_size_less_64 = hasattr(unet.config, "sample_size") and unet.config.sample_size < 64
184
+ if is_unet_version_less_0_9_0 and is_unet_sample_size_less_64:
185
+ deprecation_message = (
186
+ "The configuration file of the unet has set the default `sample_size` to smaller than"
187
+ " 64 which seems highly unlikely .If you're checkpoint is a fine-tuned version of any of the"
188
+ " following: \n- CompVis/stable-diffusion-v1-4 \n- CompVis/stable-diffusion-v1-3 \n-"
189
+ " CompVis/stable-diffusion-v1-2 \n- CompVis/stable-diffusion-v1-1 \n- runwayml/stable-diffusion-v1-5"
190
+ " \n- runwayml/stable-diffusion-inpainting \n you should change 'sample_size' to 64 in the"
191
+ " configuration file. Please make sure to update the config accordingly as leaving `sample_size=32`"
192
+ " in the config might lead to incorrect results in future versions. If you have downloaded this"
193
+ " checkpoint from the Hugging Face Hub, it would be very nice if you could open a Pull request for"
194
+ " the `unet/config.json` file"
195
+ )
196
+ deprecate("sample_size<64", "1.0.0", deprecation_message, standard_warn=False)
197
+ new_config = dict(unet.config)
198
+ new_config["sample_size"] = 64
199
+ unet._internal_dict = FrozenDict(new_config)
200
+
201
+ self.register_modules(
202
+ vae=vae,
203
+ text_encoder=text_encoder,
204
+ tokenizer=tokenizer,
205
+ unet=unet,
206
+ scheduler=scheduler,
207
+ safety_checker=safety_checker,
208
+ feature_extractor=feature_extractor,
209
+ )
210
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
211
+
212
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.enable_sequential_cpu_offload
213
+ def enable_sequential_cpu_offload(self, gpu_id=0):
214
+ r"""
215
+ Offloads all models to CPU using accelerate, significantly reducing memory usage. When called, unet,
216
+ text_encoder, vae and safety checker have their state dicts saved to CPU and then are moved to a
217
+ `torch.device('meta') and loaded to GPU only when their specific submodule has its `forward` method called.
218
+ """
219
+ if is_accelerate_available():
220
+ from accelerate import cpu_offload
221
+ else:
222
+ raise ImportError("Please install accelerate via `pip install accelerate`")
223
+
224
+ device = torch.device(f"cuda:{gpu_id}")
225
+
226
+ for cpu_offloaded_model in [self.unet, self.text_encoder, self.vae]:
227
+ if cpu_offloaded_model is not None:
228
+ cpu_offload(cpu_offloaded_model, device)
229
+
230
+ if self.safety_checker is not None:
231
+ # TODO(Patrick) - there is currently a bug with cpu offload of nn.Parameter in accelerate
232
+ # fix by only offloading self.safety_checker for now
233
+ cpu_offload(self.safety_checker.vision_model, device)
234
+
235
+ @property
236
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._execution_device
237
+ def _execution_device(self):
238
+ r"""
239
+ Returns the device on which the pipeline's models will be executed. After calling
240
+ `pipeline.enable_sequential_cpu_offload()` the execution device can only be inferred from Accelerate's module
241
+ hooks.
242
+ """
243
+ if self.device != torch.device("meta") or not hasattr(self.unet, "_hf_hook"):
244
+ return self.device
245
+ for module in self.unet.modules():
246
+ if (
247
+ hasattr(module, "_hf_hook")
248
+ and hasattr(module._hf_hook, "execution_device")
249
+ and module._hf_hook.execution_device is not None
250
+ ):
251
+ return torch.device(module._hf_hook.execution_device)
252
+ return self.device
253
+
254
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline._encode_prompt
255
+ def _encode_prompt(self, prompt, device, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
256
+ r"""
257
+ Encodes the prompt into text encoder hidden states.
258
+
259
+ Args:
260
+ prompt (`str` or `list(int)`):
261
+ prompt to be encoded
262
+ device: (`torch.device`):
263
+ torch device
264
+ num_images_per_prompt (`int`):
265
+ number of images that should be generated per prompt
266
+ do_classifier_free_guidance (`bool`):
267
+ whether to use classifier free guidance or not
268
+ negative_prompt (`str` or `List[str]`):
269
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
270
+ if `guidance_scale` is less than `1`).
271
+ """
272
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
273
+
274
+ text_inputs = self.tokenizer(
275
+ prompt,
276
+ padding="max_length",
277
+ max_length=self.tokenizer.model_max_length,
278
+ truncation=True,
279
+ return_tensors="pt",
280
+ )
281
+ text_input_ids = text_inputs.input_ids
282
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="pt").input_ids
283
+
284
+ if not torch.equal(text_input_ids, untruncated_ids):
285
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
286
+ logger.warning(
287
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
288
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
289
+ )
290
+
291
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
292
+ attention_mask = text_inputs.attention_mask.to(device)
293
+ else:
294
+ attention_mask = None
295
+
296
+ text_embeddings = self.text_encoder(
297
+ text_input_ids.to(device),
298
+ attention_mask=attention_mask,
299
+ )
300
+ text_embeddings = text_embeddings[0]
301
+
302
+ # duplicate text embeddings for each generation per prompt, using mps friendly method
303
+ bs_embed, seq_len, _ = text_embeddings.shape
304
+ text_embeddings = text_embeddings.repeat(1, num_images_per_prompt, 1)
305
+ text_embeddings = text_embeddings.view(bs_embed * num_images_per_prompt, seq_len, -1)
306
+
307
+ # get unconditional embeddings for classifier free guidance
308
+ if do_classifier_free_guidance:
309
+ uncond_tokens: List[str]
310
+ if negative_prompt is None:
311
+ uncond_tokens = [""] * batch_size
312
+ elif type(prompt) is not type(negative_prompt):
313
+ raise TypeError(
314
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
315
+ f" {type(prompt)}."
316
+ )
317
+ elif isinstance(negative_prompt, str):
318
+ uncond_tokens = [negative_prompt]
319
+ elif batch_size != len(negative_prompt):
320
+ raise ValueError(
321
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
322
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
323
+ " the batch size of `prompt`."
324
+ )
325
+ else:
326
+ uncond_tokens = negative_prompt
327
+
328
+ max_length = text_input_ids.shape[-1]
329
+ uncond_input = self.tokenizer(
330
+ uncond_tokens,
331
+ padding="max_length",
332
+ max_length=max_length,
333
+ truncation=True,
334
+ return_tensors="pt",
335
+ )
336
+
337
+ if hasattr(self.text_encoder.config, "use_attention_mask") and self.text_encoder.config.use_attention_mask:
338
+ attention_mask = uncond_input.attention_mask.to(device)
339
+ else:
340
+ attention_mask = None
341
+
342
+ uncond_embeddings = self.text_encoder(
343
+ uncond_input.input_ids.to(device),
344
+ attention_mask=attention_mask,
345
+ )
346
+ uncond_embeddings = uncond_embeddings[0]
347
+
348
+ # duplicate unconditional embeddings for each generation per prompt, using mps friendly method
349
+ seq_len = uncond_embeddings.shape[1]
350
+ uncond_embeddings = uncond_embeddings.repeat(1, num_images_per_prompt, 1)
351
+ uncond_embeddings = uncond_embeddings.view(batch_size * num_images_per_prompt, seq_len, -1)
352
+
353
+ # For classifier free guidance, we need to do two forward passes.
354
+ # Here we concatenate the unconditional and text embeddings into a single batch
355
+ # to avoid doing two forward passes
356
+ text_embeddings = torch.cat([uncond_embeddings, text_embeddings])
357
+
358
+ return text_embeddings
359
+
360
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.check_inputs
361
+ def check_inputs(self, prompt, strength, callback_steps):
362
+ if not isinstance(prompt, str) and not isinstance(prompt, list):
363
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
364
+
365
+ if strength < 0 or strength > 1:
366
+ raise ValueError(f"The value of strength should in [1.0, 1.0] but is {strength}")
367
+
368
+ if (callback_steps is None) or (
369
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
370
+ ):
371
+ raise ValueError(
372
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
373
+ f" {type(callback_steps)}."
374
+ )
375
+
376
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.prepare_extra_step_kwargs
377
+ def prepare_extra_step_kwargs(self, generator, eta):
378
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
379
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
380
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
381
+ # and should be between [0, 1]
382
+
383
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
384
+ extra_step_kwargs = {}
385
+ if accepts_eta:
386
+ extra_step_kwargs["eta"] = eta
387
+
388
+ # check if the scheduler accepts generator
389
+ accepts_generator = "generator" in set(inspect.signature(self.scheduler.step).parameters.keys())
390
+ if accepts_generator:
391
+ extra_step_kwargs["generator"] = generator
392
+ return extra_step_kwargs
393
+
394
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.run_safety_checker
395
+ def run_safety_checker(self, image, device, dtype):
396
+ if self.safety_checker is not None:
397
+ safety_checker_input = self.feature_extractor(self.numpy_to_pil(image), return_tensors="pt").to(device)
398
+ image, has_nsfw_concept = self.safety_checker(
399
+ images=image, clip_input=safety_checker_input.pixel_values.to(dtype)
400
+ )
401
+ else:
402
+ has_nsfw_concept = None
403
+ return image, has_nsfw_concept
404
+
405
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.StableDiffusionPipeline.decode_latents
406
+ def decode_latents(self, latents):
407
+ latents = 1 / 0.18215 * latents
408
+ image = self.vae.decode(latents).sample
409
+ image = (image / 2 + 0.5).clamp(0, 1)
410
+ # we always cast to float32 as this does not cause significant overhead and is compatible with bfloa16
411
+ image = image.cpu().permute(0, 2, 3, 1).float().numpy()
412
+ return image
413
+
414
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion_img2img.StableDiffusionImg2ImgPipeline.get_timesteps
415
+ def get_timesteps(self, num_inference_steps, strength, device):
416
+ # get the original timestep using init_timestep
417
+ offset = self.scheduler.config.get("steps_offset", 0)
418
+ init_timestep = int(num_inference_steps * strength) + offset
419
+ init_timestep = min(init_timestep, num_inference_steps)
420
+
421
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
422
+ timesteps = self.scheduler.timesteps[t_start:]
423
+
424
+ return timesteps, num_inference_steps - t_start
425
+
426
+ def prepare_latents(self, image, timestep, batch_size, num_images_per_prompt, dtype, device, generator=None):
427
+ image = image.to(device=device, dtype=dtype)
428
+ init_latent_dist = self.vae.encode(image).latent_dist
429
+ init_latents = init_latent_dist.sample(generator=generator)
430
+ init_latents = 0.18215 * init_latents
431
+
432
+ if batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] == 0:
433
+ # expand init_latents for batch_size
434
+ deprecation_message = (
435
+ f"You have passed {batch_size} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
436
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
437
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
438
+ " your script to pass as many initial images as text prompts to suppress this warning."
439
+ )
440
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
441
+ additional_image_per_prompt = batch_size // init_latents.shape[0]
442
+ init_latents = torch.cat([init_latents] * additional_image_per_prompt * num_images_per_prompt, dim=0)
443
+ elif batch_size > init_latents.shape[0] and batch_size % init_latents.shape[0] != 0:
444
+ raise ValueError(
445
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {batch_size} text prompts."
446
+ )
447
+ else:
448
+ init_latents = torch.cat([init_latents] * num_images_per_prompt, dim=0)
449
+
450
+ # add noise to latents using the timestep
451
+ noise = torch.randn(init_latents.shape, generator=generator, device=device, dtype=dtype)
452
+
453
+ # get latents
454
+ clean_latents = init_latents
455
+ init_latents = self.scheduler.add_noise(init_latents, noise, timestep)
456
+ latents = init_latents
457
+
458
+ return latents, clean_latents
459
+
460
+ @torch.no_grad()
461
+ def __call__(
462
+ self,
463
+ prompt: Union[str, List[str]],
464
+ source_prompt: Union[str, List[str]],
465
+ image: Union[torch.FloatTensor, PIL.Image.Image],
466
+ strength: float = 0.8,
467
+ num_inference_steps: Optional[int] = 50,
468
+ guidance_scale: Optional[float] = 7.5,
469
+ source_guidance_scale: Optional[float] = 1,
470
+ num_images_per_prompt: Optional[int] = 1,
471
+ eta: Optional[float] = 0.1,
472
+ generator: Optional[torch.Generator] = None,
473
+ output_type: Optional[str] = "pil",
474
+ return_dict: bool = True,
475
+ callback: Optional[Callable[[int, int, torch.FloatTensor], None]] = None,
476
+ callback_steps: Optional[int] = 1,
477
+ **kwargs,
478
+ ):
479
+ r"""
480
+ Function invoked when calling the pipeline for generation.
481
+
482
+ Args:
483
+ prompt (`str` or `List[str]`):
484
+ The prompt or prompts to guide the image generation.
485
+ image (`torch.FloatTensor` or `PIL.Image.Image`):
486
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
487
+ process.
488
+ strength (`float`, *optional*, defaults to 0.8):
489
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
490
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
491
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
492
+ be maximum and the denoising process will run for the full number of iterations specified in
493
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
494
+ num_inference_steps (`int`, *optional*, defaults to 50):
495
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
496
+ expense of slower inference. This parameter will be modulated by `strength`.
497
+ guidance_scale (`float`, *optional*, defaults to 7.5):
498
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
499
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
500
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
501
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
502
+ usually at the expense of lower image quality.
503
+ source_guidance_scale (`float`, *optional*, defaults to 1):
504
+ Guidance scale for the source prompt. This is useful to control the amount of influence the source
505
+ prompt for encoding.
506
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
507
+ The number of images to generate per prompt.
508
+ eta (`float`, *optional*, defaults to 0.1):
509
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
510
+ [`schedulers.DDIMScheduler`], will be ignored for others.
511
+ generator (`torch.Generator`, *optional*):
512
+ A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
513
+ deterministic.
514
+ output_type (`str`, *optional*, defaults to `"pil"`):
515
+ The output format of the generate image. Choose between
516
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
517
+ return_dict (`bool`, *optional*, defaults to `True`):
518
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
519
+ plain tuple.
520
+ callback (`Callable`, *optional*):
521
+ A function that will be called every `callback_steps` steps during inference. The function will be
522
+ called with the following arguments: `callback(step: int, timestep: int, latents: torch.FloatTensor)`.
523
+ callback_steps (`int`, *optional*, defaults to 1):
524
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
525
+ called at every step.
526
+
527
+ Returns:
528
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
529
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
530
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
531
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
532
+ (nsfw) content, according to the `safety_checker`.
533
+ """
534
+ message = "Please use `image` instead of `init_image`."
535
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
536
+ image = init_image or image
537
+
538
+ # 1. Check inputs
539
+ self.check_inputs(prompt, strength, callback_steps)
540
+
541
+ # 2. Define call parameters
542
+ batch_size = 1 if isinstance(prompt, str) else len(prompt)
543
+ device = self._execution_device
544
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
545
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
546
+ # corresponds to doing no classifier free guidance.
547
+ do_classifier_free_guidance = guidance_scale > 1.0
548
+
549
+ # 3. Encode input prompt
550
+ text_embeddings = self._encode_prompt(prompt, device, num_images_per_prompt, do_classifier_free_guidance, None)
551
+ source_text_embeddings = self._encode_prompt(
552
+ source_prompt, device, num_images_per_prompt, do_classifier_free_guidance, None
553
+ )
554
+
555
+ # 4. Preprocess image
556
+ if isinstance(image, PIL.Image.Image):
557
+ image = preprocess(image)
558
+
559
+ # 5. Prepare timesteps
560
+ self.scheduler.set_timesteps(num_inference_steps, device=device)
561
+ timesteps, num_inference_steps = self.get_timesteps(num_inference_steps, strength, device)
562
+ latent_timestep = timesteps[:1].repeat(batch_size * num_images_per_prompt)
563
+
564
+ # 6. Prepare latent variables
565
+ latents, clean_latents = self.prepare_latents(
566
+ image, latent_timestep, batch_size, num_images_per_prompt, text_embeddings.dtype, device, generator
567
+ )
568
+ source_latents = latents
569
+
570
+ # 7. Prepare extra step kwargs. TODO: Logic should ideally just be moved out of the pipeline
571
+ extra_step_kwargs = self.prepare_extra_step_kwargs(generator, eta)
572
+ generator = extra_step_kwargs.pop("generator", None)
573
+
574
+ # 8. Denoising loop
575
+ num_warmup_steps = len(timesteps) - num_inference_steps * self.scheduler.order
576
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
577
+ for i, t in enumerate(timesteps):
578
+ # expand the latents if we are doing classifier free guidance
579
+ latent_model_input = torch.cat([latents] * 2)
580
+ source_latent_model_input = torch.cat([source_latents] * 2)
581
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
582
+ source_latent_model_input = self.scheduler.scale_model_input(source_latent_model_input, t)
583
+
584
+ # predict the noise residual
585
+ concat_latent_model_input = torch.stack(
586
+ [
587
+ source_latent_model_input[0],
588
+ latent_model_input[0],
589
+ source_latent_model_input[1],
590
+ latent_model_input[1],
591
+ ],
592
+ dim=0,
593
+ )
594
+ concat_text_embeddings = torch.stack(
595
+ [
596
+ source_text_embeddings[0],
597
+ text_embeddings[0],
598
+ source_text_embeddings[1],
599
+ text_embeddings[1],
600
+ ],
601
+ dim=0,
602
+ )
603
+ concat_noise_pred = self.unet(
604
+ concat_latent_model_input, t, encoder_hidden_states=concat_text_embeddings
605
+ ).sample
606
+
607
+ # perform guidance
608
+ (
609
+ source_noise_pred_uncond,
610
+ noise_pred_uncond,
611
+ source_noise_pred_text,
612
+ noise_pred_text,
613
+ ) = concat_noise_pred.chunk(4, dim=0)
614
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
615
+ source_noise_pred = source_noise_pred_uncond + source_guidance_scale * (
616
+ source_noise_pred_text - source_noise_pred_uncond
617
+ )
618
+
619
+ # Sample source_latents from the posterior distribution.
620
+ prev_source_latents = posterior_sample(
621
+ self.scheduler, source_latents, t, clean_latents, generator=generator, **extra_step_kwargs
622
+ )
623
+ # Compute noise.
624
+ noise = compute_noise(
625
+ self.scheduler, prev_source_latents, source_latents, t, source_noise_pred, **extra_step_kwargs
626
+ )
627
+ source_latents = prev_source_latents
628
+
629
+ # compute the previous noisy sample x_t -> x_t-1
630
+ latents = self.scheduler.step(
631
+ noise_pred, t, latents, variance_noise=noise, **extra_step_kwargs
632
+ ).prev_sample
633
+
634
+ # call the callback, if provided
635
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
636
+ progress_bar.update()
637
+ if callback is not None and i % callback_steps == 0:
638
+ callback(i, t, latents)
639
+
640
+ # 9. Post-processing
641
+ image = self.decode_latents(latents)
642
+
643
+ # 10. Run safety checker
644
+ image, has_nsfw_concept = self.run_safety_checker(image, device, text_embeddings.dtype)
645
+
646
+ # 11. Convert to PIL
647
+ if output_type == "pil":
648
+ image = self.numpy_to_pil(image)
649
+
650
+ if not return_dict:
651
+ return (image, has_nsfw_concept)
652
+
653
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion.py ADDED
@@ -0,0 +1,353 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
22
+
23
+ from ...configuration_utils import FrozenDict
24
+ from ...onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
25
+ from ...pipeline_utils import DiffusionPipeline
26
+ from ...schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
27
+ from ...utils import deprecate, logging
28
+ from . import StableDiffusionPipelineOutput
29
+
30
+
31
+ logger = logging.get_logger(__name__)
32
+
33
+
34
+ class OnnxStableDiffusionPipeline(DiffusionPipeline):
35
+ vae_encoder: OnnxRuntimeModel
36
+ vae_decoder: OnnxRuntimeModel
37
+ text_encoder: OnnxRuntimeModel
38
+ tokenizer: CLIPTokenizer
39
+ unet: OnnxRuntimeModel
40
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
41
+ safety_checker: OnnxRuntimeModel
42
+ feature_extractor: CLIPFeatureExtractor
43
+
44
+ _optional_components = ["safety_checker", "feature_extractor"]
45
+
46
+ def __init__(
47
+ self,
48
+ vae_encoder: OnnxRuntimeModel,
49
+ vae_decoder: OnnxRuntimeModel,
50
+ text_encoder: OnnxRuntimeModel,
51
+ tokenizer: CLIPTokenizer,
52
+ unet: OnnxRuntimeModel,
53
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
54
+ safety_checker: OnnxRuntimeModel,
55
+ feature_extractor: CLIPFeatureExtractor,
56
+ requires_safety_checker: bool = True,
57
+ ):
58
+ super().__init__()
59
+
60
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
61
+ deprecation_message = (
62
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
63
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
64
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
65
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
66
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
67
+ " file"
68
+ )
69
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
70
+ new_config = dict(scheduler.config)
71
+ new_config["steps_offset"] = 1
72
+ scheduler._internal_dict = FrozenDict(new_config)
73
+
74
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
75
+ deprecation_message = (
76
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
77
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
78
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
79
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
80
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
81
+ )
82
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
83
+ new_config = dict(scheduler.config)
84
+ new_config["clip_sample"] = False
85
+ scheduler._internal_dict = FrozenDict(new_config)
86
+
87
+ if safety_checker is None and requires_safety_checker:
88
+ logger.warning(
89
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
90
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
91
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
92
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
93
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
94
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
95
+ )
96
+
97
+ if safety_checker is not None and feature_extractor is None:
98
+ raise ValueError(
99
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
100
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
101
+ )
102
+
103
+ self.register_modules(
104
+ vae_encoder=vae_encoder,
105
+ vae_decoder=vae_decoder,
106
+ text_encoder=text_encoder,
107
+ tokenizer=tokenizer,
108
+ unet=unet,
109
+ scheduler=scheduler,
110
+ safety_checker=safety_checker,
111
+ feature_extractor=feature_extractor,
112
+ )
113
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
114
+
115
+ def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
116
+ r"""
117
+ Encodes the prompt into text encoder hidden states.
118
+
119
+ Args:
120
+ prompt (`str` or `list(int)`):
121
+ prompt to be encoded
122
+ num_images_per_prompt (`int`):
123
+ number of images that should be generated per prompt
124
+ do_classifier_free_guidance (`bool`):
125
+ whether to use classifier free guidance or not
126
+ negative_prompt (`str` or `List[str]`):
127
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
128
+ if `guidance_scale` is less than `1`).
129
+ """
130
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
131
+
132
+ # get prompt text embeddings
133
+ text_inputs = self.tokenizer(
134
+ prompt,
135
+ padding="max_length",
136
+ max_length=self.tokenizer.model_max_length,
137
+ truncation=True,
138
+ return_tensors="np",
139
+ )
140
+ text_input_ids = text_inputs.input_ids
141
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
142
+
143
+ if not np.array_equal(text_input_ids, untruncated_ids):
144
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
145
+ logger.warning(
146
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
147
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
148
+ )
149
+
150
+ text_embeddings = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
151
+ text_embeddings = np.repeat(text_embeddings, num_images_per_prompt, axis=0)
152
+
153
+ # get unconditional embeddings for classifier free guidance
154
+ if do_classifier_free_guidance:
155
+ uncond_tokens: List[str]
156
+ if negative_prompt is None:
157
+ uncond_tokens = [""] * batch_size
158
+ elif type(prompt) is not type(negative_prompt):
159
+ raise TypeError(
160
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
161
+ f" {type(prompt)}."
162
+ )
163
+ elif isinstance(negative_prompt, str):
164
+ uncond_tokens = [negative_prompt] * batch_size
165
+ elif batch_size != len(negative_prompt):
166
+ raise ValueError(
167
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
168
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
169
+ " the batch size of `prompt`."
170
+ )
171
+ else:
172
+ uncond_tokens = negative_prompt
173
+
174
+ max_length = text_input_ids.shape[-1]
175
+ uncond_input = self.tokenizer(
176
+ uncond_tokens,
177
+ padding="max_length",
178
+ max_length=max_length,
179
+ truncation=True,
180
+ return_tensors="np",
181
+ )
182
+ uncond_embeddings = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
183
+ uncond_embeddings = np.repeat(uncond_embeddings, num_images_per_prompt, axis=0)
184
+
185
+ # For classifier free guidance, we need to do two forward passes.
186
+ # Here we concatenate the unconditional and text embeddings into a single batch
187
+ # to avoid doing two forward passes
188
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
189
+
190
+ return text_embeddings
191
+
192
+ def __call__(
193
+ self,
194
+ prompt: Union[str, List[str]],
195
+ height: Optional[int] = 512,
196
+ width: Optional[int] = 512,
197
+ num_inference_steps: Optional[int] = 50,
198
+ guidance_scale: Optional[float] = 7.5,
199
+ negative_prompt: Optional[Union[str, List[str]]] = None,
200
+ num_images_per_prompt: Optional[int] = 1,
201
+ eta: Optional[float] = 0.0,
202
+ generator: Optional[np.random.RandomState] = None,
203
+ latents: Optional[np.ndarray] = None,
204
+ output_type: Optional[str] = "pil",
205
+ return_dict: bool = True,
206
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
207
+ callback_steps: Optional[int] = 1,
208
+ ):
209
+ if isinstance(prompt, str):
210
+ batch_size = 1
211
+ elif isinstance(prompt, list):
212
+ batch_size = len(prompt)
213
+ else:
214
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
215
+
216
+ if height % 8 != 0 or width % 8 != 0:
217
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
218
+
219
+ if (callback_steps is None) or (
220
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
221
+ ):
222
+ raise ValueError(
223
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
224
+ f" {type(callback_steps)}."
225
+ )
226
+
227
+ if generator is None:
228
+ generator = np.random
229
+
230
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
231
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
232
+ # corresponds to doing no classifier free guidance.
233
+ do_classifier_free_guidance = guidance_scale > 1.0
234
+
235
+ text_embeddings = self._encode_prompt(
236
+ prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
237
+ )
238
+
239
+ # get the initial random noise unless the user supplied it
240
+ latents_dtype = text_embeddings.dtype
241
+ latents_shape = (batch_size * num_images_per_prompt, 4, height // 8, width // 8)
242
+ if latents is None:
243
+ latents = generator.randn(*latents_shape).astype(latents_dtype)
244
+ elif latents.shape != latents_shape:
245
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
246
+
247
+ # set timesteps
248
+ self.scheduler.set_timesteps(num_inference_steps)
249
+
250
+ latents = latents * np.float(self.scheduler.init_noise_sigma)
251
+
252
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
253
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
254
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
255
+ # and should be between [0, 1]
256
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
257
+ extra_step_kwargs = {}
258
+ if accepts_eta:
259
+ extra_step_kwargs["eta"] = eta
260
+
261
+ timestep_dtype = next(
262
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
263
+ )
264
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
265
+
266
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
267
+ # expand the latents if we are doing classifier free guidance
268
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
269
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
270
+ latent_model_input = latent_model_input.cpu().numpy()
271
+
272
+ # predict the noise residual
273
+ timestep = np.array([t], dtype=timestep_dtype)
274
+ noise_pred = self.unet(sample=latent_model_input, timestep=timestep, encoder_hidden_states=text_embeddings)
275
+ noise_pred = noise_pred[0]
276
+
277
+ # perform guidance
278
+ if do_classifier_free_guidance:
279
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
280
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
281
+
282
+ # compute the previous noisy sample x_t -> x_t-1
283
+ scheduler_output = self.scheduler.step(
284
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
285
+ )
286
+ latents = scheduler_output.prev_sample.numpy()
287
+
288
+ # call the callback, if provided
289
+ if callback is not None and i % callback_steps == 0:
290
+ callback(i, t, latents)
291
+
292
+ latents = 1 / 0.18215 * latents
293
+ # image = self.vae_decoder(latent_sample=latents)[0]
294
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
295
+ image = np.concatenate(
296
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
297
+ )
298
+
299
+ image = np.clip(image / 2 + 0.5, 0, 1)
300
+ image = image.transpose((0, 2, 3, 1))
301
+
302
+ if self.safety_checker is not None:
303
+ safety_checker_input = self.feature_extractor(
304
+ self.numpy_to_pil(image), return_tensors="np"
305
+ ).pixel_values.astype(image.dtype)
306
+
307
+ image, has_nsfw_concepts = self.safety_checker(clip_input=safety_checker_input, images=image)
308
+
309
+ # There will throw an error if use safety_checker batchsize>1
310
+ images, has_nsfw_concept = [], []
311
+ for i in range(image.shape[0]):
312
+ image_i, has_nsfw_concept_i = self.safety_checker(
313
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
314
+ )
315
+ images.append(image_i)
316
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
317
+ image = np.concatenate(images)
318
+ else:
319
+ has_nsfw_concept = None
320
+
321
+ if output_type == "pil":
322
+ image = self.numpy_to_pil(image)
323
+
324
+ if not return_dict:
325
+ return (image, has_nsfw_concept)
326
+
327
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
328
+
329
+
330
+ class StableDiffusionOnnxPipeline(OnnxStableDiffusionPipeline):
331
+ def __init__(
332
+ self,
333
+ vae_encoder: OnnxRuntimeModel,
334
+ vae_decoder: OnnxRuntimeModel,
335
+ text_encoder: OnnxRuntimeModel,
336
+ tokenizer: CLIPTokenizer,
337
+ unet: OnnxRuntimeModel,
338
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
339
+ safety_checker: OnnxRuntimeModel,
340
+ feature_extractor: CLIPFeatureExtractor,
341
+ ):
342
+ deprecation_message = "Please use `OnnxStableDiffusionPipeline` instead of `StableDiffusionOnnxPipeline`."
343
+ deprecate("StableDiffusionOnnxPipeline", "1.0.0", deprecation_message)
344
+ super().__init__(
345
+ vae_encoder=vae_encoder,
346
+ vae_decoder=vae_decoder,
347
+ text_encoder=text_encoder,
348
+ tokenizer=tokenizer,
349
+ unet=unet,
350
+ scheduler=scheduler,
351
+ safety_checker=safety_checker,
352
+ feature_extractor=feature_extractor,
353
+ )
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_img2img.py ADDED
@@ -0,0 +1,459 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ import PIL
22
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
23
+
24
+ from ...configuration_utils import FrozenDict
25
+ from ...onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
26
+ from ...pipeline_utils import DiffusionPipeline
27
+ from ...schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
28
+ from ...utils import PIL_INTERPOLATION, deprecate, logging
29
+ from . import StableDiffusionPipelineOutput
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ def preprocess(image):
36
+ w, h = image.size
37
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
38
+ image = image.resize((w, h), resample=PIL_INTERPOLATION["lanczos"])
39
+ image = np.array(image).astype(np.float32) / 255.0
40
+ image = image[None].transpose(0, 3, 1, 2)
41
+ return 2.0 * image - 1.0
42
+
43
+
44
+ class OnnxStableDiffusionImg2ImgPipeline(DiffusionPipeline):
45
+ r"""
46
+ Pipeline for text-guided image to image generation using Stable Diffusion.
47
+
48
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
49
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
50
+
51
+ Args:
52
+ vae ([`AutoencoderKL`]):
53
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
54
+ text_encoder ([`CLIPTextModel`]):
55
+ Frozen text-encoder. Stable Diffusion uses the text portion of
56
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
57
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
58
+ tokenizer (`CLIPTokenizer`):
59
+ Tokenizer of class
60
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
61
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
62
+ scheduler ([`SchedulerMixin`]):
63
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
64
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
65
+ safety_checker ([`StableDiffusionSafetyChecker`]):
66
+ Classification module that estimates whether generated images could be considered offensive or harmful.
67
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
68
+ feature_extractor ([`CLIPFeatureExtractor`]):
69
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
70
+ """
71
+ vae_encoder: OnnxRuntimeModel
72
+ vae_decoder: OnnxRuntimeModel
73
+ text_encoder: OnnxRuntimeModel
74
+ tokenizer: CLIPTokenizer
75
+ unet: OnnxRuntimeModel
76
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
77
+ safety_checker: OnnxRuntimeModel
78
+ feature_extractor: CLIPFeatureExtractor
79
+
80
+ _optional_components = ["safety_checker", "feature_extractor"]
81
+
82
+ def __init__(
83
+ self,
84
+ vae_encoder: OnnxRuntimeModel,
85
+ vae_decoder: OnnxRuntimeModel,
86
+ text_encoder: OnnxRuntimeModel,
87
+ tokenizer: CLIPTokenizer,
88
+ unet: OnnxRuntimeModel,
89
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
90
+ safety_checker: OnnxRuntimeModel,
91
+ feature_extractor: CLIPFeatureExtractor,
92
+ requires_safety_checker: bool = True,
93
+ ):
94
+ super().__init__()
95
+
96
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
97
+ deprecation_message = (
98
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
99
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
100
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
101
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
102
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
103
+ " file"
104
+ )
105
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
106
+ new_config = dict(scheduler.config)
107
+ new_config["steps_offset"] = 1
108
+ scheduler._internal_dict = FrozenDict(new_config)
109
+
110
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
111
+ deprecation_message = (
112
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
113
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
114
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
115
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
116
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
117
+ )
118
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
119
+ new_config = dict(scheduler.config)
120
+ new_config["clip_sample"] = False
121
+ scheduler._internal_dict = FrozenDict(new_config)
122
+
123
+ if safety_checker is None and requires_safety_checker:
124
+ logger.warning(
125
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
126
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
127
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
128
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
129
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
130
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
131
+ )
132
+
133
+ if safety_checker is not None and feature_extractor is None:
134
+ raise ValueError(
135
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
136
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
137
+ )
138
+
139
+ self.register_modules(
140
+ vae_encoder=vae_encoder,
141
+ vae_decoder=vae_decoder,
142
+ text_encoder=text_encoder,
143
+ tokenizer=tokenizer,
144
+ unet=unet,
145
+ scheduler=scheduler,
146
+ safety_checker=safety_checker,
147
+ feature_extractor=feature_extractor,
148
+ )
149
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
150
+
151
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_onnx_stable_diffusion.OnnxStableDiffusionPipeline._encode_prompt
152
+ def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
153
+ r"""
154
+ Encodes the prompt into text encoder hidden states.
155
+
156
+ Args:
157
+ prompt (`str` or `list(int)`):
158
+ prompt to be encoded
159
+ num_images_per_prompt (`int`):
160
+ number of images that should be generated per prompt
161
+ do_classifier_free_guidance (`bool`):
162
+ whether to use classifier free guidance or not
163
+ negative_prompt (`str` or `List[str]`):
164
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
165
+ if `guidance_scale` is less than `1`).
166
+ """
167
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
168
+
169
+ # get prompt text embeddings
170
+ text_inputs = self.tokenizer(
171
+ prompt,
172
+ padding="max_length",
173
+ max_length=self.tokenizer.model_max_length,
174
+ truncation=True,
175
+ return_tensors="np",
176
+ )
177
+ text_input_ids = text_inputs.input_ids
178
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
179
+
180
+ if not np.array_equal(text_input_ids, untruncated_ids):
181
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
182
+ logger.warning(
183
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
184
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
185
+ )
186
+
187
+ text_embeddings = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
188
+ text_embeddings = np.repeat(text_embeddings, num_images_per_prompt, axis=0)
189
+
190
+ # get unconditional embeddings for classifier free guidance
191
+ if do_classifier_free_guidance:
192
+ uncond_tokens: List[str]
193
+ if negative_prompt is None:
194
+ uncond_tokens = [""] * batch_size
195
+ elif type(prompt) is not type(negative_prompt):
196
+ raise TypeError(
197
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
198
+ f" {type(prompt)}."
199
+ )
200
+ elif isinstance(negative_prompt, str):
201
+ uncond_tokens = [negative_prompt] * batch_size
202
+ elif batch_size != len(negative_prompt):
203
+ raise ValueError(
204
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
205
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
206
+ " the batch size of `prompt`."
207
+ )
208
+ else:
209
+ uncond_tokens = negative_prompt
210
+
211
+ max_length = text_input_ids.shape[-1]
212
+ uncond_input = self.tokenizer(
213
+ uncond_tokens,
214
+ padding="max_length",
215
+ max_length=max_length,
216
+ truncation=True,
217
+ return_tensors="np",
218
+ )
219
+ uncond_embeddings = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
220
+ uncond_embeddings = np.repeat(uncond_embeddings, num_images_per_prompt, axis=0)
221
+
222
+ # For classifier free guidance, we need to do two forward passes.
223
+ # Here we concatenate the unconditional and text embeddings into a single batch
224
+ # to avoid doing two forward passes
225
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
226
+
227
+ return text_embeddings
228
+
229
+ def __call__(
230
+ self,
231
+ prompt: Union[str, List[str]],
232
+ image: Union[np.ndarray, PIL.Image.Image],
233
+ strength: float = 0.8,
234
+ num_inference_steps: Optional[int] = 50,
235
+ guidance_scale: Optional[float] = 7.5,
236
+ negative_prompt: Optional[Union[str, List[str]]] = None,
237
+ num_images_per_prompt: Optional[int] = 1,
238
+ eta: Optional[float] = 0.0,
239
+ generator: Optional[np.random.RandomState] = None,
240
+ output_type: Optional[str] = "pil",
241
+ return_dict: bool = True,
242
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
243
+ callback_steps: Optional[int] = 1,
244
+ **kwargs,
245
+ ):
246
+ r"""
247
+ Function invoked when calling the pipeline for generation.
248
+
249
+ Args:
250
+ prompt (`str` or `List[str]`):
251
+ The prompt or prompts to guide the image generation.
252
+ image (`np.ndarray` or `PIL.Image.Image`):
253
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
254
+ process.
255
+ strength (`float`, *optional*, defaults to 0.8):
256
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
257
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
258
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
259
+ be maximum and the denoising process will run for the full number of iterations specified in
260
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
261
+ num_inference_steps (`int`, *optional*, defaults to 50):
262
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
263
+ expense of slower inference. This parameter will be modulated by `strength`.
264
+ guidance_scale (`float`, *optional*, defaults to 7.5):
265
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
266
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
267
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
268
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
269
+ usually at the expense of lower image quality.
270
+ negative_prompt (`str` or `List[str]`, *optional*):
271
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
272
+ if `guidance_scale` is less than `1`).
273
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
274
+ The number of images to generate per prompt.
275
+ eta (`float`, *optional*, defaults to 0.0):
276
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
277
+ [`schedulers.DDIMScheduler`], will be ignored for others.
278
+ generator (`np.random.RandomState`, *optional*):
279
+ A np.random.RandomState to make generation deterministic.
280
+ output_type (`str`, *optional*, defaults to `"pil"`):
281
+ The output format of the generate image. Choose between
282
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
283
+ return_dict (`bool`, *optional*, defaults to `True`):
284
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
285
+ plain tuple.
286
+ callback (`Callable`, *optional*):
287
+ A function that will be called every `callback_steps` steps during inference. The function will be
288
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
289
+ callback_steps (`int`, *optional*, defaults to 1):
290
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
291
+ called at every step.
292
+
293
+ Returns:
294
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
295
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
296
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
297
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
298
+ (nsfw) content, according to the `safety_checker`.
299
+ """
300
+ message = "Please use `image` instead of `init_image`."
301
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
302
+ image = init_image or image
303
+
304
+ if isinstance(prompt, str):
305
+ batch_size = 1
306
+ elif isinstance(prompt, list):
307
+ batch_size = len(prompt)
308
+ else:
309
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
310
+
311
+ if strength < 0 or strength > 1:
312
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
313
+
314
+ if (callback_steps is None) or (
315
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
316
+ ):
317
+ raise ValueError(
318
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
319
+ f" {type(callback_steps)}."
320
+ )
321
+
322
+ if generator is None:
323
+ generator = np.random
324
+
325
+ # set timesteps
326
+ self.scheduler.set_timesteps(num_inference_steps)
327
+
328
+ if isinstance(image, PIL.Image.Image):
329
+ image = preprocess(image)
330
+
331
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
332
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
333
+ # corresponds to doing no classifier free guidance.
334
+ do_classifier_free_guidance = guidance_scale > 1.0
335
+
336
+ text_embeddings = self._encode_prompt(
337
+ prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
338
+ )
339
+
340
+ latents_dtype = text_embeddings.dtype
341
+ image = image.astype(latents_dtype)
342
+ # encode the init image into latents and scale the latents
343
+ init_latents = self.vae_encoder(sample=image)[0]
344
+ init_latents = 0.18215 * init_latents
345
+
346
+ if isinstance(prompt, str):
347
+ prompt = [prompt]
348
+ if len(prompt) > init_latents.shape[0] and len(prompt) % init_latents.shape[0] == 0:
349
+ # expand init_latents for batch_size
350
+ deprecation_message = (
351
+ f"You have passed {len(prompt)} text prompts (`prompt`), but only {init_latents.shape[0]} initial"
352
+ " images (`image`). Initial images are now duplicating to match the number of text prompts. Note"
353
+ " that this behavior is deprecated and will be removed in a version 1.0.0. Please make sure to update"
354
+ " your script to pass as many initial images as text prompts to suppress this warning."
355
+ )
356
+ deprecate("len(prompt) != len(image)", "1.0.0", deprecation_message, standard_warn=False)
357
+ additional_image_per_prompt = len(prompt) // init_latents.shape[0]
358
+ init_latents = np.concatenate([init_latents] * additional_image_per_prompt * num_images_per_prompt, axis=0)
359
+ elif len(prompt) > init_latents.shape[0] and len(prompt) % init_latents.shape[0] != 0:
360
+ raise ValueError(
361
+ f"Cannot duplicate `image` of batch size {init_latents.shape[0]} to {len(prompt)} text prompts."
362
+ )
363
+ else:
364
+ init_latents = np.concatenate([init_latents] * num_images_per_prompt, axis=0)
365
+
366
+ # get the original timestep using init_timestep
367
+ offset = self.scheduler.config.get("steps_offset", 0)
368
+ init_timestep = int(num_inference_steps * strength) + offset
369
+ init_timestep = min(init_timestep, num_inference_steps)
370
+
371
+ timesteps = self.scheduler.timesteps.numpy()[-init_timestep]
372
+ timesteps = np.array([timesteps] * batch_size * num_images_per_prompt)
373
+
374
+ # add noise to latents using the timesteps
375
+ noise = generator.randn(*init_latents.shape).astype(latents_dtype)
376
+ init_latents = self.scheduler.add_noise(
377
+ torch.from_numpy(init_latents), torch.from_numpy(noise), torch.from_numpy(timesteps)
378
+ )
379
+ init_latents = init_latents.numpy()
380
+
381
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
382
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
383
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
384
+ # and should be between [0, 1]
385
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
386
+ extra_step_kwargs = {}
387
+ if accepts_eta:
388
+ extra_step_kwargs["eta"] = eta
389
+
390
+ latents = init_latents
391
+
392
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
393
+ timesteps = self.scheduler.timesteps[t_start:].numpy()
394
+
395
+ timestep_dtype = next(
396
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
397
+ )
398
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
399
+
400
+ for i, t in enumerate(self.progress_bar(timesteps)):
401
+ # expand the latents if we are doing classifier free guidance
402
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
403
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
404
+ latent_model_input = latent_model_input.cpu().numpy()
405
+
406
+ # predict the noise residual
407
+ timestep = np.array([t], dtype=timestep_dtype)
408
+ noise_pred = self.unet(
409
+ sample=latent_model_input, timestep=timestep, encoder_hidden_states=text_embeddings
410
+ )[0]
411
+
412
+ # perform guidance
413
+ if do_classifier_free_guidance:
414
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
415
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
416
+
417
+ # compute the previous noisy sample x_t -> x_t-1
418
+ scheduler_output = self.scheduler.step(
419
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
420
+ )
421
+ latents = scheduler_output.prev_sample.numpy()
422
+
423
+ # call the callback, if provided
424
+ if callback is not None and i % callback_steps == 0:
425
+ callback(i, t, latents)
426
+
427
+ latents = 1 / 0.18215 * latents
428
+ # image = self.vae_decoder(latent_sample=latents)[0]
429
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
430
+ image = np.concatenate(
431
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
432
+ )
433
+
434
+ image = np.clip(image / 2 + 0.5, 0, 1)
435
+ image = image.transpose((0, 2, 3, 1))
436
+
437
+ if self.safety_checker is not None:
438
+ safety_checker_input = self.feature_extractor(
439
+ self.numpy_to_pil(image), return_tensors="np"
440
+ ).pixel_values.astype(image.dtype)
441
+ # safety_checker does not support batched inputs yet
442
+ images, has_nsfw_concept = [], []
443
+ for i in range(image.shape[0]):
444
+ image_i, has_nsfw_concept_i = self.safety_checker(
445
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
446
+ )
447
+ images.append(image_i)
448
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
449
+ image = np.concatenate(images)
450
+ else:
451
+ has_nsfw_concept = None
452
+
453
+ if output_type == "pil":
454
+ image = self.numpy_to_pil(image)
455
+
456
+ if not return_dict:
457
+ return (image, has_nsfw_concept)
458
+
459
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint.py ADDED
@@ -0,0 +1,478 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Copyright 2022 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
+ # limitations under the License.
14
+
15
+ import inspect
16
+ from typing import Callable, List, Optional, Union
17
+
18
+ import numpy as np
19
+ import torch
20
+
21
+ import PIL
22
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
23
+
24
+ from ...configuration_utils import FrozenDict
25
+ from ...onnx_utils import ORT_TO_NP_TYPE, OnnxRuntimeModel
26
+ from ...pipeline_utils import DiffusionPipeline
27
+ from ...schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
28
+ from ...utils import PIL_INTERPOLATION, deprecate, logging
29
+ from . import StableDiffusionPipelineOutput
30
+
31
+
32
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
33
+
34
+
35
+ NUM_UNET_INPUT_CHANNELS = 9
36
+ NUM_LATENT_CHANNELS = 4
37
+
38
+
39
+ def prepare_mask_and_masked_image(image, mask, latents_shape):
40
+ image = np.array(image.convert("RGB").resize((latents_shape[1] * 8, latents_shape[0] * 8)))
41
+ image = image[None].transpose(0, 3, 1, 2)
42
+ image = image.astype(np.float32) / 127.5 - 1.0
43
+
44
+ image_mask = np.array(mask.convert("L").resize((latents_shape[1] * 8, latents_shape[0] * 8)))
45
+ masked_image = image * (image_mask < 127.5)
46
+
47
+ mask = mask.resize((latents_shape[1], latents_shape[0]), PIL_INTERPOLATION["nearest"])
48
+ mask = np.array(mask.convert("L"))
49
+ mask = mask.astype(np.float32) / 255.0
50
+ mask = mask[None, None]
51
+ mask[mask < 0.5] = 0
52
+ mask[mask >= 0.5] = 1
53
+
54
+ return mask, masked_image
55
+
56
+
57
+ class OnnxStableDiffusionInpaintPipeline(DiffusionPipeline):
58
+ r"""
59
+ Pipeline for text-guided image inpainting using Stable Diffusion. *This is an experimental feature*.
60
+
61
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
62
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
63
+
64
+ Args:
65
+ vae ([`AutoencoderKL`]):
66
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
67
+ text_encoder ([`CLIPTextModel`]):
68
+ Frozen text-encoder. Stable Diffusion uses the text portion of
69
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
70
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
71
+ tokenizer (`CLIPTokenizer`):
72
+ Tokenizer of class
73
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
74
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
75
+ scheduler ([`SchedulerMixin`]):
76
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
77
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
78
+ safety_checker ([`StableDiffusionSafetyChecker`]):
79
+ Classification module that estimates whether generated images could be considered offensive or harmful.
80
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
81
+ feature_extractor ([`CLIPFeatureExtractor`]):
82
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
83
+ """
84
+ vae_encoder: OnnxRuntimeModel
85
+ vae_decoder: OnnxRuntimeModel
86
+ text_encoder: OnnxRuntimeModel
87
+ tokenizer: CLIPTokenizer
88
+ unet: OnnxRuntimeModel
89
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
90
+ safety_checker: OnnxRuntimeModel
91
+ feature_extractor: CLIPFeatureExtractor
92
+
93
+ _optional_components = ["safety_checker", "feature_extractor"]
94
+
95
+ def __init__(
96
+ self,
97
+ vae_encoder: OnnxRuntimeModel,
98
+ vae_decoder: OnnxRuntimeModel,
99
+ text_encoder: OnnxRuntimeModel,
100
+ tokenizer: CLIPTokenizer,
101
+ unet: OnnxRuntimeModel,
102
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
103
+ safety_checker: OnnxRuntimeModel,
104
+ feature_extractor: CLIPFeatureExtractor,
105
+ requires_safety_checker: bool = True,
106
+ ):
107
+ super().__init__()
108
+ logger.info("`OnnxStableDiffusionInpaintPipeline` is experimental and will very likely change in the future.")
109
+
110
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
111
+ deprecation_message = (
112
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
113
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
114
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
115
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
116
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
117
+ " file"
118
+ )
119
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
120
+ new_config = dict(scheduler.config)
121
+ new_config["steps_offset"] = 1
122
+ scheduler._internal_dict = FrozenDict(new_config)
123
+
124
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
125
+ deprecation_message = (
126
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
127
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
128
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
129
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
130
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
131
+ )
132
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
133
+ new_config = dict(scheduler.config)
134
+ new_config["clip_sample"] = False
135
+ scheduler._internal_dict = FrozenDict(new_config)
136
+
137
+ if safety_checker is None and requires_safety_checker:
138
+ logger.warning(
139
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
140
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
141
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
142
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
143
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
144
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
145
+ )
146
+
147
+ if safety_checker is not None and feature_extractor is None:
148
+ raise ValueError(
149
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
150
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
151
+ )
152
+
153
+ self.register_modules(
154
+ vae_encoder=vae_encoder,
155
+ vae_decoder=vae_decoder,
156
+ text_encoder=text_encoder,
157
+ tokenizer=tokenizer,
158
+ unet=unet,
159
+ scheduler=scheduler,
160
+ safety_checker=safety_checker,
161
+ feature_extractor=feature_extractor,
162
+ )
163
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
164
+
165
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_onnx_stable_diffusion.OnnxStableDiffusionPipeline._encode_prompt
166
+ def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
167
+ r"""
168
+ Encodes the prompt into text encoder hidden states.
169
+
170
+ Args:
171
+ prompt (`str` or `list(int)`):
172
+ prompt to be encoded
173
+ num_images_per_prompt (`int`):
174
+ number of images that should be generated per prompt
175
+ do_classifier_free_guidance (`bool`):
176
+ whether to use classifier free guidance or not
177
+ negative_prompt (`str` or `List[str]`):
178
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
179
+ if `guidance_scale` is less than `1`).
180
+ """
181
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
182
+
183
+ # get prompt text embeddings
184
+ text_inputs = self.tokenizer(
185
+ prompt,
186
+ padding="max_length",
187
+ max_length=self.tokenizer.model_max_length,
188
+ truncation=True,
189
+ return_tensors="np",
190
+ )
191
+ text_input_ids = text_inputs.input_ids
192
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
193
+
194
+ if not np.array_equal(text_input_ids, untruncated_ids):
195
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
196
+ logger.warning(
197
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
198
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
199
+ )
200
+
201
+ text_embeddings = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
202
+ text_embeddings = np.repeat(text_embeddings, num_images_per_prompt, axis=0)
203
+
204
+ # get unconditional embeddings for classifier free guidance
205
+ if do_classifier_free_guidance:
206
+ uncond_tokens: List[str]
207
+ if negative_prompt is None:
208
+ uncond_tokens = [""] * batch_size
209
+ elif type(prompt) is not type(negative_prompt):
210
+ raise TypeError(
211
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
212
+ f" {type(prompt)}."
213
+ )
214
+ elif isinstance(negative_prompt, str):
215
+ uncond_tokens = [negative_prompt] * batch_size
216
+ elif batch_size != len(negative_prompt):
217
+ raise ValueError(
218
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
219
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
220
+ " the batch size of `prompt`."
221
+ )
222
+ else:
223
+ uncond_tokens = negative_prompt
224
+
225
+ max_length = text_input_ids.shape[-1]
226
+ uncond_input = self.tokenizer(
227
+ uncond_tokens,
228
+ padding="max_length",
229
+ max_length=max_length,
230
+ truncation=True,
231
+ return_tensors="np",
232
+ )
233
+ uncond_embeddings = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
234
+ uncond_embeddings = np.repeat(uncond_embeddings, num_images_per_prompt, axis=0)
235
+
236
+ # For classifier free guidance, we need to do two forward passes.
237
+ # Here we concatenate the unconditional and text embeddings into a single batch
238
+ # to avoid doing two forward passes
239
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
240
+
241
+ return text_embeddings
242
+
243
+ @torch.no_grad()
244
+ def __call__(
245
+ self,
246
+ prompt: Union[str, List[str]],
247
+ image: PIL.Image.Image,
248
+ mask_image: PIL.Image.Image,
249
+ height: Optional[int] = 512,
250
+ width: Optional[int] = 512,
251
+ num_inference_steps: int = 50,
252
+ guidance_scale: float = 7.5,
253
+ negative_prompt: Optional[Union[str, List[str]]] = None,
254
+ num_images_per_prompt: Optional[int] = 1,
255
+ eta: float = 0.0,
256
+ generator: Optional[np.random.RandomState] = None,
257
+ latents: Optional[np.ndarray] = None,
258
+ output_type: Optional[str] = "pil",
259
+ return_dict: bool = True,
260
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
261
+ callback_steps: Optional[int] = 1,
262
+ ):
263
+ r"""
264
+ Function invoked when calling the pipeline for generation.
265
+
266
+ Args:
267
+ prompt (`str` or `List[str]`):
268
+ The prompt or prompts to guide the image generation.
269
+ image (`PIL.Image.Image`):
270
+ `Image`, or tensor representing an image batch which will be inpainted, *i.e.* parts of the image will
271
+ be masked out with `mask_image` and repainted according to `prompt`.
272
+ mask_image (`PIL.Image.Image`):
273
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
274
+ repainted, while black pixels will be preserved. If `mask_image` is a PIL image, it will be converted
275
+ to a single channel (luminance) before use. If it's a tensor, it should contain one color channel (L)
276
+ instead of 3, so the expected shape would be `(B, H, W, 1)`.
277
+ height (`int`, *optional*, defaults to 512):
278
+ The height in pixels of the generated image.
279
+ width (`int`, *optional*, defaults to 512):
280
+ The width in pixels of the generated image.
281
+ num_inference_steps (`int`, *optional*, defaults to 50):
282
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
283
+ expense of slower inference.
284
+ guidance_scale (`float`, *optional*, defaults to 7.5):
285
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
286
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
287
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
288
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
289
+ usually at the expense of lower image quality.
290
+ negative_prompt (`str` or `List[str]`, *optional*):
291
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
292
+ if `guidance_scale` is less than `1`).
293
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
294
+ The number of images to generate per prompt.
295
+ eta (`float`, *optional*, defaults to 0.0):
296
+ Corresponds to parameter eta (η) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
297
+ [`schedulers.DDIMScheduler`], will be ignored for others.
298
+ generator (`np.random.RandomState`, *optional*):
299
+ A np.random.RandomState to make generation deterministic.
300
+ latents (`np.ndarray`, *optional*):
301
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
302
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
303
+ tensor will ge generated by sampling using the supplied random `generator`.
304
+ output_type (`str`, *optional*, defaults to `"pil"`):
305
+ The output format of the generate image. Choose between
306
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
307
+ return_dict (`bool`, *optional*, defaults to `True`):
308
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
309
+ plain tuple.
310
+ callback (`Callable`, *optional*):
311
+ A function that will be called every `callback_steps` steps during inference. The function will be
312
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
313
+ callback_steps (`int`, *optional*, defaults to 1):
314
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
315
+ called at every step.
316
+
317
+ Returns:
318
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
319
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
320
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
321
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
322
+ (nsfw) content, according to the `safety_checker`.
323
+ """
324
+
325
+ if isinstance(prompt, str):
326
+ batch_size = 1
327
+ elif isinstance(prompt, list):
328
+ batch_size = len(prompt)
329
+ else:
330
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
331
+
332
+ if height % 8 != 0 or width % 8 != 0:
333
+ raise ValueError(f"`height` and `width` have to be divisible by 8 but are {height} and {width}.")
334
+
335
+ if (callback_steps is None) or (
336
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
337
+ ):
338
+ raise ValueError(
339
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
340
+ f" {type(callback_steps)}."
341
+ )
342
+
343
+ if generator is None:
344
+ generator = np.random
345
+
346
+ # set timesteps
347
+ self.scheduler.set_timesteps(num_inference_steps)
348
+
349
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
350
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
351
+ # corresponds to doing no classifier free guidance.
352
+ do_classifier_free_guidance = guidance_scale > 1.0
353
+
354
+ text_embeddings = self._encode_prompt(
355
+ prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
356
+ )
357
+
358
+ num_channels_latents = NUM_LATENT_CHANNELS
359
+ latents_shape = (batch_size * num_images_per_prompt, num_channels_latents, height // 8, width // 8)
360
+ latents_dtype = text_embeddings.dtype
361
+ if latents is None:
362
+ latents = generator.randn(*latents_shape).astype(latents_dtype)
363
+ else:
364
+ if latents.shape != latents_shape:
365
+ raise ValueError(f"Unexpected latents shape, got {latents.shape}, expected {latents_shape}")
366
+
367
+ # prepare mask and masked_image
368
+ mask, masked_image = prepare_mask_and_masked_image(image, mask_image, latents_shape[-2:])
369
+ mask = mask.astype(latents.dtype)
370
+ masked_image = masked_image.astype(latents.dtype)
371
+
372
+ masked_image_latents = self.vae_encoder(sample=masked_image)[0]
373
+ masked_image_latents = 0.18215 * masked_image_latents
374
+
375
+ # duplicate mask and masked_image_latents for each generation per prompt
376
+ mask = mask.repeat(batch_size * num_images_per_prompt, 0)
377
+ masked_image_latents = masked_image_latents.repeat(batch_size * num_images_per_prompt, 0)
378
+
379
+ mask = np.concatenate([mask] * 2) if do_classifier_free_guidance else mask
380
+ masked_image_latents = (
381
+ np.concatenate([masked_image_latents] * 2) if do_classifier_free_guidance else masked_image_latents
382
+ )
383
+
384
+ num_channels_mask = mask.shape[1]
385
+ num_channels_masked_image = masked_image_latents.shape[1]
386
+
387
+ unet_input_channels = NUM_UNET_INPUT_CHANNELS
388
+ if num_channels_latents + num_channels_mask + num_channels_masked_image != unet_input_channels:
389
+ raise ValueError(
390
+ "Incorrect configuration settings! The config of `pipeline.unet` expects"
391
+ f" {unet_input_channels} but received `num_channels_latents`: {num_channels_latents} +"
392
+ f" `num_channels_mask`: {num_channels_mask} + `num_channels_masked_image`: {num_channels_masked_image}"
393
+ f" = {num_channels_latents+num_channels_masked_image+num_channels_mask}. Please verify the config of"
394
+ " `pipeline.unet` or your `mask_image` or `image` input."
395
+ )
396
+
397
+ # set timesteps
398
+ self.scheduler.set_timesteps(num_inference_steps)
399
+
400
+ # scale the initial noise by the standard deviation required by the scheduler
401
+ latents = latents * np.float(self.scheduler.init_noise_sigma)
402
+
403
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
404
+ # eta (η) is only used with the DDIMScheduler, it will be ignored for other schedulers.
405
+ # eta corresponds to η in DDIM paper: https://arxiv.org/abs/2010.02502
406
+ # and should be between [0, 1]
407
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
408
+ extra_step_kwargs = {}
409
+ if accepts_eta:
410
+ extra_step_kwargs["eta"] = eta
411
+
412
+ timestep_dtype = next(
413
+ (input.type for input in self.unet.model.get_inputs() if input.name == "timestep"), "tensor(float)"
414
+ )
415
+ timestep_dtype = ORT_TO_NP_TYPE[timestep_dtype]
416
+
417
+ for i, t in enumerate(self.progress_bar(self.scheduler.timesteps)):
418
+ # expand the latents if we are doing classifier free guidance
419
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
420
+ # concat latents, mask, masked_image_latnets in the channel dimension
421
+ latent_model_input = self.scheduler.scale_model_input(torch.from_numpy(latent_model_input), t)
422
+ latent_model_input = latent_model_input.cpu().numpy()
423
+ latent_model_input = np.concatenate([latent_model_input, mask, masked_image_latents], axis=1)
424
+
425
+ # predict the noise residual
426
+ timestep = np.array([t], dtype=timestep_dtype)
427
+ noise_pred = self.unet(
428
+ sample=latent_model_input, timestep=timestep, encoder_hidden_states=text_embeddings
429
+ )[0]
430
+
431
+ # perform guidance
432
+ if do_classifier_free_guidance:
433
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
434
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
435
+
436
+ # compute the previous noisy sample x_t -> x_t-1
437
+ scheduler_output = self.scheduler.step(
438
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
439
+ )
440
+ latents = scheduler_output.prev_sample.numpy()
441
+
442
+ # call the callback, if provided
443
+ if callback is not None and i % callback_steps == 0:
444
+ callback(i, t, latents)
445
+
446
+ latents = 1 / 0.18215 * latents
447
+ # image = self.vae_decoder(latent_sample=latents)[0]
448
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
449
+ image = np.concatenate(
450
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
451
+ )
452
+
453
+ image = np.clip(image / 2 + 0.5, 0, 1)
454
+ image = image.transpose((0, 2, 3, 1))
455
+
456
+ if self.safety_checker is not None:
457
+ safety_checker_input = self.feature_extractor(
458
+ self.numpy_to_pil(image), return_tensors="np"
459
+ ).pixel_values.astype(image.dtype)
460
+ # safety_checker does not support batched inputs yet
461
+ images, has_nsfw_concept = [], []
462
+ for i in range(image.shape[0]):
463
+ image_i, has_nsfw_concept_i = self.safety_checker(
464
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
465
+ )
466
+ images.append(image_i)
467
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
468
+ image = np.concatenate(images)
469
+ else:
470
+ has_nsfw_concept = None
471
+
472
+ if output_type == "pil":
473
+ image = self.numpy_to_pil(image)
474
+
475
+ if not return_dict:
476
+ return (image, has_nsfw_concept)
477
+
478
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)
pix2video-main/mydiffusers/mydiffusers/pipelines/stable_diffusion/pipeline_onnx_stable_diffusion_inpaint_legacy.py ADDED
@@ -0,0 +1,461 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import inspect
2
+ from typing import Callable, List, Optional, Union
3
+
4
+ import numpy as np
5
+ import torch
6
+
7
+ import PIL
8
+ from transformers import CLIPFeatureExtractor, CLIPTokenizer
9
+
10
+ from ...configuration_utils import FrozenDict
11
+ from ...onnx_utils import OnnxRuntimeModel
12
+ from ...pipeline_utils import DiffusionPipeline
13
+ from ...schedulers import DDIMScheduler, LMSDiscreteScheduler, PNDMScheduler
14
+ from ...utils import deprecate, logging
15
+ from . import StableDiffusionPipelineOutput
16
+
17
+
18
+ logger = logging.get_logger(__name__) # pylint: disable=invalid-name
19
+
20
+
21
+ def preprocess(image):
22
+ w, h = image.size
23
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
24
+ image = image.resize((w, h), resample=PIL.Image.LANCZOS)
25
+ image = np.array(image).astype(np.float32) / 255.0
26
+ image = image[None].transpose(0, 3, 1, 2)
27
+ return 2.0 * image - 1.0
28
+
29
+
30
+ def preprocess_mask(mask, scale_factor=8):
31
+ mask = mask.convert("L")
32
+ w, h = mask.size
33
+ w, h = map(lambda x: x - x % 32, (w, h)) # resize to integer multiple of 32
34
+ mask = mask.resize((w // scale_factor, h // scale_factor), resample=PIL.Image.NEAREST)
35
+ mask = np.array(mask).astype(np.float32) / 255.0
36
+ mask = np.tile(mask, (4, 1, 1))
37
+ mask = mask[None].transpose(0, 1, 2, 3) # what does this step do?
38
+ mask = 1 - mask # repaint white, keep black
39
+ return mask
40
+
41
+
42
+ class OnnxStableDiffusionInpaintPipelineLegacy(DiffusionPipeline):
43
+ r"""
44
+ Pipeline for text-guided image inpainting using Stable Diffusion. This is a *legacy feature* for Onnx pipelines to
45
+ provide compatibility with StableDiffusionInpaintPipelineLegacy and may be removed in the future.
46
+
47
+ This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
48
+ library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
49
+
50
+ Args:
51
+ vae ([`AutoencoderKL`]):
52
+ Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
53
+ text_encoder ([`CLIPTextModel`]):
54
+ Frozen text-encoder. Stable Diffusion uses the text portion of
55
+ [CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
56
+ the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
57
+ tokenizer (`CLIPTokenizer`):
58
+ Tokenizer of class
59
+ [CLIPTokenizer](https://huggingface.co/docs/transformers/v4.21.0/en/model_doc/clip#transformers.CLIPTokenizer).
60
+ unet ([`UNet2DConditionModel`]): Conditional U-Net architecture to denoise the encoded image latents.
61
+ scheduler ([`SchedulerMixin`]):
62
+ A scheduler to be used in combination with `unet` to denoise the encoded image latents. Can be one of
63
+ [`DDIMScheduler`], [`LMSDiscreteScheduler`], or [`PNDMScheduler`].
64
+ safety_checker ([`StableDiffusionSafetyChecker`]):
65
+ Classification module that estimates whether generated images could be considered offensive or harmful.
66
+ Please, refer to the [model card](https://huggingface.co/runwayml/stable-diffusion-v1-5) for details.
67
+ feature_extractor ([`CLIPFeatureExtractor`]):
68
+ Model that extracts features from generated images to be used as inputs for the `safety_checker`.
69
+ """
70
+ _optional_components = ["safety_checker", "feature_extractor"]
71
+
72
+ vae_encoder: OnnxRuntimeModel
73
+ vae_decoder: OnnxRuntimeModel
74
+ text_encoder: OnnxRuntimeModel
75
+ tokenizer: CLIPTokenizer
76
+ unet: OnnxRuntimeModel
77
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler]
78
+ safety_checker: OnnxRuntimeModel
79
+ feature_extractor: CLIPFeatureExtractor
80
+
81
+ def __init__(
82
+ self,
83
+ vae_encoder: OnnxRuntimeModel,
84
+ vae_decoder: OnnxRuntimeModel,
85
+ text_encoder: OnnxRuntimeModel,
86
+ tokenizer: CLIPTokenizer,
87
+ unet: OnnxRuntimeModel,
88
+ scheduler: Union[DDIMScheduler, PNDMScheduler, LMSDiscreteScheduler],
89
+ safety_checker: OnnxRuntimeModel,
90
+ feature_extractor: CLIPFeatureExtractor,
91
+ requires_safety_checker: bool = True,
92
+ ):
93
+ super().__init__()
94
+
95
+ if hasattr(scheduler.config, "steps_offset") and scheduler.config.steps_offset != 1:
96
+ deprecation_message = (
97
+ f"The configuration file of this scheduler: {scheduler} is outdated. `steps_offset`"
98
+ f" should be set to 1 instead of {scheduler.config.steps_offset}. Please make sure "
99
+ "to update the config accordingly as leaving `steps_offset` might led to incorrect results"
100
+ " in future versions. If you have downloaded this checkpoint from the Hugging Face Hub,"
101
+ " it would be very nice if you could open a Pull request for the `scheduler/scheduler_config.json`"
102
+ " file"
103
+ )
104
+ deprecate("steps_offset!=1", "1.0.0", deprecation_message, standard_warn=False)
105
+ new_config = dict(scheduler.config)
106
+ new_config["steps_offset"] = 1
107
+ scheduler._internal_dict = FrozenDict(new_config)
108
+
109
+ if hasattr(scheduler.config, "clip_sample") and scheduler.config.clip_sample is True:
110
+ deprecation_message = (
111
+ f"The configuration file of this scheduler: {scheduler} has not set the configuration `clip_sample`."
112
+ " `clip_sample` should be set to False in the configuration file. Please make sure to update the"
113
+ " config accordingly as not setting `clip_sample` in the config might lead to incorrect results in"
114
+ " future versions. If you have downloaded this checkpoint from the Hugging Face Hub, it would be very"
115
+ " nice if you could open a Pull request for the `scheduler/scheduler_config.json` file"
116
+ )
117
+ deprecate("clip_sample not set", "1.0.0", deprecation_message, standard_warn=False)
118
+ new_config = dict(scheduler.config)
119
+ new_config["clip_sample"] = False
120
+ scheduler._internal_dict = FrozenDict(new_config)
121
+
122
+ if safety_checker is None and requires_safety_checker:
123
+ logger.warning(
124
+ f"You have disabled the safety checker for {self.__class__} by passing `safety_checker=None`. Ensure"
125
+ " that you abide to the conditions of the Stable Diffusion license and do not expose unfiltered"
126
+ " results in services or applications open to the public. Both the diffusers team and Hugging Face"
127
+ " strongly recommend to keep the safety filter enabled in all public facing circumstances, disabling"
128
+ " it only for use-cases that involve analyzing network behavior or auditing its results. For more"
129
+ " information, please have a look at https://github.com/huggingface/diffusers/pull/254 ."
130
+ )
131
+
132
+ if safety_checker is not None and feature_extractor is None:
133
+ raise ValueError(
134
+ "Make sure to define a feature extractor when loading {self.__class__} if you want to use the safety"
135
+ " checker. If you do not want to use the safety checker, you can pass `'safety_checker=None'` instead."
136
+ )
137
+
138
+ self.register_modules(
139
+ vae_encoder=vae_encoder,
140
+ vae_decoder=vae_decoder,
141
+ text_encoder=text_encoder,
142
+ tokenizer=tokenizer,
143
+ unet=unet,
144
+ scheduler=scheduler,
145
+ safety_checker=safety_checker,
146
+ feature_extractor=feature_extractor,
147
+ )
148
+ self.register_to_config(requires_safety_checker=requires_safety_checker)
149
+
150
+ # Copied from diffusers.pipelines.stable_diffusion.pipeline_onnx_stable_diffusion.OnnxStableDiffusionPipeline._encode_prompt
151
+ def _encode_prompt(self, prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt):
152
+ r"""
153
+ Encodes the prompt into text encoder hidden states.
154
+
155
+ Args:
156
+ prompt (`str` or `list(int)`):
157
+ prompt to be encoded
158
+ num_images_per_prompt (`int`):
159
+ number of images that should be generated per prompt
160
+ do_classifier_free_guidance (`bool`):
161
+ whether to use classifier free guidance or not
162
+ negative_prompt (`str` or `List[str]`):
163
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
164
+ if `guidance_scale` is less than `1`).
165
+ """
166
+ batch_size = len(prompt) if isinstance(prompt, list) else 1
167
+
168
+ # get prompt text embeddings
169
+ text_inputs = self.tokenizer(
170
+ prompt,
171
+ padding="max_length",
172
+ max_length=self.tokenizer.model_max_length,
173
+ truncation=True,
174
+ return_tensors="np",
175
+ )
176
+ text_input_ids = text_inputs.input_ids
177
+ untruncated_ids = self.tokenizer(prompt, padding="max_length", return_tensors="np").input_ids
178
+
179
+ if not np.array_equal(text_input_ids, untruncated_ids):
180
+ removed_text = self.tokenizer.batch_decode(untruncated_ids[:, self.tokenizer.model_max_length - 1 : -1])
181
+ logger.warning(
182
+ "The following part of your input was truncated because CLIP can only handle sequences up to"
183
+ f" {self.tokenizer.model_max_length} tokens: {removed_text}"
184
+ )
185
+
186
+ text_embeddings = self.text_encoder(input_ids=text_input_ids.astype(np.int32))[0]
187
+ text_embeddings = np.repeat(text_embeddings, num_images_per_prompt, axis=0)
188
+
189
+ # get unconditional embeddings for classifier free guidance
190
+ if do_classifier_free_guidance:
191
+ uncond_tokens: List[str]
192
+ if negative_prompt is None:
193
+ uncond_tokens = [""] * batch_size
194
+ elif type(prompt) is not type(negative_prompt):
195
+ raise TypeError(
196
+ f"`negative_prompt` should be the same type to `prompt`, but got {type(negative_prompt)} !="
197
+ f" {type(prompt)}."
198
+ )
199
+ elif isinstance(negative_prompt, str):
200
+ uncond_tokens = [negative_prompt] * batch_size
201
+ elif batch_size != len(negative_prompt):
202
+ raise ValueError(
203
+ f"`negative_prompt`: {negative_prompt} has batch size {len(negative_prompt)}, but `prompt`:"
204
+ f" {prompt} has batch size {batch_size}. Please make sure that passed `negative_prompt` matches"
205
+ " the batch size of `prompt`."
206
+ )
207
+ else:
208
+ uncond_tokens = negative_prompt
209
+
210
+ max_length = text_input_ids.shape[-1]
211
+ uncond_input = self.tokenizer(
212
+ uncond_tokens,
213
+ padding="max_length",
214
+ max_length=max_length,
215
+ truncation=True,
216
+ return_tensors="np",
217
+ )
218
+ uncond_embeddings = self.text_encoder(input_ids=uncond_input.input_ids.astype(np.int32))[0]
219
+ uncond_embeddings = np.repeat(uncond_embeddings, num_images_per_prompt, axis=0)
220
+
221
+ # For classifier free guidance, we need to do two forward passes.
222
+ # Here we concatenate the unconditional and text embeddings into a single batch
223
+ # to avoid doing two forward passes
224
+ text_embeddings = np.concatenate([uncond_embeddings, text_embeddings])
225
+
226
+ return text_embeddings
227
+
228
+ def __call__(
229
+ self,
230
+ prompt: Union[str, List[str]],
231
+ image: Union[np.ndarray, PIL.Image.Image],
232
+ mask_image: Union[np.ndarray, PIL.Image.Image],
233
+ strength: float = 0.8,
234
+ num_inference_steps: Optional[int] = 50,
235
+ guidance_scale: Optional[float] = 7.5,
236
+ negative_prompt: Optional[Union[str, List[str]]] = None,
237
+ num_images_per_prompt: Optional[int] = 1,
238
+ eta: Optional[float] = 0.0,
239
+ generator: Optional[np.random.RandomState] = None,
240
+ output_type: Optional[str] = "pil",
241
+ return_dict: bool = True,
242
+ callback: Optional[Callable[[int, int, np.ndarray], None]] = None,
243
+ callback_steps: Optional[int] = 1,
244
+ **kwargs,
245
+ ):
246
+ r"""
247
+ Function invoked when calling the pipeline for generation.
248
+
249
+ Args:
250
+ prompt (`str` or `List[str]`):
251
+ The prompt or prompts to guide the image generation.
252
+ image (`nd.ndarray` or `PIL.Image.Image`):
253
+ `Image`, or tensor representing an image batch, that will be used as the starting point for the
254
+ process. This is the image whose masked region will be inpainted.
255
+ mask_image (`nd.ndarray` or `PIL.Image.Image`):
256
+ `Image`, or tensor representing an image batch, to mask `image`. White pixels in the mask will be
257
+ replaced by noise and therefore repainted, while black pixels will be preserved. If `mask_image` is a
258
+ PIL image, it will be converted to a single channel (luminance) before use. If it's a tensor, it should
259
+ contain one color channel (L) instead of 3, so the expected shape would be `(B, H, W, 1)`.uu
260
+ strength (`float`, *optional*, defaults to 0.8):
261
+ Conceptually, indicates how much to transform the reference `image`. Must be between 0 and 1. `image`
262
+ will be used as a starting point, adding more noise to it the larger the `strength`. The number of
263
+ denoising steps depends on the amount of noise initially added. When `strength` is 1, added noise will
264
+ be maximum and the denoising process will run for the full number of iterations specified in
265
+ `num_inference_steps`. A value of 1, therefore, essentially ignores `image`.
266
+ num_inference_steps (`int`, *optional*, defaults to 50):
267
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
268
+ expense of slower inference. This parameter will be modulated by `strength`.
269
+ guidance_scale (`float`, *optional*, defaults to 7.5):
270
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
271
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
272
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
273
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
274
+ usually at the expense of lower image quality.
275
+ negative_prompt (`str` or `List[str]`, *optional*):
276
+ The prompt or prompts not to guide the image generation. Ignored when not using guidance (i.e., ignored
277
+ if `guidance_scale` is less than `1`).
278
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
279
+ The number of images to generate per prompt.
280
+ eta (`float`, *optional*, defaults to 0.0):
281
+ Corresponds to parameter eta (?) in the DDIM paper: https://arxiv.org/abs/2010.02502. Only applies to
282
+ [`schedulers.DDIMScheduler`], will be ignored for others.
283
+ generator (`np.random.RandomState`, *optional*):
284
+ A np.random.RandomState to make generation deterministic.
285
+ output_type (`str`, *optional*, defaults to `"pil"`):
286
+ The output format of the generate image. Choose between
287
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
288
+ return_dict (`bool`, *optional*, defaults to `True`):
289
+ Whether or not to return a [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] instead of a
290
+ plain tuple.
291
+ callback (`Callable`, *optional*):
292
+ A function that will be called every `callback_steps` steps during inference. The function will be
293
+ called with the following arguments: `callback(step: int, timestep: int, latents: np.ndarray)`.
294
+ callback_steps (`int`, *optional*, defaults to 1):
295
+ The frequency at which the `callback` function will be called. If not specified, the callback will be
296
+ called at every step.
297
+
298
+ Returns:
299
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] or `tuple`:
300
+ [`~pipelines.stable_diffusion.StableDiffusionPipelineOutput`] if `return_dict` is True, otherwise a `tuple.
301
+ When returning a tuple, the first element is a list with the generated images, and the second element is a
302
+ list of `bool`s denoting whether the corresponding generated image likely represents "not-safe-for-work"
303
+ (nsfw) content, according to the `safety_checker`.
304
+ """
305
+ message = "Please use `image` instead of `init_image`."
306
+ init_image = deprecate("init_image", "0.12.0", message, take_from=kwargs)
307
+ image = init_image or image
308
+
309
+ if isinstance(prompt, str):
310
+ batch_size = 1
311
+ elif isinstance(prompt, list):
312
+ batch_size = len(prompt)
313
+ else:
314
+ raise ValueError(f"`prompt` has to be of type `str` or `list` but is {type(prompt)}")
315
+
316
+ if strength < 0 or strength > 1:
317
+ raise ValueError(f"The value of strength should in [0.0, 1.0] but is {strength}")
318
+
319
+ if (callback_steps is None) or (
320
+ callback_steps is not None and (not isinstance(callback_steps, int) or callback_steps <= 0)
321
+ ):
322
+ raise ValueError(
323
+ f"`callback_steps` has to be a positive integer but is {callback_steps} of type"
324
+ f" {type(callback_steps)}."
325
+ )
326
+
327
+ if generator is None:
328
+ generator = np.random
329
+
330
+ # set timesteps
331
+ self.scheduler.set_timesteps(num_inference_steps)
332
+
333
+ if isinstance(image, PIL.Image.Image):
334
+ image = preprocess(image)
335
+
336
+ # here `guidance_scale` is defined analog to the guidance weight `w` of equation (2)
337
+ # of the Imagen paper: https://arxiv.org/pdf/2205.11487.pdf . `guidance_scale = 1`
338
+ # corresponds to doing no classifier free guidance.
339
+ do_classifier_free_guidance = guidance_scale > 1.0
340
+
341
+ text_embeddings = self._encode_prompt(
342
+ prompt, num_images_per_prompt, do_classifier_free_guidance, negative_prompt
343
+ )
344
+
345
+ latents_dtype = text_embeddings.dtype
346
+ image = image.astype(latents_dtype)
347
+
348
+ # encode the init image into latents and scale the latents
349
+ init_latents = self.vae_encoder(sample=image)[0]
350
+ init_latents = 0.18215 * init_latents
351
+
352
+ # Expand init_latents for batch_size and num_images_per_prompt
353
+ init_latents = np.concatenate([init_latents] * num_images_per_prompt, axis=0)
354
+ init_latents_orig = init_latents
355
+
356
+ # preprocess mask
357
+ if not isinstance(mask_image, np.ndarray):
358
+ mask_image = preprocess_mask(mask_image, 8)
359
+ mask_image = mask_image.astype(latents_dtype)
360
+ mask = np.concatenate([mask_image] * num_images_per_prompt, axis=0)
361
+
362
+ # check sizes
363
+ if not mask.shape == init_latents.shape:
364
+ raise ValueError("The mask and image should be the same size!")
365
+
366
+ # get the original timestep using init_timestep
367
+ offset = self.scheduler.config.get("steps_offset", 0)
368
+ init_timestep = int(num_inference_steps * strength) + offset
369
+ init_timestep = min(init_timestep, num_inference_steps)
370
+
371
+ timesteps = self.scheduler.timesteps.numpy()[-init_timestep]
372
+ timesteps = np.array([timesteps] * batch_size * num_images_per_prompt)
373
+
374
+ # add noise to latents using the timesteps
375
+ noise = generator.randn(*init_latents.shape).astype(latents_dtype)
376
+ init_latents = self.scheduler.add_noise(
377
+ torch.from_numpy(init_latents), torch.from_numpy(noise), torch.from_numpy(timesteps)
378
+ )
379
+ init_latents = init_latents.numpy()
380
+
381
+ # prepare extra kwargs for the scheduler step, since not all schedulers have the same signature
382
+ # eta (?) is only used with the DDIMScheduler, it will be ignored for other schedulers.
383
+ # eta corresponds to ? in DDIM paper: https://arxiv.org/abs/2010.02502
384
+ # and should be between [0, 1]
385
+ accepts_eta = "eta" in set(inspect.signature(self.scheduler.step).parameters.keys())
386
+ extra_step_kwargs = {}
387
+ if accepts_eta:
388
+ extra_step_kwargs["eta"] = eta
389
+
390
+ latents = init_latents
391
+
392
+ t_start = max(num_inference_steps - init_timestep + offset, 0)
393
+ timesteps = self.scheduler.timesteps[t_start:].numpy()
394
+
395
+ for i, t in enumerate(self.progress_bar(timesteps)):
396
+ # expand the latents if we are doing classifier free guidance
397
+ latent_model_input = np.concatenate([latents] * 2) if do_classifier_free_guidance else latents
398
+ latent_model_input = self.scheduler.scale_model_input(latent_model_input, t)
399
+
400
+ # predict the noise residual
401
+ noise_pred = self.unet(
402
+ sample=latent_model_input, timestep=np.array([t]), encoder_hidden_states=text_embeddings
403
+ )[0]
404
+
405
+ # perform guidance
406
+ if do_classifier_free_guidance:
407
+ noise_pred_uncond, noise_pred_text = np.split(noise_pred, 2)
408
+ noise_pred = noise_pred_uncond + guidance_scale * (noise_pred_text - noise_pred_uncond)
409
+
410
+ # compute the previous noisy sample x_t -> x_t-1
411
+ latents = self.scheduler.step(
412
+ torch.from_numpy(noise_pred), t, torch.from_numpy(latents), **extra_step_kwargs
413
+ ).prev_sample
414
+
415
+ latents = latents.numpy()
416
+
417
+ init_latents_proper = self.scheduler.add_noise(
418
+ torch.from_numpy(init_latents_orig), torch.from_numpy(noise), torch.from_numpy(np.array([t]))
419
+ )
420
+
421
+ init_latents_proper = init_latents_proper.numpy()
422
+
423
+ latents = (init_latents_proper * mask) + (latents * (1 - mask))
424
+
425
+ # call the callback, if provided
426
+ if callback is not None and i % callback_steps == 0:
427
+ callback(i, t, latents)
428
+
429
+ latents = 1 / 0.18215 * latents
430
+ # image = self.vae_decoder(latent_sample=latents)[0]
431
+ # it seems likes there is a strange result for using half-precision vae decoder if batchsize>1
432
+ image = np.concatenate(
433
+ [self.vae_decoder(latent_sample=latents[i : i + 1])[0] for i in range(latents.shape[0])]
434
+ )
435
+
436
+ image = np.clip(image / 2 + 0.5, 0, 1)
437
+ image = image.transpose((0, 2, 3, 1))
438
+
439
+ if self.safety_checker is not None:
440
+ safety_checker_input = self.feature_extractor(
441
+ self.numpy_to_pil(image), return_tensors="np"
442
+ ).pixel_values.astype(image.dtype)
443
+ # There will throw an error if use safety_checker batchsize>1
444
+ images, has_nsfw_concept = [], []
445
+ for i in range(image.shape[0]):
446
+ image_i, has_nsfw_concept_i = self.safety_checker(
447
+ clip_input=safety_checker_input[i : i + 1], images=image[i : i + 1]
448
+ )
449
+ images.append(image_i)
450
+ has_nsfw_concept.append(has_nsfw_concept_i[0])
451
+ image = np.concatenate(images)
452
+ else:
453
+ has_nsfw_concept = None
454
+
455
+ if output_type == "pil":
456
+ image = self.numpy_to_pil(image)
457
+
458
+ if not return_dict:
459
+ return (image, has_nsfw_concept)
460
+
461
+ return StableDiffusionPipelineOutput(images=image, nsfw_content_detected=has_nsfw_concept)