Skip to content

Commit 632dace

Browse files
[Custom pipeline] Easier loading of local pipelines (huggingface#1327)
* [Custom pipeline] Easier loading of local pipelines * upgrade black
1 parent 3346ec3 commit 632dace

File tree

3 files changed

+126
-2
lines changed

3 files changed

+126
-2
lines changed

src/diffusers/pipeline_utils.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@
1818
import inspect
1919
import os
2020
from dataclasses import dataclass
21+
from pathlib import Path
2122
from typing import Any, Dict, List, Optional, Union
2223

2324
import numpy as np
@@ -483,8 +484,16 @@ def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.P
483484
# 2. Load the pipeline class, if using custom module then load it from the hub
484485
# if we load from explicit class, let's use it
485486
if custom_pipeline is not None:
487+
if custom_pipeline.endswith(".py"):
488+
path = Path(custom_pipeline)
489+
# decompose into folder & file
490+
file_name = path.name
491+
custom_pipeline = path.parent.absolute()
492+
else:
493+
file_name = CUSTOM_PIPELINE_FILE_NAME
494+
486495
pipeline_class = get_class_from_dynamic_module(
487-
custom_pipeline, module_file=CUSTOM_PIPELINE_FILE_NAME, cache_dir=custom_pipeline
496+
custom_pipeline, module_file=file_name, cache_dir=custom_pipeline
488497
)
489498
elif cls != DiffusionPipeline:
490499
pipeline_class = cls
Lines changed: 101 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,101 @@
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+
14+
# limitations under the License.
15+
16+
17+
from typing import Optional, Tuple, Union
18+
19+
import torch
20+
21+
from diffusers.pipeline_utils import DiffusionPipeline, ImagePipelineOutput
22+
23+
24+
class CustomLocalPipeline(DiffusionPipeline):
25+
r"""
26+
This model inherits from [`DiffusionPipeline`]. Check the superclass documentation for the generic methods the
27+
library implements for all the pipelines (such as downloading or saving, running on a particular device, etc.)
28+
29+
Parameters:
30+
unet ([`UNet2DModel`]): U-Net architecture to denoise the encoded image.
31+
scheduler ([`SchedulerMixin`]):
32+
A scheduler to be used in combination with `unet` to denoise the encoded image. Can be one of
33+
[`DDPMScheduler`], or [`DDIMScheduler`].
34+
"""
35+
36+
def __init__(self, unet, scheduler):
37+
super().__init__()
38+
self.register_modules(unet=unet, scheduler=scheduler)
39+
40+
@torch.no_grad()
41+
def __call__(
42+
self,
43+
batch_size: int = 1,
44+
generator: Optional[torch.Generator] = None,
45+
num_inference_steps: int = 50,
46+
output_type: Optional[str] = "pil",
47+
return_dict: bool = True,
48+
**kwargs,
49+
) -> Union[ImagePipelineOutput, Tuple]:
50+
r"""
51+
Args:
52+
batch_size (`int`, *optional*, defaults to 1):
53+
The number of images to generate.
54+
generator (`torch.Generator`, *optional*):
55+
A [torch generator](https://pytorch.org/docs/stable/generated/torch.Generator.html) to make generation
56+
deterministic.
57+
eta (`float`, *optional*, defaults to 0.0):
58+
The eta parameter which controls the scale of the variance (0 is DDIM and 1 is one type of DDPM).
59+
num_inference_steps (`int`, *optional*, defaults to 50):
60+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
61+
expense of slower inference.
62+
output_type (`str`, *optional*, defaults to `"pil"`):
63+
The output format of the generate image. Choose between
64+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
65+
return_dict (`bool`, *optional*, defaults to `True`):
66+
Whether or not to return a [`~pipeline_utils.ImagePipelineOutput`] instead of a plain tuple.
67+
68+
Returns:
69+
[`~pipeline_utils.ImagePipelineOutput`] or `tuple`: [`~pipelines.utils.ImagePipelineOutput`] if
70+
`return_dict` is True, otherwise a `tuple. When returning a tuple, the first element is a list with the
71+
generated images.
72+
"""
73+
74+
# Sample gaussian noise to begin loop
75+
image = torch.randn(
76+
(batch_size, self.unet.in_channels, self.unet.sample_size, self.unet.sample_size),
77+
generator=generator,
78+
)
79+
image = image.to(self.device)
80+
81+
# set step values
82+
self.scheduler.set_timesteps(num_inference_steps)
83+
84+
for t in self.progress_bar(self.scheduler.timesteps):
85+
# 1. predict noise model_output
86+
model_output = self.unet(image, t).sample
87+
88+
# 2. predict previous mean of image x_t-1 and add variance depending on eta
89+
# eta corresponds to η in paper and should be between [0, 1]
90+
# do x_t -> x_t-1
91+
image = self.scheduler.step(model_output, t, image).prev_sample
92+
93+
image = (image / 2 + 0.5).clamp(0, 1)
94+
image = image.cpu().permute(0, 2, 3, 1).numpy()
95+
if output_type == "pil":
96+
image = self.numpy_to_pil(image)
97+
98+
if not return_dict:
99+
return (image,), "This is a local test"
100+
101+
return ImagePipelineOutput(images=image), "This is a local test"

tests/test_pipelines.py

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -192,7 +192,7 @@ def test_run_custom_pipeline(self):
192192
# compare output to https://huggingface.co/hf-internal-testing/diffusers-dummy-pipeline/blob/main/pipeline.py#L102
193193
assert output_str == "This is a test"
194194

195-
def test_local_custom_pipeline(self):
195+
def test_local_custom_pipeline_repo(self):
196196
local_custom_pipeline_path = get_tests_dir("fixtures/custom_pipeline")
197197
pipeline = DiffusionPipeline.from_pretrained(
198198
"google/ddpm-cifar10-32", custom_pipeline=local_custom_pipeline_path
@@ -205,6 +205,20 @@ def test_local_custom_pipeline(self):
205205
# compare to https://github.com/huggingface/diffusers/blob/main/tests/fixtures/custom_pipeline/pipeline.py#L102
206206
assert output_str == "This is a local test"
207207

208+
def test_local_custom_pipeline_file(self):
209+
local_custom_pipeline_path = get_tests_dir("fixtures/custom_pipeline")
210+
local_custom_pipeline_path = os.path.join(local_custom_pipeline_path, "what_ever.py")
211+
pipeline = DiffusionPipeline.from_pretrained(
212+
"google/ddpm-cifar10-32", custom_pipeline=local_custom_pipeline_path
213+
)
214+
pipeline = pipeline.to(torch_device)
215+
images, output_str = pipeline(num_inference_steps=2, output_type="np")
216+
217+
assert pipeline.__class__.__name__ == "CustomLocalPipeline"
218+
assert images[0].shape == (1, 32, 32, 3)
219+
# compare to https://github.com/huggingface/diffusers/blob/main/tests/fixtures/custom_pipeline/pipeline.py#L102
220+
assert output_str == "This is a local test"
221+
208222
@slow
209223
@require_torch_gpu
210224
def test_load_pipeline_from_git(self):

0 commit comments

Comments
 (0)