text stringlengths 1 1.02k | class_index int64 0 1.38k | source stringclasses 431
values |
|---|---|---|
if "enable_pag" in kwargs:
enable_pag = kwargs.pop("enable_pag")
if enable_pag:
text_2_image_cls = _get_task_class(
AUTO_TEXT2IMAGE_PIPELINES_MAPPING,
text_2_image_cls.__name__.replace("PAG", "").replace("Pipeline", "PAGPipeline"),
... | 32 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# allow users pass modules in `kwargs` to override the original pipeline's components
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
original_class_obj = {
k: pipeline.components[k]
for k, v in pipeline.components.items()
if k in expect... | 32 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# config that were not expected by original pipeline is stored as private attribute
# we will pass them as optional arguments if they can be accepted by the pipeline
additional_pipe_kwargs = [
k[1:]
for k in original_config.keys()
if k.startswith("_") and k[1:] in opt... | 32 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
missing_modules = (
set(expected_modules) - set(text_2_image_cls._optional_components) - set(text_2_image_kwargs.keys())
)
if len(missing_modules) > 0:
raise ValueError(
f"Pipeline {text_2_image_cls} expected {expected_modules}, but only {set(list(passed_class_ob... | 32 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
class AutoPipelineForImage2Image(ConfigMixin):
r"""
[`AutoPipelineForImage2Image`] is a generic pipeline class that instantiates an image-to-image pipeline class. The
specific underlying pipeline class is automatically selected from either the
[`~AutoPipelineForImage2Image.from_pretrained`] or [`~AutoP... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
r"""
Instantiates a image-to-image Pytorch diffusion pipeline from pretrained pipeline weight.
The from_pretrained() method takes care of returning the correct pipeline class instance by:
... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
```
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in ... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
hosted on the Hub.
- A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
saved using
[`~DiffusionP... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used. | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
output_loading_info(`bool`, *optional*, defaults to `False`)... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
allowed by Git.
custom_revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
A map that specifies where each submodule should go. It doesn’t need to be defined for each
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
same device. | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
more information about each option see [designing a device
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
max_memory (`Dict`... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
when there is some disk offload.
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
tries to not use more than 1x model size ... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
below for more information.
variant (`str`, *optional*):
... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
<Tip>
To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
`huggingface-cli login`.
</Tip>
Examples:
```py
>>> from diffusers import AutoPipelineForImage2Image
>>> pipeline = AutoPipelineForImage2Image.from_... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
load_config_kwargs = {
"cache_dir": cache_dir,
"force_download": force_download,
"proxies": proxies,
"token": token,
"local_files_only": local_files_only,
"revision": revision,
}
config = cls.load_config(pretrained_model_or_path, *... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "controlnet" in kwargs:
if isinstance(kwargs["controlnet"], ControlNetUnionModel):
orig_class_name = orig_class_name.replace(to_replace, "ControlNetUnion" + to_replace)
else:
orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
@classmethod
def from_pipe(cls, pipeline, **kwargs):
r"""
Instantiates a image-to-image Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
The from_pipe() method takes care of returning the correct pipeline class instance by finding the
image-to-image pip... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
>>> pipe_t2i = AutoPipelineForText2Image.from_pretrained(
... "stable-diffusion-v1-5/stable-diffusion-v1-5", requires_safety_checker=False
... )
>>> pipe_i2i = AutoPipelineForImage2Image.from_pipe(pipe_t2i)
>>> image = pipe_i2i(prompt, image).images[0]
```
"""
... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "controlnet" in kwargs:
if kwargs["controlnet"] is not None:
to_replace = "Img2ImgPipeline"
if "PAG" in image_2_image_cls.__name__:
to_replace = "PAG" + to_replace
image_2_image_cls = _get_task_class(
AUTO_IMAGE2IMAGE... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "enable_pag" in kwargs:
enable_pag = kwargs.pop("enable_pag")
if enable_pag:
image_2_image_cls = _get_task_class(
AUTO_IMAGE2IMAGE_PIPELINES_MAPPING,
image_2_image_cls.__name__.replace("PAG", "").replace("Img2ImgPipeline", "PAGImg2ImgPip... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# allow users pass modules in `kwargs` to override the original pipeline's components
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
original_class_obj = {
k: pipeline.components[k]
for k, v in pipeline.components.items()
if k in expect... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# config attribute that were not expected by original pipeline is stored as its private attribute
# we will pass them as optional arguments if they can be accepted by the pipeline
additional_pipe_kwargs = [
k[1:]
for k in original_config.keys()
if k.startswith("_") an... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
missing_modules = (
set(expected_modules) - set(image_2_image_cls._optional_components) - set(image_2_image_kwargs.keys())
)
if len(missing_modules) > 0:
raise ValueError(
f"Pipeline {image_2_image_cls} expected {expected_modules}, but only {set(list(passed_class... | 33 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
class AutoPipelineForInpainting(ConfigMixin):
r"""
[`AutoPipelineForInpainting`] is a generic pipeline class that instantiates an inpainting pipeline class. The
specific underlying pipeline class is automatically selected from either the
[`~AutoPipelineForInpainting.from_pretrained`] or [`~AutoPipeline... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_or_path, **kwargs):
r"""
Instantiates a inpainting Pytorch diffusion pipeline from pretrained pipeline weight.
The from_pretrained() method takes care of returning the correct pipeline class instance by:
... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
```
Some weights of UNet2DConditionModel were not initialized from the model checkpoint at stable-diffusion-v1-5/stable-diffusion-v1-5 and are newly initialized because the shapes did not match:
- conv_in.weight: found shape torch.Size([320, 4, 3, 3]) in the checkpoint and torch.Size([320, 9, 3, 3]) in ... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
hosted on the Hub.
- A path to a *directory* (for example `./my_pipeline_directory/`) containing pipeline weights
saved using
[`~DiffusionP... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Path to a directory where a downloaded pretrained model configuration is cached if the standard cache
is not used. | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
output_loading_info(`bool`, *optional*, defaults to `False`)... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
allowed by Git.
custom_revision (`str`, *optional*, defaults to `"main"`):
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
A map that specifies where each submodule should go. It doesn’t need to be defined for each
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
same device. | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
more information about each option see [designing a device
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
max_memory (`Dict`... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
when there is some disk offload.
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
tries to not use more than 1x model size ... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
Can be used to overwrite load and saveable variables (the pipeline components of the specific pipeline
class). The overwritten components are passed directly to the pipelines `__init__` method. See example
below for more information.
variant (`str`, *optional*):
... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
<Tip>
To use private or [gated](https://huggingface.co/docs/hub/models-gated#gated-models) models, log-in with
`huggingface-cli login`.
</Tip>
Examples:
```py
>>> from diffusers import AutoPipelineForInpainting
>>> pipeline = AutoPipelineForInpainting.from_pr... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
load_config_kwargs = {
"cache_dir": cache_dir,
"force_download": force_download,
"proxies": proxies,
"token": token,
"local_files_only": local_files_only,
"revision": revision,
}
config = cls.load_config(pretrained_model_or_path, *... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "controlnet" in kwargs:
if isinstance(kwargs["controlnet"], ControlNetUnionModel):
orig_class_name = orig_class_name.replace(to_replace, "ControlNetUnion" + to_replace)
else:
orig_class_name = orig_class_name.replace(to_replace, "ControlNet" + to_replace)
... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
@classmethod
def from_pipe(cls, pipeline, **kwargs):
r"""
Instantiates a inpainting Pytorch diffusion pipeline from another instantiated diffusion pipeline class.
The from_pipe() method takes care of returning the correct pipeline class instance by finding the inpainting
pipeline li... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
>>> pipe_inpaint = AutoPipelineForInpainting.from_pipe(pipe_t2i)
>>> image = pipe_inpaint(prompt, image=init_image, mask_image=mask_image).images[0]
```
"""
original_config = dict(pipeline.config)
original_cls_name = pipeline.__class__.__name__
# derive the pipeline clas... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "controlnet" in kwargs:
if kwargs["controlnet"] is not None:
inpainting_cls = _get_task_class(
AUTO_INPAINT_PIPELINES_MAPPING,
inpainting_cls.__name__.replace("ControlNet", "").replace(
"InpaintPipeline", "ControlNetInpaintPi... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if "enable_pag" in kwargs:
enable_pag = kwargs.pop("enable_pag")
if enable_pag:
inpainting_cls = _get_task_class(
AUTO_INPAINT_PIPELINES_MAPPING,
inpainting_cls.__name__.replace("PAG", "").replace("InpaintPipeline", "PAGInpaintPipeline"),
... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# allow users pass modules in `kwargs` to override the original pipeline's components
passed_class_obj = {k: kwargs.pop(k) for k in expected_modules if k in kwargs}
original_class_obj = {
k: pipeline.components[k]
for k, v in pipeline.components.items()
if k in expect... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
# config that were not expected by original pipeline is stored as private attribute
# we will pass them as optional arguments if they can be accepted by the pipeline
additional_pipe_kwargs = [
k[1:]
for k in original_config.keys()
if k.startswith("_") and k[1:] in opt... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
if len(missing_modules) > 0:
raise ValueError(
f"Pipeline {inpainting_cls} expected {expected_modules}, but only {set(list(passed_class_obj.keys()) + list(original_class_obj.keys()))} were passed"
)
model = inpainting_cls(**inpainting_kwargs)
model.register_to_co... | 34 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/auto_pipeline.py |
class FreeInitMixin:
r"""Mixin class for FreeInit."""
def enable_free_init(
self,
num_iters: int = 3,
use_fast_sampling: bool = False,
method: str = "butterworth",
order: int = 4,
spatial_stop_frequency: float = 0.25,
temporal_stop_frequency: float = 0.25... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
Args:
num_iters (`int`, *optional*, defaults to `3`):
Number of FreeInit noise re-initialization iterations.
use_fast_sampling (`bool`, *optional*, defaults to `False`):
Whether or not to speedup sampling procedure at the cost of probably lower quality results. En... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
Normalized stop frequency for spatial dimensions. Must be between 0 to 1. Referred to as `d_s` in the
original implementation.
temporal_stop_frequency (`float`, *optional*, defaults to `0.25`):
Normalized stop frequency for temporal dimensions. Must be between 0 to 1. Referre... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
def disable_free_init(self):
"""Disables the FreeInit mechanism if enabled."""
self._free_init_num_iters = None
@property
def free_init_enabled(self):
return hasattr(self, "_free_init_num_iters") and self._free_init_num_iters is not None
def _get_free_init_freq_filter(
self... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
def retrieve_mask(x):
return 1 / (1 + (x / spatial_stop_frequency**2) ** order)
elif filter_type == "gaussian":
def retrieve_mask(x):
return math.exp(-1 / (2 * spatial_stop_frequency**2) * x)
elif filter_type == "ideal":
def retrieve_mask(x):
... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
def _apply_freq_filter(self, x: torch.Tensor, noise: torch.Tensor, low_pass_filter: torch.Tensor) -> torch.Tensor:
r"""Noise reinitialization."""
# FFT
x_freq = fft.fftn(x, dim=(-3, -2, -1))
x_freq = fft.fftshift(x_freq, dim=(-3, -2, -1))
noise_freq = fft.fftn(noise, dim=(-3, -2,... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
def _apply_free_init(
self,
latents: torch.Tensor,
free_init_iteration: int,
num_inference_steps: int,
device: torch.device,
dtype: torch.dtype,
generator: torch.Generator,
):
if free_init_iteration == 0:
self._free_init_initial_noise = lat... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
current_diffuse_timestep = self.scheduler.config.num_train_timesteps - 1
diffuse_timesteps = torch.full((latent_shape[0],), current_diffuse_timestep).long()
z_t = self.scheduler.add_noise(
original_samples=latents, noise=self._free_init_initial_noise, timesteps=diffuse_timesteps... | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
if num_inference_steps > 0:
self.scheduler.set_timesteps(num_inference_steps, device=device)
return latents, self.scheduler.timesteps | 35 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/free_init_utils.py |
class OnnxRuntimeModel:
def __init__(self, model=None, **kwargs):
logger.info("`diffusers.OnnxRuntimeModel` is experimental and might change in the future.")
self.model = model
self.model_save_dir = kwargs.get("model_save_dir", None)
self.latest_model_name = kwargs.get("latest_model_... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
Arguments:
path (`str` or `Path`):
Directory from which to load
provider(`str`, *optional*):
Onnxruntime execution provider to use for loading the model, defaults to `CPUExecutionProvider`
"""
if provider is None:
logger.info("No onnxru... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
Arguments:
save_directory (`str` or `Path`):
Directory where to save the model file.
file_name(`str`, *optional*):
Overwrites the default model file name from `"model.onnx"` to `file_name`. This allows you to save the
model with a different name.
... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
# copy external weights (for models >2GB)
src_path = self.model_save_dir.joinpath(ONNX_EXTERNAL_WEIGHTS_NAME)
if src_path.exists():
dst_path = Path(save_directory).joinpath(ONNX_EXTERNAL_WEIGHTS_NAME)
try:
shutil.copyfile(src_path, dst_path)
except shu... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
# saving model weights/files
self._save_pretrained(save_directory, **kwargs)
@classmethod
@validate_hf_hub_args
def _from_pretrained(
cls,
model_id: Union[str, Path],
token: Optional[Union[bool, str, None]] = None,
revision: Optional[Union[str, None]] = None,
... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
Arguments:
model_id (`str` or `Path`):
Directory from which to load
token (`str` or `bool`):
Is needed to load models from a private or gated repository
revision (`str`):
Revision is the specific model version to use. It can be a branch... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
different model files from the same repository or directory.
provider(`str`):
The ONNX runtime provider, e.g. `CPUExecutionProvider` or `CUDAExecutionProvider`.
kwargs (`Dict`, *optional*):
kwargs will be passed to the model during initialization
"""
... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
force_download=force_download,
)
kwargs["model_save_dir"] = Path(model_cache_path).parent
kwargs["latest_model_name"] = Path(model_cache_path).name
model = OnnxRuntimeModel.load_model(model_cache_path, provider=provider, sess_options=sess_options)
return cls(model... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
@classmethod
@validate_hf_hub_args
def from_pretrained(
cls,
model_id: Union[str, Path],
force_download: bool = True,
token: Optional[str] = None,
cache_dir: Optional[str] = None,
**model_kwargs,
):
revision = None
if len(str(model_id).split("@... | 36 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/onnx_utils.py |
class ImagePipelineOutput(BaseOutput):
"""
Output class for image pipelines.
Args:
images (`List[PIL.Image.Image]` or `np.ndarray`)
List of denoised PIL images of length `batch_size` or NumPy array of shape `(batch_size, height, width,
num_channels)`.
"""
images: Un... | 37 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
class AudioPipelineOutput(BaseOutput):
"""
Output class for audio pipelines.
Args:
audios (`np.ndarray`)
List of denoised audio samples of a NumPy array of shape `(batch_size, num_channels, sample_rate)`.
"""
audios: np.ndarray | 38 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
class DiffusionPipeline(ConfigMixin, PushToHubMixin):
r"""
Base class for all pipelines.
[`DiffusionPipeline`] stores all components (models, schedulers, and processors) for diffusion pipelines and
provides methods for loading, downloading and saving models. It also includes methods to:
- move... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
config_name = "model_index.json"
model_cpu_offload_seq = None
hf_device_map = None
_optional_components = []
_exclude_from_cpu_offload = []
_load_connected_pipes = False
_is_onnx = False
def register_modules(self, **kwargs):
for name, module in kwargs.items():
# retrieve... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def __setattr__(self, name: str, value: Any):
if name in self.__dict__ and hasattr(self.config, name):
# We need to overwrite the config if name exists in config
if isinstance(getattr(self.config, name), (tuple, list)):
if value is not None and self.config[name][0] is not... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def save_pretrained(
self,
save_directory: Union[str, os.PathLike],
safe_serialization: bool = True,
variant: Optional[str] = None,
max_shard_size: Optional[Union[int, str]] = None,
push_to_hub: bool = False,
**kwargs,
):
"""
Save all saveable ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Arguments:
save_directory (`str` or `os.PathLike`):
Directory to save a pipeline to. Will be created if it doesn't exist.
safe_serialization (`bool`, *optional*, defaults to `True`):
Whether to save the model using `safetensors` or the traditional PyTorch way with... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
This is to establish a common default size for this argument across different libraries in the Hugging
Face ecosystem (`transformers`, and `accelerate`, for example).
push_to_hub (`bool`, *optional*, defaults to `False`):
Whether or not to push your model to the Hugging Face ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
kwargs (`Dict[str, Any]`, *optional*):
Additional keyword arguments passed along to the [`~utils.PushToHubMixin.push_to_hub`] method.
"""
model_index_dict = dict(self.config)
model_index_dict.pop("_class_name", None)
model_index_dict.pop("_diffusers_version", None)
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def is_saveable_module(name, value):
if name not in expected_modules:
return False
if name in self._optional_components and value[0] is None:
return False
return True
model_index_dict = {k: v for k, v in model_index_dict.items() if is_saveable... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
save_method_name = None
# search for the model's base class in LOADABLE_CLASSES
for library_name, library_classes in LOADABLE_CLASSES.items():
if library_name in sys.modules:
library = importlib.import_module(library_name)
else:
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
for base_class, save_load_methods in library_classes.items():
class_candidate = getattr(library, base_class, None)
if class_candidate is not None and issubclass(model_cls, class_candidate):
# if we found a suitable base class in LOADABLE_CLASSES then grab ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# Call the save method with the argument safe_serialization only if it's supported
save_method_signature = inspect.signature(save_method)
save_method_accept_safe = "safe_serialization" in save_method_signature.parameters
save_method_accept_variant = "variant" in save_method_signature... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# finally save the config
self.save_config(save_directory)
if push_to_hub:
# Create a new empty model card and eventually tag it
model_card = load_or_create_model_card(repo_id, token=token, is_pipeline=True)
model_card = populate_model_card(model_card)
mo... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
If the pipeline already has the correct torch.dtype and torch.device, then it is returned as is. Otherwise,
the returned pipeline is a copy of self with the desired torch.dtype and torch.device.
</Tip>
Here are the ways to call `to`:
- `to(dtype, silence_dtype_warnings=False) → D... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Arguments:
dtype (`torch.dtype`, *optional*):
Returns a pipeline with the specified
[`dtype`](https://pytorch.org/docs/stable/tensor_attributes.html#torch.dtype)
device (`torch.Device`, *optional*):
Returns a pipeline with the specified
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
dtype_arg = None
device_arg = None
if len(args) == 1:
if isinstance(args[0], torch.dtype):
dtype_arg = args[0]
else:
device_arg = torch.device(args[0]) if args[0] is not None else None
elif len(args) == 2:
if isinstance(args[0],... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
dtype = dtype or dtype_arg
if device is not None and device_arg is not None:
raise ValueError(
"You have passed `device` both as an argument and as a keyword argument. Please only pass one of the two."
)
device = device or device_arg
pipeline_has_bnb = a... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
def module_is_offloaded(module):
if not is_accelerate_available() or is_accelerate_version("<", "0.17.0.dev0"):
return False
return hasattr(module, "_hf_hook") and isinstance(module._hf_hook, accelerate.hooks.CpuOffload)
# .to("cuda") would raise an error if the pipelin... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if device and torch.device(device).type == "cuda":
if pipeline_is_sequentially_offloaded and not pipeline_has_bnb:
raise ValueError(
"It seems like you have activated sequential model offloading by calling `enable_sequential_cpu_offload`, but are now attempting to move th... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
# Display a warning in this case (the operation succeeds but the benefits are lost)
pipeline_is_offloaded = any(module_is_offloaded(module) for _, module in self.components.items())
if pipeline_is_offloaded and device and torch.device(device).type == "cuda":
logger.warning(
f... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
module_names, _ = self._get_signature_keys(self)
modules = [getattr(self, n, None) for n in module_names]
modules = [m for m in modules if isinstance(m, torch.nn.Module)]
is_offloaded = pipeline_is_offloaded or pipeline_is_sequentially_offloaded
for module in modules:
_, is_... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if is_loaded_in_8bit_bnb and device is not None:
logger.warning(
f"The module '{module.__class__.__name__}' has been loaded in `bitsandbytes` 8bit and moving it to {device} via `.to()` is not supported. Module is still on {module.device}."
)
# This can ha... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
if (
module.dtype == torch.float16
and str(device) in ["cpu"]
and not silence_dtype_warnings
and not is_offloaded
):
logger.warning(
"Pipelines loaded with `dtype=torch.float16` cannot run with `cpu` device. ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
@property
def device(self) -> torch.device:
r"""
Returns:
`torch.device`: The torch device on which the pipeline is located.
"""
module_names, _ = self._get_signature_keys(self)
modules = [getattr(self, n, None) for n in module_names]
modules = [m for m in... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
@classmethod
@validate_hf_hub_args
def from_pretrained(cls, pretrained_model_name_or_path: Optional[Union[str, os.PathLike]], **kwargs):
r"""
Instantiate a PyTorch diffusion pipeline from pretrained pipeline weights.
The pipeline is set in evaluation mode (`model.eval()`) by default.
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Parameters:
pretrained_model_name_or_path (`str` or `os.PathLike`, *optional*):
Can be either:
- A string, the *repo id* (for example `CompVis/ldm-text2im-large-256`) of a pretrained pipeline
hosted on the Hub.
- A path to a *dir... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
🧪 This is an experimental feature and may change in the future.
</Tip>
Can be either: | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
- A string, the *repo id* (for example `hf-internal-testing/diffusers-dummy-pipeline`) of a custom
pipeline hosted on the Hub. The repository must contain a file called pipeline.py that defines
the custom pipeline.
- A string, the *file name* of a communit... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
For more information on how to load and create custom pipelines, please have a look at [Loading and
Adding Custom
Pipelines](https://huggingface.co/docs/diffusers/using-diffusers/custom_pipeline_overview)
force_download (`bool`, *optional*, defaults to `False`):
... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
proxies (`Dict[str, str]`, *optional*):
A dictionary of proxy servers to use by protocol or endpoint, for example, `{'http': 'foo.bar:3128',
'http://hostname': 'foo.bar:4012'}`. The proxies are used on each request.
output_loading_info(`bool`, *optional*, defaults to `False`)... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
The specific model version to use. It can be a branch name, a tag name, a commit id, or any identifier
allowed by Git.
custom_revision (`str`, *optional*):
The specific model version to use. It can be a branch name, a tag name, or a commit id similar to
`revis... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
parameter/buffer name; once a given module name is inside, every submodule of it will be sent to the
same device. | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Set `device_map="auto"` to have 🤗 Accelerate automatically compute the most optimized `device_map`. For
more information about each option see [designing a device
map](https://hf.co/docs/accelerate/main/en/usage_guides/big_modeling#designing-a-device-map).
max_memory (`Dict`... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
when there is some disk offload.
low_cpu_mem_usage (`bool`, *optional*, defaults to `True` if torch version >= 1.9.0 else `False`):
Speed up model loading only loading the pretrained weights and not initializing the weights. This also
tries to not use more than 1x model size ... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
If set to `True`, ONNX weights will always be downloaded if present. If set to `False`, ONNX weights
will never be downloaded. By default `use_onnx` defaults to the `_is_onnx` class attribute which is
`False` for non-ONNX pipelines and `True` for ONNX pipelines. ONNX weights include both... | 39 | /Users/nielsrogge/Documents/python_projecten/diffusers/src/diffusers/pipelines/pipeline_utils.py |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.